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