merge with 2.5 (not trunk, last merge message said that on accident) at r22252
[blender.git] / source / blender / render / intern / source / convertblender.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * Contributors: 2004/2005/2006 Blender Foundation, full recode
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 #include <math.h>
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <limits.h>
33
34 #include "MTC_matrixops.h"
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_arithb.h"
39 #include "BLI_blenlib.h"
40 #include "BLI_rand.h"
41 #include "BLI_memarena.h"
42 #include "BLI_ghash.h"
43
44 #include "DNA_armature_types.h"
45 #include "DNA_camera_types.h"
46 #include "DNA_material_types.h"
47 #include "DNA_curve_types.h"
48 #include "DNA_effect_types.h"
49 #include "DNA_group_types.h"
50 #include "DNA_lamp_types.h"
51 #include "DNA_image_types.h"
52 #include "DNA_lattice_types.h"
53 #include "DNA_mesh_types.h"
54 #include "DNA_meshdata_types.h"
55 #include "DNA_meta_types.h"
56 #include "DNA_modifier_types.h"
57 #include "DNA_node_types.h"
58 #include "DNA_object_types.h"
59 #include "DNA_object_force.h"
60 #include "DNA_object_fluidsim.h"
61 #include "DNA_particle_types.h"
62 #include "DNA_scene_types.h"
63 #include "DNA_texture_types.h"
64 #include "DNA_view3d_types.h"
65
66 #include "BKE_anim.h"
67 #include "BKE_armature.h"
68 #include "BKE_action.h"
69 #include "BKE_curve.h"
70 #include "BKE_customdata.h"
71 #include "BKE_colortools.h"
72 #include "BKE_constraint.h"
73 #include "BKE_displist.h"
74 #include "BKE_deform.h"
75 #include "BKE_DerivedMesh.h"
76 #include "BKE_effect.h"
77 #include "BKE_global.h"
78 #include "BKE_group.h"
79 #include "BKE_key.h"
80 #include "BKE_ipo.h"
81 #include "BKE_image.h"
82 #include "BKE_lattice.h"
83 #include "BKE_library.h"
84 #include "BKE_material.h"
85 #include "BKE_main.h"
86 #include "BKE_mball.h"
87 #include "BKE_mesh.h"
88 #include "BKE_modifier.h"
89 #include "BKE_node.h"
90 #include "BKE_object.h"
91 #include "BKE_particle.h"
92 #include "BKE_scene.h"
93 #include "BKE_subsurf.h"
94 #include "BKE_texture.h"
95 #include "BKE_utildefines.h"
96 #include "BKE_world.h"
97
98 #include "PIL_time.h"
99 #include "IMB_imbuf_types.h"
100
101 #include "envmap.h"
102 #include "occlusion.h"
103 #include "render_types.h"
104 #include "rendercore.h"
105 #include "renderdatabase.h"
106 #include "renderpipeline.h"
107 #include "shadbuf.h"
108 #include "shading.h"
109 #include "strand.h"
110 #include "texture.h"
111 #include "sss.h"
112 #include "strand.h"
113 #include "zbuf.h"
114 #include "sunsky.h"
115
116
117 /* 10 times larger than normal epsilon, test it on default nurbs sphere with ray_transp (for quad detection) */
118 /* or for checking vertex normal flips */
119 #define FLT_EPSILON10 1.19209290e-06F
120
121 /* ------------------------------------------------------------------------- */
122
123 /* Stuff for stars. This sits here because it uses gl-things. Part of
124 this code may move down to the converter.  */
125 /* ------------------------------------------------------------------------- */
126 /* this is a bad beast, since it is misused by the 3d view drawing as well. */
127
128 static HaloRen *initstar(Render *re, ObjectRen *obr, float *vec, float hasize)
129 {
130         HaloRen *har;
131         float hoco[4];
132         
133         projectverto(vec, re->winmat, hoco);
134         
135         har= RE_findOrAddHalo(obr, obr->tothalo++);
136         
137         /* projectvert is done in function zbufvlaggen again, because of parts */
138         VECCOPY(har->co, vec);
139         har->hasize= hasize;
140         
141         har->zd= 0.0;
142         
143         return har;
144 }
145
146 /* there must be a 'fixed' amount of stars generated between
147 *         near and far
148 * all stars must by preference lie on the far and solely
149 *        differ in clarity/color
150 */
151
152 void RE_make_stars(Render *re, Scene *scenev3d, void (*initfunc)(void),
153                                    void (*vertexfunc)(float*),  void (*termfunc)(void))
154 {
155         extern unsigned char hash[512];
156         ObjectRen *obr= NULL;
157         World *wrld= NULL;
158         HaloRen *har;
159         Scene *scene;
160         Camera *camera;
161         double dblrand, hlfrand;
162         float vec[4], fx, fy, fz;
163         float fac, starmindist, clipend;
164         float mat[4][4], stargrid, maxrand, maxjit, force, alpha;
165         int x, y, z, sx, sy, sz, ex, ey, ez, done = 0;
166         
167         if(initfunc) {
168                 scene= scenev3d;
169                 wrld= scene->world;
170         }
171         else {
172                 scene= re->scene;
173                 wrld= &(re->wrld);
174         }
175         
176         stargrid = wrld->stardist;                      /* distance between stars */
177         maxrand = 2.0;                                          /* amount a star can be shifted (in grid units) */
178         maxjit = (wrld->starcolnoise);          /* amount a color is being shifted */
179         
180         /* size of stars */
181         force = ( wrld->starsize );
182         
183         /* minimal free space (starting at camera) */
184         starmindist= wrld->starmindist;
185         
186         if (stargrid <= 0.10) return;
187         
188         if (re) re->flag |= R_HALO;
189         else stargrid *= 1.0;                           /* then it draws fewer */
190         
191         if(re) MTC_Mat4Invert(mat, re->viewmat);
192         else MTC_Mat4One(mat);
193         
194         /* BOUNDING BOX CALCULATION
195                 * bbox goes from z = loc_near_var | loc_far_var,
196                 * x = -z | +z,
197                 * y = -z | +z
198                 */
199         
200         if(scene->camera==NULL)
201                 return;
202         camera = scene->camera->data;
203         clipend = camera->clipend;
204         
205         /* convert to grid coordinates */
206         
207         sx = ((mat[3][0] - clipend) / stargrid) - maxrand;
208         sy = ((mat[3][1] - clipend) / stargrid) - maxrand;
209         sz = ((mat[3][2] - clipend) / stargrid) - maxrand;
210         
211         ex = ((mat[3][0] + clipend) / stargrid) + maxrand;
212         ey = ((mat[3][1] + clipend) / stargrid) + maxrand;
213         ez = ((mat[3][2] + clipend) / stargrid) + maxrand;
214         
215         dblrand = maxrand * stargrid;
216         hlfrand = 2.0 * dblrand;
217         
218         if (initfunc) {
219                 initfunc();     
220         }
221
222         if(re) /* add render object for stars */
223                 obr= RE_addRenderObject(re, NULL, NULL, 0, 0, 0);
224         
225         for (x = sx, fx = sx * stargrid; x <= ex; x++, fx += stargrid) {
226                 for (y = sy, fy = sy * stargrid; y <= ey ; y++, fy += stargrid) {
227                         for (z = sz, fz = sz * stargrid; z <= ez; z++, fz += stargrid) {
228
229                                 BLI_srand((hash[z & 0xff] << 24) + (hash[y & 0xff] << 16) + (hash[x & 0xff] << 8));
230                                 vec[0] = fx + (hlfrand * BLI_drand()) - dblrand;
231                                 vec[1] = fy + (hlfrand * BLI_drand()) - dblrand;
232                                 vec[2] = fz + (hlfrand * BLI_drand()) - dblrand;
233                                 vec[3] = 1.0;
234                                 
235                                 if (vertexfunc) {
236                                         if(done & 1) vertexfunc(vec);
237                                         done++;
238                                 }
239                                 else {
240                                         MTC_Mat4MulVecfl(re->viewmat, vec);
241                                         
242                                         /* in vec are global coordinates
243                                         * calculate distance to camera
244                                         * and using that, define the alpha
245                                         */
246                                         
247                                         {
248                                                 float tx, ty, tz;
249                                                 
250                                                 tx = vec[0];
251                                                 ty = vec[1];
252                                                 tz = vec[2];
253                                                 
254                                                 alpha = sqrt(tx * tx + ty * ty + tz * tz);
255                                                 
256                                                 if (alpha >= clipend) alpha = 0.0;
257                                                 else if (alpha <= starmindist) alpha = 0.0;
258                                                 else if (alpha <= 2.0 * starmindist) {
259                                                         alpha = (alpha - starmindist) / starmindist;
260                                                 } else {
261                                                         alpha -= 2.0 * starmindist;
262                                                         alpha /= (clipend - 2.0 * starmindist);
263                                                         alpha = 1.0 - alpha;
264                                                 }
265                                         }
266                                         
267                                         
268                                         if (alpha != 0.0) {
269                                                 fac = force * BLI_drand();
270                                                 
271                                                 har = initstar(re, obr, vec, fac);
272                                                 
273                                                 if (har) {
274                                                         har->alfa = sqrt(sqrt(alpha));
275                                                         har->add= 255;
276                                                         har->r = har->g = har->b = 1.0;
277                                                         if (maxjit) {
278                                                                 har->r += ((maxjit * BLI_drand()) ) - maxjit;
279                                                                 har->g += ((maxjit * BLI_drand()) ) - maxjit;
280                                                                 har->b += ((maxjit * BLI_drand()) ) - maxjit;
281                                                         }
282                                                         har->hard = 32;
283                                                         har->lay= -1;
284                                                         har->type |= HA_ONLYSKY;
285                                                         done++;
286                                                 }
287                                         }
288                                 }
289                         }
290                         /* do not call blender_test_break() here, since it is used in UI as well, confusing the callback system */
291                         /* main cause is G.afbreek of course, a global again... (ton) */
292                 }
293         }
294         if (termfunc) termfunc();
295
296         if(obr)
297                 re->tothalo += obr->tothalo;
298 }
299
300
301 /* ------------------------------------------------------------------------- */
302 /* tool functions/defines for ad hoc simplification and possible future 
303    cleanup      */
304 /* ------------------------------------------------------------------------- */
305
306 #define UVTOINDEX(u,v) (startvlak + (u) * sizev + (v))
307 /*
308
309 NOTE THAT U/V COORDINATES ARE SOMETIMES SWAPPED !!
310         
311 ^       ()----p4----p3----()
312 |       |     |     |     |
313 u       |     |  F1 |  F2 |
314         |     |     |     |
315         ()----p1----p2----()
316                v ->
317 */
318
319 /* ------------------------------------------------------------------------- */
320
321 static void split_v_renderfaces(ObjectRen *obr, int startvlak, int startvert, int usize, int vsize, int uIndex, int cyclu, int cyclv)
322 {
323         int vLen = vsize-1+(!!cyclv);
324         int v;
325
326         for (v=0; v<vLen; v++) {
327                 VlakRen *vlr = RE_findOrAddVlak(obr, startvlak + vLen*uIndex + v);
328                 VertRen *vert = RE_vertren_copy(obr, vlr->v2);
329
330                 if (cyclv) {
331                         vlr->v2 = vert;
332
333                         if (v==vLen-1) {
334                                 VlakRen *vlr = RE_findOrAddVlak(obr, startvlak + vLen*uIndex + 0);
335                                 vlr->v1 = vert;
336                         } else {
337                                 VlakRen *vlr = RE_findOrAddVlak(obr, startvlak + vLen*uIndex + v+1);
338                                 vlr->v1 = vert;
339                         }
340                 } else {
341                         vlr->v2 = vert;
342
343                         if (v<vLen-1) {
344                                 VlakRen *vlr = RE_findOrAddVlak(obr, startvlak + vLen*uIndex + v+1);
345                                 vlr->v1 = vert;
346                         }
347
348                         if (v==0) {
349                                 vlr->v1 = RE_vertren_copy(obr, vlr->v1);
350                         } 
351                 }
352         }
353 }
354
355 /* ------------------------------------------------------------------------- */
356
357 static int check_vnormal(float *n, float *veno)
358 {
359         float inp;
360
361         inp=n[0]*veno[0]+n[1]*veno[1]+n[2]*veno[2];
362         if(inp < -FLT_EPSILON10) return 1;
363         return 0;
364 }
365
366 /* ------------------------------------------------------------------------- */
367 /* Stress, tangents and normals                                              */
368 /* ------------------------------------------------------------------------- */
369
370 static void calc_edge_stress_add(float *accum, VertRen *v1, VertRen *v2)
371 {
372         float len= VecLenf(v1->co, v2->co)/VecLenf(v1->orco, v2->orco);
373         float *acc;
374         
375         acc= accum + 2*v1->index;
376         acc[0]+= len;
377         acc[1]+= 1.0f;
378         
379         acc= accum + 2*v2->index;
380         acc[0]+= len;
381         acc[1]+= 1.0f;
382 }
383
384 static void calc_edge_stress(Render *re, ObjectRen *obr, Mesh *me)
385 {
386         float loc[3], size[3], *accum, *acc, *accumoffs, *stress;
387         int a;
388         
389         if(obr->totvert==0) return;
390         
391         mesh_get_texspace(me, loc, NULL, size);
392         
393         accum= MEM_callocN(2*sizeof(float)*obr->totvert, "temp accum for stress");
394         
395         /* de-normalize orco */
396         for(a=0; a<obr->totvert; a++) {
397                 VertRen *ver= RE_findOrAddVert(obr, a);
398                 if(ver->orco) {
399                         ver->orco[0]= ver->orco[0]*size[0] +loc[0];
400                         ver->orco[1]= ver->orco[1]*size[1] +loc[1];
401                         ver->orco[2]= ver->orco[2]*size[2] +loc[2];
402                 }
403         }
404         
405         /* add stress values */
406         accumoffs= accum;       /* so we can use vertex index */
407         for(a=0; a<obr->totvlak; a++) {
408                 VlakRen *vlr= RE_findOrAddVlak(obr, a);
409
410                 if(vlr->v1->orco && vlr->v4) {
411                         calc_edge_stress_add(accumoffs, vlr->v1, vlr->v2);
412                         calc_edge_stress_add(accumoffs, vlr->v2, vlr->v3);
413                         calc_edge_stress_add(accumoffs, vlr->v3, vlr->v1);
414                         if(vlr->v4) {
415                                 calc_edge_stress_add(accumoffs, vlr->v3, vlr->v4);
416                                 calc_edge_stress_add(accumoffs, vlr->v4, vlr->v1);
417                                 calc_edge_stress_add(accumoffs, vlr->v2, vlr->v4);
418                         }
419                 }
420         }
421         
422         for(a=0; a<obr->totvert; a++) {
423                 VertRen *ver= RE_findOrAddVert(obr, a);
424                 if(ver->orco) {
425                         /* find stress value */
426                         acc= accumoffs + 2*ver->index;
427                         if(acc[1]!=0.0f)
428                                 acc[0]/= acc[1];
429                         stress= RE_vertren_get_stress(obr, ver, 1);
430                         *stress= *acc;
431                         
432                         /* restore orcos */
433                         ver->orco[0] = (ver->orco[0]-loc[0])/size[0];
434                         ver->orco[1] = (ver->orco[1]-loc[1])/size[1];
435                         ver->orco[2] = (ver->orco[2]-loc[2])/size[2];
436                 }
437         }
438         
439         MEM_freeN(accum);
440 }
441
442 /* gets tangent from tface or orco */
443 static void calc_tangent_vector(ObjectRen *obr, VertexTangent **vtangents, MemArena *arena, VlakRen *vlr, int do_nmap_tangent, int do_tangent)
444 {
445         MTFace *tface= RE_vlakren_get_tface(obr, vlr, obr->actmtface, NULL, 0);
446         VertRen *v1=vlr->v1, *v2=vlr->v2, *v3=vlr->v3, *v4=vlr->v4;
447         float tang[3], *tav;
448         float *uv1, *uv2, *uv3, *uv4;
449         float uv[4][2];
450         
451         if(tface) {
452                 uv1= tface->uv[0];
453                 uv2= tface->uv[1];
454                 uv3= tface->uv[2];
455                 uv4= tface->uv[3];
456         }
457         else if(v1->orco) {
458                 uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
459                 spheremap(v1->orco[0], v1->orco[1], v1->orco[2], &uv[0][0], &uv[0][1]);
460                 spheremap(v2->orco[0], v2->orco[1], v2->orco[2], &uv[1][0], &uv[1][1]);
461                 spheremap(v3->orco[0], v3->orco[1], v3->orco[2], &uv[2][0], &uv[2][1]);
462                 if(v4)
463                         spheremap(v4->orco[0], v4->orco[1], v4->orco[2], &uv[3][0], &uv[3][1]);
464         }
465         else return;
466
467         tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, vlr->n, tang);
468         
469         if(do_tangent) {
470                 tav= RE_vertren_get_tangent(obr, v1, 1);
471                 VECADD(tav, tav, tang);
472                 tav= RE_vertren_get_tangent(obr, v2, 1);
473                 VECADD(tav, tav, tang);
474                 tav= RE_vertren_get_tangent(obr, v3, 1);
475                 VECADD(tav, tav, tang);
476         }
477         
478         if(do_nmap_tangent) {
479                 sum_or_add_vertex_tangent(arena, &vtangents[v1->index], tang, uv1);
480                 sum_or_add_vertex_tangent(arena, &vtangents[v2->index], tang, uv2);
481                 sum_or_add_vertex_tangent(arena, &vtangents[v3->index], tang, uv3);
482         }
483
484         if(v4) {
485                 tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, vlr->n, tang);
486                 
487                 if(do_tangent) {
488                         tav= RE_vertren_get_tangent(obr, v1, 1);
489                         VECADD(tav, tav, tang);
490                         tav= RE_vertren_get_tangent(obr, v3, 1);
491                         VECADD(tav, tav, tang);
492                         tav= RE_vertren_get_tangent(obr, v4, 1);
493                         VECADD(tav, tav, tang);
494                 }
495
496                 if(do_nmap_tangent) {
497                         sum_or_add_vertex_tangent(arena, &vtangents[v1->index], tang, uv1);
498                         sum_or_add_vertex_tangent(arena, &vtangents[v3->index], tang, uv3);
499                         sum_or_add_vertex_tangent(arena, &vtangents[v4->index], tang, uv4);
500                 }
501         }
502 }
503
504
505 static void calc_vertexnormals(Render *re, ObjectRen *obr, int do_tangent, int do_nmap_tangent)
506 {
507         MemArena *arena= NULL;
508         VertexTangent **vtangents= NULL;
509         int a;
510
511         if(do_nmap_tangent) {
512                 arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
513                 BLI_memarena_use_calloc(arena);
514
515                 vtangents= MEM_callocN(sizeof(VertexTangent*)*obr->totvert, "VertexTangent");
516         }
517
518                 /* clear all vertex normals */
519         for(a=0; a<obr->totvert; a++) {
520                 VertRen *ver= RE_findOrAddVert(obr, a);
521                 ver->n[0]=ver->n[1]=ver->n[2]= 0.0f;
522         }
523
524                 /* calculate cos of angles and point-masses, use as weight factor to
525                    add face normal to vertex */
526         for(a=0; a<obr->totvlak; a++) {
527                 VlakRen *vlr= RE_findOrAddVlak(obr, a);
528                 if(vlr->flag & ME_SMOOTH) {
529                         VertRen *v1= vlr->v1;
530                         VertRen *v2= vlr->v2;
531                         VertRen *v3= vlr->v3;
532                         VertRen *v4= vlr->v4;
533                         float n1[3], n2[3], n3[3], n4[3];
534                         float fac1, fac2, fac3, fac4=0.0f;
535                         
536                         if(re->flag & R_GLOB_NOPUNOFLIP)
537                                 vlr->flag |= R_NOPUNOFLIP;
538                         
539                         VecSubf(n1, v2->co, v1->co);
540                         Normalize(n1);
541                         VecSubf(n2, v3->co, v2->co);
542                         Normalize(n2);
543                         if(v4==NULL) {
544                                 VecSubf(n3, v1->co, v3->co);
545                                 Normalize(n3);
546
547                                 fac1= saacos(-n1[0]*n3[0]-n1[1]*n3[1]-n1[2]*n3[2]);
548                                 fac2= saacos(-n1[0]*n2[0]-n1[1]*n2[1]-n1[2]*n2[2]);
549                                 fac3= saacos(-n2[0]*n3[0]-n2[1]*n3[1]-n2[2]*n3[2]);
550                         }
551                         else {
552                                 VecSubf(n3, v4->co, v3->co);
553                                 Normalize(n3);
554                                 VecSubf(n4, v1->co, v4->co);
555                                 Normalize(n4);
556
557                                 fac1= saacos(-n4[0]*n1[0]-n4[1]*n1[1]-n4[2]*n1[2]);
558                                 fac2= saacos(-n1[0]*n2[0]-n1[1]*n2[1]-n1[2]*n2[2]);
559                                 fac3= saacos(-n2[0]*n3[0]-n2[1]*n3[1]-n2[2]*n3[2]);
560                                 fac4= saacos(-n3[0]*n4[0]-n3[1]*n4[1]-n3[2]*n4[2]);
561
562                                 if(!(vlr->flag & R_NOPUNOFLIP)) {
563                                         if( check_vnormal(vlr->n, v4->n) ) fac4= -fac4;
564                                 }
565
566                                 v4->n[0] +=fac4*vlr->n[0];
567                                 v4->n[1] +=fac4*vlr->n[1];
568                                 v4->n[2] +=fac4*vlr->n[2];
569                         }
570
571                         if(!(vlr->flag & R_NOPUNOFLIP)) {
572                                 if( check_vnormal(vlr->n, v1->n) ) fac1= -fac1;
573                                 if( check_vnormal(vlr->n, v2->n) ) fac2= -fac2;
574                                 if( check_vnormal(vlr->n, v3->n) ) fac3= -fac3;
575                         }
576
577                         v1->n[0] +=fac1*vlr->n[0];
578                         v1->n[1] +=fac1*vlr->n[1];
579                         v1->n[2] +=fac1*vlr->n[2];
580
581                         v2->n[0] +=fac2*vlr->n[0];
582                         v2->n[1] +=fac2*vlr->n[1];
583                         v2->n[2] +=fac2*vlr->n[2];
584
585                         v3->n[0] +=fac3*vlr->n[0];
586                         v3->n[1] +=fac3*vlr->n[1];
587                         v3->n[2] +=fac3*vlr->n[2];
588                         
589                 }
590                 if(do_nmap_tangent || do_tangent) {
591                         /* tangents still need to be calculated for flat faces too */
592                         /* weighting removed, they are not vertexnormals */
593                         calc_tangent_vector(obr, vtangents, arena, vlr, do_nmap_tangent, do_tangent);
594                 }
595         }
596
597                 /* do solid faces */
598         for(a=0; a<obr->totvlak; a++) {
599                 VlakRen *vlr= RE_findOrAddVlak(obr, a);
600                 if((vlr->flag & ME_SMOOTH)==0) {
601                         float *f1= vlr->v1->n;
602                         if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
603                         f1= vlr->v2->n;
604                         if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
605                         f1= vlr->v3->n;
606                         if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
607                         if(vlr->v4) {
608                                 f1= vlr->v4->n;
609                                 if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
610                         }
611                 }
612
613                 if(do_nmap_tangent) {
614                         VertRen *v1=vlr->v1, *v2=vlr->v2, *v3=vlr->v3, *v4=vlr->v4;
615                         MTFace *tface= RE_vlakren_get_tface(obr, vlr, obr->actmtface, NULL, 0);
616
617                         if(tface) {
618                                 float *vtang, *ftang= RE_vlakren_get_nmap_tangent(obr, vlr, 1);
619
620                                 vtang= find_vertex_tangent(vtangents[v1->index], tface->uv[0]);
621                                 VECCOPY(ftang, vtang);
622                                 Normalize(ftang);
623                                 vtang= find_vertex_tangent(vtangents[v2->index], tface->uv[1]);
624                                 VECCOPY(ftang+3, vtang);
625                                 Normalize(ftang+3);
626                                 vtang= find_vertex_tangent(vtangents[v3->index], tface->uv[2]);
627                                 VECCOPY(ftang+6, vtang);
628                                 Normalize(ftang+6);
629                                 if(v4) {
630                                         vtang= find_vertex_tangent(vtangents[v4->index], tface->uv[3]);
631                                         VECCOPY(ftang+9, vtang);
632                                         Normalize(ftang+9);
633                                 }
634                         }
635                 }
636         }
637         
638                 /* normalize vertex normals */
639         for(a=0; a<obr->totvert; a++) {
640                 VertRen *ver= RE_findOrAddVert(obr, a);
641                 Normalize(ver->n);
642                 if(do_tangent) {
643                         float *tav= RE_vertren_get_tangent(obr, ver, 0);
644                         if (tav) {
645                                 /* orthonorm. */
646                                 float tdn = tav[0]*ver->n[0] + tav[1]*ver->n[1] + tav[2]*ver->n[2];
647                                 tav[0] -= ver->n[0]*tdn;
648                                 tav[1] -= ver->n[1]*tdn;
649                                 tav[2] -= ver->n[2]*tdn;
650                                 Normalize(tav);
651                         }
652                 }
653         }
654
655
656         if(arena)
657                 BLI_memarena_free(arena);
658         if(vtangents)
659                 MEM_freeN(vtangents);
660 }
661
662 /* ------------------------------------------------------------------------- */
663 /* Autosmoothing:                                                            */
664 /* ------------------------------------------------------------------------- */
665
666 typedef struct ASvert {
667         int totface;
668         ListBase faces;
669 } ASvert;
670
671 typedef struct ASface {
672         struct ASface *next, *prev;
673         VlakRen *vlr[4];
674         VertRen *nver[4];
675 } ASface;
676
677 static void as_addvert(ASvert *asv, VertRen *v1, VlakRen *vlr)
678 {
679         ASface *asf;
680         int a;
681         
682         if(v1 == NULL) return;
683         
684         if(asv->faces.first==NULL) {
685                 asf= MEM_callocN(sizeof(ASface), "asface");
686                 BLI_addtail(&asv->faces, asf);
687         }
688         
689         asf= asv->faces.last;
690         for(a=0; a<4; a++) {
691                 if(asf->vlr[a]==NULL) {
692                         asf->vlr[a]= vlr;
693                         asv->totface++;
694                         break;
695                 }
696         }
697         
698         /* new face struct */
699         if(a==4) {
700                 asf= MEM_callocN(sizeof(ASface), "asface");
701                 BLI_addtail(&asv->faces, asf);
702                 asf->vlr[0]= vlr;
703                 asv->totface++;
704         }
705 }
706
707 static int as_testvertex(VlakRen *vlr, VertRen *ver, ASvert *asv, float thresh) 
708 {
709         /* return 1: vertex needs a copy */
710         ASface *asf;
711         float inp;
712         int a;
713         
714         if(vlr==0) return 0;
715         
716         asf= asv->faces.first;
717         while(asf) {
718                 for(a=0; a<4; a++) {
719                         if(asf->vlr[a] && asf->vlr[a]!=vlr) {
720                                 inp= fabs( vlr->n[0]*asf->vlr[a]->n[0] + vlr->n[1]*asf->vlr[a]->n[1] + vlr->n[2]*asf->vlr[a]->n[2] );
721                                 if(inp < thresh) return 1;
722                         }
723                 }
724                 asf= asf->next;
725         }
726         
727         return 0;
728 }
729
730 static VertRen *as_findvertex(VlakRen *vlr, VertRen *ver, ASvert *asv, float thresh) 
731 {
732         /* return when new vertex already was made */
733         ASface *asf;
734         float inp;
735         int a;
736         
737         asf= asv->faces.first;
738         while(asf) {
739                 for(a=0; a<4; a++) {
740                         if(asf->vlr[a] && asf->vlr[a]!=vlr) {
741                                 /* this face already made a copy for this vertex! */
742                                 if(asf->nver[a]) {
743                                         inp= fabs( vlr->n[0]*asf->vlr[a]->n[0] + vlr->n[1]*asf->vlr[a]->n[1] + vlr->n[2]*asf->vlr[a]->n[2] );
744                                         if(inp >= thresh) {
745                                                 return asf->nver[a];
746                                         }
747                                 }
748                         }
749                 }
750                 asf= asf->next;
751         }
752         
753         return NULL;
754 }
755
756 /* note; autosmooth happens in object space still, after applying autosmooth we rotate */
757 /* note2; actually, when original mesh and displist are equal sized, face normals are from original mesh */
758 static void autosmooth(Render *re, ObjectRen *obr, float mat[][4], int degr)
759 {
760         ASvert *asv, *asverts;
761         ASface *asf;
762         VertRen *ver, *v1;
763         VlakRen *vlr;
764         float thresh;
765         int a, b, totvert;
766         
767         if(obr->totvert==0) return;
768         asverts= MEM_callocN(sizeof(ASvert)*obr->totvert, "all smooth verts");
769         
770         thresh= cos( M_PI*(0.5f+(float)degr)/180.0 );
771         
772         /* step zero: give faces normals of original mesh, if this is provided */
773         
774         
775         /* step one: construct listbase of all vertices and pointers to faces */
776         for(a=0; a<obr->totvlak; a++) {
777                 vlr= RE_findOrAddVlak(obr, a);
778                 /* skip wire faces */
779                 if(vlr->v2 != vlr->v3) {
780                         as_addvert(asverts+vlr->v1->index, vlr->v1, vlr);
781                         as_addvert(asverts+vlr->v2->index, vlr->v2, vlr);
782                         as_addvert(asverts+vlr->v3->index, vlr->v3, vlr);
783                         if(vlr->v4) 
784                                 as_addvert(asverts+vlr->v4->index, vlr->v4, vlr);
785                 }
786         }
787         
788         totvert= obr->totvert;
789         /* we now test all vertices, when faces have a normal too much different: they get a new vertex */
790         for(a=0, asv=asverts; a<totvert; a++, asv++) {
791                 if(asv && asv->totface>1) {
792                         ver= RE_findOrAddVert(obr, a);
793
794                         asf= asv->faces.first;
795                         while(asf) {
796                                 for(b=0; b<4; b++) {
797                                 
798                                         /* is there a reason to make a new vertex? */
799                                         vlr= asf->vlr[b];
800                                         if( as_testvertex(vlr, ver, asv, thresh) ) {
801                                                 
802                                                 /* already made a new vertex within threshold? */
803                                                 v1= as_findvertex(vlr, ver, asv, thresh);
804                                                 if(v1==NULL) {
805                                                         /* make a new vertex */
806                                                         v1= RE_vertren_copy(obr, ver);
807                                                 }
808                                                 asf->nver[b]= v1;
809                                                 if(vlr->v1==ver) vlr->v1= v1;
810                                                 if(vlr->v2==ver) vlr->v2= v1;
811                                                 if(vlr->v3==ver) vlr->v3= v1;
812                                                 if(vlr->v4==ver) vlr->v4= v1;
813                                         }
814                                 }
815                                 asf= asf->next;
816                         }
817                 }
818         }
819         
820         /* free */
821         for(a=0; a<totvert; a++) {
822                 BLI_freelistN(&asverts[a].faces);
823         }
824         MEM_freeN(asverts);
825         
826         /* rotate vertices and calculate normal of faces */
827         for(a=0; a<obr->totvert; a++) {
828                 ver= RE_findOrAddVert(obr, a);
829                 MTC_Mat4MulVecfl(mat, ver->co);
830         }
831         for(a=0; a<obr->totvlak; a++) {
832                 vlr= RE_findOrAddVlak(obr, a);
833                 
834                 /* skip wire faces */
835                 if(vlr->v2 != vlr->v3) {
836                         if(vlr->v4) 
837                                 CalcNormFloat4(vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co, vlr->n);
838                         else 
839                                 CalcNormFloat(vlr->v3->co, vlr->v2->co, vlr->v1->co, vlr->n);
840                 }
841         }               
842 }
843
844 /* ------------------------------------------------------------------------- */
845 /* Orco hash and Materials                                                   */
846 /* ------------------------------------------------------------------------- */
847
848 static float *get_object_orco(Render *re, Object *ob)
849 {
850         float *orco;
851         
852         if (!re->orco_hash)
853                 re->orco_hash = BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
854         
855         orco = BLI_ghash_lookup(re->orco_hash, ob);
856         
857         if (!orco) {
858                 if (ELEM(ob->type, OB_CURVE, OB_FONT)) {
859                         orco = make_orco_curve(re->scene, ob);
860                 } else if (ob->type==OB_SURF) {
861                         orco = make_orco_surf(ob);
862                 } else if (ob->type==OB_MBALL) {
863                         orco = make_orco_mball(ob);
864                 }
865                 
866                 if (orco)
867                         BLI_ghash_insert(re->orco_hash, ob, orco);
868         }
869         
870         return orco;
871 }
872
873 static void set_object_orco(Render *re, void *ob, float *orco)
874 {
875         if (!re->orco_hash)
876                 re->orco_hash = BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
877         
878         BLI_ghash_insert(re->orco_hash, ob, orco);
879 }
880
881 static void free_mesh_orco_hash(Render *re) 
882 {
883         if (re->orco_hash) {
884                 BLI_ghash_free(re->orco_hash, NULL, (GHashValFreeFP)MEM_freeN);
885                 re->orco_hash = NULL;
886         }
887 }
888
889 static void flag_render_node_material(Render *re, bNodeTree *ntree)
890 {
891         bNode *node;
892
893         for(node=ntree->nodes.first; node; node= node->next) {
894                 if(node->id) {
895                         if(GS(node->id->name)==ID_MA) {
896                                 Material *ma= (Material *)node->id;
897
898                                 if(ma->mode & MA_ZTRA)
899                                         re->flag |= R_ZTRA;
900
901                                 ma->flag |= MA_IS_USED;
902                         }
903                         else if(node->type==NODE_GROUP)
904                                 flag_render_node_material(re, (bNodeTree *)node->id);
905                 }
906         }
907 }
908
909 static Material *give_render_material(Render *re, Object *ob, int nr)
910 {
911         extern Material defmaterial;    /* material.c */
912         Material *ma;
913         
914         ma= give_current_material(ob, nr);
915         if(ma==NULL) 
916                 ma= &defmaterial;
917         
918         if(re->r.mode & R_SPEED) ma->texco |= NEED_UV;
919         
920         if(ma->mode & MA_ZTRA)
921                 re->flag |= R_ZTRA;
922         
923         /* for light groups */
924         ma->flag |= MA_IS_USED;
925
926         if(ma->nodetree && ma->use_nodes)
927                 flag_render_node_material(re, ma->nodetree);
928         
929         return ma;
930 }
931
932 /* ------------------------------------------------------------------------- */
933 /* Particles                                                                 */
934 /* ------------------------------------------------------------------------- */
935 typedef struct ParticleStrandData
936 {
937         struct MCol *mcol;
938         float *orco, *uvco, *surfnor;
939         float time, adapt_angle, adapt_pix, size;
940         int totuv, totcol;
941         int first, line, adapt, override_uv;
942 }
943 ParticleStrandData;
944 /* future thread problem... */
945 static void static_particle_strand(Render *re, ObjectRen *obr, Material *ma, ParticleStrandData *sd, float *vec, float *vec1)
946 {
947         static VertRen *v1= NULL, *v2= NULL;
948         VlakRen *vlr= NULL;
949         float nor[3], cross[3], crosslen, w, dx, dy, width;
950         static float anor[3], avec[3];
951         int flag, i;
952         static int second=0;
953         
954         VecSubf(nor, vec, vec1);
955         Normalize(nor);         // nor needed as tangent 
956         Crossf(cross, vec, nor);
957
958         /* turn cross in pixelsize */
959         w= vec[2]*re->winmat[2][3] + re->winmat[3][3];
960         dx= re->winx*cross[0]*re->winmat[0][0];
961         dy= re->winy*cross[1]*re->winmat[1][1];
962         w= sqrt(dx*dx + dy*dy)/w;
963         
964         if(w!=0.0f) {
965                 float fac;
966                 if(ma->strand_ease!=0.0f) {
967                         if(ma->strand_ease<0.0f)
968                                 fac= pow(sd->time, 1.0+ma->strand_ease);
969                         else
970                                 fac= pow(sd->time, 1.0/(1.0f-ma->strand_ease));
971                 }
972                 else fac= sd->time;
973
974                 width= ((1.0f-fac)*ma->strand_sta + (fac)*ma->strand_end);
975
976                 /* use actual Blender units for strand width and fall back to minimum width */
977                 if(ma->mode & MA_STR_B_UNITS){
978             crosslen= VecLength(cross);
979             w= 2.0f*crosslen*ma->strand_min/w;
980
981                         if(width < w)
982                                 width= w;
983
984                         /*cross is the radius of the strand so we want it to be half of full width */
985                         VecMulf(cross,0.5/crosslen);
986                 }
987                 else
988                         width/=w;
989
990                 VecMulf(cross, width);
991         }
992         else width= 1.0f;
993         
994         if(ma->mode & MA_TANGENT_STR)
995                 flag= R_SMOOTH|R_NOPUNOFLIP|R_TANGENT;
996         else
997                 flag= R_SMOOTH;
998         
999         /* only 1 pixel wide strands filled in as quads now, otherwise zbuf errors */
1000         if(ma->strand_sta==1.0f)
1001                 flag |= R_STRAND;
1002         
1003         /* single face line */
1004         if(sd->line) {
1005                 vlr= RE_findOrAddVlak(obr, obr->totvlak++);
1006                 vlr->flag= flag;
1007                 vlr->v1= RE_findOrAddVert(obr, obr->totvert++);
1008                 vlr->v2= RE_findOrAddVert(obr, obr->totvert++);
1009                 vlr->v3= RE_findOrAddVert(obr, obr->totvert++);
1010                 vlr->v4= RE_findOrAddVert(obr, obr->totvert++);
1011                 
1012                 VECCOPY(vlr->v1->co, vec);
1013                 VecAddf(vlr->v1->co, vlr->v1->co, cross);
1014                 VECCOPY(vlr->v1->n, nor);
1015                 vlr->v1->orco= sd->orco;
1016                 vlr->v1->accum= -1.0f;  // accum abuse for strand texco
1017                 
1018                 VECCOPY(vlr->v2->co, vec);
1019                 VecSubf(vlr->v2->co, vlr->v2->co, cross);
1020                 VECCOPY(vlr->v2->n, nor);
1021                 vlr->v2->orco= sd->orco;
1022                 vlr->v2->accum= vlr->v1->accum;
1023
1024                 VECCOPY(vlr->v4->co, vec1);
1025                 VecAddf(vlr->v4->co, vlr->v4->co, cross);
1026                 VECCOPY(vlr->v4->n, nor);
1027                 vlr->v4->orco= sd->orco;
1028                 vlr->v4->accum= 1.0f;   // accum abuse for strand texco
1029                 
1030                 VECCOPY(vlr->v3->co, vec1);
1031                 VecSubf(vlr->v3->co, vlr->v3->co, cross);
1032                 VECCOPY(vlr->v3->n, nor);
1033                 vlr->v3->orco= sd->orco;
1034                 vlr->v3->accum= vlr->v4->accum;
1035
1036                 CalcNormFloat4(vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co, vlr->n);
1037                 
1038                 vlr->mat= ma;
1039                 vlr->ec= ME_V2V3;
1040
1041                 if(sd->surfnor) {
1042                         float *snor= RE_vlakren_get_surfnor(obr, vlr, 1);
1043                         VECCOPY(snor, sd->surfnor);
1044                 }
1045
1046                 if(sd->uvco){
1047                         for(i=0; i<sd->totuv; i++){
1048                                 MTFace *mtf;
1049                                 mtf=RE_vlakren_get_tface(obr,vlr,i,NULL,1);
1050                                 mtf->uv[0][0]=mtf->uv[1][0]=
1051                                 mtf->uv[2][0]=mtf->uv[3][0]=(sd->uvco+2*i)[0];
1052                                 mtf->uv[0][1]=mtf->uv[1][1]=
1053                                 mtf->uv[2][1]=mtf->uv[3][1]=(sd->uvco+2*i)[1];
1054                         }
1055                         if(sd->override_uv>=0){
1056                                 MTFace *mtf;
1057                                 mtf=RE_vlakren_get_tface(obr,vlr,sd->override_uv,NULL,0);
1058                                 
1059                                 mtf->uv[0][0]=mtf->uv[3][0]=0.0f;
1060                                 mtf->uv[1][0]=mtf->uv[2][0]=1.0f;
1061
1062                                 mtf->uv[0][1]=mtf->uv[1][1]=0.0f;
1063                                 mtf->uv[2][1]=mtf->uv[3][1]=1.0f;
1064                         }
1065                 }
1066                 if(sd->mcol){
1067                         for(i=0; i<sd->totcol; i++){
1068                                 MCol *mc;
1069                                 mc=RE_vlakren_get_mcol(obr,vlr,i,NULL,1);
1070                                 mc[0]=mc[1]=mc[2]=mc[3]=sd->mcol[i];
1071                                 mc[0]=mc[1]=mc[2]=mc[3]=sd->mcol[i];
1072                         }
1073                 }
1074         }
1075         /* first two vertices of a strand */
1076         else if(sd->first) {
1077                 if(sd->adapt){
1078                         VECCOPY(anor, nor);
1079                         VECCOPY(avec, vec);
1080                         second=1;
1081                 }
1082
1083                 v1= RE_findOrAddVert(obr, obr->totvert++);
1084                 v2= RE_findOrAddVert(obr, obr->totvert++);
1085                 
1086                 VECCOPY(v1->co, vec);
1087                 VecAddf(v1->co, v1->co, cross);
1088                 VECCOPY(v1->n, nor);
1089                 v1->orco= sd->orco;
1090                 v1->accum= -1.0f;       // accum abuse for strand texco
1091                 
1092                 VECCOPY(v2->co, vec);
1093                 VecSubf(v2->co, v2->co, cross);
1094                 VECCOPY(v2->n, nor);
1095                 v2->orco= sd->orco;
1096                 v2->accum= v1->accum;
1097         }
1098         /* more vertices & faces to strand */
1099         else {
1100                 if(sd->adapt==0 || second){
1101                         vlr= RE_findOrAddVlak(obr, obr->totvlak++);
1102                         vlr->flag= flag;
1103                         vlr->v1= v1;
1104                         vlr->v2= v2;
1105                         vlr->v3= RE_findOrAddVert(obr, obr->totvert++);
1106                         vlr->v4= RE_findOrAddVert(obr, obr->totvert++);
1107                         
1108                         v1= vlr->v4; // cycle
1109                         v2= vlr->v3; // cycle
1110
1111                         
1112                         if(sd->adapt){
1113                                 second=0;
1114                                 VECCOPY(anor,nor);
1115                                 VECCOPY(avec,vec);
1116                         }
1117
1118                 }
1119                 else if(sd->adapt){
1120                         float dvec[3],pvec[3];
1121                         VecSubf(dvec,avec,vec);
1122                         Projf(pvec,dvec,vec);
1123                         VecSubf(dvec,dvec,pvec);
1124
1125                         w= vec[2]*re->winmat[2][3] + re->winmat[3][3];
1126                         dx= re->winx*dvec[0]*re->winmat[0][0]/w;
1127                         dy= re->winy*dvec[1]*re->winmat[1][1]/w;
1128                         w= sqrt(dx*dx + dy*dy);
1129                         if(Inpf(anor,nor)<sd->adapt_angle && w>sd->adapt_pix){
1130                                 vlr= RE_findOrAddVlak(obr, obr->totvlak++);
1131                                 vlr->flag= flag;
1132                                 vlr->v1= v1;
1133                                 vlr->v2= v2;
1134                                 vlr->v3= RE_findOrAddVert(obr, obr->totvert++);
1135                                 vlr->v4= RE_findOrAddVert(obr, obr->totvert++);
1136                                 
1137                                 v1= vlr->v4; // cycle
1138                                 v2= vlr->v3; // cycle
1139
1140                                 VECCOPY(anor,nor);
1141                                 VECCOPY(avec,vec);
1142                         }
1143                         else{
1144                                 vlr= RE_findOrAddVlak(obr, obr->totvlak-1);
1145                         }
1146                 }
1147         
1148                 VECCOPY(vlr->v4->co, vec);
1149                 VecAddf(vlr->v4->co, vlr->v4->co, cross);
1150                 VECCOPY(vlr->v4->n, nor);
1151                 vlr->v4->orco= sd->orco;
1152                 vlr->v4->accum= -1.0f + 2.0f*sd->time;  // accum abuse for strand texco
1153                 
1154                 VECCOPY(vlr->v3->co, vec);
1155                 VecSubf(vlr->v3->co, vlr->v3->co, cross);
1156                 VECCOPY(vlr->v3->n, nor);
1157                 vlr->v3->orco= sd->orco;
1158                 vlr->v3->accum= vlr->v4->accum;
1159                 
1160                 CalcNormFloat4(vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co, vlr->n);
1161                 
1162                 vlr->mat= ma;
1163                 vlr->ec= ME_V2V3;
1164
1165                 if(sd->surfnor) {
1166                         float *snor= RE_vlakren_get_surfnor(obr, vlr, 1);
1167                         VECCOPY(snor, sd->surfnor);
1168                 }
1169
1170                 if(sd->uvco){
1171                         for(i=0; i<sd->totuv; i++){
1172                                 MTFace *mtf;
1173                                 mtf=RE_vlakren_get_tface(obr,vlr,i,NULL,1);
1174                                 mtf->uv[0][0]=mtf->uv[1][0]=
1175                                 mtf->uv[2][0]=mtf->uv[3][0]=(sd->uvco+2*i)[0];
1176                                 mtf->uv[0][1]=mtf->uv[1][1]=
1177                                 mtf->uv[2][1]=mtf->uv[3][1]=(sd->uvco+2*i)[1];
1178                         }
1179                         if(sd->override_uv>=0){
1180                                 MTFace *mtf;
1181                                 mtf=RE_vlakren_get_tface(obr,vlr,sd->override_uv,NULL,0);
1182                                 
1183                                 mtf->uv[0][0]=mtf->uv[3][0]=0.0f;
1184                                 mtf->uv[1][0]=mtf->uv[2][0]=1.0f;
1185
1186                                 mtf->uv[0][1]=mtf->uv[1][1]=(vlr->v1->accum+1.0f)/2.0f;
1187                                 mtf->uv[2][1]=mtf->uv[3][1]=(vlr->v3->accum+1.0f)/2.0f;
1188                         }
1189                 }
1190                 if(sd->mcol){
1191                         for(i=0; i<sd->totcol; i++){
1192                                 MCol *mc;
1193                                 mc=RE_vlakren_get_mcol(obr,vlr,i,NULL,1);
1194                                 mc[0]=mc[1]=mc[2]=mc[3]=sd->mcol[i];
1195                                 mc[0]=mc[1]=mc[2]=mc[3]=sd->mcol[i];
1196                         }
1197                 }
1198         }
1199 }
1200
1201 static void static_particle_wire(ObjectRen *obr, Material *ma, float *vec, float *vec1, int first, int line)
1202 {
1203         VlakRen *vlr;
1204         static VertRen *v1;
1205
1206         if(line) {
1207                 vlr= RE_findOrAddVlak(obr, obr->totvlak++);
1208                 vlr->v1= RE_findOrAddVert(obr, obr->totvert++);
1209                 vlr->v2= RE_findOrAddVert(obr, obr->totvert++);
1210                 vlr->v3= vlr->v2;
1211                 vlr->v4= NULL;
1212                 
1213                 VECCOPY(vlr->v1->co, vec);
1214                 VECCOPY(vlr->v2->co, vec1);
1215                 
1216                 VecSubf(vlr->n, vec, vec1);
1217                 Normalize(vlr->n);
1218                 VECCOPY(vlr->v1->n, vlr->n);
1219                 VECCOPY(vlr->v2->n, vlr->n);
1220                 
1221                 vlr->mat= ma;
1222                 vlr->ec= ME_V1V2;
1223
1224         }
1225         else if(first) {
1226                 v1= RE_findOrAddVert(obr, obr->totvert++);
1227                 VECCOPY(v1->co, vec);
1228         }
1229         else {
1230                 vlr= RE_findOrAddVlak(obr, obr->totvlak++);
1231                 vlr->v1= v1;
1232                 vlr->v2= RE_findOrAddVert(obr, obr->totvert++);
1233                 vlr->v3= vlr->v2;
1234                 vlr->v4= NULL;
1235                 
1236                 v1= vlr->v2; // cycle
1237                 VECCOPY(v1->co, vec);
1238                 
1239                 VecSubf(vlr->n, vec, vec1);
1240                 Normalize(vlr->n);
1241                 VECCOPY(v1->n, vlr->n);
1242                 
1243                 vlr->mat= ma;
1244                 vlr->ec= ME_V1V2;
1245         }
1246
1247 }
1248
1249 static void particle_curve(Render *re, ObjectRen *obr, DerivedMesh *dm, Material *ma, ParticleStrandData *sd, float *loc, float *loc1,  int seed)
1250 {
1251         HaloRen *har=0;
1252
1253         if(ma->material_type == MA_TYPE_WIRE)
1254                 static_particle_wire(obr, ma, loc, loc1, sd->first, sd->line);
1255         else if(ma->material_type == MA_TYPE_HALO) {
1256                 har= RE_inithalo_particle(re, obr, dm, ma, loc, loc1, sd->orco, sd->uvco, sd->size, 1.0, seed);
1257                 if(har) har->lay= obr->ob->lay;
1258         }
1259         else
1260                 static_particle_strand(re, obr, ma, sd, loc, loc1);
1261 }
1262 static void particle_billboard(Render *re, ObjectRen *obr, Material *ma, ParticleBillboardData *bb)
1263 {
1264         VlakRen *vlr;
1265         MTFace *mtf;
1266         float xvec[3], yvec[3], zvec[3], bb_center[3];
1267         float uvx = 0.0f, uvy = 0.0f, uvdx = 1.0f, uvdy = 1.0f, time = 0.0f;
1268
1269         vlr= RE_findOrAddVlak(obr, obr->totvlak++);
1270         vlr->v1= RE_findOrAddVert(obr, obr->totvert++);
1271         vlr->v2= RE_findOrAddVert(obr, obr->totvert++);
1272         vlr->v3= RE_findOrAddVert(obr, obr->totvert++);
1273         vlr->v4= RE_findOrAddVert(obr, obr->totvert++);
1274
1275         psys_make_billboard(bb, xvec, yvec, zvec, bb_center);
1276
1277         VECADD(vlr->v1->co, bb_center, xvec);
1278         VECADD(vlr->v1->co, vlr->v1->co, yvec);
1279         MTC_Mat4MulVecfl(re->viewmat, vlr->v1->co);
1280
1281         VECSUB(vlr->v2->co, bb_center, xvec);
1282         VECADD(vlr->v2->co, vlr->v2->co, yvec);
1283         MTC_Mat4MulVecfl(re->viewmat, vlr->v2->co);
1284
1285         VECSUB(vlr->v3->co, bb_center, xvec);
1286         VECSUB(vlr->v3->co, vlr->v3->co, yvec);
1287         MTC_Mat4MulVecfl(re->viewmat, vlr->v3->co);
1288
1289         VECADD(vlr->v4->co, bb_center, xvec);
1290         VECSUB(vlr->v4->co, vlr->v4->co, yvec);
1291         MTC_Mat4MulVecfl(re->viewmat, vlr->v4->co);
1292
1293         CalcNormFloat4(vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co, vlr->n);
1294         VECCOPY(vlr->v1->n,vlr->n);
1295         VECCOPY(vlr->v2->n,vlr->n);
1296         VECCOPY(vlr->v3->n,vlr->n);
1297         VECCOPY(vlr->v4->n,vlr->n);
1298         
1299         vlr->mat= ma;
1300         vlr->ec= ME_V2V3;
1301
1302         if(bb->uv_split > 1){
1303                 uvdx = uvdy = 1.0f / (float)bb->uv_split;
1304                 if(bb->anim == PART_BB_ANIM_TIME) {
1305                         if(bb->split_offset == PART_BB_OFF_NONE)
1306                                 time = bb->time;
1307                         else if(bb->split_offset == PART_BB_OFF_LINEAR)
1308                                 time = (float)fmod(bb->time + (float)bb->num / (float)(bb->uv_split * bb->uv_split), 1.0f);
1309                         else /* split_offset==PART_BB_OFF_RANDOM */
1310                                 time = (float)fmod(bb->time + bb->random, 1.0f);
1311
1312                 }
1313                 else if(bb->anim == PART_BB_ANIM_ANGLE) {
1314                         if(bb->align == PART_BB_VIEW) {
1315                                 time = (float)fmod((bb->tilt + 1.0f) / 2.0f, 1.0);
1316                         }
1317                         else{
1318                                 float axis1[3] = {0.0f,0.0f,0.0f};
1319                                 float axis2[3] = {0.0f,0.0f,0.0f};
1320                                 axis1[(bb->align + 1) % 3] = 1.0f;
1321                                 axis2[(bb->align + 2) % 3] = 1.0f;
1322                                 if(bb->lock == 0) {
1323                                         zvec[bb->align] = 0.0f;
1324                                         Normalize(zvec);
1325                                 }
1326                                 time = saacos(Inpf(zvec, axis1)) / (float)M_PI;
1327                                 if(Inpf(zvec, axis2) < 0.0f)
1328                                         time = 1.0f - time / 2.0f;
1329                                 else
1330                                         time = time / 2.0f;
1331                         }
1332                         if(bb->split_offset == PART_BB_OFF_LINEAR)
1333                                 time = (float)fmod(bb->time + (float)bb->num / (float)(bb->uv_split * bb->uv_split), 1.0f);
1334                         else if(bb->split_offset == PART_BB_OFF_RANDOM)
1335                                 time = (float)fmod(bb->time + bb->random, 1.0f);
1336                 }
1337                 else{
1338                         if(bb->split_offset == PART_BB_OFF_NONE)
1339                                 time = 0.0f;
1340                         else if(bb->split_offset == PART_BB_OFF_LINEAR)
1341                                 time = (float)fmod((float)bb->num /(float)(bb->uv_split * bb->uv_split) , 1.0f);
1342                         else /* split_offset==PART_BB_OFF_RANDOM */
1343                                 time = bb->random;
1344                 }
1345                 uvx = uvdx * floor((float)(bb->uv_split * bb->uv_split) * (float)fmod((double)time, (double)uvdx));
1346                 uvy = uvdy * floor((1.0f - time) * (float)bb->uv_split);
1347                 if(fmod(time, 1.0f / bb->uv_split) == 0.0f)
1348                         uvy -= uvdy;
1349         }
1350
1351         /* normal UVs */
1352         if(bb->uv[0] >= 0){
1353                 mtf = RE_vlakren_get_tface(obr, vlr, bb->uv[0], NULL, 1);
1354                 mtf->uv[0][0] = 1.0f;
1355                 mtf->uv[0][1] = 1.0f;
1356                 mtf->uv[1][0] = 0.0f;
1357                 mtf->uv[1][1] = 1.0f;
1358                 mtf->uv[2][0] = 0.0f;
1359                 mtf->uv[2][1] = 0.0f;
1360                 mtf->uv[3][0] = 1.0f;
1361                 mtf->uv[3][1] = 0.0f;
1362         }
1363
1364         /* time-index UVs */
1365         if(bb->uv[1] >= 0){
1366                 mtf = RE_vlakren_get_tface(obr, vlr, bb->uv[1], NULL, 1);
1367                 mtf->uv[0][0] = mtf->uv[1][0] = mtf->uv[2][0] = mtf->uv[3][0] = bb->time;
1368                 mtf->uv[0][1] = mtf->uv[1][1] = mtf->uv[2][1] = mtf->uv[3][1] = (float)bb->num/(float)bb->totnum;
1369         }
1370
1371         /* split UVs */
1372         if(bb->uv_split > 1 && bb->uv[2] >= 0){
1373                 mtf = RE_vlakren_get_tface(obr, vlr, bb->uv[2], NULL, 1);
1374                 mtf->uv[0][0] = uvx + uvdx;
1375                 mtf->uv[0][1] = uvy + uvdy;
1376                 mtf->uv[1][0] = uvx;
1377                 mtf->uv[1][1] = uvy + uvdy;
1378                 mtf->uv[2][0] = uvx;
1379                 mtf->uv[2][1] = uvy;
1380                 mtf->uv[3][0] = uvx + uvdx;
1381                 mtf->uv[3][1] = uvy;
1382         }
1383 }
1384 static void particle_normal_ren(short ren_as, ParticleSettings *part, Render *re, ObjectRen *obr, DerivedMesh *dm, Material *ma, ParticleStrandData *sd, ParticleBillboardData *bb, ParticleKey *state, int seed, float hasize)
1385 {
1386         float loc[3], loc0[3], loc1[3], vel[3];
1387         
1388         VECCOPY(loc, state->co);
1389
1390         if(ren_as != PART_DRAW_BB)
1391                 MTC_Mat4MulVecfl(re->viewmat, loc);
1392
1393         switch(ren_as) {
1394                 case PART_DRAW_LINE:
1395                         sd->line = 1;
1396                         sd->time = 0.0f;
1397                         sd->size = hasize;
1398
1399                         VECCOPY(vel, state->vel);
1400                         MTC_Mat4Mul3Vecfl(re->viewmat, vel);
1401                         Normalize(vel);
1402
1403                         if(part->draw & PART_DRAW_VEL_LENGTH)
1404                                 VecMulf(vel, VecLength(state->vel));
1405
1406                         VECADDFAC(loc0, loc, vel, -part->draw_line[0]);
1407                         VECADDFAC(loc1, loc, vel, part->draw_line[1]);
1408
1409                         particle_curve(re, obr, dm, ma, sd, loc0, loc1, seed);
1410
1411                         break;
1412
1413                 case PART_DRAW_BB:
1414
1415                         VECCOPY(bb->vec, loc);
1416                         VECCOPY(bb->vel, state->vel);
1417
1418                         particle_billboard(re, obr, ma, bb);
1419
1420                         break;
1421
1422                 default:
1423                 {
1424                         HaloRen *har=0;
1425
1426                         har = RE_inithalo_particle(re, obr, dm, ma, loc, NULL, sd->orco, sd->uvco, hasize, 0.0, seed);
1427                         
1428                         if(har) har->lay= obr->ob->lay;
1429
1430                         break;
1431                 }
1432         }
1433 }
1434 static void get_particle_uvco_mcol(short from, DerivedMesh *dm, float *fuv, int num, ParticleStrandData *sd)
1435 {
1436         int i;
1437
1438         /* get uvco */
1439         if(sd->uvco && ELEM(from,PART_FROM_FACE,PART_FROM_VOLUME)) {
1440                 for(i=0; i<sd->totuv; i++) {
1441                         if(num != DMCACHE_NOTFOUND) {
1442                                 MFace *mface = dm->getTessFaceData(dm, num, CD_MFACE);
1443                                 MTFace *mtface = (MTFace*)CustomData_get_layer_n(&dm->faceData, CD_MTFACE, i);
1444                                 mtface += num;
1445                                 
1446                                 psys_interpolate_uvs(mtface, mface->v4, fuv, sd->uvco + 2 * i);
1447                         }
1448                         else {
1449                                 sd->uvco[2*i] = 0.0f;
1450                                 sd->uvco[2*i + 1] = 0.0f;
1451                         }
1452                 }
1453         }
1454
1455         /* get mcol */
1456         if(sd->mcol && ELEM(from,PART_FROM_FACE,PART_FROM_VOLUME)) {
1457                 for(i=0; i<sd->totcol; i++) {
1458                         if(num != DMCACHE_NOTFOUND) {
1459                                 MFace *mface = dm->getTessFaceData(dm, num, CD_MFACE);
1460                                 MCol *mc = (MCol*)CustomData_get_layer_n(&dm->faceData, CD_MCOL, i);
1461                                 mc += num * 4;
1462
1463                                 psys_interpolate_mcol(mc, mface->v4, fuv, sd->mcol + i);
1464                         }
1465                         else
1466                                 memset(&sd->mcol[i], 0, sizeof(MCol));
1467                 }
1468         }
1469 }
1470 static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem *psys, int timeoffset)
1471 {
1472         Object *ob= obr->ob;
1473         Object *tob=0;
1474         Material *ma=0;
1475         ParticleSystemModifierData *psmd;
1476         ParticleSystem *tpsys=0;
1477         ParticleSettings *part, *tpart=0;
1478         ParticleData *pars, *pa=0,*tpa=0;
1479         ParticleKey *states=0;
1480         ParticleKey state;
1481         ParticleCacheKey *cache=0;
1482         ParticleBillboardData bb;
1483         ParticleStrandData sd;
1484         StrandBuffer *strandbuf=0;
1485         StrandVert *svert=0;
1486         StrandBound *sbound= 0;
1487         StrandRen *strand=0;
1488         RNG *rng= 0;
1489         float loc[3],loc1[3],loc0[3],mat[4][4],nmat[3][3],co[3],nor[3],time;
1490         float strandlen=0.0f, curlen=0.0f;
1491         float hasize, pa_size, r_tilt, r_length, cfra=bsystem_time(re->scene, ob, (float)re->scene->r.cfra, 0.0);
1492         float pa_time, pa_birthtime, pa_dietime;
1493         float random, simplify[2];
1494         int i, a, k, max_k=0, totpart, dosimplify = 0, dosurfacecache = 0;
1495         int totchild=0;
1496         int seed, path_nbr=0, orco1=0, num;
1497         int totface, *origindex = 0;
1498         char **uv_name=0;
1499
1500 /* 1. check that everything is ok & updated */
1501         if(psys==NULL)
1502                 return 0;
1503         
1504         totchild=psys->totchild;
1505
1506         part=psys->part;
1507         pars=psys->particles;
1508
1509         if(part==NULL || pars==NULL || !psys_check_enabled(ob, psys))
1510                 return 0;
1511         
1512         if(part->ren_as==PART_DRAW_OB || part->ren_as==PART_DRAW_GR || part->ren_as==PART_DRAW_NOT)
1513                 return 1;
1514
1515 /* 2. start initialising things */
1516         if(part->phystype==PART_PHYS_KEYED)
1517                 psys_count_keyed_targets(ob,psys);
1518
1519         /* last possibility to bail out! */
1520         psmd= psys_get_modifier(ob,psys);
1521         if(!(psmd->modifier.mode & eModifierMode_Render))
1522                 return 0;
1523
1524         if(G.rendering == 0) { /* preview render */
1525                 totchild = (int)((float)totchild * (float)part->disp / 100.0f);
1526         }
1527
1528         psys->flag |= PSYS_DRAWING;
1529
1530         rng= rng_new(psys->seed);
1531
1532         totpart=psys->totpart;
1533
1534         memset(&sd, 0, sizeof(ParticleStrandData));
1535         sd.override_uv = -1;
1536
1537 /* 2.1 setup material stff */
1538         ma= give_render_material(re, ob, part->omat);
1539         
1540 #if 0 // XXX old animation system
1541         if(ma->ipo){
1542                 calc_ipo(ma->ipo, cfra);
1543                 execute_ipo((ID *)ma, ma->ipo);
1544         }
1545 #endif // XXX old animation system
1546
1547         hasize = ma->hasize;
1548         seed = ma->seed1;
1549
1550         re->flag |= R_HALO;
1551
1552         RE_set_customdata_names(obr, &psmd->dm->faceData);
1553         sd.totuv = CustomData_number_of_layers(&psmd->dm->faceData, CD_MTFACE);
1554         sd.totcol = CustomData_number_of_layers(&psmd->dm->faceData, CD_MCOL);
1555
1556         if(ma->texco & TEXCO_UV && sd.totuv) {
1557                 sd.uvco = MEM_callocN(sd.totuv * 2 * sizeof(float), "particle_uvs");
1558
1559                 if(ma->strand_uvname[0]) {
1560                         sd.override_uv = CustomData_get_named_layer_index(&psmd->dm->faceData, CD_MTFACE, ma->strand_uvname);
1561                         sd.override_uv -= CustomData_get_layer_index(&psmd->dm->faceData, CD_MTFACE);
1562                 }
1563         }
1564         else
1565                 sd.uvco = NULL;
1566
1567         if(sd.totcol)
1568                 sd.mcol = MEM_callocN(sd.totcol * sizeof(MCol), "particle_mcols");
1569
1570 /* 2.2 setup billboards */
1571         if(part->ren_as == PART_DRAW_BB) {
1572                 int first_uv = CustomData_get_layer_index(&psmd->dm->faceData, CD_MTFACE);
1573
1574                 bb.uv[0] = CustomData_get_named_layer_index(&psmd->dm->faceData, CD_MTFACE, psys->bb_uvname[0]);
1575                 if(bb.uv[0] < 0)
1576                         bb.uv[0] = CustomData_get_active_layer_index(&psmd->dm->faceData, CD_MTFACE);
1577
1578                 bb.uv[1] = CustomData_get_named_layer_index(&psmd->dm->faceData, CD_MTFACE, psys->bb_uvname[1]);
1579
1580                 bb.uv[2] = CustomData_get_named_layer_index(&psmd->dm->faceData, CD_MTFACE, psys->bb_uvname[2]);
1581
1582                 if(first_uv >= 0) {
1583                         bb.uv[0] -= first_uv;
1584                         bb.uv[1] -= first_uv;
1585                         bb.uv[2] -= first_uv;
1586                 }
1587
1588                 bb.align = part->bb_align;
1589                 bb.anim = part->bb_anim;
1590                 bb.lock = part->draw & PART_DRAW_BB_LOCK;
1591                 bb.ob = (part->bb_ob ? part->bb_ob : re->scene->camera);
1592                 bb.offset[0] = part->bb_offset[0];
1593                 bb.offset[1] = part->bb_offset[1];
1594                 bb.split_offset = part->bb_split_offset;
1595                 bb.totnum = totpart+totchild;
1596                 bb.uv_split = part->bb_uv_split;
1597         }
1598
1599 #if 0 // XXX old animation system
1600 /* 2.3 setup time */
1601         if(part->flag&PART_ABS_TIME && part->ipo) {
1602                 calc_ipo(part->ipo, cfra);
1603                 execute_ipo((ID *)part, part->ipo);
1604         }
1605
1606         if(part->flag & PART_GLOB_TIME)
1607 #endif // XXX old animation system
1608         cfra = bsystem_time(re->scene, 0, (float)re->scene->r.cfra, 0.0);
1609
1610 /* 2.4 setup reactors */
1611         if(part->type == PART_REACTOR){
1612                 psys_get_reactor_target(ob, psys, &tob, &tpsys);
1613                 if(tpsys && (part->from==PART_FROM_PARTICLE || part->phystype==PART_PHYS_NO)){
1614                         psmd = psys_get_modifier(tob,tpsys);
1615                         tpart = tpsys->part;
1616                 }
1617         }
1618         
1619 /* 2.5 setup matrices */
1620         MTC_Mat4MulMat4(mat, ob->obmat, re->viewmat);
1621         MTC_Mat4Invert(ob->imat, mat);  /* need to be that way, for imat texture */
1622         Mat3CpyMat4(nmat, ob->imat);
1623         Mat3Transp(nmat);
1624
1625 /* 2.6 setup strand rendering */
1626         if(part->ren_as == PART_DRAW_PATH && psys->pathcache){
1627                 path_nbr=(int)pow(2.0,(double) part->ren_step);
1628
1629                 if(path_nbr) {
1630                         if(!ELEM(ma->material_type, MA_TYPE_HALO, MA_TYPE_WIRE)) {
1631                                 sd.orco = MEM_mallocN(3*sizeof(float)*(totpart+totchild), "particle orcos");
1632                                 set_object_orco(re, psys, sd.orco);
1633                         }
1634                 }
1635
1636                 if(part->draw & PART_DRAW_REN_ADAPT) {
1637                         sd.adapt = 1;
1638                         sd.adapt_pix = (float)part->adapt_pix;
1639                         sd.adapt_angle = cos((float)part->adapt_angle * (float)(M_PI / 180.0));
1640                 }
1641
1642                 if(re->r.renderer==R_INTERN && part->draw&PART_DRAW_REN_STRAND) {
1643                         strandbuf= RE_addStrandBuffer(obr, (totpart+totchild)*(path_nbr+1));
1644                         strandbuf->ma= ma;
1645                         strandbuf->lay= ob->lay;
1646                         Mat4CpyMat4(strandbuf->winmat, re->winmat);
1647                         strandbuf->winx= re->winx;
1648                         strandbuf->winy= re->winy;
1649                         strandbuf->maxdepth= 2;
1650                         strandbuf->adaptcos= cos((float)part->adapt_angle*(float)(M_PI/180.0));
1651                         strandbuf->overrideuv= sd.override_uv;
1652                         strandbuf->minwidth= ma->strand_min;
1653
1654                         if(ma->strand_widthfade == 0.0f)
1655                                 strandbuf->widthfade= 0.0f;
1656                         else if(ma->strand_widthfade >= 1.0f)
1657                                 strandbuf->widthfade= 2.0f - ma->strand_widthfade;
1658                         else
1659                                 strandbuf->widthfade= 1.0f/MAX2(ma->strand_widthfade, 1e-5f);
1660
1661                         if(part->flag & PART_HAIR_BSPLINE)
1662                                 strandbuf->flag |= R_STRAND_BSPLINE;
1663                         if(ma->mode & MA_STR_B_UNITS)
1664                                 strandbuf->flag |= R_STRAND_B_UNITS;
1665
1666                         svert= strandbuf->vert;
1667
1668                         if(re->r.mode & R_SPEED)
1669                                 dosurfacecache= 1;
1670                         else if((re->wrld.mode & WO_AMB_OCC) && (re->wrld.ao_gather_method == WO_AOGATHER_APPROX))
1671                                 if(ma->amb != 0.0f)
1672                                         dosurfacecache= 1;
1673
1674                         totface= psmd->dm->getNumTessFaces(psmd->dm);
1675                         origindex= psmd->dm->getTessFaceDataArray(psmd->dm, CD_ORIGINDEX);
1676                         if(origindex) {
1677                                 for(a=0; a<totface; a++)
1678                                         strandbuf->totbound= MAX2(strandbuf->totbound, origindex[a]);
1679                                 strandbuf->totbound++;
1680                         }
1681                         strandbuf->totbound++;
1682                         strandbuf->bound= MEM_callocN(sizeof(StrandBound)*strandbuf->totbound, "StrandBound");
1683                         sbound= strandbuf->bound;
1684                         sbound->start= sbound->end= 0;
1685                 }
1686         }
1687
1688         if(sd.orco == 0) {
1689                 sd.orco = MEM_mallocN(3 * sizeof(float), "particle orco");
1690                 orco1 = 1;
1691         }
1692
1693         if(path_nbr == 0)
1694                 psys->lattice = psys_get_lattice(re->scene, ob, psys);
1695
1696 /* 3. start creating renderable things */
1697         for(a=0,pa=pars; a<totpart+totchild; a++, pa++, seed++) {
1698                 random = rng_getFloat(rng);
1699                 /* setup per particle individual stuff */
1700                 if(a<totpart){
1701                         if(pa->flag & PARS_UNEXIST) continue;
1702
1703                         pa_time=(cfra-pa->time)/pa->lifetime;
1704                         pa_birthtime = pa->time;
1705                         pa_dietime = pa->dietime;
1706 #if 0 // XXX old animation system
1707                         if((part->flag&PART_ABS_TIME) == 0){
1708                                 if(ma->ipo) {
1709                                         /* correction for lifetime */
1710                                         calc_ipo(ma->ipo, 100.0f * pa_time);
1711                                         execute_ipo((ID *)ma, ma->ipo);
1712                                 }
1713                                 if(part->ipo){
1714                                         /* correction for lifetime */
1715                                         calc_ipo(part->ipo, 100.0f*pa_time);
1716                                         execute_ipo((ID *)part, part->ipo);
1717                                 }
1718                         }
1719 #endif // XXX old animation system
1720
1721                         hasize = ma->hasize;
1722
1723                         /* get orco */
1724                         if(tpsys && (part->from==PART_FROM_PARTICLE || part->phystype==PART_PHYS_NO)){
1725                                 tpa=tpsys->particles+pa->num;
1726                                 psys_particle_on_emitter(psmd,tpart->from,tpa->num,pa->num_dmcache,tpa->fuv,tpa->foffset,co,nor,0,0,sd.orco,0);
1727                         }
1728                         else
1729                                 psys_particle_on_emitter(psmd,part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,nor,0,0,sd.orco,0);
1730
1731                         /* get uvco & mcol */
1732                         num= pa->num_dmcache;
1733
1734                         if(num == DMCACHE_NOTFOUND)
1735                                 if(pa->num < psmd->dm->getNumTessFaces(psmd->dm))
1736                                         num= pa->num;
1737
1738                         get_particle_uvco_mcol(part->from, psmd->dm, pa->fuv, num, &sd);
1739
1740                         pa_size = pa->size;
1741
1742                         r_tilt = 1.0f + pa->r_ave[0];
1743                         r_length = 0.5f * (1.0f + pa->r_ave[1]);
1744
1745                         if(path_nbr) {
1746                                 cache = psys->pathcache[a];
1747                                 max_k = (int)cache->steps;
1748                         }
1749
1750                         if(totchild && (part->draw&PART_DRAW_PARENT)==0) continue;
1751                 }
1752                 else {
1753                         ChildParticle *cpa= psys->child+a-totpart;
1754
1755                         if(path_nbr) {
1756                                 cache = psys->childcache[a-totpart];
1757
1758                                 if(cache->steps < 0)
1759                                         continue;
1760
1761                                 max_k = (int)cache->steps;
1762                         }
1763                         
1764                         pa_time = psys_get_child_time(psys, cpa, cfra, &pa_birthtime, &pa_dietime);
1765
1766 #if 0 // XXX old animation system
1767                         if((part->flag & PART_ABS_TIME) == 0) {
1768                                 if(ma->ipo){
1769                                         /* correction for lifetime */
1770                                         calc_ipo(ma->ipo, 100.0f * pa_time);
1771                                         execute_ipo((ID *)ma, ma->ipo);
1772                                 }
1773                                 if(part->ipo) {
1774                                         /* correction for lifetime */
1775                                         calc_ipo(part->ipo, 100.0f * pa_time);
1776                                         execute_ipo((ID *)part, part->ipo);
1777                                 }
1778                         }
1779 #endif // XXX old animation system
1780
1781                         pa_size = psys_get_child_size(psys, cpa, cfra, &pa_time);
1782
1783                         r_tilt = 2.0f * cpa->rand[2];
1784                         r_length = cpa->rand[1];
1785
1786                         num = cpa->num;
1787
1788                         /* get orco */
1789                         if(part->childtype == PART_CHILD_FACES) {
1790                                 psys_particle_on_emitter(psmd,
1791                                         PART_FROM_FACE, cpa->num,DMCACHE_ISCHILD,
1792                                         cpa->fuv,cpa->foffset,co,nor,0,0,sd.orco,0);
1793                         }
1794                         else {
1795                                 ParticleData *par = psys->particles + cpa->parent;
1796                                 psys_particle_on_emitter(psmd, part->from,
1797                                         par->num,DMCACHE_ISCHILD,par->fuv,
1798                                         par->foffset,co,nor,0,0,sd.orco,0);
1799                         }
1800
1801                         /* get uvco & mcol */
1802                         if(part->from!=PART_FROM_PARTICLE && part->childtype==PART_CHILD_FACES) {
1803                                 get_particle_uvco_mcol(PART_FROM_FACE, psmd->dm, cpa->fuv, cpa->num, &sd);
1804                         }
1805                         else {
1806                                 ParticleData *parent = psys->particles + cpa->parent;
1807                                 num = parent->num_dmcache;
1808
1809                                 if(num == DMCACHE_NOTFOUND)
1810                                         if(parent->num < psmd->dm->getNumTessFaces(psmd->dm))
1811                                                 num = parent->num;
1812
1813                                 get_particle_uvco_mcol(part->from, psmd->dm, parent->fuv, num, &sd);
1814                         }
1815
1816                         dosimplify = psys_render_simplify_params(psys, cpa, simplify);
1817
1818                         if(strandbuf) {
1819                                 if(origindex[cpa->num]+1 > sbound - strandbuf->bound) {
1820                                         sbound= strandbuf->bound + origindex[cpa->num]+1;
1821                                         sbound->start= sbound->end= obr->totstrand;
1822                                 }
1823                         }
1824                 }
1825
1826                 /* surface normal shading setup */
1827                 if(ma->mode_l & MA_STR_SURFDIFF) {
1828                         Mat3MulVecfl(nmat, nor);
1829                         sd.surfnor= nor;
1830                 }
1831                 else
1832                         sd.surfnor= NULL;
1833
1834                 /* strand render setup */
1835                 if(strandbuf) {
1836                         strand= RE_findOrAddStrand(obr, obr->totstrand++);
1837                         strand->buffer= strandbuf;
1838                         strand->vert= svert;
1839                         VECCOPY(strand->orco, sd.orco);
1840
1841                         if(dosimplify) {
1842                                 float *ssimplify= RE_strandren_get_simplify(obr, strand, 1);
1843                                 ssimplify[0]= simplify[0];
1844                                 ssimplify[1]= simplify[1];
1845                         }
1846
1847                         if(sd.surfnor) {
1848                                 float *snor= RE_strandren_get_surfnor(obr, strand, 1);
1849                                 VECCOPY(snor, sd.surfnor);
1850                         }
1851
1852                         if(dosurfacecache && num >= 0) {
1853                                 int *facenum= RE_strandren_get_face(obr, strand, 1);
1854                                 *facenum= num;
1855                         }
1856
1857                         if(sd.uvco) {
1858                                 for(i=0; i<sd.totuv; i++) {
1859                                         if(i != sd.override_uv) {
1860                                                 float *uv= RE_strandren_get_uv(obr, strand, i, NULL, 1);
1861
1862                                                 uv[0]= sd.uvco[2*i];
1863                                                 uv[1]= sd.uvco[2*i+1];
1864                                         }
1865                                 }
1866                         }
1867                         if(sd.mcol) {
1868                                 for(i=0; i<sd.totcol; i++) {
1869                                         MCol *mc= RE_strandren_get_mcol(obr, strand, i, NULL, 1);
1870                                         *mc = sd.mcol[i];
1871                                 }
1872                         }
1873
1874                         sbound->end++;
1875                 }
1876
1877                 /* strandco computation setup */
1878                 if(path_nbr) {
1879                         strandlen= 0.0f;
1880                         curlen= 0.0f;
1881                         for(k=1; k<=path_nbr; k++)
1882                                 if(k<=max_k)
1883                                         strandlen += VecLenf((cache+k-1)->co, (cache+k)->co);
1884                 }
1885
1886                 if(path_nbr) {
1887                         /* render strands */
1888                         for(k=0; k<=path_nbr; k++){
1889                                 if(k<=max_k){
1890                                         VECCOPY(state.co,(cache+k)->co);
1891                                         VECCOPY(state.vel,(cache+k)->vel);
1892                                 }
1893                                 else
1894                                         continue;       
1895
1896                                 if(k > 0)
1897                                         curlen += VecLenf((cache+k-1)->co, (cache+k)->co);
1898                                 time= curlen/strandlen;
1899
1900                                 VECCOPY(loc,state.co);
1901                                 MTC_Mat4MulVecfl(re->viewmat,loc);
1902
1903                                 if(strandbuf) {
1904                                         VECCOPY(svert->co, loc);
1905                                         svert->strandco= -1.0f + 2.0f*time;
1906                                         svert++;
1907                                         strand->totvert++;
1908                                 }
1909                                 else{
1910                                         sd.size = hasize;
1911
1912                                         if(k==1){
1913                                                 sd.first = 1;
1914                                                 sd.time = 0.0f;
1915                                                 VECSUB(loc0,loc1,loc);
1916                                                 VECADD(loc0,loc1,loc0);
1917
1918                                                 particle_curve(re, obr, psmd->dm, ma, &sd, loc1, loc0, seed);
1919                                         }
1920
1921                                         sd.first = 0;
1922                                         sd.time = time;
1923
1924                                         if(k)
1925                                                 particle_curve(re, obr, psmd->dm, ma, &sd, loc, loc1, seed);
1926
1927                                         VECCOPY(loc1,loc);
1928                                 }
1929                         }
1930
1931                 }
1932                 else {
1933                         /* render normal particles */
1934                         if(part->trail_count > 1) {
1935                                 float length = part->path_end * (1.0 - part->randlength * r_length);
1936                                 int trail_count = part->trail_count * (1.0 - part->randlength * r_length);
1937                                 float ct = (part->draw & PART_ABS_PATH_TIME) ? cfra : pa_time;
1938                                 float dt = length / (trail_count ? (float)trail_count : 1.0f);
1939
1940                                 for(i=0; i < trail_count; i++, ct -= dt) {
1941                                         if(part->draw & PART_ABS_PATH_TIME) {
1942                                                 if(ct < pa_birthtime || ct > pa_dietime)
1943                                                         continue;
1944                                         }
1945                                         else if(ct < 0.0f || ct > 1.0f)
1946                                                 continue;
1947
1948                                         state.time = (part->draw & PART_ABS_PATH_TIME) ? -ct : ct;
1949                                         psys_get_particle_on_path(re->scene,ob,psys,a,&state,1);
1950
1951                                         if(psys->parent)
1952                                                 Mat4MulVecfl(psys->parent->obmat, state.co);
1953
1954                                         if(part->ren_as == PART_DRAW_BB) {
1955                                                 bb.random = random;
1956                                                 bb.size = pa_size;
1957                                                 bb.tilt = part->bb_tilt * (1.0f - part->bb_rand_tilt * r_tilt);
1958                                                 bb.time = ct;
1959                                                 bb.num = a;
1960                                         }
1961
1962                                         particle_normal_ren(part->ren_as, part, re, obr, psmd->dm, ma, &sd, &bb, &state, seed, hasize);
1963                                 }
1964                         }
1965                         else {
1966                                 time=0.0f;
1967                                 state.time=cfra;
1968                                 if(psys_get_particle_state(re->scene,ob,psys,a,&state,0)==0)
1969                                         continue;
1970
1971                                 if(psys->parent)
1972                                         Mat4MulVecfl(psys->parent->obmat, state.co);
1973
1974                                 if(part->ren_as == PART_DRAW_BB) {
1975                                         bb.random = random;
1976                                         bb.size = pa_size;
1977                                         bb.tilt = part->bb_tilt * (1.0f - part->bb_rand_tilt * r_tilt);
1978                                         bb.time = pa_time;
1979                                         bb.num = a;
1980                                 }
1981
1982                                 particle_normal_ren(part->ren_as, part, re, obr, psmd->dm, ma, &sd, &bb, &state, seed, hasize);
1983                         }
1984                 }
1985
1986                 if(orco1==0)
1987                         sd.orco+=3;
1988
1989                 if(re->test_break(re->tbh))
1990                         break;
1991         }
1992
1993         if(dosurfacecache)
1994                 strandbuf->surface= cache_strand_surface(re, obr, psmd->dm, mat, timeoffset);
1995
1996 /* 4. clean up */
1997 #if 0 // XXX old animation system
1998         if(ma) do_mat_ipo(re->scene, ma);
1999 #endif // XXX old animation system
2000         
2001         if(orco1)
2002                 MEM_freeN(sd.orco);
2003
2004         if(sd.uvco)
2005                 MEM_freeN(sd.uvco);
2006         
2007         if(sd.mcol)
2008                 MEM_freeN(sd.mcol);
2009
2010         if(uv_name)
2011                 MEM_freeN(uv_name);
2012
2013         if(states)
2014                 MEM_freeN(states);
2015         
2016         rng_free(rng);
2017
2018         psys->flag &= ~PSYS_DRAWING;
2019
2020         if(psys->lattice){
2021                 end_latt_deform(psys->lattice);
2022                 psys->lattice= NULL;
2023         }
2024
2025         if(path_nbr && (ma->mode_l & MA_TANGENT_STR)==0)
2026                 calc_vertexnormals(re, obr, 0, 0);
2027
2028         return 1;
2029 }
2030
2031 /* ------------------------------------------------------------------------- */
2032 /* Halo's                                                                                                                                */
2033 /* ------------------------------------------------------------------------- */
2034
2035 static void make_render_halos(Render *re, ObjectRen *obr, Mesh *me, int totvert, MVert *mvert, Material *ma, float *orco)
2036 {
2037         Object *ob= obr->ob;
2038         HaloRen *har;
2039         float xn, yn, zn, nor[3], view[3];
2040         float vec[3], hasize, mat[4][4], imat[3][3];
2041         int a, ok, seed= ma->seed1;
2042
2043         MTC_Mat4MulMat4(mat, ob->obmat, re->viewmat);
2044         MTC_Mat3CpyMat4(imat, ob->imat);
2045
2046         re->flag |= R_HALO;
2047
2048         for(a=0; a<totvert; a++, mvert++) {
2049                 ok= 1;
2050
2051                 if(ok) {
2052                         hasize= ma->hasize;
2053
2054                         VECCOPY(vec, mvert->co);
2055                         MTC_Mat4MulVecfl(mat, vec);
2056
2057                         if(ma->mode & MA_HALOPUNO) {
2058                                 xn= mvert->no[0];
2059                                 yn= mvert->no[1];
2060                                 zn= mvert->no[2];
2061
2062                                 /* transpose ! */
2063                                 nor[0]= imat[0][0]*xn+imat[0][1]*yn+imat[0][2]*zn;
2064                                 nor[1]= imat[1][0]*xn+imat[1][1]*yn+imat[1][2]*zn;
2065                                 nor[2]= imat[2][0]*xn+imat[2][1]*yn+imat[2][2]*zn;
2066                                 Normalize(nor);
2067
2068                                 VECCOPY(view, vec);
2069                                 Normalize(view);
2070
2071                                 zn= nor[0]*view[0]+nor[1]*view[1]+nor[2]*view[2];
2072                                 if(zn>=0.0) hasize= 0.0;
2073                                 else hasize*= zn*zn*zn*zn;
2074                         }
2075
2076                         if(orco) har= RE_inithalo(re, obr, ma, vec, NULL, orco, hasize, 0.0, seed);
2077                         else har= RE_inithalo(re, obr, ma, vec, NULL, mvert->co, hasize, 0.0, seed);
2078                         if(har) har->lay= ob->lay;
2079                 }
2080                 if(orco) orco+= 3;
2081                 seed++;
2082         }
2083 }
2084
2085 static int verghalo(const void *a1, const void *a2)
2086 {
2087         const HaloRen *har1= *(const HaloRen**)a1;
2088         const HaloRen *har2= *(const HaloRen**)a2;
2089         
2090         if(har1->zs < har2->zs) return 1;
2091         else if(har1->zs > har2->zs) return -1;
2092         return 0;
2093 }
2094
2095 static void sort_halos(Render *re, int totsort)
2096 {
2097         ObjectRen *obr;
2098         HaloRen *har= NULL, **haso;
2099         int a;
2100
2101         if(re->tothalo==0) return;
2102
2103         re->sortedhalos= MEM_callocN(sizeof(HaloRen*)*re->tothalo, "sorthalos");
2104         haso= re->sortedhalos;
2105
2106         for(obr=re->objecttable.first; obr; obr=obr->next) {
2107                 for(a=0; a<obr->tothalo; a++) {
2108                         if((a & 255)==0) har= obr->bloha[a>>8];
2109                         else har++;
2110
2111                         *(haso++)= har;
2112                 }
2113         }
2114
2115         qsort(re->sortedhalos, totsort, sizeof(HaloRen*), verghalo);
2116 }
2117
2118 /* ------------------------------------------------------------------------- */
2119 /* Displacement Mapping                                                                                                          */
2120 /* ------------------------------------------------------------------------- */
2121
2122 static short test_for_displace(Render *re, Object *ob)
2123 {
2124         /* return 1 when this object uses displacement textures. */
2125         Material *ma;
2126         int i;
2127         
2128         for (i=1; i<=ob->totcol; i++) {
2129                 ma=give_render_material(re, ob, i);
2130                 /* ma->mapto is ORed total of all mapto channels */
2131                 if(ma && (ma->mapto & MAP_DISPLACE)) return 1;
2132         }
2133         return 0;
2134 }
2135
2136 static void displace_render_vert(Render *re, ObjectRen *obr, ShadeInput *shi, VertRen *vr, int vindex, float *scale, float mat[][4], float imat[][3])
2137 {
2138         MTFace *tface;
2139         short texco= shi->mat->texco;
2140         float sample=0, displace[3];
2141         char *name;
2142         int i;
2143
2144         /* shi->co is current render coord, just make sure at least some vector is here */
2145         VECCOPY(shi->co, vr->co);
2146         /* vertex normal is used for textures type 'col' and 'var' */
2147         VECCOPY(shi->vn, vr->n);
2148
2149         if(mat)
2150                 Mat4MulVecfl(mat, shi->co);
2151
2152         if(imat) {
2153                 shi->vn[0]= imat[0][0]*vr->n[0]+imat[0][1]*vr->n[1]+imat[0][2]*vr->n[2];
2154                 shi->vn[1]= imat[1][0]*vr->n[0]+imat[1][1]*vr->n[1]+imat[1][2]*vr->n[2];
2155                 shi->vn[2]= imat[2][0]*vr->n[0]+imat[2][1]*vr->n[1]+imat[2][2]*vr->n[2];
2156         }
2157
2158         if (texco & TEXCO_UV) {
2159                 shi->totuv= 0;
2160                 shi->actuv= obr->actmtface;
2161
2162                 for (i=0; (tface=RE_vlakren_get_tface(obr, shi->vlr, i, &name, 0)); i++) {
2163                         ShadeInputUV *suv= &shi->uv[i];
2164
2165                         /* shi.uv needs scale correction from tface uv */
2166                         suv->uv[0]= 2*tface->uv[vindex][0]-1.0f;
2167                         suv->uv[1]= 2*tface->uv[vindex][1]-1.0f;
2168                         suv->uv[2]= 0.0f;
2169                         suv->name= name;
2170                         shi->totuv++;
2171                 }
2172         }
2173
2174         /* set all rendercoords, 'texco' is an ORed value for all textures needed */
2175         if ((texco & TEXCO_ORCO) && (vr->orco)) {
2176                 VECCOPY(shi->lo, vr->orco);
2177         }
2178         if (texco & TEXCO_STICKY) {
2179                 float *sticky= RE_vertren_get_sticky(obr, vr, 0);
2180                 if(sticky) {
2181                         shi->sticky[0]= sticky[0];
2182                         shi->sticky[1]= sticky[1];
2183                         shi->sticky[2]= 0.0f;
2184                 }
2185         }
2186         if (texco & TEXCO_GLOB) {
2187                 VECCOPY(shi->gl, shi->co);
2188                 MTC_Mat4MulVecfl(re->viewinv, shi->gl);
2189         }
2190         if (texco & TEXCO_NORM) {
2191                 VECCOPY(shi->orn, shi->vn);
2192         }
2193         if(texco & TEXCO_REFL) {
2194                 /* not (yet?) */
2195         }
2196         
2197         shi->displace[0]= shi->displace[1]= shi->displace[2]= 0.0;
2198         
2199         do_material_tex(shi);
2200         
2201         //printf("no=%f, %f, %f\nbefore co=%f, %f, %f\n", vr->n[0], vr->n[1], vr->n[2], 
2202         //vr->co[0], vr->co[1], vr->co[2]);
2203
2204         displace[0]= shi->displace[0] * scale[0];
2205         displace[1]= shi->displace[1] * scale[1];
2206         displace[2]= shi->displace[2] * scale[2];
2207         
2208         if(mat)
2209                 Mat3MulVecfl(imat, displace);
2210
2211         /* 0.5 could become button once?  */
2212         vr->co[0] += displace[0]; 
2213         vr->co[1] += displace[1];
2214         vr->co[2] += displace[2];
2215         
2216         //printf("after co=%f, %f, %f\n", vr->co[0], vr->co[1], vr->co[2]); 
2217         
2218         /* we just don't do this vertex again, bad luck for other face using same vertex with
2219                 different material... */
2220         vr->flag |= 1;
2221         
2222         /* Pass sample back so displace_face can decide which way to split the quad */
2223         sample  = shi->displace[0]*shi->displace[0];
2224         sample += shi->displace[1]*shi->displace[1];
2225         sample += shi->displace[2]*shi->displace[2];
2226         
2227         vr->accum=sample; 
2228         /* Should be sqrt(sample), but I'm only looking for "bigger".  Save the cycles. */
2229         return;
2230 }
2231
2232 static void displace_render_face(Render *re, ObjectRen *obr, VlakRen *vlr, float *scale, float mat[][4], float imat[][3])
2233 {
2234         ShadeInput shi;
2235
2236         /* Warning, This is not that nice, and possibly a bit slow,
2237         however some variables were not initialized properly in, unless using shade_input_initialize(...), we need to do a memset */
2238         memset(&shi, 0, sizeof(ShadeInput)); 
2239         /* end warning! - Campbell */
2240         
2241         /* set up shadeinput struct for multitex() */
2242         
2243         /* memset above means we dont need this */
2244         /*shi.osatex= 0;*/              /* signal not to use dx[] and dy[] texture AA vectors */
2245
2246         shi.obr= obr;
2247         shi.vlr= vlr;           /* current render face */
2248         shi.mat= vlr->mat;              /* current input material */
2249         shi.thread= 0;
2250         
2251         /* Displace the verts, flag is set when done */
2252         if (!vlr->v1->flag)
2253                 displace_render_vert(re, obr, &shi, vlr->v1,0,  scale, mat, imat);
2254         
2255         if (!vlr->v2->flag)
2256                 displace_render_vert(re, obr, &shi, vlr->v2, 1, scale, mat, imat);
2257
2258         if (!vlr->v3->flag)
2259                 displace_render_vert(re, obr, &shi, vlr->v3, 2, scale, mat, imat);
2260
2261         if (vlr->v4) {
2262                 if (!vlr->v4->flag)
2263                         displace_render_vert(re, obr, &shi, vlr->v4, 3, scale, mat, imat);
2264
2265                 /*      closest in displace value.  This will help smooth edges.   */ 
2266                 if ( fabs(vlr->v1->accum - vlr->v3->accum) > fabs(vlr->v2->accum - vlr->v4->accum)) 
2267                         vlr->flag |= R_DIVIDE_24;
2268                 else vlr->flag &= ~R_DIVIDE_24;
2269         }
2270         
2271         /* Recalculate the face normal  - if flipped before, flip now */
2272         if(vlr->v4) {
2273                 CalcNormFloat4(vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co, vlr->n);
2274         }       
2275         else {
2276                 CalcNormFloat(vlr->v3->co, vlr->v2->co, vlr->v1->co, vlr->n);
2277         }
2278 }
2279
2280 static void do_displacement(Render *re, ObjectRen *obr, float mat[][4], float imat[][3])
2281 {
2282         VertRen *vr;
2283         VlakRen *vlr;
2284 //      float min[3]={1e30, 1e30, 1e30}, max[3]={-1e30, -1e30, -1e30};
2285         float scale[3]={1.0f, 1.0f, 1.0f}, temp[3];//, xn
2286         int i; //, texflag=0;
2287         Object *obt;
2288                 
2289         /* Object Size with parenting */
2290         obt=obr->ob;
2291         while(obt){
2292                 VecAddf(temp, obt->size, obt->dsize);
2293                 scale[0]*=temp[0]; scale[1]*=temp[1]; scale[2]*=temp[2];
2294                 obt=obt->parent;
2295         }
2296         
2297         /* Clear all flags */
2298         for(i=0; i<obr->totvert; i++){ 
2299                 vr= RE_findOrAddVert(obr, i);
2300                 vr->flag= 0;
2301         }
2302
2303         for(i=0; i<obr->totvlak; i++){
2304                 vlr=RE_findOrAddVlak(obr, i);
2305                 displace_render_face(re, obr, vlr, scale, mat, imat);
2306         }
2307         
2308         /* Recalc vertex normals */
2309         calc_vertexnormals(re, obr, 0, 0);
2310 }
2311
2312 /* ------------------------------------------------------------------------- */
2313 /* Metaball                                                                                                                              */
2314 /* ------------------------------------------------------------------------- */
2315
2316 static void init_render_mball(Render *re, ObjectRen *obr)
2317 {
2318         Object *ob= obr->ob;
2319         DispList *dl;
2320         VertRen *ver;
2321         VlakRen *vlr, *vlr1;
2322         Material *ma;
2323         float *data, *nors, *orco, mat[4][4], imat[3][3], xn, yn, zn;
2324         int a, need_orco, vlakindex, *index;
2325
2326         if (ob!=find_basis_mball(re->scene, ob))
2327                 return;
2328
2329         MTC_Mat4MulMat4(mat, ob->obmat, re->viewmat);
2330         MTC_Mat4Invert(ob->imat, mat);
2331         MTC_Mat3CpyMat4(imat, ob->imat);
2332
2333         ma= give_render_material(re, ob, 1);
2334
2335         need_orco= 0;
2336         if(ma->texco & TEXCO_ORCO) {
2337                 need_orco= 1;
2338         }
2339         
2340         makeDispListMBall(re->scene, ob);
2341         dl= ob->disp.first;
2342         if(dl==0) return;
2343
2344         data= dl->verts;
2345         nors= dl->nors;
2346         orco= get_object_orco(re, ob);
2347
2348         for(a=0; a<dl->nr; a++, data+=3, nors+=3, orco+=3) {
2349
2350                 ver= RE_findOrAddVert(obr, obr->totvert++);
2351                 VECCOPY(ver->co, data);
2352                 MTC_Mat4MulVecfl(mat, ver->co);
2353
2354                 /* render normals are inverted */
2355                 xn= -nors[0];
2356                 yn= -nors[1];
2357                 zn= -nors[2];
2358
2359                 /* transpose ! */
2360                 ver->n[0]= imat[0][0]*xn+imat[0][1]*yn+imat[0][2]*zn;
2361                 ver->n[1]= imat[1][0]*xn+imat[1][1]*yn+imat[1][2]*zn;
2362                 ver->n[2]= imat[2][0]*xn+imat[2][1]*yn+imat[2][2]*zn;
2363                 Normalize(ver->n);
2364                 //if(ob->transflag & OB_NEG_SCALE) VecMulf(ver->n. -1.0);
2365                 
2366                 if(need_orco) ver->orco= orco;
2367         }
2368
2369         index= dl->index;
2370         for(a=0; a<dl->parts; a++, index+=4) {
2371
2372                 vlr= RE_findOrAddVlak(obr, obr->totvlak++);
2373                 vlr->v1= RE_findOrAddVert(obr, index[0]);
2374                 vlr->v2= RE_findOrAddVert(obr, index[1]);
2375                 vlr->v3= RE_findOrAddVert(obr, index[2]);
2376                 vlr->v4= 0;
2377
2378                 if(ob->transflag & OB_NEG_SCALE) 
2379                         CalcNormFloat(vlr->v1->co, vlr->v2->co, vlr->v3->co, vlr->n);
2380                 else
2381                         CalcNormFloat(vlr->v3->co, vlr->v2->co, vlr->v1->co, vlr->n);
2382
2383                 vlr->mat= ma;
2384                 vlr->flag= ME_SMOOTH+R_NOPUNOFLIP;
2385                 vlr->ec= 0;
2386
2387                 /* mball -too bad- always has triangles, because quads can be non-planar */
2388                 if(index[3] && index[3]!=index[2]) {
2389                         vlr1= RE_findOrAddVlak(obr, obr->totvlak++);
2390                         vlakindex= vlr1->index;
2391                         *vlr1= *vlr;
2392                         vlr1->index= vlakindex;
2393                         vlr1->v2= vlr1->v3;
2394                         vlr1->v3= RE_findOrAddVert(obr, index[3]);
2395                         if(ob->transflag & OB_NEG_SCALE) 
2396                                 CalcNormFloat(vlr1->v1->co, vlr1->v2->co, vlr1->v3->co, vlr1->n);
2397                         else
2398                                 CalcNormFloat(vlr1->v3->co, vlr1->v2->co, vlr1->v1->co, vlr1->n);
2399                 }
2400         }
2401
2402         /* enforce display lists remade */
2403         freedisplist(&ob->disp);
2404         
2405         /* this enforces remake for real, orco displist is small (in scale) */
2406         ob->recalc |= OB_RECALC_DATA;
2407 }
2408
2409 /* ------------------------------------------------------------------------- */
2410 /* Surfaces and Curves                                                                                                           */
2411 /* ------------------------------------------------------------------------- */
2412
2413 /* returns amount of vertices added for orco */
2414 static int dl_surf_to_renderdata(ObjectRen *obr, DispList *dl, Material **matar, float *orco, float mat[4][4])
2415 {
2416         Object *ob= obr->ob;
2417         VertRen *v1, *v2, *v3, *v4, *ver;
2418         VlakRen *vlr, *vlr1, *vlr2, *vlr3;
2419         Curve *cu= ob->data;
2420         float *data, n1[3];
2421         int u, v, orcoret= 0;
2422         int p1, p2, p3, p4, a;
2423         int sizeu, nsizeu, sizev, nsizev;
2424         int startvert, startvlak;
2425         
2426         startvert= obr->totvert;
2427         nsizeu = sizeu = dl->parts; nsizev = sizev = dl->nr; 
2428         
2429         data= dl->verts;
2430         for (u = 0; u < sizeu; u++) {
2431                 v1 = RE_findOrAddVert(obr, obr->totvert++); /* save this for possible V wrapping */
2432                 VECCOPY(v1->co, data); data += 3;
2433                 if(orco) {
2434                         v1->orco= orco; orco+= 3; orcoret++;
2435                 }       
2436                 MTC_Mat4MulVecfl(mat, v1->co);
2437                 
2438                 for (v = 1; v < sizev; v++) {
2439                         ver= RE_findOrAddVert(obr, obr->totvert++);
2440                         VECCOPY(ver->co, data); data += 3;
2441                         if(orco) {
2442                                 ver->orco= orco; orco+= 3; orcoret++;
2443                         }       
2444                         MTC_Mat4MulVecfl(mat, ver->co);
2445                 }
2446                 /* if V-cyclic, add extra vertices at end of the row */
2447                 if (dl->flag & DL_CYCL_U) {
2448                         ver= RE_findOrAddVert(obr, obr->totvert++);
2449                         VECCOPY(ver->co, v1->co);
2450                         if(orco) {
2451                                 ver->orco= orco; orco+=3; orcoret++; //orcobase + 3*(u*sizev + 0);
2452                         }
2453                 }       
2454         }       
2455         
2456         /* Done before next loop to get corner vert */
2457         if (dl->flag & DL_CYCL_U) nsizev++;
2458         if (dl->flag & DL_CYCL_V) nsizeu++;
2459         
2460         /* if U cyclic, add extra row at end of column */
2461         if (dl->flag & DL_CYCL_V) {
2462                 for (v = 0; v < nsizev; v++) {
2463                         v1= RE_findOrAddVert(obr, startvert + v);
2464                         ver= RE_findOrAddVert(obr, obr->totvert++);
2465                         VECCOPY(ver->co, v1->co);
2466                         if(orco) {
2467                                 ver->orco= orco; orco+=3; orcoret++; //ver->orco= orcobase + 3*(0*sizev + v);
2468                         }
2469                 }
2470         }
2471         
2472         sizeu = nsizeu;
2473         sizev = nsizev;
2474         
2475         startvlak= obr->totvlak;
2476         
2477         for(u = 0; u < sizeu - 1; u++) {
2478                 p1 = startvert + u * sizev; /* walk through face list */
2479                 p2 = p1 + 1;
2480                 p3 = p2 + sizev;
2481                 p4 = p3 - 1;
2482                 
2483                 for(v = 0; v < sizev - 1; v++) {
2484                         v1= RE_findOrAddVert(obr, p1);
2485                         v2= RE_findOrAddVert(obr, p2);
2486                         v3= RE_findOrAddVert(obr, p3);
2487                         v4= RE_findOrAddVert(obr, p4);
2488                         
2489                         vlr= RE_findOrAddVlak(obr, obr->totvlak++);
2490                         vlr->v1= v1; vlr->v2= v2; vlr->v3= v3; vlr->v4= v4;
2491                         
2492                         CalcNormFloat4(vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co, n1);
2493                         
2494                         VECCOPY(vlr->n, n1);
2495                         
2496                         vlr->mat= matar[ dl->col];
2497                         vlr->ec= ME_V1V2+ME_V2V3;
2498                         vlr->flag= dl->rt;
2499                         if( (cu->flag & CU_NOPUNOFLIP) ) {
2500                                 vlr->flag |= R_NOPUNOFLIP;
2501                         }
2502                         
2503                         VecAddf(v1->n, v1->n, n1);
2504                         VecAddf(v2->n, v2->n, n1);
2505                         VecAddf(v3->n, v3->n, n1);
2506                         VecAddf(v4->n, v4->n, n1);
2507                         
2508                         p1++; p2++; p3++; p4++;
2509                 }
2510         }       
2511         /* fix normals for U resp. V cyclic faces */
2512         sizeu--; sizev--;  /* dec size for face array */
2513         if (dl->flag & DL_CYCL_V) {
2514                 
2515                 for (v = 0; v < sizev; v++)
2516                 {
2517                         /* optimize! :*/
2518                         vlr= RE_findOrAddVlak(obr, UVTOINDEX(sizeu - 1, v));
2519                         vlr1= RE_findOrAddVlak(obr, UVTOINDEX(0, v));
2520                         VecAddf(vlr1->v1->n, vlr1->v1->n, vlr->n);
2521                         VecAddf(vlr1->v2->n, vlr1->v2->n, vlr->n);
2522                         VecAddf(vlr->v3->n, vlr->v3->n, vlr1->n);
2523                         VecAddf(vlr->v4->n, vlr->v4->n, vlr1->n);
2524                 }
2525         }
2526         if (dl->flag & DL_CYCL_U) {
2527                 
2528                 for (u = 0; u < sizeu; u++)
2529                 {
2530                         /* optimize! :*/
2531                         vlr= RE_findOrAddVlak(obr, UVTOINDEX(u, 0));
2532                         vlr1= RE_findOrAddVlak(obr, UVTOINDEX(u, sizev-1));
2533                         VecAddf(vlr1->v2->n, vlr1->v2->n, vlr->n);
2534                         VecAddf(vlr1->v3->n, vlr1->v3->n, vlr->n);
2535                         VecAddf(vlr->v1->n, vlr->v1->n, vlr1->n);
2536                         VecAddf(vlr->v4->n, vlr->v4->n, vlr1->n);
2537                 }
2538         }
2539         /* last vertex is an extra case: 
2540                 
2541                 ^       ()----()----()----()
2542                 |       |     |     ||     |
2543                 u       |     |(0,n)||(0,0)|
2544                 |     |     ||     |
2545                 ()====()====[]====()
2546                 |     |     ||     |
2547                 |     |(m,n)||(m,0)|
2548                 |     |     ||     |
2549                 ()----()----()----()
2550                 v ->
2551                 
2552                 vertex [] is no longer shared, therefore distribute
2553                 normals of the surrounding faces to all of the duplicates of []
2554                 */
2555         
2556         if ((dl->flag & DL_CYCL_V) && (dl->flag & DL_CYCL_U))
2557         {
2558                 vlr= RE_findOrAddVlak(obr, UVTOINDEX(sizeu - 1, sizev - 1)); /* (m,n) */
2559                 vlr1= RE_findOrAddVlak(obr, UVTOINDEX(0,0));  /* (0,0) */
2560                 VecAddf(n1, vlr->n, vlr1->n);
2561                 vlr2= RE_findOrAddVlak(obr, UVTOINDEX(0, sizev-1)); /* (0,n) */
2562                 VecAddf(n1, n1, vlr2->n);
2563                 vlr3= RE_findOrAddVlak(obr, UVTOINDEX(sizeu-1, 0)); /* (m,0) */
2564                 VecAddf(n1, n1, vlr3->n);
2565                 VECCOPY(vlr->v3->n, n1);
2566                 VECCOPY(vlr1->v1->n, n1);
2567                 VECCOPY(vlr2->v2->n, n1);
2568                 VECCOPY(vlr3->v4->n, n1);
2569         }
2570         for(a = startvert; a < obr->totvert; a++) {
2571                 ver= RE_findOrAddVert(obr, a);
2572                 Normalize(ver->n);
2573         }
2574         
2575         
2576         return orcoret;
2577 }
2578
2579 static void init_render_surf(Render *re, ObjectRen *obr)
2580 {
2581         Object *ob= obr->ob;
2582         Nurb *nu=0;
2583         Curve *cu;
2584         ListBase displist;
2585         DispList *dl;
2586         Material **matar;
2587         float *orco=NULL, *orcobase=NULL, mat[4][4];
2588         int a, totmat, need_orco=0;
2589
2590         cu= ob->data;
2591         nu= cu->nurb.first;
2592         if(nu==0) return;
2593
2594         MTC_Mat4MulMat4(mat, ob->obmat, re->viewmat);
2595         MTC_Mat4Invert(ob->imat, mat);
2596
2597         /* material array */
2598         totmat= ob->totcol+1;
2599         matar= MEM_callocN(sizeof(Material*)*totmat, "init_render_surf matar");
2600
2601         for(a=0; a<totmat; a++) {
2602                 matar[a]= give_render_material(re, ob, a+1);
2603
2604                 if(matar[a] && matar[a]->texco & TEXCO_ORCO)
2605                         need_orco= 1;
2606         }
2607
2608         if(ob->parent && (ob->parent->type==OB_LATTICE)) need_orco= 1;
2609
2610         if(need_orco) orcobase= orco= get_object_orco(re, ob);
2611
2612         displist.first= displist.last= 0;
2613         makeDispListSurf(re->scene, ob, &displist, 1, 0);
2614
2615         /* walk along displaylist and create rendervertices/-faces */
2616         for(dl=displist.first; dl; dl=dl->next) {
2617                 /* watch out: u ^= y, v ^= x !! */
2618                 if(dl->type==DL_SURF)
2619                         orco+= 3*dl_surf_to_renderdata(obr, dl, matar, orco, mat);
2620         }
2621
2622         freedisplist(&displist);
2623         MEM_freeN(matar);
2624 }
2625
2626 static void init_render_curve(Render *re, ObjectRen *obr, int timeoffset)
2627 {
2628         Object *ob= obr->ob;
2629         Curve *cu;
2630         VertRen *ver;
2631         VlakRen *vlr;
2632         DispList *dl;
2633         ListBase olddl={NULL, NULL};
2634         Material **matar;
2635         float len, *data, *fp, *orco=NULL, *orcobase= NULL;
2636         float n[3], mat[4][4];
2637         int nr, startvert, startvlak, a, b;
2638         int frontside, need_orco=0, totmat;
2639
2640         cu= ob->data;
2641         if(ob->type==OB_FONT && cu->str==NULL) return;
2642         else if(ob->type==OB_CURVE && cu->nurb.first==NULL) return;
2643
2644         /* no modifier call here, is in makedisp */
2645
2646         if(cu->resolu_ren) 
2647                 SWAP(ListBase, olddl, cu->disp);
2648         
2649         /* test displist */
2650         if(cu->disp.first==NULL) 
2651                 makeDispListCurveTypes(re->scene, ob, 0);
2652         dl= cu->disp.first;
2653         if(cu->disp.first==NULL) return;
2654         
2655         MTC_Mat4MulMat4(mat, ob->obmat, re->viewmat);
2656         MTC_Mat4Invert(ob->imat, mat);
2657
2658         /* material array */
2659         totmat= ob->totcol+1;
2660         matar= MEM_callocN(sizeof(Material*)*totmat, "init_render_surf matar");
2661
2662         for(a=0; a<totmat; a++) {
2663                 matar[a]= give_render_material(re, ob, a+1);
2664
2665                 if(matar[a] && matar[a]->texco & TEXCO_ORCO)
2666                         need_orco= 1;
2667         }
2668
2669         if(need_orco) orcobase=orco= get_object_orco(re, ob);
2670
2671         dl= cu->disp.first;
2672         while(dl) {
2673                 if(dl->type==DL_INDEX3) {
2674                         int *index;
2675
2676                         startvert= obr->totvert;
2677                         data= dl->verts;
2678
2679                         n[0]= ob->imat[0][2];
2680                         n[1]= ob->imat[1][2];
2681                         n[2]= ob->imat[2][2];
2682                         Normalize(n);
2683
2684                         for(a=0; a<dl->nr; a++, data+=3) {
2685                                 ver= RE_findOrAddVert(obr, obr->totvert++);
2686                                 VECCOPY(ver->co, data);
2687
2688                                 /* flip normal if face is backfacing, also used in face loop below */
2689                                 if(ver->co[2] < 0.0) {
2690                                         VECCOPY(ver->n, n);
2691                                         ver->flag = 1;
2692                                 }
2693                                 else {
2694                                         ver->n[0]= -n[0]; ver->n[1]= -n[1]; ver->n[2]= -n[2];
2695                                         ver->flag = 0;
2696                                 }
2697
2698                                 MTC_Mat4MulVecfl(mat, ver->co);
2699                                 
2700                                 if (orco) {
2701                                         ver->orco = orco;
2702                                         orco += 3;
2703                                 }
2704                         }
2705                         
2706                         if(timeoffset==0) {
2707                                 startvlak= obr->totvlak;
2708                                 index= dl->index;
2709                                 for(a=0; a<dl->parts; a++, index+=3) {
2710
2711                                         vlr= RE_findOrAddVlak(obr, obr->totvlak++);
2712                                         vlr->v1= RE_findOrAddVert(obr, startvert+index[0]);
2713                                         vlr->v2= RE_findOrAddVert(obr, startvert+index[1]);
2714                                         vlr->v3= RE_findOrAddVert(obr, startvert+index[2]);
2715                                         vlr->v4= NULL;
2716                                         
2717                                         if(vlr->v1->flag) {
2718                                                 VECCOPY(vlr->n, n);
2719                                         }
2720                                         else {
2721                                                 vlr->n[0]= -n[0]; vlr->n[1]= -n[1]; vlr->n[2]= -n[2];
2722                                         }
2723                                         
2724                                         vlr->mat= matar[ dl->col ];
2725                                         vlr->flag= 0;
2726                                         if( (cu->flag & CU_NOPUNOFLIP) ) {
2727                                                 vlr->flag |= R_NOPUNOFLIP;
2728                                         }
2729                                         vlr->ec= 0;
2730                                 }
2731                         }
2732                 }
2733                 else if (dl->type==DL_SURF) {
2734                         
2735                         /* cyclic U means an extruded full circular curve, we skip bevel splitting then */
2736                         if (dl->flag & DL_CYCL_U) {
2737                                 orco+= 3*dl_surf_to_renderdata(obr, dl, matar, orco, mat);
2738                         }
2739                         else {
2740                                 int p1,p2,p3,p4;
2741
2742                                 fp= dl->verts;
2743                                 startvert= obr->totvert;
2744                                 nr= dl->nr*dl->parts;
2745
2746                                 while(nr--) {
2747                                         ver= RE_findOrAddVert(obr, obr->totvert++);
2748                                                 
2749                                         VECCOPY(ver->co, fp);
2750                                         MTC_Mat4MulVecfl(mat, ver->co);
2751                                         fp+= 3;
2752
2753                                         if (orco) {
2754                                                 ver->orco = orco;
2755                                                 orco += 3;
2756                                         }
2757                                 }
2758
2759                                 if(dl->bevelSplitFlag || timeoffset==0) {
2760                                         startvlak= obr->totvlak;
2761
2762                                         for(a=0; a<dl->parts; a++) {
2763
2764                                                 frontside= (a >= dl->nr/2);
2765                                                 
2766                                                 if (surfindex_displist(dl, a, &b, &p1, &p2, &p3, &p4)==0)
2767                                                         break;
2768                                                 
2769                                                 p1+= startvert;
2770                                                 p2+= startvert;
2771                                                 p3+= startvert;
2772                                                 p4+= startvert;
2773
2774                                                 for(; b<dl->nr; b++) {
2775                                                         vlr= RE_findOrAddVlak(obr, obr->totvlak++);
2776                                                         vlr->v1= RE_findOrAddVert(obr, p2);
2777                                                         vlr->v2= RE_findOrAddVert(obr, p1);
2778                                                         vlr->v3= RE_findOrAddVert(obr, p3);
2779                                                         vlr->v4= RE_findOrAddVert(obr, p4);
2780                                                         vlr->ec= ME_V2V3+ME_V3V4;
2781                                                         if(a==0) vlr->ec+= ME_V1V2;
2782
2783                                                         vlr->flag= dl->rt;
2784
2785                                                         /* this is not really scientific: the vertices
2786                                                                 * 2, 3 en 4 seem to give better vertexnormals than 1 2 3:
2787                                                                 * front and backside treated different!!
2788                                                                 */
2789
2790                                                         if(frontside)
2791                                                                 CalcNormFloat(vlr->v2->co, vlr->v3->co, vlr->v4->co, vlr->n);
2792                                                         else 
2793                                                                 CalcNormFloat(vlr->v1->co, vlr->v2->co, vlr->v3->co, vlr->n);
2794
2795                                                         vlr->mat= matar[ dl->col ];
2796
2797                                                         p4= p3;
2798                                                         p3++;
2799                                                         p2= p1;
2800                                                         p1++;
2801                                                 }
2802                                         }
2803
2804                                         if (dl->bevelSplitFlag) {
2805                                                 for(a=0; a<dl->parts-1+!!(dl->flag&DL_CYCL_V); a++)
2806                                                         if(dl->bevelSplitFlag[a>>5]&(1<<(a&0x1F)))
2807                                                                 split_v_renderfaces(obr, startvlak, startvert, dl->parts, dl->nr, a, dl->flag&DL_CYCL_V, dl->flag&DL_CYCL_U);
2808                                         }
2809
2810                                         /* vertex normals */
2811                                         for(a= startvlak; a<obr->totvlak; a++) {
2812                                                 vlr= RE_findOrAddVlak(obr, a);
2813
2814                                                 VecAddf(vlr->v1->n, vlr->v1->n, vlr->n);
2815                                                 VecAddf(vlr->v3->n, vlr->v3->n, vlr->n);
2816                                                 VecAddf(vlr->v2->n, vlr->v2->n, vlr->n);
2817                                                 VecAddf(vlr->v4->n, vlr->v4->n, vlr->n);
2818                                         }
2819                                         for(a=startvert; a<obr->totvert; a++) {
2820                                                 ver= RE_findOrAddVert(obr, a);
2821                                                 len= Normalize(ver->n);
2822                                                 if(len==0.0) ver->flag= 1;      /* flag abuse, its only used in zbuf now  */
2823                                                 else ver->flag= 0;
2824                                         }
2825                                         for(a= startvlak; a<obr->totvlak; a++) {
2826                                                 vlr= RE_findOrAddVlak(obr, a);
2827                                                 if(vlr->v1->flag) VECCOPY(vlr->v1->n, vlr->n);
2828                                                 if(vlr->v2->flag) VECCOPY(vlr->v2->n, vlr->n);
2829                                                 if(vlr->v3->flag) VECCOPY(vlr->v3->n, vlr->n);
2830                                                 if(vlr->v4->flag) VECCOPY(vlr->v4->n, vlr->n);
2831                                         }
2832                                 }
2833                         }
2834                 }
2835
2836                 dl= dl->next;
2837         }
2838         
2839         /* not very elegant... but we want original displist in UI */
2840         if(cu->resolu_ren) {
2841                 freedisplist(&cu->disp);
2842                 SWAP(ListBase, olddl, cu->disp);
2843         }
2844
2845         MEM_freeN(matar);
2846 }
2847
2848 /* ------------------------------------------------------------------------- */
2849 /* Mesh                                                                                                                                  */
2850 /* ------------------------------------------------------------------------- */
2851
2852 struct edgesort {
2853         int v1, v2;
2854         int f;
2855         int i1, i2;
2856 };
2857
2858 /* edges have to be added with lowest index first for sorting */
2859 static void to_edgesort(struct edgesort *ed, int i1, int i2, int v1, int v2, int f)
2860 {
2861         if(v1>v2) {
2862                 SWAP(int, v1, v2);
2863                 SWAP(int, i1, i2);
2864         }
2865
2866         ed->v1= v1;
2867         ed->v2= v2;
2868         ed->i1= i1;
2869         ed->i2= i2;
2870         ed->f = f;
2871 }
2872
2873 static int vergedgesort(const void *v1, const void *v2)
2874 {
2875         const struct edgesort *x1=v1, *x2=v2;
2876         
2877         if( x1->v1 > x2->v1) return 1;
2878         else if( x1->v1 < x2->v1) return -1;
2879         else if( x1->v2 > x2->v2) return 1;
2880         else if( x1->v2 < x2->v2) return -1;
2881         
2882         return 0;
2883 }
2884
2885 static struct edgesort *make_mesh_edge_lookup(DerivedMesh *dm, int *totedgesort)
2886 {
2887         MFace *mf, *mface;
2888         MTFace *tface=NULL;
2889         struct edgesort *edsort, *ed;
2890         unsigned int *mcol=NULL;
2891         int a, totedge=0, totface;
2892         
2893         mface= dm->getTessFaceArray(dm);
2894         totface= dm->getNumTessFaces(dm);
2895         tface= dm->getTessFaceDataArray(dm, CD_MTFACE);
2896         mcol= dm->getTessFaceDataArray(dm, CD_MCOL);
2897         
2898         if(mcol==NULL && tface==NULL) return NULL;
2899         
2900         /* make sorted table with edges and face in