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