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