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