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