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