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