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