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