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