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