Welcome to mirror list, hosted at ThFree Co, Russian Federation.

git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
path: root/source
diff options
context:
space:
mode:
authorBrecht Van Lommel <brechtvanlommel@pandora.be>2008-11-13 00:16:53 +0300
committerBrecht Van Lommel <brechtvanlommel@pandora.be>2008-11-13 00:16:53 +0300
commitbdfe7d89e2f1292644577972c716931b4ce3c6c3 (patch)
treed00eb50b749cb001e2b08272c91791e66740b05d /source
parent78a1c27c4a6abe0ed31ca93ad21910f3df04da56 (diff)
parent7e4db234cee71ead34ee81a12e27da4bd548eb4b (diff)
Merge of trunk into blender 2.5:
svn merge https://svn.blender.org/svnroot/bf-blender/trunk/blender -r12987:17416 Issues: * GHOST/X11 had conflicting changes. Some code was added in 2.5, which was later added in trunk also, but reverted partially, specifically revision 16683. I have left out this reversion in the 2.5 branch since I think it is needed there. http://projects.blender.org/plugins/scmsvn/viewcvs.php?view=rev&root=bf-blender&revision=16683 * Scons had various conflicting changes, I decided to go with trunk version for everything except priorities and some library renaming. * In creator.c, there were various fixes and fixes for fixes related to the -w -W and -p options. In 2.5 -w and -W is not coded yet, and -p is done differently. Since this is changed so much, and I don't think those fixes would be needed in 2.5, I've left them out. * Also in creator.c: there was code for a python bugfix where the screen was not initialized when running with -P. The code that initializes the screen there I had to disable, that can't work in 2.5 anymore but left it commented as a reminder. Further I had to disable some new function calls. using src/ and python/, as was done already in this branch, disabled function calls: * bpath.c: error reporting * BME_conversions.c: editmesh conversion functions. * SHD_dynamic: disabled almost completely, there is no python/. * KX_PythonInit.cpp and Ketsji/ build files: Mathutils is not there, disabled. * text.c: clipboard copy call. * object.c: OB_SUPPORT_MATERIAL. * DerivedMesh.c and subsurf_ccg, stipple_quarttone. Still to be done: * Go over files and functions that were moved to a different location but could still use changes that were done in trunk.
Diffstat (limited to 'source')
-rw-r--r--source/Makefile28
-rw-r--r--source/SConscript2
-rw-r--r--source/blender/CMakeLists.txt6
-rw-r--r--source/blender/Makefile5
-rw-r--r--source/blender/SConscript65
-rw-r--r--source/blender/avi/SConscript2
-rw-r--r--source/blender/avi/intern/avi.c192
-rw-r--r--source/blender/avi/intern/avirgb.c2
-rw-r--r--source/blender/avi/intern/endian.c4
-rw-r--r--source/blender/blenkernel/BKE_DerivedMesh.h72
-rw-r--r--source/blender/blenkernel/BKE_action.h14
-rw-r--r--source/blender/blenkernel/BKE_anim.h5
-rw-r--r--source/blender/blenkernel/BKE_armature.h2
-rw-r--r--source/blender/blenkernel/BKE_bmesh.h253
-rw-r--r--source/blender/blenkernel/BKE_bmeshCustomData.h108
-rw-r--r--source/blender/blenkernel/BKE_brush.h2
-rw-r--r--source/blender/blenkernel/BKE_bullet.h43
-rw-r--r--source/blender/blenkernel/BKE_bvhutils.h98
-rw-r--r--source/blender/blenkernel/BKE_cloth.h282
-rw-r--r--source/blender/blenkernel/BKE_collision.h150
-rw-r--r--source/blender/blenkernel/BKE_colortools.h1
-rw-r--r--source/blender/blenkernel/BKE_constraint.h10
-rw-r--r--source/blender/blenkernel/BKE_curve.h19
-rw-r--r--source/blender/blenkernel/BKE_customdata.h33
-rw-r--r--source/blender/blenkernel/BKE_deform.h4
-rw-r--r--source/blender/blenkernel/BKE_depsgraph.h2
-rw-r--r--source/blender/blenkernel/BKE_displist.h23
-rw-r--r--source/blender/blenkernel/BKE_effect.h14
-rw-r--r--source/blender/blenkernel/BKE_endian.h6
-rw-r--r--source/blender/blenkernel/BKE_fluidsim.h56
-rw-r--r--source/blender/blenkernel/BKE_font.h10
-rw-r--r--source/blender/blenkernel/BKE_global.h27
-rw-r--r--source/blender/blenkernel/BKE_group.h5
-rw-r--r--source/blender/blenkernel/BKE_idprop.h6
-rw-r--r--source/blender/blenkernel/BKE_image.h7
-rw-r--r--source/blender/blenkernel/BKE_ipo.h61
-rw-r--r--source/blender/blenkernel/BKE_key.h11
-rw-r--r--source/blender/blenkernel/BKE_lattice.h3
-rw-r--r--source/blender/blenkernel/BKE_main.h2
-rw-r--r--source/blender/blenkernel/BKE_mball.h7
-rw-r--r--source/blender/blenkernel/BKE_mesh.h7
-rw-r--r--source/blender/blenkernel/BKE_modifier.h2
-rw-r--r--source/blender/blenkernel/BKE_multires.h2
-rw-r--r--source/blender/blenkernel/BKE_node.h85
-rw-r--r--source/blender/blenkernel/BKE_object.h13
-rw-r--r--source/blender/blenkernel/BKE_particle.h39
-rw-r--r--source/blender/blenkernel/BKE_plugin_types.h5
-rw-r--r--source/blender/blenkernel/BKE_pointcache.h77
-rw-r--r--source/blender/blenkernel/BKE_property.h3
-rw-r--r--source/blender/blenkernel/BKE_scene.h11
-rw-r--r--source/blender/blenkernel/BKE_screen.h2
-rw-r--r--source/blender/blenkernel/BKE_sculpt.h26
-rw-r--r--source/blender/blenkernel/BKE_shrinkwrap.h150
-rw-r--r--source/blender/blenkernel/BKE_simple_deform.h39
-rw-r--r--source/blender/blenkernel/BKE_softbody.h8
-rw-r--r--source/blender/blenkernel/BKE_suggestions.h93
-rw-r--r--source/blender/blenkernel/BKE_text.h30
-rw-r--r--source/blender/blenkernel/BKE_texture.h3
-rw-r--r--source/blender/blenkernel/BKE_utildefines.h35
-rw-r--r--source/blender/blenkernel/BKE_writeffmpeg.h12
-rw-r--r--source/blender/blenkernel/BKE_writeframeserver.h2
-rw-r--r--source/blender/blenkernel/CMakeLists.txt16
-rw-r--r--source/blender/blenkernel/SConscript49
-rw-r--r--source/blender/blenkernel/depsgraph_private.h3
-rw-r--r--source/blender/blenkernel/intern/BME_Customdata.c199
-rw-r--r--source/blender/blenkernel/intern/BME_conversions.c646
-rw-r--r--source/blender/blenkernel/intern/BME_eulers.c977
-rw-r--r--source/blender/blenkernel/intern/BME_mesh.c285
-rw-r--r--source/blender/blenkernel/intern/BME_structure.c627
-rw-r--r--source/blender/blenkernel/intern/BME_tools.c1323
-rw-r--r--source/blender/blenkernel/intern/CCGSubSurf.c114
-rw-r--r--source/blender/blenkernel/intern/CCGSubSurf.h28
-rw-r--r--source/blender/blenkernel/intern/DerivedMesh.c1270
-rw-r--r--source/blender/blenkernel/intern/Makefile8
-rw-r--r--source/blender/blenkernel/intern/action.c200
-rw-r--r--source/blender/blenkernel/intern/anim.c552
-rw-r--r--source/blender/blenkernel/intern/armature.c244
-rw-r--r--source/blender/blenkernel/intern/blender.c76
-rw-r--r--source/blender/blenkernel/intern/bmesh_private.h70
-rw-r--r--source/blender/blenkernel/intern/brush.c24
-rw-r--r--source/blender/blenkernel/intern/bullet.c96
-rw-r--r--source/blender/blenkernel/intern/bvhutils.c577
-rw-r--r--source/blender/blenkernel/intern/cdderivedmesh.c165
-rw-r--r--source/blender/blenkernel/intern/cloth.c1290
-rw-r--r--source/blender/blenkernel/intern/collision.c1677
-rw-r--r--source/blender/blenkernel/intern/colortools.c57
-rw-r--r--source/blender/blenkernel/intern/constraint.c526
-rw-r--r--source/blender/blenkernel/intern/curve.c605
-rw-r--r--source/blender/blenkernel/intern/customdata.c432
-rw-r--r--source/blender/blenkernel/intern/deform.c25
-rw-r--r--source/blender/blenkernel/intern/depsgraph.c514
-rw-r--r--source/blender/blenkernel/intern/displist.c114
-rw-r--r--source/blender/blenkernel/intern/effect.c2107
-rw-r--r--source/blender/blenkernel/intern/exotic.c34
-rw-r--r--source/blender/blenkernel/intern/fluidsim.c660
-rw-r--r--source/blender/blenkernel/intern/font.c84
-rw-r--r--source/blender/blenkernel/intern/group.c75
-rw-r--r--source/blender/blenkernel/intern/icons.c17
-rw-r--r--source/blender/blenkernel/intern/idprop.c40
-rw-r--r--source/blender/blenkernel/intern/image.c588
-rw-r--r--source/blender/blenkernel/intern/implicit.c1709
-rw-r--r--source/blender/blenkernel/intern/ipo.c3733
-rw-r--r--source/blender/blenkernel/intern/key.c24
-rw-r--r--source/blender/blenkernel/intern/lattice.c61
-rw-r--r--source/blender/blenkernel/intern/library.c79
-rw-r--r--source/blender/blenkernel/intern/material.c29
-rw-r--r--source/blender/blenkernel/intern/mball.c198
-rw-r--r--source/blender/blenkernel/intern/mesh.c58
-rw-r--r--source/blender/blenkernel/intern/modifier.c4001
-rw-r--r--source/blender/blenkernel/intern/multires-firstlevel.c10
-rw-r--r--source/blender/blenkernel/intern/multires.c18
-rw-r--r--source/blender/blenkernel/intern/node.c579
-rw-r--r--source/blender/blenkernel/intern/object.c453
-rw-r--r--source/blender/blenkernel/intern/packedFile.c10
-rw-r--r--source/blender/blenkernel/intern/particle.c1482
-rw-r--r--source/blender/blenkernel/intern/particle_system.c2493
-rw-r--r--source/blender/blenkernel/intern/pointcache.c493
-rw-r--r--source/blender/blenkernel/intern/property.c16
-rw-r--r--source/blender/blenkernel/intern/sca.c16
-rw-r--r--source/blender/blenkernel/intern/scene.c139
-rw-r--r--source/blender/blenkernel/intern/screen.c4
-rw-r--r--source/blender/blenkernel/intern/script.c18
-rw-r--r--source/blender/blenkernel/intern/shrinkwrap.c599
-rw-r--r--source/blender/blenkernel/intern/simple_deform.c256
-rw-r--r--source/blender/blenkernel/intern/softbody.c2337
-rw-r--r--source/blender/blenkernel/intern/sound.c6
-rw-r--r--source/blender/blenkernel/intern/subsurf_ccg.c449
-rw-r--r--source/blender/blenkernel/intern/suggestions.c254
-rw-r--r--source/blender/blenkernel/intern/text.c610
-rw-r--r--source/blender/blenkernel/intern/texture.c77
-rw-r--r--source/blender/blenkernel/intern/world.c19
-rw-r--r--source/blender/blenkernel/intern/writeavi.c2
-rw-r--r--source/blender/blenkernel/intern/writeffmpeg.c136
-rw-r--r--source/blender/blenkernel/intern/writeframeserver.c2
-rw-r--r--source/blender/blenlib/BLI_arithb.h38
-rw-r--r--source/blender/blenlib/BLI_blenlib.h44
-rw-r--r--source/blender/blenlib/BLI_bpath.h38
-rw-r--r--source/blender/blenlib/BLI_edgehash.h3
-rw-r--r--source/blender/blenlib/BLI_editVert.h10
-rw-r--r--source/blender/blenlib/BLI_ghash.h16
-rw-r--r--source/blender/blenlib/BLI_graph.h125
-rw-r--r--source/blender/blenlib/BLI_kdopbvh.h97
-rw-r--r--source/blender/blenlib/BLI_mempool.h44
-rw-r--r--source/blender/blenlib/BLI_rand.h1
-rw-r--r--source/blender/blenlib/BLI_threads.h27
-rw-r--r--source/blender/blenlib/BLI_winstuff.h14
-rw-r--r--source/blender/blenlib/CMakeLists.txt7
-rw-r--r--source/blender/blenlib/SConscript15
-rw-r--r--source/blender/blenlib/intern/BLI_ghash.c25
-rw-r--r--source/blender/blenlib/intern/BLI_kdopbvh.c1526
-rw-r--r--source/blender/blenlib/intern/BLI_kdtree.c34
-rw-r--r--source/blender/blenlib/intern/BLI_mempool.c140
-rw-r--r--source/blender/blenlib/intern/BLI_storage.h7
-rw-r--r--source/blender/blenlib/intern/Makefile3
-rw-r--r--source/blender/blenlib/intern/arithb.c761
-rw-r--r--source/blender/blenlib/intern/boxpack2d.c12
-rw-r--r--source/blender/blenlib/intern/bpath.c355
-rw-r--r--source/blender/blenlib/intern/dynlib.c9
-rw-r--r--source/blender/blenlib/intern/edgehash.c19
-rw-r--r--source/blender/blenlib/intern/fileops.c108
-rw-r--r--source/blender/blenlib/intern/freetypefont.c4
-rw-r--r--source/blender/blenlib/intern/graph.c1087
-rw-r--r--source/blender/blenlib/intern/noise.c564
-rw-r--r--source/blender/blenlib/intern/psfont.c566
-rw-r--r--source/blender/blenlib/intern/rand.c18
-rw-r--r--source/blender/blenlib/intern/storage.c50
-rw-r--r--source/blender/blenlib/intern/threads.c173
-rw-r--r--source/blender/blenlib/intern/util.c505
-rw-r--r--source/blender/blenlib/intern/winstuff.c21
-rw-r--r--source/blender/blenloader/BLO_readfile.h4
-rw-r--r--source/blender/blenloader/BLO_soundfile.h2
-rw-r--r--source/blender/blenloader/BLO_sys_types.h29
-rw-r--r--source/blender/blenloader/SConscript3
-rw-r--r--source/blender/blenloader/intern/readblenentry.c7
-rw-r--r--source/blender/blenloader/intern/readfile.c1296
-rw-r--r--source/blender/blenloader/intern/readfile.h5
-rw-r--r--source/blender/blenloader/intern/writefile.c228
-rw-r--r--source/blender/blenpluginapi/SConscript4
-rw-r--r--source/blender/blenpluginapi/externdef.h5
-rw-r--r--source/blender/blenpluginapi/iff.h67
-rw-r--r--source/blender/blenpluginapi/intern/pluginapi.c80
-rw-r--r--source/blender/blenpluginapi/plugin.h19
-rw-r--r--source/blender/editors/datafiles/SConscript2
-rw-r--r--source/blender/editors/include/BIF_gl.h14
-rw-r--r--source/blender/editors/include/BIF_interface_icons.h0
-rw-r--r--source/blender/editors/include/BIF_resources.h0
-rw-r--r--source/blender/editors/include/BIF_view2d.h0
-rw-r--r--source/blender/editors/interface/Makefile6
-rw-r--r--source/blender/editors/interface/SConscript10
-rw-r--r--source/blender/editors/screen/Makefile1
-rw-r--r--source/blender/editors/screen/SConscript2
-rw-r--r--source/blender/editors/screen/glutil.c1
-rw-r--r--source/blender/editors/space_time/Makefile1
-rw-r--r--source/blender/editors/space_time/SConscript2
-rw-r--r--source/blender/editors/space_view3d/Makefile1
-rw-r--r--source/blender/editors/space_view3d/SConscript2
-rw-r--r--source/blender/ftfont/intern/FTF_TTFont.cpp44
-rw-r--r--source/blender/gpu/CMakeLists.txt34
-rw-r--r--source/blender/gpu/GPU_draw.h116
-rw-r--r--source/blender/gpu/GPU_extensions.h145
-rw-r--r--source/blender/gpu/GPU_material.h169
-rw-r--r--source/blender/gpu/Makefile37
-rw-r--r--source/blender/gpu/SConscript11
-rw-r--r--source/blender/gpu/intern/Makefile53
-rw-r--r--source/blender/gpu/intern/gpu_codegen.c1445
-rw-r--r--source/blender/gpu/intern/gpu_codegen.h87
-rw-r--r--source/blender/gpu/intern/gpu_draw.c1185
-rw-r--r--source/blender/gpu/intern/gpu_extensions.c998
-rw-r--r--source/blender/gpu/intern/gpu_material.c1502
-rw-r--r--source/blender/gpu/intern/gpu_shader_material.glsl1555
-rw-r--r--source/blender/gpu/intern/gpu_shader_material.glsl.c1032
-rw-r--r--source/blender/gpu/intern/gpu_shader_vertex.glsl12
-rw-r--r--source/blender/gpu/intern/gpu_shader_vertex.glsl.c13
-rw-r--r--source/blender/imbuf/CMakeLists.txt4
-rw-r--r--source/blender/imbuf/IMB_imbuf.h2
-rw-r--r--source/blender/imbuf/IMB_imbuf_types.h4
-rw-r--r--source/blender/imbuf/SConscript28
-rw-r--r--source/blender/imbuf/intern/IMB_anim.h17
-rw-r--r--source/blender/imbuf/intern/allocimbuf.c4
-rw-r--r--source/blender/imbuf/intern/amiga.c8
-rw-r--r--source/blender/imbuf/intern/anim.c270
-rw-r--r--source/blender/imbuf/intern/bmp.c4
-rw-r--r--source/blender/imbuf/intern/cineon/SConscript14
-rw-r--r--source/blender/imbuf/intern/cineon/cineon_dpx.c32
-rw-r--r--source/blender/imbuf/intern/cineon/cineonlib.c46
-rw-r--r--source/blender/imbuf/intern/cineon/dpxlib.c93
-rw-r--r--source/blender/imbuf/intern/cineon/logImageCore.c29
-rw-r--r--source/blender/imbuf/intern/cineon/logImageCore.h10
-rw-r--r--source/blender/imbuf/intern/cineon/logImageLib.c5
-rw-r--r--source/blender/imbuf/intern/cineon/logImageLib.h1
-rw-r--r--source/blender/imbuf/intern/cineon/logmemfile.c6
-rw-r--r--source/blender/imbuf/intern/cineon/logmemfile.h2
-rw-r--r--source/blender/imbuf/intern/dds/BlockDXT.cpp214
-rw-r--r--source/blender/imbuf/intern/dds/BlockDXT.h137
-rw-r--r--source/blender/imbuf/intern/dds/CMakeLists.txt45
-rw-r--r--source/blender/imbuf/intern/dds/ColorBlock.cpp117
-rw-r--r--source/blender/imbuf/intern/dds/ColorBlock.h27
-rw-r--r--source/blender/imbuf/intern/dds/Common.h18
-rw-r--r--source/blender/imbuf/intern/dds/DirectDrawSurface.cpp875
-rw-r--r--source/blender/imbuf/intern/dds/DirectDrawSurface.h115
-rw-r--r--source/blender/imbuf/intern/dds/Image.cpp14
-rw-r--r--source/blender/imbuf/intern/dds/Image.h29
-rw-r--r--source/blender/imbuf/intern/dds/PixelFormat.h107
-rw-r--r--source/blender/imbuf/intern/dds/dds_api.cpp1
-rw-r--r--source/blender/imbuf/intern/divers.c2
-rw-r--r--source/blender/imbuf/intern/dynlibtiff.c15
-rw-r--r--source/blender/imbuf/intern/filter.c122
-rwxr-xr-xsource/blender/imbuf/intern/gen_dynlibtiff.py8
-rw-r--r--source/blender/imbuf/intern/hamx.c2
-rw-r--r--source/blender/imbuf/intern/imageprocess.c87
-rw-r--r--source/blender/imbuf/intern/imbuf.h2
-rw-r--r--source/blender/imbuf/intern/imbuf_patch.h2
-rw-r--r--source/blender/imbuf/intern/openexr/openexr_api.cpp143
-rw-r--r--source/blender/imbuf/intern/openexr/openexr_multi.h8
-rw-r--r--source/blender/imbuf/intern/radiance_hdr.c26
-rw-r--r--source/blender/imbuf/intern/readimage.c12
-rw-r--r--source/blender/imbuf/intern/rectop.c17
-rw-r--r--source/blender/imbuf/intern/rotate.c61
-rw-r--r--source/blender/imbuf/intern/scaling.c475
-rw-r--r--source/blender/imbuf/intern/thumbs.c7
-rw-r--r--source/blender/imbuf/intern/tiff.c134
-rw-r--r--source/blender/imbuf/intern/util.c57
-rw-r--r--source/blender/makesdna/DNA_ID.h5
-rw-r--r--source/blender/makesdna/DNA_action_types.h113
-rw-r--r--source/blender/makesdna/DNA_actuator_types.h130
-rw-r--r--source/blender/makesdna/DNA_armature_types.h12
-rw-r--r--source/blender/makesdna/DNA_brush_types.h4
-rw-r--r--source/blender/makesdna/DNA_cloth_types.h95
-rw-r--r--source/blender/makesdna/DNA_color_types.h5
-rw-r--r--source/blender/makesdna/DNA_constraint_types.h42
-rw-r--r--source/blender/makesdna/DNA_controller_types.h7
-rw-r--r--source/blender/makesdna/DNA_curve_types.h45
-rw-r--r--source/blender/makesdna/DNA_customdata_types.h12
-rw-r--r--source/blender/makesdna/DNA_gpencil_types.h145
-rw-r--r--source/blender/makesdna/DNA_group_types.h2
-rw-r--r--source/blender/makesdna/DNA_image_types.h8
-rw-r--r--source/blender/makesdna/DNA_ipo_types.h170
-rw-r--r--source/blender/makesdna/DNA_lamp_types.h40
-rw-r--r--source/blender/makesdna/DNA_material_types.h24
-rw-r--r--source/blender/makesdna/DNA_meshdata_types.h31
-rw-r--r--source/blender/makesdna/DNA_modifier_types.h157
-rw-r--r--source/blender/makesdna/DNA_node_types.h43
-rw-r--r--source/blender/makesdna/DNA_object_fluidsim.h20
-rw-r--r--source/blender/makesdna/DNA_object_force.h95
-rw-r--r--source/blender/makesdna/DNA_object_types.h68
-rw-r--r--source/blender/makesdna/DNA_particle_types.h61
-rw-r--r--source/blender/makesdna/DNA_scene_types.h183
-rw-r--r--source/blender/makesdna/DNA_screen_types.h3
-rw-r--r--source/blender/makesdna/DNA_scriptlink_types.h3
-rw-r--r--source/blender/makesdna/DNA_sensor_types.h34
-rw-r--r--source/blender/makesdna/DNA_sequence_types.h71
-rw-r--r--source/blender/makesdna/DNA_space_types.h100
-rw-r--r--source/blender/makesdna/DNA_text_types.h25
-rw-r--r--source/blender/makesdna/DNA_texture_types.h18
-rw-r--r--source/blender/makesdna/DNA_userdef_types.h76
-rw-r--r--source/blender/makesdna/DNA_view3d_types.h42
-rw-r--r--source/blender/makesdna/DNA_world_types.h14
-rw-r--r--source/blender/makesdna/intern/CMakeLists.txt2
-rw-r--r--source/blender/makesdna/intern/SConscript29
-rw-r--r--source/blender/makesdna/intern/makesdna.c23
-rw-r--r--source/blender/makesrna/intern/makesrna.c4
-rw-r--r--source/blender/nodes/CMP_node.h3
-rw-r--r--source/blender/nodes/CMakeLists.txt5
-rw-r--r--source/blender/nodes/Makefile2
-rw-r--r--source/blender/nodes/SConscript40
-rw-r--r--source/blender/nodes/SHD_node.h2
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_alphaOver.c57
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_bilateralblur.c272
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_blur.c17
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_brightness.c4
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_curves.c8
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_defocus.c31
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_directionalblur.c143
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_displace.c71
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_gamma.c5
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_glare.c18
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_hueSatVal.c2
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_idMask.c22
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_image.c54
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_math.c21
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_premulkey.c77
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_texture.c26
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_tonemap.c11
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_zcombine.c75
-rw-r--r--source/blender/nodes/intern/CMP_nodes/Makefile2
-rw-r--r--source/blender/nodes/intern/CMP_util.c193
-rw-r--r--source/blender/nodes/intern/CMP_util.h5
-rw-r--r--source/blender/nodes/intern/Makefile2
-rw-r--r--source/blender/nodes/intern/SHD_nodes/Makefile5
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_camera.c10
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_curves.c24
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_dynamic.c808
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_geom.c16
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_hueSatVal.c11
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_invert.c8
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_mapping.c17
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_material.c82
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_math.c61
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_mixRgb.c14
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_normal.c11
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_output.c16
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_rgb.c11
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_sepcombRGB.c16
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_squeeze.c8
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_texture.c17
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_valToRgb.c20
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_value.c9
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_vectMath.c31
-rw-r--r--source/blender/nodes/intern/SHD_util.c4
-rw-r--r--source/blender/nodes/intern/SHD_util.h15
-rw-r--r--source/blender/python/BPY_extern.h27
-rw-r--r--source/blender/python/Makefile4
-rw-r--r--source/blender/quicktime/SConscript10
-rw-r--r--source/blender/quicktime/apple/quicktime_export.c28
-rw-r--r--source/blender/radiosity/CMakeLists.txt4
-rw-r--r--source/blender/radiosity/SConscript2
-rw-r--r--source/blender/radiosity/intern/source/Makefile2
-rw-r--r--source/blender/radiosity/intern/source/radfactors.c18
-rw-r--r--source/blender/radiosity/intern/source/radnode.c26
-rw-r--r--source/blender/radiosity/intern/source/radpreprocess.c6
-rw-r--r--source/blender/radiosity/intern/source/radrender.c138
-rw-r--r--source/blender/readblenfile/intern/BLO_readblenfile.c2
-rw-r--r--source/blender/render/CMakeLists.txt2
-rw-r--r--source/blender/render/SConscript22
-rw-r--r--source/blender/render/extern/include/RE_pipeline.h31
-rw-r--r--source/blender/render/extern/include/RE_raytrace.h4
-rw-r--r--source/blender/render/extern/include/RE_shader_ext.h10
-rw-r--r--source/blender/render/intern/include/occlusion.h49
-rw-r--r--source/blender/render/intern/include/pixelblending.h2
-rw-r--r--source/blender/render/intern/include/pixelshading.h5
-rw-r--r--source/blender/render/intern/include/render_types.h89
-rw-r--r--source/blender/render/intern/include/rendercore.h14
-rw-r--r--source/blender/render/intern/include/renderdatabase.h12
-rw-r--r--source/blender/render/intern/include/shadbuf.h2
-rw-r--r--source/blender/render/intern/include/shading.h10
-rw-r--r--source/blender/render/intern/include/sss.h2
-rw-r--r--source/blender/render/intern/include/strand.h19
-rw-r--r--source/blender/render/intern/include/sunsky.h144
-rw-r--r--source/blender/render/intern/include/texture.h2
-rw-r--r--source/blender/render/intern/include/zbuf.h24
-rw-r--r--source/blender/render/intern/source/convertblender.c1527
-rw-r--r--source/blender/render/intern/source/envmap.c39
-rw-r--r--source/blender/render/intern/source/imagetexture.c40
-rw-r--r--source/blender/render/intern/source/initrender.c26
-rw-r--r--source/blender/render/intern/source/occlusion.c1763
-rw-r--r--source/blender/render/intern/source/pipeline.c636
-rw-r--r--source/blender/render/intern/source/pixelblending.c125
-rw-r--r--source/blender/render/intern/source/pixelshading.c154
-rw-r--r--source/blender/render/intern/source/rayshade.c316
-rw-r--r--source/blender/render/intern/source/raytrace.c35
-rw-r--r--source/blender/render/intern/source/rendercore.c1103
-rw-r--r--source/blender/render/intern/source/renderdatabase.c198
-rw-r--r--source/blender/render/intern/source/shadbuf.c61
-rw-r--r--source/blender/render/intern/source/shadeinput.c323
-rw-r--r--source/blender/render/intern/source/shadeoutput.c185
-rw-r--r--source/blender/render/intern/source/sss.c41
-rw-r--r--source/blender/render/intern/source/strand.c1186
-rw-r--r--source/blender/render/intern/source/sunsky.c499
-rw-r--r--source/blender/render/intern/source/texture.c200
-rw-r--r--source/blender/render/intern/source/zbuf.c1180
-rw-r--r--source/blender/windowmanager/SConscript2
-rw-r--r--source/blender/windowmanager/intern/Makefile1
-rw-r--r--source/blender/windowmanager/intern/wm_init_exit.c4
-rw-r--r--source/blender/yafray/intern/export_File.cpp21
-rw-r--r--source/blender/yafray/intern/export_File.h2
-rw-r--r--source/blender/yafray/intern/export_Plugin.cpp62
-rw-r--r--source/blender/yafray/intern/export_Plugin.h12
-rw-r--r--source/blender/yafray/intern/yafray_Render.cpp9
-rw-r--r--source/blender/yafray/intern/yafray_Render.h10
-rw-r--r--source/creator/CMakeLists.txt95
-rw-r--r--source/creator/Makefile7
-rw-r--r--source/creator/SConscript25
-rw-r--r--source/creator/creator.c232
-rw-r--r--source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp269
-rw-r--r--source/gameengine/BlenderRoutines/CMakeLists.txt2
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderCanvas.cpp12
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderCanvas.h12
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderGL.cpp129
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderGL.h3
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderPolyMaterial.cpp114
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderPolyMaterial.h99
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderRenderTools.cpp280
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderRenderTools.h74
-rw-r--r--source/gameengine/BlenderRoutines/Makefile5
-rw-r--r--source/gameengine/BlenderRoutines/SConscript1
-rw-r--r--source/gameengine/CMakeLists.txt1
-rw-r--r--source/gameengine/Converter/BL_ActionActuator.cpp259
-rw-r--r--source/gameengine/Converter/BL_ActionActuator.h12
-rw-r--r--source/gameengine/Converter/BL_ArmatureObject.cpp94
-rw-r--r--source/gameengine/Converter/BL_ArmatureObject.h10
-rw-r--r--source/gameengine/Converter/BL_BlenderDataConversion.cpp1414
-rw-r--r--source/gameengine/Converter/BL_DeformableGameObject.cpp55
-rw-r--r--source/gameengine/Converter/BL_DeformableGameObject.h53
-rw-r--r--source/gameengine/Converter/BL_MeshDeformer.cpp227
-rw-r--r--source/gameengine/Converter/BL_MeshDeformer.h28
-rw-r--r--source/gameengine/Converter/BL_ShapeActionActuator.cpp842
-rw-r--r--source/gameengine/Converter/BL_ShapeActionActuator.h138
-rw-r--r--source/gameengine/Converter/BL_ShapeDeformer.cpp182
-rw-r--r--source/gameengine/Converter/BL_ShapeDeformer.h88
-rw-r--r--source/gameengine/Converter/BL_SkinDeformer.cpp172
-rw-r--r--source/gameengine/Converter/BL_SkinDeformer.h56
-rw-r--r--source/gameengine/Converter/BL_SkinMeshObject.cpp186
-rw-r--r--source/gameengine/Converter/BL_SkinMeshObject.h134
-rw-r--r--source/gameengine/Converter/CMakeLists.txt1
-rw-r--r--source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp13
-rw-r--r--source/gameengine/Converter/KX_BlenderSceneConverter.cpp196
-rw-r--r--source/gameengine/Converter/KX_BlenderSceneConverter.h21
-rw-r--r--source/gameengine/Converter/KX_ConvertActuators.cpp506
-rw-r--r--source/gameengine/Converter/KX_ConvertControllers.cpp31
-rw-r--r--source/gameengine/Converter/KX_ConvertProperties.cpp15
-rw-r--r--source/gameengine/Converter/KX_ConvertSensors.cpp92
-rw-r--r--source/gameengine/Converter/KX_ConvertSensors.h1
-rw-r--r--source/gameengine/Converter/KX_IpoConvert.cpp104
-rw-r--r--source/gameengine/Converter/KX_IpoConvert.h2
-rw-r--r--source/gameengine/Converter/Makefile1
-rw-r--r--source/gameengine/Converter/SConscript2
-rw-r--r--source/gameengine/Expressions/Expression.cpp4
-rw-r--r--source/gameengine/Expressions/InputParser.cpp5
-rw-r--r--source/gameengine/Expressions/ListValue.cpp13
-rw-r--r--source/gameengine/Expressions/Makefile1
-rw-r--r--source/gameengine/Expressions/PyObjectPlus.cpp16
-rw-r--r--source/gameengine/Expressions/PyObjectPlus.h128
-rw-r--r--source/gameengine/Expressions/Value.cpp183
-rw-r--r--source/gameengine/Expressions/Value.h5
-rw-r--r--source/gameengine/GameLogic/CMakeLists.txt1
-rw-r--r--source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp333
-rw-r--r--source/gameengine/GameLogic/Joystick/SCA_Joystick.h260
-rw-r--r--source/gameengine/GameLogic/Joystick/SCA_JoystickDefines.h8
-rw-r--r--source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp89
-rw-r--r--source/gameengine/GameLogic/Joystick/SCA_JoystickPrivate.h7
-rw-r--r--source/gameengine/GameLogic/Makefile2
-rw-r--r--source/gameengine/GameLogic/SCA_2DFilterActuator.cpp118
-rw-r--r--source/gameengine/GameLogic/SCA_2DFilterActuator.h44
-rw-r--r--source/gameengine/GameLogic/SCA_ActuatorEventManager.cpp67
-rw-r--r--source/gameengine/GameLogic/SCA_ActuatorEventManager.h51
-rw-r--r--source/gameengine/GameLogic/SCA_ActuatorSensor.cpp196
-rw-r--r--source/gameengine/GameLogic/SCA_ActuatorSensor.h74
-rw-r--r--source/gameengine/GameLogic/SCA_AlwaysEventManager.cpp11
-rw-r--r--source/gameengine/GameLogic/SCA_AlwaysEventManager.h1
-rw-r--r--source/gameengine/GameLogic/SCA_AlwaysSensor.cpp7
-rw-r--r--source/gameengine/GameLogic/SCA_AlwaysSensor.h2
-rw-r--r--source/gameengine/GameLogic/SCA_DelaySensor.cpp257
-rw-r--r--source/gameengine/GameLogic/SCA_DelaySensor.h77
-rw-r--r--source/gameengine/GameLogic/SCA_EventManager.cpp17
-rw-r--r--source/gameengine/GameLogic/SCA_EventManager.h10
-rw-r--r--source/gameengine/GameLogic/SCA_IActuator.cpp10
-rw-r--r--source/gameengine/GameLogic/SCA_IActuator.h17
-rw-r--r--source/gameengine/GameLogic/SCA_IController.cpp99
-rw-r--r--source/gameengine/GameLogic/SCA_IController.h4
-rw-r--r--source/gameengine/GameLogic/SCA_ILogicBrick.cpp21
-rw-r--r--source/gameengine/GameLogic/SCA_ILogicBrick.h7
-rw-r--r--source/gameengine/GameLogic/SCA_IObject.cpp104
-rw-r--r--source/gameengine/GameLogic/SCA_IObject.h39
-rw-r--r--source/gameengine/GameLogic/SCA_IScene.cpp22
-rw-r--r--source/gameengine/GameLogic/SCA_IScene.h3
-rw-r--r--source/gameengine/GameLogic/SCA_ISensor.cpp163
-rw-r--r--source/gameengine/GameLogic/SCA_ISensor.h53
-rw-r--r--source/gameengine/GameLogic/SCA_JoystickManager.cpp43
-rw-r--r--source/gameengine/GameLogic/SCA_JoystickManager.h5
-rw-r--r--source/gameengine/GameLogic/SCA_JoystickSensor.cpp331
-rw-r--r--source/gameengine/GameLogic/SCA_JoystickSensor.h54
-rw-r--r--source/gameengine/GameLogic/SCA_KeyboardManager.cpp15
-rw-r--r--source/gameengine/GameLogic/SCA_KeyboardManager.h1
-rw-r--r--source/gameengine/GameLogic/SCA_KeyboardSensor.cpp191
-rw-r--r--source/gameengine/GameLogic/SCA_KeyboardSensor.h2
-rw-r--r--source/gameengine/GameLogic/SCA_LogicManager.cpp92
-rw-r--r--source/gameengine/GameLogic/SCA_LogicManager.h9
-rw-r--r--source/gameengine/GameLogic/SCA_MouseManager.cpp14
-rw-r--r--source/gameengine/GameLogic/SCA_MouseManager.h1
-rw-r--r--source/gameengine/GameLogic/SCA_MouseSensor.cpp51
-rw-r--r--source/gameengine/GameLogic/SCA_MouseSensor.h2
-rw-r--r--source/gameengine/GameLogic/SCA_NANDController.cpp144
-rw-r--r--source/gameengine/GameLogic/SCA_NANDController.h56
-rw-r--r--source/gameengine/GameLogic/SCA_NORController.cpp144
-rw-r--r--source/gameengine/GameLogic/SCA_NORController.h56
-rw-r--r--source/gameengine/GameLogic/SCA_PropertyActuator.cpp63
-rw-r--r--source/gameengine/GameLogic/SCA_PropertyActuator.h8
-rw-r--r--source/gameengine/GameLogic/SCA_PropertyEventManager.cpp11
-rw-r--r--source/gameengine/GameLogic/SCA_PropertyEventManager.h1
-rw-r--r--source/gameengine/GameLogic/SCA_PropertySensor.cpp73
-rw-r--r--source/gameengine/GameLogic/SCA_PropertySensor.h2
-rw-r--r--source/gameengine/GameLogic/SCA_PythonController.cpp172
-rw-r--r--source/gameengine/GameLogic/SCA_PythonController.h30
-rw-r--r--source/gameengine/GameLogic/SCA_RandomActuator.cpp74
-rw-r--r--source/gameengine/GameLogic/SCA_RandomEventManager.cpp11
-rw-r--r--source/gameengine/GameLogic/SCA_RandomEventManager.h1
-rw-r--r--source/gameengine/GameLogic/SCA_RandomSensor.cpp54
-rw-r--r--source/gameengine/GameLogic/SCA_RandomSensor.h2
-rw-r--r--source/gameengine/GameLogic/SCA_TimeEventManager.cpp5
-rw-r--r--source/gameengine/GameLogic/SCA_TimeEventManager.h1
-rw-r--r--source/gameengine/GameLogic/SCA_XNORController.cpp148
-rw-r--r--source/gameengine/GameLogic/SCA_XNORController.h56
-rw-r--r--source/gameengine/GameLogic/SCA_XORController.cpp148
-rw-r--r--source/gameengine/GameLogic/SCA_XORController.h56
-rw-r--r--source/gameengine/GameLogic/SConscript12
-rw-r--r--source/gameengine/GamePlayer/CMakeLists.txt4
-rw-r--r--source/gameengine/GamePlayer/Makefile2
-rw-r--r--source/gameengine/GamePlayer/SConscript2
-rw-r--r--source/gameengine/GamePlayer/common/CMakeLists.txt3
-rw-r--r--source/gameengine/GamePlayer/common/GPC_Canvas.h24
-rw-r--r--source/gameengine/GamePlayer/common/GPC_KeyboardDevice.cpp2
-rw-r--r--source/gameengine/GamePlayer/common/GPC_KeyboardDevice.h2
-rw-r--r--source/gameengine/GamePlayer/common/GPC_PolygonMaterial.cpp30
-rw-r--r--source/gameengine/GamePlayer/common/GPC_RawImage.cpp2
-rw-r--r--source/gameengine/GamePlayer/common/GPC_RawImage.h2
-rw-r--r--source/gameengine/GamePlayer/common/GPC_RenderTools.cpp538
-rw-r--r--source/gameengine/GamePlayer/common/GPC_RenderTools.h179
-rw-r--r--source/gameengine/GamePlayer/common/Makefile3
-rw-r--r--source/gameengine/GamePlayer/common/SConscript96
-rw-r--r--source/gameengine/GamePlayer/common/unix/GPU_PolygonMaterial.h4
-rw-r--r--source/gameengine/GamePlayer/common/windows/GPW_Canvas.h2
-rw-r--r--source/gameengine/GamePlayer/ghost/CMakeLists.txt2
-rw-r--r--source/gameengine/GamePlayer/ghost/GPG_Application.cpp159
-rw-r--r--source/gameengine/GamePlayer/ghost/GPG_Application.h18
-rw-r--r--source/gameengine/GamePlayer/ghost/GPG_ghost.cpp157
-rw-r--r--source/gameengine/GamePlayer/ghost/Makefile6
-rw-r--r--source/gameengine/GamePlayer/ghost/SConscript74
-rw-r--r--source/gameengine/Ketsji/BL_BlenderShader.cpp170
-rw-r--r--source/gameengine/Ketsji/BL_BlenderShader.h53
-rw-r--r--source/gameengine/Ketsji/BL_Material.cpp7
-rw-r--r--source/gameengine/Ketsji/BL_Material.h19
-rw-r--r--source/gameengine/Ketsji/BL_Shader.cpp395
-rw-r--r--source/gameengine/Ketsji/BL_Shader.h6
-rw-r--r--source/gameengine/Ketsji/BL_Texture.cpp108
-rw-r--r--source/gameengine/Ketsji/BL_Texture.h8
-rw-r--r--source/gameengine/Ketsji/CMakeLists.txt18
-rw-r--r--source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.cpp17
-rw-r--r--source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.h3
-rw-r--r--source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.cpp14
-rw-r--r--source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp100
-rw-r--r--source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h11
-rw-r--r--source/gameengine/Ketsji/KX_BlenderMaterial.cpp476
-rw-r--r--source/gameengine/Ketsji/KX_BlenderMaterial.h32
-rw-r--r--source/gameengine/Ketsji/KX_BulletPhysicsController.cpp98
-rw-r--r--source/gameengine/Ketsji/KX_BulletPhysicsController.h14
-rw-r--r--source/gameengine/Ketsji/KX_Camera.cpp48
-rw-r--r--source/gameengine/Ketsji/KX_Camera.h23
-rw-r--r--source/gameengine/Ketsji/KX_CameraActuator.cpp164
-rw-r--r--source/gameengine/Ketsji/KX_CameraActuator.h12
-rw-r--r--source/gameengine/Ketsji/KX_ConstraintActuator.cpp805
-rw-r--r--source/gameengine/Ketsji/KX_ConstraintActuator.h85
-rw-r--r--source/gameengine/Ketsji/KX_ConstraintWrapper.cpp4
-rw-r--r--source/gameengine/Ketsji/KX_ConvertPhysicsObject.h42
-rw-r--r--source/gameengine/Ketsji/KX_ConvertPhysicsObjects.cpp695
-rw-r--r--source/gameengine/Ketsji/KX_GameActuator.cpp74
-rw-r--r--source/gameengine/Ketsji/KX_GameActuator.h2
-rw-r--r--source/gameengine/Ketsji/KX_GameObject.cpp1414
-rw-r--r--source/gameengine/Ketsji/KX_GameObject.h341
-rw-r--r--source/gameengine/Ketsji/KX_IPO_SGController.cpp232
-rw-r--r--source/gameengine/Ketsji/KX_IPO_SGController.h47
-rw-r--r--source/gameengine/Ketsji/KX_IPhysicsController.h10
-rw-r--r--source/gameengine/Ketsji/KX_ISceneConverter.h9
-rw-r--r--source/gameengine/Ketsji/KX_IpoActuator.cpp327
-rw-r--r--source/gameengine/Ketsji/KX_IpoActuator.h26
-rw-r--r--source/gameengine/Ketsji/KX_KetsjiEngine.cpp340
-rw-r--r--source/gameengine/Ketsji/KX_KetsjiEngine.h34
-rw-r--r--source/gameengine/Ketsji/KX_Light.cpp98
-rw-r--r--source/gameengine/Ketsji/KX_Light.h23
-rw-r--r--source/gameengine/Ketsji/KX_MaterialIpoController.cpp11
-rw-r--r--source/gameengine/Ketsji/KX_MaterialIpoController.h8
-rw-r--r--source/gameengine/Ketsji/KX_MeshProxy.cpp60
-rw-r--r--source/gameengine/Ketsji/KX_MeshProxy.h2
-rw-r--r--source/gameengine/Ketsji/KX_MouseFocusSensor.cpp81
-rw-r--r--source/gameengine/Ketsji/KX_MouseFocusSensor.h17
-rw-r--r--source/gameengine/Ketsji/KX_NearSensor.cpp97
-rw-r--r--source/gameengine/Ketsji/KX_NearSensor.h3
-rw-r--r--source/gameengine/Ketsji/KX_ObjectActuator.cpp364
-rw-r--r--source/gameengine/Ketsji/KX_ObjectActuator.h59
-rw-r--r--source/gameengine/Ketsji/KX_OdePhysicsController.cpp10
-rw-r--r--source/gameengine/Ketsji/KX_OdePhysicsController.h6
-rw-r--r--source/gameengine/Ketsji/KX_ParentActuator.cpp221
-rw-r--r--source/gameengine/Ketsji/KX_ParentActuator.h89
-rw-r--r--source/gameengine/Ketsji/KX_PhysicsObjectWrapper.cpp22
-rw-r--r--source/gameengine/Ketsji/KX_PolyProxy.cpp265
-rw-r--r--source/gameengine/Ketsji/KX_PolyProxy.h71
-rw-r--r--source/gameengine/Ketsji/KX_PolygonMaterial.cpp60
-rw-r--r--source/gameengine/Ketsji/KX_PolygonMaterial.h5
-rw-r--r--source/gameengine/Ketsji/KX_PyConstraintBinding.cpp141
-rw-r--r--source/gameengine/Ketsji/KX_PyMath.h23
-rw-r--r--source/gameengine/Ketsji/KX_PythonInit.cpp1063
-rw-r--r--source/gameengine/Ketsji/KX_PythonInit.h17
-rw-r--r--source/gameengine/Ketsji/KX_RadarSensor.cpp55
-rw-r--r--source/gameengine/Ketsji/KX_RayCast.cpp80
-rw-r--r--source/gameengine/Ketsji/KX_RayCast.h60
-rw-r--r--source/gameengine/Ketsji/KX_RayEventManager.cpp9
-rw-r--r--source/gameengine/Ketsji/KX_RayEventManager.h1
-rw-r--r--source/gameengine/Ketsji/KX_RaySensor.cpp96
-rw-r--r--source/gameengine/Ketsji/KX_RaySensor.h9
-rw-r--r--source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp243
-rw-r--r--source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h47
-rw-r--r--source/gameengine/Ketsji/KX_SCA_DynamicActuator.cpp206
-rw-r--r--source/gameengine/Ketsji/KX_SCA_DynamicActuator.h76
-rw-r--r--source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp43
-rw-r--r--source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h2
-rw-r--r--source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp2
-rw-r--r--source/gameengine/Ketsji/KX_SG_NodeRelationships.h21
-rw-r--r--source/gameengine/Ketsji/KX_Scene.cpp660
-rw-r--r--source/gameengine/Ketsji/KX_Scene.h66
-rw-r--r--source/gameengine/Ketsji/KX_SceneActuator.cpp78
-rw-r--r--source/gameengine/Ketsji/KX_SceneActuator.h3
-rw-r--r--source/gameengine/Ketsji/KX_SoundActuator.cpp125
-rw-r--r--source/gameengine/Ketsji/KX_StateActuator.cpp207
-rw-r--r--source/gameengine/Ketsji/KX_StateActuator.h83
-rw-r--r--source/gameengine/Ketsji/KX_SumoPhysicsController.cpp10
-rw-r--r--source/gameengine/Ketsji/KX_SumoPhysicsController.h7
-rw-r--r--source/gameengine/Ketsji/KX_TouchEventManager.cpp70
-rw-r--r--source/gameengine/Ketsji/KX_TouchEventManager.h9
-rw-r--r--source/gameengine/Ketsji/KX_TouchSensor.cpp85
-rw-r--r--source/gameengine/Ketsji/KX_TouchSensor.h11
-rw-r--r--source/gameengine/Ketsji/KX_TrackToActuator.cpp185
-rw-r--r--source/gameengine/Ketsji/KX_TrackToActuator.h7
-rw-r--r--source/gameengine/Ketsji/KX_VehicleWrapper.cpp105
-rw-r--r--source/gameengine/Ketsji/KX_VertexProxy.cpp14
-rw-r--r--source/gameengine/Ketsji/KX_VisibilityActuator.cpp14
-rw-r--r--source/gameengine/Ketsji/KX_VisibilityActuator.h2
-rw-r--r--source/gameengine/Ketsji/Makefile7
-rw-r--r--source/gameengine/Ketsji/SConscript23
-rw-r--r--source/gameengine/Makefile2
-rw-r--r--source/gameengine/Physics/BlOde/OdePhysicsController.h2
-rw-r--r--source/gameengine/Physics/BlOde/OdePhysicsEnvironment.cpp5
-rw-r--r--source/gameengine/Physics/BlOde/OdePhysicsEnvironment.h4
-rw-r--r--source/gameengine/Physics/BlOde/SConscript6
-rw-r--r--source/gameengine/Physics/Bullet/CMakeLists.txt4
-rw-r--r--source/gameengine/Physics/Bullet/CcdPhysicsController.cpp1175
-rw-r--r--source/gameengine/Physics/Bullet/CcdPhysicsController.h293
-rw-r--r--source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp949
-rw-r--r--source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h59
-rw-r--r--source/gameengine/Physics/Bullet/Makefile5
-rw-r--r--source/gameengine/Physics/Bullet/SConscript6
-rw-r--r--source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.cpp6
-rw-r--r--source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h6
-rw-r--r--source/gameengine/Physics/Sumo/Fuzzics/include/SM_Callback.h1
-rw-r--r--source/gameengine/Physics/Sumo/Fuzzics/src/SM_Scene.cpp17
-rw-r--r--source/gameengine/Physics/Sumo/SConscript17
-rw-r--r--source/gameengine/Physics/Sumo/SumoPhysicsController.h1
-rw-r--r--source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.cpp43
-rw-r--r--source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.h6
-rw-r--r--source/gameengine/Physics/common/PHY_DynamicTypes.h16
-rw-r--r--source/gameengine/Physics/common/PHY_IPhysicsController.h4
-rw-r--r--source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h51
-rw-r--r--source/gameengine/PyDoc/BL_ActionActuator.py28
-rw-r--r--source/gameengine/PyDoc/BL_ShapeActionActuator.py167
-rw-r--r--source/gameengine/PyDoc/GameKeys.py9
-rw-r--r--source/gameengine/PyDoc/GameLogic.py95
-rw-r--r--source/gameengine/PyDoc/KX_ActuatorSensor.py25
-rw-r--r--source/gameengine/PyDoc/KX_CameraActuator.py8
-rw-r--r--source/gameengine/PyDoc/KX_ConstraintActuator.py126
-rw-r--r--source/gameengine/PyDoc/KX_GameObject.py221
-rw-r--r--source/gameengine/PyDoc/KX_IpoActuator.py17
-rw-r--r--source/gameengine/PyDoc/KX_MeshProxy.py15
-rw-r--r--source/gameengine/PyDoc/KX_ObjectActuator.py106
-rw-r--r--source/gameengine/PyDoc/KX_ParentActuator.py23
-rw-r--r--source/gameengine/PyDoc/KX_PolyProxy.py100
-rw-r--r--source/gameengine/PyDoc/KX_SCA_AddObjectActuator.py30
-rw-r--r--source/gameengine/PyDoc/KX_SCA_ReplaceMeshActuator.py5
-rw-r--r--source/gameengine/PyDoc/KX_StateActuator.py26
-rw-r--r--source/gameengine/PyDoc/KX_TrackToActuator.py10
-rw-r--r--source/gameengine/PyDoc/Makefile13
-rw-r--r--source/gameengine/PyDoc/Rasterizer.py53
-rw-r--r--source/gameengine/PyDoc/SCA_DelaySensor.py56
-rw-r--r--source/gameengine/PyDoc/SCA_ISensor.py31
-rw-r--r--source/gameengine/PyDoc/SCA_JoystickSensor.py106
-rw-r--r--source/gameengine/PyDoc/SCA_PythonController.py8
-rw-r--r--source/gameengine/PyDoc/SConscript28
-rw-r--r--source/gameengine/PyDoc/epy_docgen.sh11
-rw-r--r--source/gameengine/Rasterizer/CMakeLists.txt3
-rw-r--r--source/gameengine/Rasterizer/Makefile7
-rw-r--r--source/gameengine/Rasterizer/RAS_2DFilterManager.cpp500
-rw-r--r--source/gameengine/Rasterizer/RAS_2DFilterManager.h98
-rw-r--r--source/gameengine/Rasterizer/RAS_BucketManager.cpp268
-rw-r--r--source/gameengine/Rasterizer/RAS_BucketManager.h22
-rw-r--r--source/gameengine/Rasterizer/RAS_CameraData.h9
-rw-r--r--source/gameengine/Rasterizer/RAS_Deformer.h8
-rw-r--r--source/gameengine/Rasterizer/RAS_FramingManager.h15
-rw-r--r--source/gameengine/Rasterizer/RAS_ICanvas.h8
-rw-r--r--source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp60
-rw-r--r--source/gameengine/Rasterizer/RAS_IPolygonMaterial.h24
-rw-r--r--source/gameengine/Rasterizer/RAS_IRasterizer.h125
-rw-r--r--source/gameengine/Rasterizer/RAS_IRenderTools.cpp24
-rw-r--r--source/gameengine/Rasterizer/RAS_IRenderTools.h58
-rw-r--r--source/gameengine/Rasterizer/RAS_MaterialBucket.cpp633
-rw-r--r--source/gameengine/Rasterizer/RAS_MaterialBucket.h235
-rw-r--r--source/gameengine/Rasterizer/RAS_MeshObject.cpp761
-rw-r--r--source/gameengine/Rasterizer/RAS_MeshObject.h246
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Blur2DFilter.h51
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Dilation2DFilter.h51
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h50
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_GrayScale2DFilter.h41
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Invert2DFilter.h41
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Laplacian2DFilter.h53
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Prewitt2DFilter.h58
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sepia2DFilter.h41
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sharpen2DFilter.h52
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sobel2DFilter.h57
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/ARB_multitexture.h150
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt2
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/EXT_separate_specular_color.h12
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/Makefile5
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_GLExtensionManager.cpp677
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_GLExtensionManager.h500
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp159
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h44
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp1537
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h96
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.cpp441
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.h29
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/SConscript6
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/glext.h6495
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/mkglext.py627
-rw-r--r--source/gameengine/Rasterizer/RAS_Polygon.cpp101
-rw-r--r--source/gameengine/Rasterizer/RAS_Polygon.h56
-rw-r--r--source/gameengine/Rasterizer/RAS_TexVert.cpp65
-rw-r--r--source/gameengine/Rasterizer/RAS_TexVert.h67
-rw-r--r--source/gameengine/Rasterizer/SConscript8
-rw-r--r--source/gameengine/SConscript37
-rw-r--r--source/gameengine/SceneGraph/SG_Controller.h4
-rw-r--r--source/gameengine/SceneGraph/SG_IObject.cpp11
-rw-r--r--source/gameengine/SceneGraph/SG_IObject.h2
-rw-r--r--source/gameengine/SceneGraph/SG_Node.cpp50
-rw-r--r--source/gameengine/SceneGraph/SG_Node.h18
-rw-r--r--source/gameengine/SceneGraph/SG_ParentRelation.h19
-rw-r--r--source/gameengine/SceneGraph/SG_Spatial.cpp7
-rw-r--r--source/gameengine/SceneGraph/SG_Spatial.h4
-rw-r--r--source/gameengine/VideoTexture/BlendType.h75
-rw-r--r--source/gameengine/VideoTexture/CMakeLists.txt61
-rw-r--r--source/gameengine/VideoTexture/Common.h55
-rw-r--r--source/gameengine/VideoTexture/Exception.cpp209
-rw-r--r--source/gameengine/VideoTexture/Exception.h210
-rw-r--r--source/gameengine/VideoTexture/FilterBase.cpp150
-rw-r--r--source/gameengine/VideoTexture/FilterBase.h138
-rw-r--r--source/gameengine/VideoTexture/FilterBlueScreen.cpp178
-rw-r--r--source/gameengine/VideoTexture/FilterBlueScreen.h97
-rw-r--r--source/gameengine/VideoTexture/FilterColor.cpp350
-rw-r--r--source/gameengine/VideoTexture/FilterColor.h168
-rw-r--r--source/gameengine/VideoTexture/FilterNormal.cpp162
-rw-r--r--source/gameengine/VideoTexture/FilterNormal.h107
-rw-r--r--source/gameengine/VideoTexture/FilterSource.cpp171
-rw-r--r--source/gameengine/VideoTexture/FilterSource.h258
-rw-r--r--source/gameengine/VideoTexture/ImageBase.cpp529
-rw-r--r--source/gameengine/VideoTexture/ImageBase.h349
-rw-r--r--source/gameengine/VideoTexture/ImageBuff.cpp166
-rw-r--r--source/gameengine/VideoTexture/ImageBuff.h51
-rw-r--r--source/gameengine/VideoTexture/ImageMix.cpp205
-rw-r--r--source/gameengine/VideoTexture/ImageMix.h123
-rw-r--r--source/gameengine/VideoTexture/ImageRender.cpp267
-rw-r--r--source/gameengine/VideoTexture/ImageRender.h90
-rw-r--r--source/gameengine/VideoTexture/ImageViewport.cpp297
-rw-r--r--source/gameengine/VideoTexture/ImageViewport.h84
-rw-r--r--source/gameengine/VideoTexture/Makefile65
-rw-r--r--source/gameengine/VideoTexture/PyTypeList.cpp83
-rw-r--r--source/gameengine/VideoTexture/PyTypeList.h85
-rw-r--r--source/gameengine/VideoTexture/SConscript32
-rw-r--r--source/gameengine/VideoTexture/Texture.cpp475
-rw-r--r--source/gameengine/VideoTexture/Texture.h86
-rw-r--r--source/gameengine/VideoTexture/VideoBase.cpp195
-rw-r--r--source/gameengine/VideoTexture/VideoBase.h185
-rw-r--r--source/gameengine/VideoTexture/VideoFFmpeg.cpp927
-rw-r--r--source/gameengine/VideoTexture/VideoFFmpeg.h173
-rw-r--r--source/gameengine/VideoTexture/blendVideoTex.cpp194
-rw-r--r--source/kernel/CMakeLists.txt2
-rw-r--r--source/kernel/SConscript4
-rw-r--r--source/kernel/gen_system/GEN_HashedPtr.cpp8
-rw-r--r--source/kernel/gen_system/GEN_HashedPtr.h1
-rw-r--r--source/kernel/gen_system/GEN_Map.h31
-rw-r--r--source/kernel/gen_system/Makefile1
-rw-r--r--source/nan_compile.mk28
-rw-r--r--source/nan_definitions.mk21
-rw-r--r--source/nan_link.mk19
808 files changed, 89406 insertions, 34692 deletions
diff --git a/source/Makefile b/source/Makefile
index 7efb45bdca9..18c2da6b4c3 100644
--- a/source/Makefile
+++ b/source/Makefile
@@ -99,8 +99,13 @@ COMLIB += $(OCGDIR)/blender/nodes_cmp/$(DEBUG_DIR)libnodes_cmp.a
COMLIB += $(OCGDIR)/blender/nodes/$(DEBUG_DIR)libnodes.a
COMLIB += $(OCGDIR)/blender/imbuf/$(DEBUG_DIR)libimbuf.a
COMLIB += $(OCGDIR)/blender/blenlib/$(DEBUG_DIR)libblenlib.a
+COMLIB += $(NAN_IKSOLVER)/lib/libiksolver.a
+COMLIB += $(NAN_OPENNL)/lib/$(DEBUG_DIR)libopennl.a
+COMLIB += $(NAN_SUPERLU)/lib/$(DEBUG_DIR)libsuperlu.a
COMLIB += $(OCGDIR)/blender/avi/$(DEBUG_DIR)libavi.a
COMLIB += $(NAN_JPEG)/lib/libjpeg.a
+COMLIB += $(OCGDIR)/blender/gpu/$(DEBUG_DIR)libgpu.a
+COMLIB += $(NAN_GLEW)/lib/libglew.a
ifneq ($(NAN_NO_KETSJI),true)
COMLIB += $(OCGDIR)/gameengine/bloutines/$(DEBUG_DIR)libbloutines.a
@@ -136,6 +141,7 @@ ifneq ($(NAN_NO_KETSJI),true)
COMLIB += $(OCGDIR)/gameengine/OpenGLrasterizer/$(DEBUG_DIR)libOpenGLrasterizer.a
COMLIB += $(OCGDIR)/gameengine/expression/$(DEBUG_DIR)libexpression.a
COMLIB += $(OCGDIR)/gameengine/scenegraph/$(DEBUG_DIR)libscenegraph.a
+ COMLIB += $(OCGDIR)/gameengine/videotex/$(DEBUG_DIR)libvideotex.a
# COMLIB += $(OCGDIR)/sumo/$(DEBUG_DIR)libfuzzics.a
# COMLIB += $(OCGDIR)/sumo/$(DEBUG_DIR)libsolid.a
COMLIB += $(NAN_MOTO)/lib/libmoto.a
@@ -170,6 +176,10 @@ ifeq ($(WITH_DDS), true)
COMLIB += $(OCGDIR)/blender/imbuf/dds/$(DEBUG_DIR)libdds.a
endif
+ifeq ($(WITH_BINRELOC), true)
+ COMLIB += $(OCGDIR)/extern/binreloc/$(DEBUG_DIR)libbinreloc.a
+endif
+
ifeq ($(WITH_FREETYPE2), true)
COMLIB += $(OCGDIR)/blender/ftfont/$(DEBUG_DIR)libftfont.a
ifeq ($(OS), windows)
@@ -219,15 +229,14 @@ ifeq ($(WITH_OPENEXR), true)
COMLIB += $(NAN_OPENEXR_LIBS)
endif
-PULIB = $(NAN_IKSOLVER)/lib/libiksolver.a
-PULIB += $(NAN_MOTO)/lib/libmoto.a
+PULIB = $(NAN_MOTO)/lib/libmoto.a
PULIB += $(NAN_ELBEEM)/lib/$(DEBUG_DIR)libelbeem.a
PULIB += $(OCGDIR)/blender/readblenfile/$(DEBUG_DIR)libreadblenfile.a
-PULIB += $(OCGDIR)/blender/ed_datafiles/libed_datafiles.a
PULIB += $(OCGDIR)/blender/ed_screen/libed_screen.a
PULIB += $(OCGDIR)/blender/ed_time/libed_time.a
PULIB += $(OCGDIR)/blender/ed_view3d/libed_view3d.a
PULIB += $(OCGDIR)/blender/ed_interface/libed_interface.a
+PULIB += $(OCGDIR)/blender/ed_datafiles/libed_datafiles.a
PULIB += $(OCGDIR)/blender/windowmanager/libwindowmanager.a
PULIB += $(OCGDIR)/blender/python/$(DEBUG_DIR)libpython.a
PULIB += $(OCGDIR)/blender/makesrna/$(DEBUG_DIR)librna.a
@@ -241,6 +250,7 @@ endif
SPLIB1 = $(OCGDIR)/gameengine/GamePlayer/ghost/$(DEBUG_DIR)libghost.a
SPLIB1 += $(OCGDIR)/gameengine/GamePlayer/common/$(DEBUG_DIR)libcommon.a
+SPLIB1 += $(OCGDIR)/gameengine/blconverter/$(DEBUG_DIR)libblconverter.a
SPLIB1 += $(NAN_STRING)/lib/$(DEBUG_DIR)libstring.a
SPLIB1 += $(NAN_GHOST)/lib/$(DEBUG_DIR)libghost.a
@@ -316,12 +326,10 @@ ifeq ($(WITH_BF_BLENDERPLAYER), true)
endif
ifeq ($(WITH_BF_WEBPLUGIN), true)
- ifneq ($(NAN_NO_PLUGIN), true)
- BINTARGETS += plugin
- ifeq ($(OS),linux)
- ifeq ($(CPU),i386)
- BINTARGETS += xplink
- endif
+ BINTARGETS += plugin
+ ifeq ($(OS),linux)
+ ifeq ($(CPU),i386)
+ BINTARGETS += xplink
endif
endif
endif
@@ -347,7 +355,7 @@ ifeq ($(NAN_NO_OPENAL), true)
NAN_SND_LIBS += $(SOUNDSYSTEM)
else
ifeq ($(OS),$(findstring $(OS), "freebsd linux windows"))
- ifeq ($(CPU),$(findstring $(CPU), "i386 powerpc x86_64"))
+ ifeq ($(CPU),$(findstring $(CPU), "i386 powerpc x86_64 parisc64"))
NAN_SND_LIBS = $(SOUNDSYSTEM)
NAN_SND_LIBS += $(DUMMYSOUND)
NAN_SND_LIBS += $(OPENALSOUND)
diff --git a/source/SConscript b/source/SConscript
index ca264579f6e..9b497edd85a 100644
--- a/source/SConscript
+++ b/source/SConscript
@@ -4,7 +4,7 @@ Import ('env')
SConscript(['blender/SConscript',
'kernel/SConscript',
'creator/SConscript'])
-if env['WITH_BF_GAMEENGINE'] == 1:
+if env['WITH_BF_GAMEENGINE']:
SConscript (['gameengine/SConscript'])
if env['OURPLATFORM'] in ('win32-vc', 'win32-mingw'):
diff --git a/source/blender/CMakeLists.txt b/source/blender/CMakeLists.txt
index 8551b6412bb..beffd2b13f1 100644
--- a/source/blender/CMakeLists.txt
+++ b/source/blender/CMakeLists.txt
@@ -24,7 +24,7 @@
#
# ***** END GPL LICENSE BLOCK *****
-SUBDIRS(windowmanager editors avi nodes blenkernel blenlib blenloader blenpluginapi imbuf imbuf/intern/cineon makesdna python radiosity readblenfile render yafray)
+SUBDIRS(windowmanager editors avi nodes blenkernel blenlib blenloader blenpluginapi imbuf imbuf/intern/cineon gpu makesdna python radiosity readblenfile render yafray)
IF(WITH_INTERNATIONAL)
SUBDIRS(ftfont)
@@ -34,6 +34,10 @@ IF(WITH_OPENEXR)
SUBDIRS(imbuf/intern/openexr)
ENDIF(WITH_OPENEXR)
+IF(WITH_DDS)
+ SUBDIRS(imbuf/intern/dds)
+ENDIF(WITH_DDS)
+
IF(WITH_QUICKTIME)
SUBDIRS(quicktime)
ENDIF(WITH_QUICKTIME)
diff --git a/source/blender/Makefile b/source/blender/Makefile
index e66c32443a5..37d647788d0 100644
--- a/source/blender/Makefile
+++ b/source/blender/Makefile
@@ -32,11 +32,10 @@ include nan_definitions.mk
DIRS = windowmanager editors blenloader readblenfile
DIRS += avi imbuf render radiosity blenlib blenkernel blenpluginapi
-DIRS += nodes
DIRS += makesdna makesrna yafray
-DIRS += python
+DIRS += python nodes gpu
-ifeq ($(INTERNATIONAL), true)
+ifeq ($(WITH_FREETYPE2), true)
DIRS += ftfont
endif
diff --git a/source/blender/SConscript b/source/blender/SConscript
index 2c39a6d6ff8..93acf8a8430 100644
--- a/source/blender/SConscript
+++ b/source/blender/SConscript
@@ -3,33 +3,38 @@ Import ('env')
import sys
SConscript(['avi/SConscript',
- 'blenkernel/SConscript',
- 'blenlib/SConscript',
- 'blenloader/SConscript',
- 'blenpluginapi/SConscript',
- 'editors/SConscript',
- 'imbuf/SConscript',
- 'imbuf/intern/cineon/SConscript',
- 'makesdna/SConscript',
- 'makesrna/SConscript',
- 'python/SConscript',
- 'radiosity/SConscript',
- 'readblenfile/SConscript',
- 'render/SConscript',
- 'nodes/SConscript',
- 'windowmanager/SConscript'])
-
-if env['WITH_BF_YAFRAY'] == 1:
- SConscript(['yafray/SConscript'])
-
-if env['WITH_BF_INTERNATIONAL'] == 1:
- SConscript (['ftfont/SConscript'])
-
-if env['WITH_BF_DDS'] == 1:
- SConscript (['imbuf/intern/dds/SConscript'])
-
-if env['WITH_BF_OPENEXR'] == 1:
- SConscript (['imbuf/intern/openexr/SConscript'])
-
-if env['WITH_BF_QUICKTIME'] == 1:
- SConscript (['quicktime/SConscript'])
+ 'blenkernel/SConscript',
+ 'blenlib/SConscript',
+ 'blenloader/SConscript',
+ 'blenpluginapi/SConscript',
+ 'gpu/SConscript',
+ 'editors/SConscript',
+ 'imbuf/SConscript',
+ 'imbuf/intern/cineon/SConscript',
+ 'makesdna/SConscript',
+ 'makesrna/SConscript',
+ 'radiosity/SConscript',
+ 'readblenfile/SConscript',
+ 'render/SConscript',
+ 'nodes/SConscript',
+ 'windowmanager/SConscript'])
+
+
+
+if env['WITH_BF_PYTHON']:
+ SConscript(['python/SConscript'])
+
+if env['WITH_BF_YAFRAY']:
+ SConscript(['yafray/SConscript'])
+
+if env['WITH_BF_INTERNATIONAL']:
+ SConscript (['ftfont/SConscript'])
+
+if env['WITH_BF_DDS']:
+ SConscript (['imbuf/intern/dds/SConscript'])
+
+if env['WITH_BF_OPENEXR']:
+ SConscript (['imbuf/intern/openexr/SConscript'])
+
+if env['WITH_BF_QUICKTIME']:
+ SConscript (['quicktime/SConscript'])
diff --git a/source/blender/avi/SConscript b/source/blender/avi/SConscript
index 8c16af9de9d..91239c66ead 100644
--- a/source/blender/avi/SConscript
+++ b/source/blender/avi/SConscript
@@ -7,4 +7,4 @@ sources = env.Glob('intern/*.c')
incs = '. #/intern/guardedalloc'
incs += ' ' + env['BF_JPEG_INC']
-env.BlenderLib ('bf_avi', sources, Split(incs), [], libtype=['core','player'], priority = [105, 40] )
+env.BlenderLib ('bf_avi', sources, Split(incs), [], libtype=['core','player'], priority = [90, 50] )
diff --git a/source/blender/avi/intern/avi.c b/source/blender/avi/intern/avi.c
index 6178807c493..386597c6d85 100644
--- a/source/blender/avi/intern/avi.c
+++ b/source/blender/avi/intern/avi.c
@@ -187,6 +187,7 @@ void AVI_set_debug (int mode) {
AVI_DEBUG= mode;
}
+/*
int AVI_is_avi (char *name) {
FILE *fp;
int ret;
@@ -206,6 +207,195 @@ int AVI_is_avi (char *name) {
fclose(fp);
return ret;
}
+*/
+
+int AVI_is_avi (char *name) {
+ int temp, fcca, j;
+ AviMovie movie;
+ AviMainHeader header;
+ AviBitmapInfoHeader bheader;
+
+ DEBUG("opening movie\n");
+
+ memset(&movie, 0, sizeof(AviMovie));
+
+ movie.type = AVI_MOVIE_READ;
+ movie.fp = fopen (name, "rb");
+ movie.offset_table = NULL;
+
+ if (movie.fp == NULL)
+ return 0;
+
+ if (GET_FCC (movie.fp) != FCC("RIFF") ||
+ !(movie.size = GET_FCC (movie.fp))) {
+ fclose(movie.fp);
+ return 0;
+ }
+
+ movie.header = &header;
+
+ if (GET_FCC (movie.fp) != FCC("AVI ") ||
+ GET_FCC (movie.fp) != FCC("LIST") ||
+ !GET_FCC (movie.fp) ||
+ GET_FCC (movie.fp) != FCC("hdrl") ||
+ (movie.header->fcc = GET_FCC (movie.fp)) != FCC("avih") ||
+ !(movie.header->size = GET_FCC (movie.fp))) {
+ DEBUG("bad initial header info\n");
+ fclose(movie.fp);
+ return 0;
+ }
+
+ movie.header->MicroSecPerFrame = GET_FCC(movie.fp);
+ movie.header->MaxBytesPerSec = GET_FCC(movie.fp);
+ movie.header->PaddingGranularity = GET_FCC(movie.fp);
+ movie.header->Flags = GET_FCC(movie.fp);
+ movie.header->TotalFrames = GET_FCC(movie.fp);
+ movie.header->InitialFrames = GET_FCC(movie.fp);
+ movie.header->Streams = GET_FCC(movie.fp);
+ movie.header->SuggestedBufferSize = GET_FCC(movie.fp);
+ movie.header->Width = GET_FCC(movie.fp);
+ movie.header->Height = GET_FCC(movie.fp);
+ movie.header->Reserved[0] = GET_FCC(movie.fp);
+ movie.header->Reserved[1] = GET_FCC(movie.fp);
+ movie.header->Reserved[2] = GET_FCC(movie.fp);
+ movie.header->Reserved[3] = GET_FCC(movie.fp);
+
+ fseek (movie.fp, movie.header->size-14*4, SEEK_CUR);
+
+ if (movie.header->Streams < 1) {
+ DEBUG("streams less than 1\n");
+ fclose(movie.fp);
+ return 0;
+ }
+
+ movie.streams = (AviStreamRec *) MEM_callocN (sizeof(AviStreamRec) * movie.header->Streams, "moviestreams");
+
+ for (temp=0; temp < movie.header->Streams; temp++) {
+
+ if (GET_FCC(movie.fp) != FCC("LIST") ||
+ !GET_FCC (movie.fp) ||
+ GET_FCC (movie.fp) != FCC ("strl") ||
+ (movie.streams[temp].sh.fcc = GET_FCC (movie.fp)) != FCC ("strh") ||
+ !(movie.streams[temp].sh.size = GET_FCC (movie.fp))) {
+ DEBUG("bad stream header information\n");
+
+ MEM_freeN(movie.streams);
+ fclose(movie.fp);
+ return 0;
+ }
+
+ movie.streams[temp].sh.Type = GET_FCC (movie.fp);
+ movie.streams[temp].sh.Handler = GET_FCC (movie.fp);
+
+ fcca = movie.streams[temp].sh.Handler;
+
+ if (movie.streams[temp].sh.Type == FCC("vids")) {
+ if (fcca == FCC ("DIB ") ||
+ fcca == FCC ("RGB ") ||
+ fcca == FCC ("rgb ") ||
+ fcca == FCC ("RAW ") ||
+ fcca == 0) {
+ movie.streams[temp].format = AVI_FORMAT_AVI_RGB;
+ } else if (fcca == FCC ("mjpg")||fcca == FCC ("MJPG")) {
+ movie.streams[temp].format = AVI_FORMAT_MJPEG;
+ } else {
+ MEM_freeN(movie.streams);
+ fclose(movie.fp);
+ return 0;
+ }
+ }
+
+ movie.streams[temp].sh.Flags = GET_FCC (movie.fp);
+ movie.streams[temp].sh.Priority = GET_TCC (movie.fp);
+ movie.streams[temp].sh.Language = GET_TCC (movie.fp);
+ movie.streams[temp].sh.InitialFrames = GET_FCC (movie.fp);
+ movie.streams[temp].sh.Scale = GET_FCC (movie.fp);
+ movie.streams[temp].sh.Rate = GET_FCC (movie.fp);
+ movie.streams[temp].sh.Start = GET_FCC (movie.fp);
+ movie.streams[temp].sh.Length = GET_FCC (movie.fp);
+ movie.streams[temp].sh.SuggestedBufferSize = GET_FCC (movie.fp);
+ movie.streams[temp].sh.Quality = GET_FCC (movie.fp);
+ movie.streams[temp].sh.SampleSize = GET_FCC (movie.fp);
+ movie.streams[temp].sh.left = GET_TCC (movie.fp);
+ movie.streams[temp].sh.top = GET_TCC (movie.fp);
+ movie.streams[temp].sh.right = GET_TCC (movie.fp);
+ movie.streams[temp].sh.bottom = GET_TCC (movie.fp);
+
+ fseek (movie.fp, movie.streams[temp].sh.size-14*4, SEEK_CUR);
+
+ if (GET_FCC (movie.fp) != FCC("strf")) {
+ DEBUG("no stream format information\n");
+ MEM_freeN(movie.streams);
+ fclose(movie.fp);
+ return 0;
+ }
+
+ movie.streams[temp].sf_size= GET_FCC(movie.fp);
+ if (movie.streams[temp].sh.Type == FCC("vids")) {
+ j = movie.streams[temp].sf_size - (sizeof(AviBitmapInfoHeader) - 8);
+ if (j >= 0) {
+ AviBitmapInfoHeader *bi;
+
+ movie.streams[temp].sf= &bheader;
+ bi= (AviBitmapInfoHeader *) movie.streams[temp].sf;
+
+ bi->fcc= FCC("strf");
+ bi->size= movie.streams[temp].sf_size;
+ bi->Size= GET_FCC(movie.fp);
+ bi->Width= GET_FCC(movie.fp);
+ bi->Height= GET_FCC(movie.fp);
+ bi->Planes= GET_TCC(movie.fp);
+ bi->BitCount= GET_TCC(movie.fp);
+ bi->Compression= GET_FCC(movie.fp);
+ bi->SizeImage= GET_FCC(movie.fp);
+ bi->XPelsPerMeter= GET_FCC(movie.fp);
+ bi->YPelsPerMeter= GET_FCC(movie.fp);
+ bi->ClrUsed= GET_FCC(movie.fp);
+ bi->ClrImportant= GET_FCC(movie.fp);
+
+ fcca = bi->Compression;
+
+ if ( movie.streams[temp].format ==
+ AVI_FORMAT_AVI_RGB) {
+ if (fcca == FCC ("DIB ") ||
+ fcca == FCC ("RGB ") ||
+ fcca == FCC ("rgb ") ||
+ fcca == FCC ("RAW ") ||
+ fcca == 0 ) {
+ } else if ( fcca == FCC ("mjpg") ||
+ fcca == FCC ("MJPG")) {
+ movie.streams[temp].format = AVI_FORMAT_MJPEG;
+ } else {
+ MEM_freeN(movie.streams);
+ fclose(movie.fp);
+ return 0;
+ }
+ }
+
+ }
+ if (j > 0) fseek (movie.fp, j, SEEK_CUR);
+ } else fseek (movie.fp, movie.streams[temp].sf_size, SEEK_CUR);
+
+ /* Walk to the next LIST */
+ while (GET_FCC (movie.fp) != FCC("LIST")) {
+ temp= GET_FCC (movie.fp);
+ if (temp<0 || ftell(movie.fp) > movie.size) {
+ DEBUG("incorrect size in header or error in AVI\n");
+
+ MEM_freeN(movie.streams);
+ fclose(movie.fp);
+ return 0;
+ }
+ fseek(movie.fp, temp, SEEK_CUR);
+ }
+
+ fseek(movie.fp, -4L, SEEK_CUR);
+ }
+
+ MEM_freeN(movie.streams);
+ fclose(movie.fp);
+ return 1;
+}
AviError AVI_open_movie (char *name, AviMovie *movie) {
int temp, fcca, size, j;
@@ -439,7 +629,7 @@ AviError AVI_open_movie (char *name, AviMovie *movie) {
}
void *AVI_read_frame (AviMovie *movie, AviFormat format, int frame, int stream) {
- int cur_frame, temp, i, rewind=1;
+ int cur_frame=-1, temp, i=0, rewind=1;
void *buffer;
/* Retrieve the record number of the desired frame in the index
diff --git a/source/blender/avi/intern/avirgb.c b/source/blender/avi/intern/avirgb.c
index 9731a8f0e28..3a28f4da8a0 100644
--- a/source/blender/avi/intern/avirgb.c
+++ b/source/blender/avi/intern/avirgb.c
@@ -43,7 +43,7 @@
#include "MEM_guardedalloc.h"
#include "avirgb.h"
-#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
+#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__hppa__) || defined (__BIG_ENDIAN__)
#define WORDS_BIGENDIAN
#endif
diff --git a/source/blender/avi/intern/endian.c b/source/blender/avi/intern/endian.c
index 2e549e3f298..ecbabf07039 100644
--- a/source/blender/avi/intern/endian.c
+++ b/source/blender/avi/intern/endian.c
@@ -43,10 +43,11 @@
#include "endian.h"
#include "avi_intern.h"
-#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
+#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__hppa__) || defined (__BIG_ENDIAN__)
#define WORDS_BIGENDIAN
#endif
+#ifdef WORDS_BIGENDIAN
static void invert (int *num) {
int new=0,i,j;
@@ -76,6 +77,7 @@ static void Ichunk (AviChunk *chunk) {
invert (&chunk->fcc);
invert (&chunk->size);
}
+#endif
#ifdef WORDS_BIGENDIAN
static void Ilist (AviList *list){
diff --git a/source/blender/blenkernel/BKE_DerivedMesh.h b/source/blender/blenkernel/BKE_DerivedMesh.h
index b66e009e3d3..5a1e266adeb 100644
--- a/source/blender/blenkernel/BKE_DerivedMesh.h
+++ b/source/blender/blenkernel/BKE_DerivedMesh.h
@@ -55,6 +55,7 @@ struct EditMesh;
struct ModifierData;
struct MCol;
struct ColorBand;
+struct GPUVertexAttribs;
/* number of sub-elements each mesh element has (for interpolation) */
#define SUB_ELEMS_VERT 0
@@ -198,7 +199,8 @@ struct DerivedMesh {
*
* Also called for *final* editmode DerivedMeshes
*/
- void (*drawFacesSolid)(DerivedMesh *dm, int (*setMaterial)(int));
+ void (*drawFacesSolid)(DerivedMesh *dm,
+ int (*setMaterial)(int, void *attribs));
/* Draw all faces
* o If useTwoSided, draw front and back using col arrays
@@ -215,6 +217,13 @@ struct DerivedMesh {
int (*setDrawOptions)(struct MTFace *tface,
struct MCol *mcol, int matnr));
+ /* Draw all faces with GLSL materials
+ * o setMaterial is called for every different material nr
+ * o Only if setMaterial returns true
+ */
+ void (*drawFacesGLSL)(DerivedMesh *dm,
+ int (*setMaterial)(int, void *attribs));
+
/* Draw mapped faces (no color, or texture)
* o Only if !setDrawOptions or
* setDrawOptions(userData, mapped-face-index, drawSmooth_r)
@@ -241,6 +250,15 @@ struct DerivedMesh {
int index),
void *userData);
+ /* Draw mapped faces with GLSL materials
+ * o setMaterial is called for every different material nr
+ * o setDrawOptions is called for every face
+ * o Only if setMaterial and setDrawOptions return true
+ */
+ void (*drawMappedFacesGLSL)(DerivedMesh *dm,
+ int (*setMaterial)(int, void *attribs),
+ int (*setDrawOptions)(void *userData, int index), void *userData);
+
/* Draw mapped edges as lines
* o Only if !setDrawOptions or setDrawOptions(userData, mapped-edge)
* returns true
@@ -412,7 +430,10 @@ DerivedMesh *mesh_create_derived_for_modifier(struct Object *ob, struct Modifier
DerivedMesh *mesh_create_derived_render(struct Object *ob,
CustomDataMask dataMask);
-/* same as above but wont use render settings */
+
+DerivedMesh *mesh_create_derived_index_render(struct Object *ob, CustomDataMask dataMask, int index);
+
+ /* same as above but wont use render settings */
DerivedMesh *mesh_create_derived_view(struct Object *ob,
CustomDataMask dataMask);
DerivedMesh *mesh_create_derived_no_deform(struct Object *ob,
@@ -437,23 +458,36 @@ void weight_to_rgb(float input, float *fr, float *fg, float *fb);
/* determines required DerivedMesh data according to view and edit modes */
CustomDataMask get_viewedit_datamask();
-/* repeate this pattern
- X000X000
- 00000000
- 00X000X0
- 00000000 */
-
-#define DM_FACE_STIPPLE \
-{ \
- 136,136,136,136,0,0,0,0,34,34,34,34,0,0,0,0, \
- 136,136,136,136,0,0,0,0,34,34,34,34,0,0,0,0, \
- 136,136,136,136,0,0,0,0,34,34,34,34,0,0,0,0, \
- 136,136,136,136,0,0,0,0,34,34,34,34,0,0,0,0, \
- 136,136,136,136,0,0,0,0,34,34,34,34,0,0,0,0, \
- 136,136,136,136,0,0,0,0,34,34,34,34,0,0,0,0, \
- 136,136,136,136,0,0,0,0,34,34,34,34,0,0,0,0, \
- 136,136,136,136,0,0,0,0,34,34,34,34,0,0,0,0 \
-}
+/* convert layers requested by a GLSL material to actually available layers in
+ * the DerivedMesh, with both a pointer for arrays and an offset for editmesh */
+typedef struct DMVertexAttribs {
+ struct {
+ struct MTFace *array;
+ int emOffset, glIndex;
+ } tface[MAX_MTFACE];
+
+ struct {
+ struct MCol *array;
+ int emOffset, glIndex;
+ } mcol[MAX_MCOL];
+
+ struct {
+ float (*array)[3];
+ int emOffset, glIndex;
+ } tang;
+
+ struct {
+ float (*array)[3];
+ int emOffset, glIndex;
+ } orco;
+
+ int tottface, totmcol, tottang, totorco;
+} DMVertexAttribs;
+
+void DM_vertex_attributes_from_gpu(DerivedMesh *dm,
+ struct GPUVertexAttribs *gattribs, DMVertexAttribs *attribs);
+
+void DM_add_tangent_layer(DerivedMesh *dm);
#endif
diff --git a/source/blender/blenkernel/BKE_action.h b/source/blender/blenkernel/BKE_action.h
index efdd75d1046..37ced4cb00b 100644
--- a/source/blender/blenkernel/BKE_action.h
+++ b/source/blender/blenkernel/BKE_action.h
@@ -44,6 +44,7 @@ struct bActionChannel;
struct bPose;
struct bPoseChannel;
struct Object;
+struct ID;
/* Kernel prototypes */
#ifdef __cplusplus
@@ -57,6 +58,11 @@ extern "C" {
*/
void free_pose_channels(struct bPose *pose);
+/**
+ * Removes and deallocates all data from a pose, and also frees the pose.
+ */
+void free_pose(struct bPose *pose);
+
/**
* Allocate a new pose on the heap, and copy the src pose and it's channels
* into the new pose. *dst is set to the newly allocated structure, and assumed to be NULL.
@@ -152,6 +158,14 @@ void rest_pose(struct bPose *pose);
float get_action_frame(struct Object *ob, float cframe);
/* map strip time to global time (frame nr) */
float get_action_frame_inv(struct Object *ob, float cframe);
+/* builds a list of NlaIpoChannel with ipo values to write in datablock */
+void extract_ipochannels_from_action(ListBase *lb, struct ID *id, struct bAction *act, const char *name, float ctime);
+/* write values returned by extract_ipochannels_from_action, returns the number of value written */
+int execute_ipochannels(ListBase *lb);
+
+/* functions used by the game engine */
+void game_copy_pose(struct bPose **dst, struct bPose *src);
+void game_free_pose(struct bPose *pose);
#ifdef __cplusplus
};
diff --git a/source/blender/blenkernel/BKE_anim.h b/source/blender/blenkernel/BKE_anim.h
index 2b7a4c5af46..5ea511738ad 100644
--- a/source/blender/blenkernel/BKE_anim.h
+++ b/source/blender/blenkernel/BKE_anim.h
@@ -31,6 +31,8 @@
#ifndef BKE_ANIM_H
#define BKE_ANIM_H
+#define MAX_DUPLI_RECUR 8
+
struct Path;
struct Object;
struct PartEff;
@@ -41,8 +43,9 @@ typedef struct DupliObject {
struct DupliObject *next, *prev;
struct Object *ob;
unsigned int origlay;
- int index, no_draw;
+ int index, no_draw, type, animated;
float mat[4][4], omat[4][4];
+ float orco[3], uv[2];
} DupliObject;
void free_path(struct Path *path);
diff --git a/source/blender/blenkernel/BKE_armature.h b/source/blender/blenkernel/BKE_armature.h
index 6739f3118af..62061238131 100644
--- a/source/blender/blenkernel/BKE_armature.h
+++ b/source/blender/blenkernel/BKE_armature.h
@@ -75,7 +75,9 @@ void unlink_armature(struct bArmature *arm);
void free_armature(struct bArmature *arm);
void make_local_armature(struct bArmature *arm);
struct bArmature *copy_armature(struct bArmature *arm);
+
void bone_flip_name (char *name, int strip_number);
+void bone_autoside_name (char *name, int strip_number, short axis, float head, float tail);
struct bArmature *get_armature (struct Object *ob);
struct Bone *get_named_bone (struct bArmature *arm, const char *name);
diff --git a/source/blender/blenkernel/BKE_bmesh.h b/source/blender/blenkernel/BKE_bmesh.h
new file mode 100644
index 00000000000..71c042e34fe
--- /dev/null
+++ b/source/blender/blenkernel/BKE_bmesh.h
@@ -0,0 +1,253 @@
+/**
+ * BKE_bmesh.h jan 2007
+ *
+ * BMesh modeler structure and functions.
+ *
+ * $Id: BKE_bmesh.h,v 1.00 2007/01/17 17:42:01 Briggs Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2004 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Geoffrey Bantle.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef BKE_BMESH_H
+#define BKE_BMESH_H
+
+#include "DNA_listBase.h"
+#include "BLI_ghash.h"
+#include "BLI_mempool.h"
+#include "BLI_memarena.h"
+#include "DNA_image_types.h"
+#include "BLI_editVert.h"
+#include "BKE_DerivedMesh.h"
+//XXX #include "transform.h"
+
+/*forward declerations*/
+struct BME_Vert;
+struct BME_Edge;
+struct BME_Poly;
+struct BME_Loop;
+
+
+/*Notes on further structure Cleanup:
+ -Remove the tflags, they belong in custom data layers
+ -Remove the eflags completely, they are mostly not used
+ -Remove the selection/vis/bevel weight flag/values ect and move them to custom data
+ -Remove EID member and move to custom data
+ -Add a radial cycle length, disk cycle length and loop cycle lenght attributes to custom data and have eulers maintain/use them if present.
+ -Move data such as vertex coordinates/normals to custom data and leave pointers in structures to active layer data.
+ -Remove BME_CycleNode structure?
+*/
+typedef struct BME_CycleNode{
+ struct BME_CycleNode *next, *prev;
+ void *data;
+} BME_CycleNode;
+
+typedef struct BME_Mesh
+{
+ ListBase verts, edges, polys;
+ /*memory pools used for storing mesh elements*/
+ struct BLI_mempool *vpool;
+ struct BLI_mempool *epool;
+ struct BLI_mempool *ppool;
+ struct BLI_mempool *lpool;
+ /*some scratch arrays used by eulers*/
+ struct BME_Vert **vtar;
+ struct BME_Edge **edar;
+ struct BME_Loop **lpar;
+ struct BME_Poly **plar;
+ int vtarlen, edarlen, lparlen, plarlen;
+ int totvert, totedge, totpoly, totloop; /*record keeping*/
+ int nextv, nexte, nextp, nextl; /*Next element ID for verts/edges/faces/loops. Never reused*/
+ struct CustomData vdata, edata, pdata, ldata; /*Custom Data Layer information*/
+} BME_Mesh;
+
+typedef struct BME_Vert
+{
+ struct BME_Vert *next, *prev;
+ int EID;
+ float co[3];
+ float no[3];
+ struct BME_Edge *edge; /*first edge in the disk cycle for this vertex*/
+ void *data; /*custom vertex data*/
+ int eflag1, eflag2; /*reserved for use by eulers*/
+ int tflag1, tflag2; /*reserved for use by tools*/
+ unsigned short flag, h;
+ float bweight;
+} BME_Vert;
+
+typedef struct BME_Edge
+{
+ struct BME_Edge *next, *prev;
+ int EID;
+ struct BME_Vert *v1, *v2; /*note that order of vertex pointers means nothing to eulers*/
+ struct BME_CycleNode d1, d2; /*disk cycle nodes for v1 and v2 respectivley*/
+ struct BME_Loop *loop; /*first BME_Loop in the radial cycle around this edge*/
+ void *data; /*custom edge data*/
+ int eflag1, eflag2; /*reserved for use by eulers*/
+ int tflag1, tflag2; /*reserved for use by tools*/
+ unsigned short flag, h;
+ float crease, bweight;
+} BME_Edge;
+
+typedef struct BME_Loop
+{
+ struct BME_Loop *next, *prev; /*circularly linked list around face*/
+ int EID;
+ struct BME_CycleNode radial; /*circularly linked list used to find faces around an edge*/
+ struct BME_Vert *v; /*vertex that this loop starts at.*/
+ struct BME_Edge *e; /*edge this loop belongs to*/
+ struct BME_Poly *f; /*face this loop belongs to*/
+ void *data; /*custom per face vertex data*/
+ int eflag1, eflag2; /*reserved for use by eulers*/
+ int tflag1, tflag2; /*reserved for use by tools*/
+ unsigned short flag, h;
+} BME_Loop;
+
+typedef struct BME_Poly
+{
+ struct BME_Poly *next, *prev;
+ int EID;
+ struct BME_Loop *loopbase; /*First editloop around Polygon.*/
+ unsigned int len; /*total length of the face. Eulers should preserve this data*/
+ void *data; /*custom face data*/
+ int eflag1, eflag2; /*reserved for use by eulers*/
+ int tflag1, tflag2; /*reserved for use by tools*/
+ unsigned short flag, h, mat_nr;
+} BME_Poly;
+
+/*EDGE UTILITIES*/
+int BME_verts_in_edge(struct BME_Vert *v1, struct BME_Vert *v2, struct BME_Edge *e);
+int BME_vert_in_edge(struct BME_Edge *e, BME_Vert *v);
+struct BME_Vert *BME_edge_getothervert(struct BME_Edge *e, struct BME_Vert *v);
+
+/*GENERAL CYCLE*/
+int BME_cycle_length(void *h);
+
+/*DISK CYCLE*/
+struct BME_Edge *BME_disk_nextedge(struct BME_Edge *e, struct BME_Vert *v);
+struct BME_CycleNode *BME_disk_getpointer(struct BME_Edge *e, struct BME_Vert *v);
+struct BME_Edge *BME_disk_next_edgeflag(struct BME_Edge *e, struct BME_Vert *v, int eflag, int tflag);
+int BME_disk_count_edgeflag(struct BME_Vert *v, int eflag, int tflag);
+
+/*RADIAL CYCLE*/
+struct BME_Loop *BME_radial_nextloop(struct BME_Loop *l);
+int BME_radial_find_face(struct BME_Edge *e,struct BME_Poly *f);
+
+/*LOOP CYCLE*/
+struct BME_Loop *BME_loop_find_loop(struct BME_Poly *f, struct BME_Vert *v);
+
+/*MESH CREATION/DESTRUCTION*/
+struct BME_Mesh *BME_make_mesh(int allocsize[4]);
+void BME_free_mesh(struct BME_Mesh *bm);
+/*FULL MESH VALIDATION*/
+int BME_validate_mesh(struct BME_Mesh *bm, int halt);
+/*ENTER/EXIT MODELLING LOOP*/
+int BME_model_begin(struct BME_Mesh *bm);
+void BME_model_end(struct BME_Mesh *bm);
+
+/*MESH CONSTRUCTION API.*/
+/*MAKE*/
+struct BME_Vert *BME_MV(struct BME_Mesh *bm, float *vec);
+struct BME_Edge *BME_ME(struct BME_Mesh *bm, struct BME_Vert *v1, struct BME_Vert *v2);
+struct BME_Poly *BME_MF(struct BME_Mesh *bm, struct BME_Vert *v1, struct BME_Vert *v2, struct BME_Edge **elist, int len);
+/*KILL*/
+int BME_KV(struct BME_Mesh *bm, struct BME_Vert *v);
+int BME_KE(struct BME_Mesh *bm, struct BME_Edge *e);
+int BME_KF(struct BME_Mesh *bm, struct BME_Poly *bply);
+/*SPLIT*/
+struct BME_Vert *BME_SEMV(struct BME_Mesh *bm, struct BME_Vert *tv, struct BME_Edge *e, struct BME_Edge **re);
+struct BME_Poly *BME_SFME(struct BME_Mesh *bm, struct BME_Poly *f, struct BME_Vert *v1, struct BME_Vert *v2, struct BME_Loop **rl);
+/*JOIN*/
+int BME_JEKV(struct BME_Mesh *bm, struct BME_Edge *ke, struct BME_Vert *kv);
+struct BME_Poly *BME_JFKE(struct BME_Mesh *bm, struct BME_Poly *f1, struct BME_Poly *f2,struct BME_Edge *e); /*no reason to return BME_Poly pointer?*/
+/*NORMAL FLIP(Is its own inverse)*/
+int BME_loop_reverse(struct BME_Mesh *bm, struct BME_Poly *f);
+
+/* bevel tool defines */
+/* element flags */
+#define BME_BEVEL_ORIG 1
+#define BME_BEVEL_BEVEL (1<<1)
+#define BME_BEVEL_NONMAN (1<<2)
+#define BME_BEVEL_WIRE (1<<3)
+
+/* tool options */
+#define BME_BEVEL_SELECT 1
+#define BME_BEVEL_VERT (1<<1)
+#define BME_BEVEL_RADIUS (1<<2)
+#define BME_BEVEL_ANGLE (1<<3)
+#define BME_BEVEL_WEIGHT (1<<4)
+//~ #define BME_BEVEL_EWEIGHT (1<<4)
+//~ #define BME_BEVEL_VWEIGHT (1<<5)
+#define BME_BEVEL_PERCENT (1<<6)
+#define BME_BEVEL_EMIN (1<<7)
+#define BME_BEVEL_EMAX (1<<8)
+#define BME_BEVEL_RUNNING (1<<9)
+#define BME_BEVEL_RES (1<<10)
+
+typedef struct BME_TransData {
+ BME_Mesh *bm; /* the bmesh the vert belongs to */
+ BME_Vert *v; /* pointer to the vert this tdata applies to */
+ float co[3]; /* the original coordinate */
+ float org[3]; /* the origin */
+ float vec[3]; /* a directional vector; always, always normalize! */
+ void *loc; /* a pointer to the data to transform (likely the vert's cos) */
+ float factor; /* primary scaling factor; also accumulates number of weighted edges for beveling tool */
+ float weight; /* another scaling factor; used primarily for propogating vertex weights to transforms; */
+ /* weight is also used across recursive bevels to help with the math */
+ float maxfactor; /* the unscaled, original factor (used only by "edge verts" in recursive beveling) */
+ float *max; /* the maximum distance this vert can be transformed; negative is infinite
+ * it points to the "parent" maxfactor (where maxfactor makes little sense)
+ * where the max limit is stored (limits are stored per-corner) */
+} BME_TransData;
+
+typedef struct BME_TransData_Head {
+ GHash *gh; /* the hash structure for element lookup */
+ MemArena *ma; /* the memory "pool" we will be drawing individual elements from */
+ int len;
+} BME_TransData_Head;
+
+typedef struct BME_Glob { /* stored in Global G for Transform() purposes */
+ BME_Mesh *bm;
+ BME_TransData_Head *td;
+ struct TransInfo *Trans; /* a pointer to the global Trans struct */
+ int imval[2]; /* for restoring original mouse co when initTransform() is called multiple times */
+ int options;
+ int res;
+} BME_Glob;
+
+struct BME_TransData *BME_get_transdata(struct BME_TransData_Head *td, struct BME_Vert *v);
+void BME_free_transdata(struct BME_TransData_Head *td);
+float *BME_bevel_calc_polynormal(struct BME_Poly *f, struct BME_TransData_Head *td);
+struct BME_Mesh *BME_bevel(struct BME_Mesh *bm, float value, int res, int options, int defgrp_index, float angle, BME_TransData_Head **rtd);
+
+/*CONVERSION FUNCTIONS*/
+struct BME_Mesh *BME_editmesh_to_bmesh(EditMesh *em);
+struct EditMesh *BME_bmesh_to_editmesh(struct BME_Mesh *bm, BME_TransData_Head *td);
+struct BME_Mesh *BME_derivedmesh_to_bmesh(struct DerivedMesh *dm);
+struct DerivedMesh *BME_bmesh_to_derivedmesh(struct BME_Mesh *bm, struct DerivedMesh *dm);
+#endif
diff --git a/source/blender/blenkernel/BKE_bmeshCustomData.h b/source/blender/blenkernel/BKE_bmeshCustomData.h
new file mode 100644
index 00000000000..4f5f2641f54
--- /dev/null
+++ b/source/blender/blenkernel/BKE_bmeshCustomData.h
@@ -0,0 +1,108 @@
+/**
+ * BKE_bmesh.h jan 2007
+ *
+ * BMesh modeler structure and functions.
+ *
+ * $Id: BKE_bmesh.h,v 1.00 2007/01/17 17:42:01 Briggs Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2004 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Geoffrey Bantle.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+
+#ifndef BKE_BMESHCUSTOMDATA_H
+#define BKE_BMESHCUSTOMDATA_H
+
+struct BLI_mempool;
+
+/*Custom Data Types and defines
+ Eventual plan is to move almost everything to custom data and let caller
+ decide when making the mesh what layers they want to store in the mesh
+
+ This stuff should probably go in a seperate file....
+*/
+
+#define BME_CD_FACETEX 0 /*Image texture/texface*/
+#define BME_CD_LOOPTEX 1 /*UV coordinates*/
+#define BME_CD_LOOPCOL 2 /*Vcolors*/
+#define BME_CD_DEFORMVERT 3 /*Vertex Group/Weights*/
+#define BME_CD_NUMTYPES 4
+
+typedef struct BME_CustomDataLayer {
+ int type; /* type of data in layer */
+ int offset; /* offset of layer in block */
+ int active; /* offset of active layer*/
+ char name[32]; /* layer name */
+} BME_CustomDataLayer;
+
+typedef struct BME_CustomData {
+ struct BME_CustomDataLayer *layers; /*Custom Data Layers*/
+ struct BLI_mempool *pool; /*pool for alloc of blocks*/
+ int totlayer, totsize; /*total layers and total size in bytes of each block*/
+} BME_CustomData;
+
+typedef struct BME_CustomDataInit{
+ int layout[BME_CD_NUMTYPES];
+ int active[BME_CD_NUMTYPES];
+ int totlayers;
+ char *nametemplate;
+} BME_CustomDataInit;
+
+/*Custom data types*/
+typedef struct BME_DeformWeight {
+ int def_nr;
+ float weight;
+} BME_DeformWeight;
+
+typedef struct BME_DeformVert {
+ struct BME_DeformWeight *dw;
+ int totweight;
+} BME_DeformVert;
+
+typedef struct BME_facetex{
+ struct Image *tpage;
+ char flag, transp;
+ short mode, tile, unwrap;
+}BME_facetex;
+
+typedef struct BME_looptex{
+ float u, v;
+}BME_looptex;
+
+typedef struct BME_loopcol{
+ char r, g, b, a;
+}BME_loopcol;
+
+/*CUSTOM DATA API*/
+void BME_CD_Create(struct BME_CustomData *data, struct BME_CustomDataInit *init, int initalloc);
+void BME_CD_Free(struct BME_CustomData *data);
+void BME_CD_free_block(struct BME_CustomData *data, void **block);
+void BME_CD_copy_data(const struct BME_CustomData *source, struct BME_CustomData *dest, void *src_block, void **dest_block);
+void BME_CD_set_default(struct BME_CustomData *data, void **block);
+
+#endif
diff --git a/source/blender/blenkernel/BKE_brush.h b/source/blender/blenkernel/BKE_brush.h
index bf8e046eb20..f1f4653f092 100644
--- a/source/blender/blenkernel/BKE_brush.h
+++ b/source/blender/blenkernel/BKE_brush.h
@@ -45,7 +45,7 @@ void free_brush(struct Brush *brush);
int brush_set_nr(struct Brush **current_brush, int nr);
int brush_delete(struct Brush **current_brush);
void brush_check_exists(struct Brush **brush);
-void brush_toggle_fake_user(struct Brush *brush);
+void brush_toggled_fake_user(struct Brush *brush);
int brush_texture_set_nr(struct Brush *brush, int nr);
int brush_texture_delete(struct Brush *brush);
int brush_clone_image_set_nr(struct Brush *brush, int nr);
diff --git a/source/blender/blenkernel/BKE_bullet.h b/source/blender/blenkernel/BKE_bullet.h
new file mode 100644
index 00000000000..1c3bb175d66
--- /dev/null
+++ b/source/blender/blenkernel/BKE_bullet.h
@@ -0,0 +1,43 @@
+/**
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef BKE_BULLET_H
+#define BKE_BULLET_H
+
+struct BulletSoftBody;
+
+
+/* allocates and initializes general main data */
+extern struct BulletSoftBody *bsbNew(void);
+
+/* frees internal data and softbody itself */
+extern void bsbFree(struct BulletSoftBody *sb);
+
+#endif
+
diff --git a/source/blender/blenkernel/BKE_bvhutils.h b/source/blender/blenkernel/BKE_bvhutils.h
new file mode 100644
index 00000000000..dd9ea61f24b
--- /dev/null
+++ b/source/blender/blenkernel/BKE_bvhutils.h
@@ -0,0 +1,98 @@
+/**
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2006 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): André Pinto
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef BKE_BVHUTILS_H
+#define BKE_BVHUTILS_H
+
+#include "BLI_kdopbvh.h"
+
+/*
+ * This header encapsulates necessary code to buld a BVH
+ */
+
+struct DerivedMesh;
+struct MVert;
+struct MFace;
+
+/*
+ * struct that kepts basic information about a BVHTree build from a mesh
+ */
+typedef struct BVHTreeFromMesh
+{
+ struct BVHTree *tree;
+
+ /* default callbacks to bvh nearest and raycast */
+ BVHTree_NearestPointCallback nearest_callback;
+ BVHTree_RayCastCallback raycast_callback;
+
+ /* Mesh represented on this BVHTree */
+ struct DerivedMesh *mesh;
+
+ /* Vertex array, so that callbacks have instante access to data */
+ struct MVert *vert;
+ struct MFace *face;
+
+ /* radius for raycast */
+ float sphere_radius;
+
+} BVHTreeFromMesh;
+
+/*
+ * Builds a bvh tree where nodes are the vertexs of the given mesh.
+ * Configures BVHTreeFromMesh.
+ *
+ * The tree is build in mesh space coordinates, this means special care must be made on queries
+ * so that the coordinates and rays are first translated on the mesh local coordinates.
+ * Reason for this is that later bvh_from_mesh_* might use a cache system and so it becames possible to reuse
+ * a BVHTree.
+ *
+ * free_bvhtree_from_mesh should be called when the tree is no longer needed.
+ */
+void bvhtree_from_mesh_verts(struct BVHTreeFromMesh *data, struct DerivedMesh *mesh, float epsilon, int tree_type, int axis);
+
+/*
+ * Builds a bvh tree where nodes are the faces of the given mesh.
+ * Configures BVHTreeFromMesh.
+ *
+ * The tree is build in mesh space coordinates, this means special care must be made on queries
+ * so that the coordinates and rays are first translated on the mesh local coordinates.
+ * Reason for this is that later bvh_from_mesh_* might use a cache system and so it becames possible to reuse
+ * a BVHTree.
+ *
+ * free_bvhtree_from_mesh should be called when the tree is no longer needed.
+ */
+void bvhtree_from_mesh_faces(struct BVHTreeFromMesh *data, struct DerivedMesh *mesh, float epsilon, int tree_type, int axis);
+
+/*
+ * Frees data allocated by a call to bvhtree_from_mesh_*.
+ */
+void free_bvhtree_from_mesh(struct BVHTreeFromMesh *data);
+
+#endif
+
diff --git a/source/blender/blenkernel/BKE_cloth.h b/source/blender/blenkernel/BKE_cloth.h
new file mode 100644
index 00000000000..f3c13d3d820
--- /dev/null
+++ b/source/blender/blenkernel/BKE_cloth.h
@@ -0,0 +1,282 @@
+/**
+ * BKE_cloth.h
+ *
+ * $Id: BKE_cloth.h,v 1.1 2007/08/01 02:07:27 daniel Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Daniel Genrich
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef BKE_CLOTH_H
+#define BKE_CLOTH_H
+
+#include <float.h>
+
+#include "BLI_linklist.h"
+#include "BKE_customdata.h"
+#include "BKE_DerivedMesh.h"
+
+#include "BLI_blenlib.h"
+#include "BLI_arithb.h"
+#include "BLI_edgehash.h"
+
+#include "DNA_cloth_types.h"
+#include "DNA_customdata_types.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_modifier_types.h"
+#include "DNA_object_types.h"
+
+#include "BKE_collision.h"
+
+struct Object;
+
+struct MFace;
+struct DerivedMesh;
+struct ClothModifierData;
+struct CollisionTree;
+
+// this is needed for inlining behaviour
+#if defined _WIN32
+# define DO_INLINE __inline
+#elif defined (__sgi)
+# define DO_INLINE
+#elif defined (__sun) || defined (__sun__)
+# define DO_INLINE
+#else
+# define DO_INLINE inline
+# define LINUX
+#endif
+
+#define CLOTH_MAX_THREAD 2
+
+/* goal defines */
+#define SOFTGOALSNAP 0.999f
+
+/* This is approximately the smallest number that can be
+* represented by a float, given its precision. */
+#define ALMOST_ZERO FLT_EPSILON
+
+/* Bits to or into the ClothVertex.flags. */
+#define CLOTH_VERT_FLAG_PINNED 1
+#define CLOTH_VERT_FLAG_COLLISION 2
+#define CLOTH_VERT_FLAG_PINNED_EM 3
+
+/**
+* This structure describes a cloth object against which the
+* simulation can run.
+*
+* The m and n members of this structure represent the assumed
+* rectangular ordered grid for which the original paper is written.
+* At some point they need to disappear and we need to determine out
+* own connectivity of the mesh based on the actual edges in the mesh.
+*
+**/
+typedef struct Cloth
+{
+ struct ClothVertex *verts; /* The vertices that represent this cloth. */
+ struct LinkNode *springs; /* The springs connecting the mesh. */
+ unsigned int numverts; /* The number of verts == m * n. */
+ unsigned int numsprings; /* The count of springs. */
+ unsigned int numfaces;
+ unsigned char old_solver_type; /* unused, only 1 solver here */
+ unsigned char pad2;
+ short pad3;
+ struct BVHTree *bvhtree; /* collision tree for this cloth object */
+ struct BVHTree *bvhselftree; /* collision tree for this cloth object */
+ struct MFace *mfaces;
+ struct Implicit_Data *implicit; /* our implicit solver connects to this pointer */
+ struct Implicit_Data *implicitEM; /* our implicit solver connects to this pointer */
+ struct EdgeHash *edgehash; /* used for selfcollisions */
+} Cloth;
+
+/**
+ * The definition of a cloth vertex.
+ */
+typedef struct ClothVertex
+{
+ int flags; /* General flags per vertex. */
+ float v [3]; /* The velocity of the point. */
+ float xconst [3]; /* constrained position */
+ float x [3]; /* The current position of this vertex. */
+ float xold [3]; /* The previous position of this vertex.*/
+ float tx [3]; /* temporary position */
+ float txold [3]; /* temporary old position */
+ float tv[3]; /* temporary "velocity", mostly used as tv = tx-txold */
+ float mass; /* mass / weight of the vertex */
+ float goal; /* goal, from SB */
+ float impulse[3]; /* used in collision.c */
+ unsigned int impulse_count; /* same as above */
+ float avg_spring_len; /* average length of connected springs */
+ float struct_stiff;
+ float bend_stiff;
+ float shear_stiff;
+ int spring_count; /* how many springs attached? */
+}
+ClothVertex;
+
+/**
+ * The definition of a spring.
+ */
+typedef struct ClothSpring
+{
+ int ij; /* Pij from the paper, one end of the spring. */
+ int kl; /* Pkl from the paper, one end of the spring. */
+ float restlen; /* The original length of the spring. */
+ int matrix_index; /* needed for implicit solver (fast lookup) */
+ int type; /* types defined in BKE_cloth.h ("springType") */
+ int flags; /* defined in BKE_cloth.h, e.g. deactivated due to tearing */
+ float dfdx[3][3];
+ float dfdv[3][3];
+ float f[3];
+ float stiffness; /* stiffness factor from the vertex groups */
+ float editrestlen;
+}
+ClothSpring;
+
+// some macro enhancements for vector treatment
+#define VECADDADD(v1,v2,v3) {*(v1)+= *(v2) + *(v3); *(v1+1)+= *(v2+1) + *(v3+1); *(v1+2)+= *(v2+2) + *(v3+2);}
+#define VECSUBADD(v1,v2,v3) {*(v1)-= *(v2) + *(v3); *(v1+1)-= *(v2+1) + *(v3+1); *(v1+2)-= *(v2+2) + *(v3+2);}
+#define VECADDSUB(v1,v2,v3) {*(v1)+= *(v2) - *(v3); *(v1+1)+= *(v2+1) - *(v3+1); *(v1+2)+= *(v2+2) - *(v3+2);}
+#define VECSUBADDSS(v1,v2,aS,v3,bS) {*(v1)-= *(v2)*aS + *(v3)*bS; *(v1+1)-= *(v2+1)*aS + *(v3+1)*bS; *(v1+2)-= *(v2+2)*aS + *(v3+2)*bS;}
+#define VECADDSUBSS(v1,v2,aS,v3,bS) {*(v1)+= *(v2)*aS - *(v3)*bS; *(v1+1)+= *(v2+1)*aS - *(v3+1)*bS; *(v1+2)+= *(v2+2)*aS - *(v3+2)*bS;}
+#define VECADDSS(v1,v2,aS,v3,bS) {*(v1)= *(v2)*aS + *(v3)*bS; *(v1+1)= *(v2+1)*aS + *(v3+1)*bS; *(v1+2)= *(v2+2)*aS + *(v3+2)*bS;}
+#define VECADDS(v1,v2,v3,bS) {*(v1)= *(v2) + *(v3)*bS; *(v1+1)= *(v2+1) + *(v3+1)*bS; *(v1+2)= *(v2+2) + *(v3+2)*bS;}
+#define VECSUBMUL(v1,v2,aS) {*(v1)-= *(v2) * aS; *(v1+1)-= *(v2+1) * aS; *(v1+2)-= *(v2+2) * aS;}
+#define VECSUBS(v1,v2,v3,bS) {*(v1)= *(v2) - *(v3)*bS; *(v1+1)= *(v2+1) - *(v3+1)*bS; *(v1+2)= *(v2+2) - *(v3+2)*bS;}
+#define VECSUBSB(v1,v2, v3,bS) {*(v1)= (*(v2)- *(v3))*bS; *(v1+1)= (*(v2+1) - *(v3+1))*bS; *(v1+2)= (*(v2+2) - *(v3+2))*bS;}
+#define VECMULS(v1,aS) {*(v1)*= aS; *(v1+1)*= aS; *(v1+2)*= *aS;}
+#define VECADDMUL(v1,v2,aS) {*(v1)+= *(v2) * aS; *(v1+1)+= *(v2+1) * aS; *(v1+2)+= *(v2+2) * aS;}
+
+/* SIMULATION FLAGS: goal flags,.. */
+/* These are the bits used in SimSettings.flags. */
+typedef enum
+{
+ CLOTH_SIMSETTINGS_FLAG_COLLOBJ = ( 1 << 2 ),// object is only collision object, no cloth simulation is done
+ CLOTH_SIMSETTINGS_FLAG_GOAL = ( 1 << 3 ), // we have goals enabled
+ CLOTH_SIMSETTINGS_FLAG_TEARING = ( 1 << 4 ),// true if tearing is enabled
+ CLOTH_SIMSETTINGS_FLAG_SCALING = ( 1 << 8 ), /* is advanced scaling active? */
+ CLOTH_SIMSETTINGS_FLAG_CCACHE_EDIT = (1 << 12) /* edit cache in editmode */
+} CLOTH_SIMSETTINGS_FLAGS;
+
+/* COLLISION FLAGS */
+typedef enum
+{
+ CLOTH_COLLSETTINGS_FLAG_ENABLED = ( 1 << 1 ), /* enables cloth - object collisions */
+ CLOTH_COLLSETTINGS_FLAG_SELF = ( 1 << 2 ), /* enables selfcollisions */
+} CLOTH_COLLISIONSETTINGS_FLAGS;
+
+/* Spring types as defined in the paper.*/
+typedef enum
+{
+ CLOTH_SPRING_TYPE_STRUCTURAL = ( 1 << 1 ),
+ CLOTH_SPRING_TYPE_SHEAR = ( 1 << 2 ) ,
+ CLOTH_SPRING_TYPE_BENDING = ( 1 << 3 ),
+ CLOTH_SPRING_TYPE_GOAL = ( 1 << 4 ),
+} CLOTH_SPRING_TYPES;
+
+/* SPRING FLAGS */
+typedef enum
+{
+ CLOTH_SPRING_FLAG_DEACTIVATE = ( 1 << 1 ),
+ CLOTH_SPRING_FLAG_NEEDED = ( 1 << 2 ), // springs has values to be applied
+} CLOTH_SPRINGS_FLAGS;
+
+
+/////////////////////////////////////////////////
+// collision.c
+////////////////////////////////////////////////
+
+// needed for implicit.c
+int cloth_bvh_objcollision ( Object *ob, ClothModifierData * clmd, float step, float dt );
+
+////////////////////////////////////////////////
+
+
+////////////////////////////////////////////////
+// implicit.c
+////////////////////////////////////////////////
+
+// needed for cloth.c
+int implicit_init ( Object *ob, ClothModifierData *clmd );
+int implicit_free ( ClothModifierData *clmd );
+int implicit_solver ( Object *ob, float frame, ClothModifierData *clmd, ListBase *effectors );
+void implicit_set_positions ( ClothModifierData *clmd );
+
+// globally needed
+void clmdSetInterruptCallBack ( int ( *f ) ( void ) );
+////////////////////////////////////////////////
+
+
+/////////////////////////////////////////////////
+// cloth.c
+////////////////////////////////////////////////
+
+// needed for modifier.c
+void cloth_free_modifier_extern ( ClothModifierData *clmd );
+void cloth_free_modifier ( Object *ob, ClothModifierData *clmd );
+void cloth_init ( ClothModifierData *clmd );
+DerivedMesh *clothModifier_do ( ClothModifierData *clmd,Object *ob, DerivedMesh *dm, int useRenderParams, int isFinalCalc );
+
+void cloth_update_normals ( ClothVertex *verts, int nVerts, MFace *face, int totface );
+
+// needed for collision.c
+void bvhtree_update_from_cloth ( ClothModifierData *clmd, int moving );
+void bvhselftree_update_from_cloth ( ClothModifierData *clmd, int moving );
+
+// needed for editmesh.c
+void cloth_write_cache ( Object *ob, ClothModifierData *clmd, float framenr );
+int cloth_read_cache ( Object *ob, ClothModifierData *clmd, float framenr );
+
+// needed for button_object.c
+void cloth_clear_cache ( Object *ob, ClothModifierData *clmd, float framenr );
+
+// needed for cloth.c
+int cloth_add_spring ( ClothModifierData *clmd, unsigned int indexA, unsigned int indexB, float restlength, int spring_type);
+
+////////////////////////////////////////////////
+
+
+/* This enum provides the IDs for our solvers. */
+// only one available in the moment
+typedef enum
+{
+ CM_IMPLICIT = 0,
+} CM_SOLVER_ID;
+
+
+/* This structure defines how to call the solver.
+*/
+typedef struct
+{
+ char *name;
+ CM_SOLVER_ID id;
+ int ( *init ) ( Object *ob, ClothModifierData *clmd );
+ int ( *solver ) ( Object *ob, float framenr, ClothModifierData *clmd, ListBase *effectors );
+ int ( *free ) ( ClothModifierData *clmd );
+}
+CM_SOLVER_DEF;
+
+
+#endif
+
diff --git a/source/blender/blenkernel/BKE_collision.h b/source/blender/blenkernel/BKE_collision.h
new file mode 100644
index 00000000000..c483148e4de
--- /dev/null
+++ b/source/blender/blenkernel/BKE_collision.h
@@ -0,0 +1,150 @@
+/**
+ * BKE_cloth.h
+ *
+ * $Id: BKE_cloth.h,v 1.1 2007/08/01 02:07:27 daniel Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Daniel Genrich
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef BKE_COLLISIONS_H
+#define BKE_COLLISIONS_H
+
+#include <math.h>
+#include <float.h>
+#include <stdlib.h>
+#include <string.h>
+
+/* types */
+#include "BLI_linklist.h"
+#include "BKE_collision.h"
+#include "BKE_customdata.h"
+#include "BKE_DerivedMesh.h"
+#include "DNA_cloth_types.h"
+#include "DNA_customdata_types.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_modifier_types.h"
+#include "DNA_object_types.h"
+
+#include "BLI_kdopbvh.h"
+
+struct Object;
+struct Cloth;
+struct MFace;
+struct DerivedMesh;
+struct ClothModifierData;
+
+////////////////////////////////////////
+// used for collisions in collision.c
+////////////////////////////////////////
+
+/* COLLISION FLAGS */
+typedef enum
+{
+ COLLISION_IN_FUTURE = ( 1 << 1 ),
+} COLLISION_FLAGS;
+
+
+////////////////////////////////////////
+// used for collisions in collision.c
+////////////////////////////////////////
+/* used for collisions in collision.c */
+typedef struct CollPair
+{
+ unsigned int face1; // cloth face
+ unsigned int face2; // object face
+ double distance; // magnitude of vector
+ float normal[3];
+ float vector[3]; // unnormalized collision vector: p2-p1
+ float pa[3], pb[3]; // collision point p1 on face1, p2 on face2
+ int flag;
+ float time; // collision time, from 0 up to 1
+ int ap1, ap2, ap3, bp1, bp2, bp3;
+ int pointsb[4];
+}
+CollPair;
+
+/* used for collisions in collision.c */
+typedef struct EdgeCollPair
+{
+ unsigned int p11, p12, p21, p22;
+ float normal[3];
+ float vector[3];
+ float time;
+ int lastsign;
+ float pa[3], pb[3]; // collision point p1 on face1, p2 on face2
+}
+EdgeCollPair;
+
+/* used for collisions in collision.c */
+typedef struct FaceCollPair
+{
+ unsigned int p11, p12, p13, p21;
+ float normal[3];
+ float vector[3];
+ float time;
+ int lastsign;
+ float pa[3], pb[3]; // collision point p1 on face1, p2 on face2
+}
+FaceCollPair;
+////////////////////////////////////////
+
+
+
+/////////////////////////////////////////////////
+// forward declarations
+/////////////////////////////////////////////////
+
+/////////////////////////////////////////////////
+// used in modifier.c from collision.c
+/////////////////////////////////////////////////
+
+BVHTree *bvhtree_build_from_mvert ( MFace *mfaces, unsigned int numfaces, MVert *x, unsigned int numverts, float epsilon );
+void bvhtree_update_from_mvert ( BVHTree * bvhtree, MFace *faces, int numfaces, MVert *x, MVert *xnew, int numverts, int moving );
+
+/////////////////////////////////////////////////
+
+LinkNode *BLI_linklist_append_fast ( LinkNode **listp, void *ptr );
+
+// move Collision modifier object inter-frame with step = [0,1]
+// defined in collisions.c
+void collision_move_object ( CollisionModifierData *collmd, float step, float prevstep );
+
+// interface for collision functions
+void collisions_compute_barycentric ( float pv[3], float p1[3], float p2[3], float p3[3], float *w1, float *w2, float *w3 );
+void interpolateOnTriangle ( float to[3], float v1[3], float v2[3], float v3[3], double w1, double w2, double w3 );
+
+/////////////////////////////////////////////////
+// used in effect.c
+/////////////////////////////////////////////////
+CollisionModifierData **get_collisionobjects(Object *self, int *numcollobj);
+
+/////////////////////////////////////////////////
+
+
+
+/////////////////////////////////////////////////
+
+#endif
+
diff --git a/source/blender/blenkernel/BKE_colortools.h b/source/blender/blenkernel/BKE_colortools.h
index e78882220a9..555b467b1d6 100644
--- a/source/blender/blenkernel/BKE_colortools.h
+++ b/source/blender/blenkernel/BKE_colortools.h
@@ -57,6 +57,7 @@ void curvemapping_do_ibuf(struct CurveMapping *cumap, struct ImBuf *ibuf);
void curvemapping_premultiply(struct CurveMapping *cumap, int restore);
int curvemapping_RGBA_does_something(struct CurveMapping *cumap);
void curvemapping_initialize(struct CurveMapping *cumap);
+void curvemapping_table_RGBA(struct CurveMapping *cumap, float **array, int *size);
#endif
diff --git a/source/blender/blenkernel/BKE_constraint.h b/source/blender/blenkernel/BKE_constraint.h
index 0b544f20d2a..2f92fadd5ee 100644
--- a/source/blender/blenkernel/BKE_constraint.h
+++ b/source/blender/blenkernel/BKE_constraint.h
@@ -67,7 +67,7 @@ typedef struct bConstraintTypeInfo {
/* admin/ident */
short type; /* CONSTRAINT_TYPE_### */
short size; /* size in bytes of the struct */
- char name[32]; /* name constraint in interface */
+ char name[32]; /* name of constraint in interface */
char structName[32]; /* name of struct for SDNA */
/* data management function pointers - special handling */
@@ -81,8 +81,8 @@ typedef struct bConstraintTypeInfo {
void (*new_data)(void *cdata);
/* target handling function pointers */
- /* for multi-target constraints: return that list; otherwise make a temporary list */
- void (*get_constraint_targets)(struct bConstraint *con, struct ListBase *list);
+ /* for multi-target constraints: return that list; otherwise make a temporary list (returns number of targets) */
+ int (*get_constraint_targets)(struct bConstraint *con, struct ListBase *list);
/* for single-target constraints only: flush data back to source data, and the free memory used */
void (*flush_constraint_targets)(struct bConstraint *con, struct ListBase *list, short nocopy);
@@ -114,6 +114,9 @@ void copy_constraints(struct ListBase *dst, struct ListBase *src);
void relink_constraints(struct ListBase *list);
void free_constraint_data(struct bConstraint *con);
+/* Constraints + Proxies function prototypes */
+void extract_proxylocal_constraints(struct ListBase *dst, struct ListBase *src);
+short proxylocked_constraints_owner(struct Object *ob, struct bPoseChannel *pchan);
/* Constraint Channel function prototypes */
struct bConstraintChannel *get_constraint_channel(struct ListBase *list, const char *name);
@@ -123,6 +126,7 @@ void copy_constraint_channels(struct ListBase *dst, struct ListBase *src);
void clone_constraint_channels(struct ListBase *dst, struct ListBase *src);
void free_constraint_channels(struct ListBase *chanbase);
+
/* Constraint Evaluation function prototypes */
struct bConstraintOb *constraints_make_evalob(struct Object *ob, void *subdata, short datatype);
void constraints_clear_evalob(struct bConstraintOb *cob);
diff --git a/source/blender/blenkernel/BKE_curve.h b/source/blender/blenkernel/BKE_curve.h
index 60444675047..25d6d78c4aa 100644
--- a/source/blender/blenkernel/BKE_curve.h
+++ b/source/blender/blenkernel/BKE_curve.h
@@ -39,9 +39,12 @@ struct ListBase;
struct BezTriple;
struct BevList;
-#define KNOTSU(nu) ( (nu)->orderu+ (nu)->pntsu+ (nu->orderu-1)*((nu)->flagu & 1) )
-#define KNOTSV(nu) ( (nu)->orderv+ (nu)->pntsv+ (nu->orderv-1)*((nu)->flagv & 1) )
+#define KNOTSU(nu) ( (nu)->orderu+ (nu)->pntsu+ (((nu)->flagu & CU_CYCLIC) ? (nu->orderu-1) : 0) )
+#define KNOTSV(nu) ( (nu)->orderv+ (nu)->pntsv+ (((nu)->flagv & CU_CYCLIC) ? (nu->orderv-1) : 0) )
+/* Non cyclic nurbs have 1 less segment */
+#define SEGMENTSU(nu) ( ((nu)->flagu & CU_CYCLIC) ? (nu)->pntsu : (nu)->pntsu-1 )
+#define SEGMENTSV(nu) ( ((nu)->flagv & CU_CYCLIC) ? (nu)->pntsv : (nu)->pntsv-1 )
void unlink_curve( struct Curve *cu);
void free_curve( struct Curve *cu);
@@ -62,15 +65,14 @@ void minmaxNurb( struct Nurb *nu, float *min, float *max);
void makeknots( struct Nurb *nu, short uv, short type);
-void makeNurbfaces( struct Nurb *nu, float *data, int rowstride);
-void makeNurbcurve( struct Nurb *nu, float *data, int resolu, int dim);
+void makeNurbfaces(struct Nurb *nu, float *coord_array, int rowstride);
+void makeNurbcurve(struct Nurb *nu, float *coord_array, float *tilt_array, float *radius_array, int resolu);
void forward_diff_bezier(float q0, float q1, float q2, float q3, float *p, int it, int stride);
float *make_orco_curve( struct Object *ob);
float *make_orco_surf( struct Object *ob);
void makebevelcurve( struct Object *ob, struct ListBase *disp);
void makeBevelList( struct Object *ob);
-float calc_curve_subdiv_radius( struct Curve *cu, struct Nurb *nu, int cursubdiv);
void calchandleNurb( struct BezTriple *bezt, struct BezTriple *prev, struct BezTriple *next, int mode);
void calchandlesNurb( struct Nurb *nu);
@@ -84,5 +86,12 @@ void switchdirectionNurb( struct Nurb *nu);
float (*curve_getVertexCos(struct Curve *cu, struct ListBase *lb, int *numVerts_r))[3];
void curve_applyVertexCos(struct Curve *cu, struct ListBase *lb, float (*vertexCos)[3]);
+/* nurb checks if they can be drawn, also clamp order func */
+int check_valid_nurb_u( struct Nurb *nu);
+int check_valid_nurb_v( struct Nurb *nu);
+
+int clamp_nurb_order_u( struct Nurb *nu);
+int clamp_nurb_order_v( struct Nurb *nu);
+
#endif
diff --git a/source/blender/blenkernel/BKE_customdata.h b/source/blender/blenkernel/BKE_customdata.h
index d0535f1752e..c84b690bc49 100644
--- a/source/blender/blenkernel/BKE_customdata.h
+++ b/source/blender/blenkernel/BKE_customdata.h
@@ -32,14 +32,18 @@
#ifndef BKE_CUSTOMDATA_H
#define BKE_CUSTOMDATA_H
+#include "BLO_sys_types.h" // for intptr_t support
+
struct CustomData;
struct CustomDataLayer;
-typedef long CustomDataMask;
+typedef intptr_t CustomDataMask;
extern const CustomDataMask CD_MASK_BAREMESH;
extern const CustomDataMask CD_MASK_MESH;
extern const CustomDataMask CD_MASK_EDITMESH;
extern const CustomDataMask CD_MASK_DERIVEDMESH;
+extern const CustomDataMask CD_MASK_BMESH;
+extern const CustomDataMask CD_MASK_FACECORNERS;
/* for ORIGINDEX layer type, indicates no original index for this element */
#define ORIGINDEX_NONE -1
@@ -134,6 +138,9 @@ void CustomData_copy_data(const struct CustomData *source,
void CustomData_em_copy_data(const struct CustomData *source,
struct CustomData *dest, void *src_block,
void **dest_block);
+void CustomData_bmesh_copy_data(const struct CustomData *source,
+ struct CustomData *dest,void *src_block,
+ void **dest_block);
/* frees data in a CustomData object
* return 1 on success, 0 on failure
@@ -160,6 +167,10 @@ void CustomData_interp(const struct CustomData *source, struct CustomData *dest,
void CustomData_em_interp(struct CustomData *data, void **src_blocks,
float *weights, float *sub_weights, int count,
void *dest_block);
+void CustomData_bmesh_interp(struct CustomData *data, void **src_blocks,
+ float *weights, float *sub_weights, int count,
+ void *dest_block);
+
/* swaps the data in the element corners, to new corners with indices as
specified in corner_indices. for edges this is an array of length 2, for
@@ -172,6 +183,8 @@ void CustomData_swap(struct CustomData *data, int index, int *corner_indices);
void *CustomData_get(const struct CustomData *data, int index, int type);
void *CustomData_em_get(const struct CustomData *data, void *block, int type);
void *CustomData_em_get_n(const struct CustomData *data, void *block, int type, int n);
+void *CustomData_bmesh_get(const struct CustomData *data, void *block, int type);
+void *CustomData_bmesh_get_n(const struct CustomData *data, void *block, int type, int n);
/* gets a pointer to the active or first layer of type
* returns NULL if there is no layer of type
@@ -199,6 +212,12 @@ void CustomData_em_set(struct CustomData *data, void *block, int type,
void CustomData_em_set_n(struct CustomData *data, void *block, int type, int n,
void *source);
+void CustomData_bmesh_set(const struct CustomData *data, void *block, int type,
+ void *source);
+
+void CustomData_bmesh_set_n(struct CustomData *data, void *block, int type, int n,
+ void *source);
+
/* set the pointer of to the first layer of type. the old data is not freed.
* returns the value of ptr if the layer is found, NULL otherwise
*/
@@ -220,12 +239,20 @@ void CustomData_set_layer_flag(struct CustomData *data, int type, int flag);
void CustomData_em_set_default(struct CustomData *data, void **block);
void CustomData_em_free_block(struct CustomData *data, void **block);
+void CustomData_bmesh_set_default(struct CustomData *data, void **block);
+void CustomData_bmesh_free_block(struct CustomData *data, void **block);
+
/* copy custom data to/from layers as in mesh/derivedmesh, to editmesh
blocks of data. the CustomData's must not be compatible */
void CustomData_to_em_block(const struct CustomData *source,
struct CustomData *dest, int index, void **block);
void CustomData_from_em_block(const struct CustomData *source,
struct CustomData *dest, void *block, int index);
+void CustomData_to_bmesh_block(const struct CustomData *source,
+ struct CustomData *dest, int src_index, void **dest_block);
+void CustomData_from_bmesh_block(const struct CustomData *source,
+ struct CustomData *dest, void *src_block, int dest_index);
+
/* query info over types */
void CustomData_file_write_info(int type, char **structname, int *structnum);
@@ -241,4 +268,8 @@ void CustomData_set_layer_unique_name(struct CustomData *data, int index);
only after this test passes, layer->data should be assigned */
int CustomData_verify_versions(struct CustomData *data, int index);
+/*BMesh specific customdata stuff*/
+void CustomData_to_bmeshpoly(struct CustomData *fdata, struct CustomData *pdata, struct CustomData *ldata);
+void CustomData_from_bmeshpoly(struct CustomData *fdata, struct CustomData *pdata, struct CustomData *ldata, int total);
+void CustomData_bmesh_init_pool(struct CustomData *data, int allocsize);
#endif
diff --git a/source/blender/blenkernel/BKE_deform.h b/source/blender/blenkernel/BKE_deform.h
index a1975dd4265..e982806a6cc 100644
--- a/source/blender/blenkernel/BKE_deform.h
+++ b/source/blender/blenkernel/BKE_deform.h
@@ -38,6 +38,7 @@
struct Object;
struct ListBase;
struct bDeformGroup;
+struct MDeformVert;
void copy_defgroups (struct ListBase *lb1, struct ListBase *lb2);
struct bDeformGroup *copy_defgroup (struct bDeformGroup *ingroup);
@@ -46,5 +47,8 @@ int get_defgroup_num (struct Object *ob, struct bDeformGroup *dg);
int get_named_vertexgroup_num (Object *ob, char *name);
void unique_vertexgroup_name (struct bDeformGroup *dg, struct Object *ob);
+float deformvert_get_weight(const struct MDeformVert *dvert, int group_num);
+float vertexgroup_get_vertex_weight(const struct MDeformVert *dvert, int index, int group_num);
+
#endif
diff --git a/source/blender/blenkernel/BKE_depsgraph.h b/source/blender/blenkernel/BKE_depsgraph.h
index 48a8f8e4ffb..b86a58780dc 100644
--- a/source/blender/blenkernel/BKE_depsgraph.h
+++ b/source/blender/blenkernel/BKE_depsgraph.h
@@ -101,7 +101,7 @@ void DAG_scene_update_flags(struct Scene *sce, unsigned int lay);
void DAG_object_update_flags(struct Scene *sce, struct Object *ob, unsigned int lay);
/* flushes all recalc flags in objects down the dependency tree */
-void DAG_scene_flush_update(struct Scene *sce, unsigned int lay);
+void DAG_scene_flush_update(struct Scene *sce, unsigned int lay, int time);
/* flushes all recalc flags for this object down the dependency tree */
void DAG_object_flush_update(struct Scene *sce, struct Object *ob, short flag);
diff --git a/source/blender/blenkernel/BKE_displist.h b/source/blender/blenkernel/BKE_displist.h
index d6b438a3010..a534dcc3669 100644
--- a/source/blender/blenkernel/BKE_displist.h
+++ b/source/blender/blenkernel/BKE_displist.h
@@ -50,28 +50,6 @@
#define DL_FRONT_CURVE 4
#define DL_BACK_CURVE 8
-#define DL_SURFINDEX(cyclu, cyclv, sizeu, sizev) \
-\
-if( (cyclv)==0 && a==(sizev)-1) break; \
-if(cyclu) { \
- p1= sizeu*a; \
- p2= p1+ sizeu-1; \
- p3= p1+ sizeu; \
- p4= p2+ sizeu; \
- b= 0; \
-} \
-else { \
- p2= sizeu*a; \
- p1= p2+1; \
- p4= p2+ sizeu; \
- p3= p1+ sizeu; \
- b= 1; \
-} \
-if( (cyclv) && a==sizev-1) { \
- p3-= sizeu*sizev; \
- p4-= sizeu*sizev; \
-}
-
/* prototypes */
@@ -114,6 +92,7 @@ extern void makeDispListMBall(struct Object *ob);
extern void shadeDispList(struct Base *base);
extern void shadeMeshMCol(struct Object *ob, struct Mesh *me);
+int surfindex_displist(DispList *dl, int a, int *b, int *p1, int *p2, int *p3, int *p4);
void imagestodisplist(void);
void reshadeall_displist(void);
void filldisplist(struct ListBase *dispbase, struct ListBase *to);
diff --git a/source/blender/blenkernel/BKE_effect.h b/source/blender/blenkernel/BKE_effect.h
index 92aecfaa6f0..6475f7a71ac 100644
--- a/source/blender/blenkernel/BKE_effect.h
+++ b/source/blender/blenkernel/BKE_effect.h
@@ -35,9 +35,9 @@
struct Effect;
struct ListBase;
-struct PartEff;
struct Particle;
struct Group;
+struct RNG;
typedef struct pEffectorCache {
struct pEffectorCache *next, *prev;
@@ -51,25 +51,25 @@ typedef struct pEffectorCache {
Object obcopy; /* for restoring transformation data */
} pEffectorCache;
-
-struct Effect *add_effect(int type);
void free_effect(struct Effect *eff);
void free_effects(struct ListBase *lb);
struct Effect *copy_effect(struct Effect *eff);
-void copy_act_effect(struct Object *ob);
void copy_effects(struct ListBase *lbn, struct ListBase *lb);
void deselectall_eff(struct Object *ob);
-struct PartEff *give_parteff(struct Object *ob);
-void where_is_particle(struct PartEff *paf, struct Particle *pa, float ctime, float *vec);
-void build_particle_system(struct Object *ob);
/* particle deflector */
#define PE_WIND_AS_SPEED 0x00000001
+struct PartEff *give_parteff(struct Object *ob);
struct ListBase *pdInitEffectors(struct Object *obsrc, struct Group *group);
void pdEndEffectors(struct ListBase *lb);
void pdDoEffectors(struct ListBase *lb, float *opco, float *force, float *speed, float cur_time, float loc_time, unsigned int flags);
+/* required for particle_system.c */
+void do_physical_effector(Object *ob, float *opco, short type, float force_val, float distance, float falloff, float size, float damp, float *eff_velocity, float *vec_to_part, float *velocity, float *field, int planar, struct RNG *rng, float noise_factor, float charge, float pa_size);
+float effector_falloff(struct PartDeflect *pd, float *eff_velocity, float *vec_to_part);
+
+
#endif
diff --git a/source/blender/blenkernel/BKE_endian.h b/source/blender/blenkernel/BKE_endian.h
index 1757103eaf6..dc5efd5ea46 100644
--- a/source/blender/blenkernel/BKE_endian.h
+++ b/source/blender/blenkernel/BKE_endian.h
@@ -33,11 +33,11 @@
#define BKE_ENDIANNESS(a) { \
union { \
- long l; \
- char c[sizeof (long)]; \
+ intptr_t l; \
+ char c[sizeof (intptr_t)]; \
} u; \
u.l = 1; \
- a = (u.c[sizeof (long) - 1] == 1) ? 1 : 0; \
+ a = (u.c[sizeof (intptr_t) - 1] == 1) ? 1 : 0; \
}
#endif
diff --git a/source/blender/blenkernel/BKE_fluidsim.h b/source/blender/blenkernel/BKE_fluidsim.h
new file mode 100644
index 00000000000..4aac5eafa00
--- /dev/null
+++ b/source/blender/blenkernel/BKE_fluidsim.h
@@ -0,0 +1,56 @@
+/**
+ * BKE_fluidsim.h
+ *
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "DNA_modifier_types.h"
+#include "DNA_object_fluidsim.h" // N_T
+#include "DNA_object_types.h"
+
+#include "BKE_DerivedMesh.h"
+
+/* old interface */
+FluidsimSettings *fluidsimSettingsNew(Object *srcob);
+
+void initElbeemMesh(Object *ob, int *numVertices, float **vertices, int *numTriangles, int **triangles, int useGlobalCoords, int modifierIndex);
+
+
+/* new fluid-modifier interface */
+void fluidsim_init(FluidsimModifierData *fluidmd);
+void fluidsim_free(FluidsimModifierData *fluidmd);
+
+DerivedMesh *fluidsim_read_cache(Object *ob, DerivedMesh *orgdm, FluidsimModifierData *fluidmd, int framenr, int useRenderParams);
+void fluidsim_read_vel_cache(FluidsimModifierData *fluidmd, DerivedMesh *dm, char *filename);
+DerivedMesh *fluidsimModifier_do(FluidsimModifierData *fluidmd, Object *ob, DerivedMesh *dm, int useRenderParams, int isFinalCalc);
+
+// get bounding box of mesh
+void fluid_get_bb(MVert *mvert, int totvert, float obmat[][4],
+ /*RET*/ float start[3], /*RET*/ float size[3] );
+
+
+
diff --git a/source/blender/blenkernel/BKE_font.h b/source/blender/blenkernel/BKE_font.h
index c840c3d5cfc..3f6b295b9ba 100644
--- a/source/blender/blenkernel/BKE_font.h
+++ b/source/blender/blenkernel/BKE_font.h
@@ -31,6 +31,10 @@
#ifndef BKE_VFONT_H
#define BKE_VFONT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#include <wchar.h>
struct VFont;
@@ -68,7 +72,11 @@ int getselection(int *start, int *end);
void chtoutf8(unsigned long c, char *o);
void wcs2utf8s(char *dst, wchar_t *src);
int wcsleninu8(wchar_t *src);
-int utf8towchar_(wchar_t *w, char *c);
+int utf8towchar(wchar_t *w, char *c);
+
+#ifdef __cplusplus
+}
+#endif
#endif
diff --git a/source/blender/blenkernel/BKE_global.h b/source/blender/blenkernel/BKE_global.h
index f2929bd8d61..498fd6169b2 100644
--- a/source/blender/blenkernel/BKE_global.h
+++ b/source/blender/blenkernel/BKE_global.h
@@ -61,6 +61,7 @@ struct Object;
struct bSoundListener;
struct BMF_Font;
struct EditMesh;
+struct BME_Glob;
/* former global stuff. context is derived, not storage! */
typedef struct bContext {
@@ -131,6 +132,9 @@ typedef struct Global {
/* Editmode lists */
struct EditMesh *editMesh;
+
+ /* Used for BMesh transformations */
+ struct BME_Glob *editBMesh;
float textcurs[4][2];
@@ -165,6 +169,9 @@ typedef struct Global {
int compat; /* toggle compatibility mode for edge rendering */
int notonlysolid;/* T-> also edge-render transparent faces */
+ /* ndof device found ? */
+ int ndofdevice;
+
/* confusing... G.f and G.flags */
int flags;
@@ -173,10 +180,10 @@ typedef struct Global {
/* **************** GLOBAL ********************* */
/* G.f */
-#define G_DISABLE_OK (1 << 0)
+#define G_RENDER_OGL (1 << 0)
#define G_PLAYANIM (1 << 1)
/* also uses G_FILE_AUTOPLAY */
-#define G_SIMULATION (1 << 3)
+#define G_RENDER_SHADOW (1 << 3)
#define G_BACKBUFSEL (1 << 4)
#define G_PICKSEL (1 << 5)
#define G_DRAWNORMALS (1 << 6)
@@ -191,6 +198,7 @@ typedef struct Global {
#define G_WEIGHTPAINT (1 << 15)
#define G_TEXTUREPAINT (1 << 16)
/* #define G_NOFROZEN (1 << 17) also removed */
+#define G_GREASEPENCIL (1 << 17)
#define G_DRAWEDGES (1 << 18)
#define G_DRAWCREASES (1 << 19)
#define G_DRAWSEAMS (1 << 20)
@@ -200,7 +208,7 @@ typedef struct Global {
#define G_DRAW_FACEAREA (1 << 23)
#define G_DRAW_EDGEANG (1 << 24)
-#define G_RECORDKEYS (1 << 25)
+/* #define G_RECORDKEYS (1 << 25) also removed */
/*#ifdef WITH_VERSE*/
#define G_VERSE_CONNECTED (1 << 26)
#define G_DRAW_VERSE_DEBUG (1 << 27)
@@ -209,8 +217,9 @@ typedef struct Global {
#define G_SCULPTMODE (1 << 29)
#define G_PARTICLEEDIT (1 << 30)
-#define G_AUTOMATKEYS (1 << 30)
+/* #define G_AUTOMATKEYS (1 << 30) also removed */
#define G_HIDDENHANDLES (1 << 31) /* used for curves only */
+#define G_DRAWBWEIGHTS (1 << 31)
/* macro for testing face select mode
* Texture paint could be removed since selected faces are not used
@@ -232,8 +241,15 @@ typedef struct Global {
#define G_FILE_NO_UI (1 << 10)
#define G_FILE_GAME_TO_IPO (1 << 11)
#define G_FILE_GAME_MAT (1 << 12)
-#define G_FILE_DIAPLAY_LISTS (1 << 13)
+#define G_FILE_DISPLAY_LISTS (1 << 13)
#define G_FILE_SHOW_PHYSICS (1 << 14)
+#define G_FILE_GAME_MAT_GLSL (1 << 15)
+#define G_FILE_GLSL_NO_LIGHTS (1 << 16)
+#define G_FILE_GLSL_NO_SHADERS (1 << 17)
+#define G_FILE_GLSL_NO_SHADOWS (1 << 18)
+#define G_FILE_GLSL_NO_RAMPS (1 << 19)
+#define G_FILE_GLSL_NO_NODES (1 << 20)
+#define G_FILE_GLSL_NO_EXTRA_TEX (1 << 21)
/* G.windowstate */
#define G_WINDOWSTATE_USERDEF 0
@@ -280,3 +296,4 @@ extern Global G;
#endif
+
diff --git a/source/blender/blenkernel/BKE_group.h b/source/blender/blenkernel/BKE_group.h
index db2008cfef3..764bdf5d910 100644
--- a/source/blender/blenkernel/BKE_group.h
+++ b/source/blender/blenkernel/BKE_group.h
@@ -41,9 +41,10 @@ void free_group(struct Group *group);
void unlink_group(struct Group *group);
struct Group *add_group(char *name);
void add_to_group(struct Group *group, struct Object *ob);
-void rem_from_group(struct Group *group, struct Object *ob);
-struct Group *find_group(struct Object *ob);
+int rem_from_group(struct Group *group, struct Object *ob);
+struct Group *find_group(struct Object *ob, struct Group *group);
int object_in_group(struct Object *ob, struct Group *group);
+int group_is_animated(struct Object *parent, struct Group *group);
void group_tag_recalc(struct Group *group);
void group_handle_recalc_and_update(struct Object *parent, struct Group *group);
diff --git a/source/blender/blenkernel/BKE_idprop.h b/source/blender/blenkernel/BKE_idprop.h
index 46252b310ae..2274c54ad3b 100644
--- a/source/blender/blenkernel/BKE_idprop.h
+++ b/source/blender/blenkernel/BKE_idprop.h
@@ -46,6 +46,7 @@ struct ID;
typedef union {
int i;
float f;
+ double d;
char *str;
struct ID *id;
struct {
@@ -171,4 +172,9 @@ void IDP_FreeProperty(struct IDProperty *prop);
/*Unlinks any struct IDProperty<->ID linkage that might be going on.*/
void IDP_UnlinkProperty(struct IDProperty *prop);
+#define IDP_Int(prop) (prop->data.val)
+#define IDP_Float(prop) (*(float*)&prop->data.val)
+#define IDP_String(prop) ((char*)prop->data.pointer)
+#define IDP_Array(prop) (prop->data.pointer)
+
#endif /* _BKE_IDPROP_H */
diff --git a/source/blender/blenkernel/BKE_image.h b/source/blender/blenkernel/BKE_image.h
index d1aeb9d8a25..8dac282eedf 100644
--- a/source/blender/blenkernel/BKE_image.h
+++ b/source/blender/blenkernel/BKE_image.h
@@ -44,7 +44,7 @@ struct anim;
void free_image(struct Image *me);
void BKE_stamp_info(struct ImBuf *ibuf);
-void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height);
+void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height, int channels);
int BKE_write_ibuf(struct ImBuf *ibuf, char *name, int imtype, int subimtype, int quality);
void BKE_makepicstring(char *string, char *base, int frame, int imtype);
void BKE_add_image_extension(char *string, int imtype);
@@ -111,7 +111,7 @@ struct ImBuf *BKE_image_get_ibuf(struct Image *ima, struct ImageUser *iuser);
struct Image *BKE_add_image_file(const char *name);
/* adds image, adds ibuf, generates color or pattern */
-struct Image *BKE_add_image_size(int width, int height, char *name, short uvtestgrid, float color[4]);
+struct Image *BKE_add_image_size(int width, int height, char *name, int floatbuf, short uvtestgrid, float color[4]);
/* for reload, refresh, pack */
void BKE_image_signal(struct Image *ima, struct ImageUser *iuser, int signal);
@@ -145,6 +145,9 @@ void BKE_image_all_free_anim_ibufs(int except_frame);
void BKE_image_memorypack(struct Image *ima);
+/* prints memory statistics for images */
+void BKE_image_print_memlist(void);
+
#ifdef __cplusplus
}
#endif
diff --git a/source/blender/blenkernel/BKE_ipo.h b/source/blender/blenkernel/BKE_ipo.h
index 922f3201345..fdd176e0e64 100644
--- a/source/blender/blenkernel/BKE_ipo.h
+++ b/source/blender/blenkernel/BKE_ipo.h
@@ -31,6 +31,10 @@
#ifndef BKE_IPO_H
#define BKE_IPO_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
typedef struct CfraElem {
struct CfraElem *next, *prev;
float cfra;
@@ -50,41 +54,71 @@ struct bPoseChannel;
struct bActionChannel;
struct rctf;
+/* ------------ Time Management ------------ */
+
float frame_to_float(int cfra);
+/* ------------ IPO Management ---------- */
+
void free_ipo_curve(struct IpoCurve *icu);
void free_ipo(struct Ipo *ipo);
+
void ipo_default_v2d_cur(int blocktype, struct rctf *cur);
+
struct Ipo *add_ipo(char *name, int idcode);
struct Ipo *copy_ipo(struct Ipo *ipo);
+
void ipo_idnew(struct Ipo *ipo);
+
+struct IpoCurve *find_ipocurve(struct Ipo *ipo, int adrcode);
+short has_ipo_code(struct Ipo *ipo, int code);
+
+/* -------------- Make Local -------------- */
+
void make_local_obipo(struct Ipo *ipo);
void make_local_matipo(struct Ipo *ipo);
void make_local_keyipo(struct Ipo *ipo);
void make_local_ipo(struct Ipo *ipo);
-struct IpoCurve *find_ipocurve(struct Ipo *ipo, int adrcode);
+
+/* ------------ IPO-Curve Sanity ---------------- */
void calchandles_ipocurve(struct IpoCurve *icu);
void testhandles_ipocurve(struct IpoCurve *icu);
void sort_time_ipocurve(struct IpoCurve *icu);
int test_time_ipocurve(struct IpoCurve *icu);
+
+/* -------- IPO-Curve (Bezier) Calculations ---------- */
+
void correct_bezpart(float *v1, float *v2, float *v3, float *v4);
int findzero(float x, float q0, float q1, float q2, float q3, float *o);
void berekeny(float f1, float f2, float f3, float f4, float *o, int b);
void berekenx(float *f, float *o, int b);
+
+/* -------- IPO Curve Calculation and Evaluation --------- */
+
float eval_icu(struct IpoCurve *icu, float ipotime);
void calc_icu(struct IpoCurve *icu, float ctime);
float calc_ipo_time(struct Ipo *ipo, float ctime);
void calc_ipo(struct Ipo *ipo, float ctime);
+
+/* ------------ Keyframe Column Tools -------------- */
+
+void add_to_cfra_elem(struct ListBase *lb, struct BezTriple *bezt);
+void make_cfra_list(struct Ipo *ipo, struct ListBase *elems);
+
+/* ---------------- IPO DataAPI ----------------- */
+
void write_ipo_poin(void *poin, int type, float val);
float read_ipo_poin(void *poin, int type);
-void *give_mtex_poin(struct MTex *mtex, int adrcode );
-void *get_ipo_poin(struct ID *id, struct IpoCurve *icu, int *type);
+void *give_mtex_poin(struct MTex *mtex, int adrcode );
void *get_pchan_ipo_poin(struct bPoseChannel *pchan, int adrcode);
+void *get_ipo_poin(struct ID *id, struct IpoCurve *icu, int *type);
void set_icu_vars(struct IpoCurve *icu);
+/* ---------------- IPO Execution --------------- */
+
void execute_ipo(struct ID *id, struct Ipo *ipo);
void execute_action_ipo(struct bActionChannel *achan, struct bPoseChannel *pchan);
@@ -95,21 +129,20 @@ void do_ob_ipo(struct Object *ob);
void do_seq_ipo(struct Sequence *seq, int cfra);
void do_ob_ipodrivers(struct Object *ob, struct Ipo *ipo, float ctime);
-int has_ipo_code(struct Ipo *ipo, int code);
void do_all_data_ipos(void);
-int calc_ipo_spec(struct Ipo *ipo, int adrcode, float *ctime);
+short calc_ipo_spec(struct Ipo *ipo, int adrcode, float *ctime);
void clear_delta_obipo(struct Ipo *ipo);
-void add_to_cfra_elem(struct ListBase *lb, struct BezTriple *bezt);
-void make_cfra_list(struct Ipo *ipo, struct ListBase *elems);
-/* the sort is an IPO_Channel... */
-int IPO_GetChannels(struct Ipo *ipo, short *channels);
+/* ----------- IPO <-> GameEngine API ---------------- */
+
+/* the short is an IPO_Channel... */
-float IPO_GetFloatValue(struct Ipo *ipo,
-/* struct IPO_Channel channel, */
- /* channels are shorts... bit ugly for now*/
- short c,
- float ctime);
+short IPO_GetChannels(struct Ipo *ipo, short *channels);
+float IPO_GetFloatValue(struct Ipo *ipo, short c, float ctime);
+
+#ifdef __cplusplus
+};
+#endif
#endif
diff --git a/source/blender/blenkernel/BKE_key.h b/source/blender/blenkernel/BKE_key.h
index a6871aa837f..faf8692b89a 100644
--- a/source/blender/blenkernel/BKE_key.h
+++ b/source/blender/blenkernel/BKE_key.h
@@ -40,6 +40,11 @@ struct Object;
struct Lattice;
struct Mesh;
+/* Kernel prototypes */
+#ifdef __cplusplus
+extern "C" {
+#endif
+
void free_key(struct Key *sc);
struct Key *add_key(struct ID *id);
struct Key *copy_key(struct Key *key);
@@ -57,6 +62,12 @@ int do_ob_key(struct Object *ob);
struct Key *ob_get_key(struct Object *ob);
struct KeyBlock *ob_get_keyblock(struct Object *ob);
struct KeyBlock *key_get_keyblock(struct Key *key, int index);
+// needed for the GE
+void do_rel_key(int start, int end, int tot, char *basispoin, struct Key *key, int mode);
+
+#ifdef __cplusplus
+};
+#endif
#endif
diff --git a/source/blender/blenkernel/BKE_lattice.h b/source/blender/blenkernel/BKE_lattice.h
index 5620674e791..dc7c9dcd5e5 100644
--- a/source/blender/blenkernel/BKE_lattice.h
+++ b/source/blender/blenkernel/BKE_lattice.h
@@ -35,6 +35,7 @@ struct Lattice;
struct Object;
struct DerivedMesh;
struct BPoint;
+struct MDeformVert;
extern struct Lattice *editLatt;
@@ -67,5 +68,7 @@ float (*lattice_getVertexCos(struct Object *ob, int *numVerts_r))[3];
void lattice_applyVertexCos(struct Object *ob, float (*vertexCos)[3]);
void lattice_calc_modifiers(struct Object *ob);
+struct MDeformVert* lattice_get_deform_verts(struct Object *lattice);
+
#endif
diff --git a/source/blender/blenkernel/BKE_main.h b/source/blender/blenkernel/BKE_main.h
index 3b7c3bfbc0a..34ecb2bbba1 100644
--- a/source/blender/blenkernel/BKE_main.h
+++ b/source/blender/blenkernel/BKE_main.h
@@ -44,7 +44,7 @@ struct Library;
typedef struct Main {
struct Main *next, *prev;
- char name[160];
+ char name[240];
short versionfile, subversionfile;
short minversionfile, minsubversionfile;
diff --git a/source/blender/blenkernel/BKE_mball.h b/source/blender/blenkernel/BKE_mball.h
index 7dc70abde97..0dfc8ae6b28 100644
--- a/source/blender/blenkernel/BKE_mball.h
+++ b/source/blender/blenkernel/BKE_mball.h
@@ -91,7 +91,6 @@ typedef struct process { /* parameters, function, storage */
float (*function)(float, float, float);
float size, delta; /* cube size, normal delta */
int bounds; /* cube range within lattice */
- MB_POINT start; /* start point on surface */
CUBES *cubes; /* active cubes */
VERTICES vertices; /* surface vertices */
CENTERLIST **centers; /* cube center hash table */
@@ -151,7 +150,7 @@ void add_cube(PROCESS *mbproc, int i, int j, int k, int count);
void find_first_points(PROCESS *mbproc, struct MetaBall *mb, int a);
void fill_metaball_octal_node(octal_node *node, struct MetaElem *ml, short i);
-void subdivide_metaball_octal_node(octal_node *node, float *size, short depth);
+void subdivide_metaball_octal_node(octal_node *node, float size_x, float size_y, float size_z, short depth);
void free_metaball_octal_node(octal_node *node);
void init_metaball_octal_tree(int depth);
void polygonize(PROCESS *mbproc, struct MetaBall *mb);
@@ -162,8 +161,8 @@ void free_mball(struct MetaBall *mb);
struct MetaBall *add_mball(char *name);
struct MetaBall *copy_mball(struct MetaBall *mb);
void make_local_mball(struct MetaBall *mb);
-void tex_space_mball( struct Object *ob);
-void make_orco_mball( struct Object *ob);
+void tex_space_mball(struct Object *ob);
+float *make_orco_mball(struct Object *ob);
struct Object *find_basis_mball( struct Object *ob);
int is_basis_mball(struct Object *ob);
void metaball_polygonize(struct Object *ob);
diff --git a/source/blender/blenkernel/BKE_mesh.h b/source/blender/blenkernel/BKE_mesh.h
index be7e74bce99..2ca4b3aa39a 100644
--- a/source/blender/blenkernel/BKE_mesh.h
+++ b/source/blender/blenkernel/BKE_mesh.h
@@ -61,14 +61,13 @@ void boundbox_mesh(struct Mesh *me, float *loc, float *size);
void tex_space_mesh(struct Mesh *me);
float *get_mesh_orco_verts(struct Object *ob);
void transform_mesh_orco_verts(struct Mesh *me, float (*orco)[3], int totvert, int invert);
-void test_index_face(struct MFace *mface, struct CustomData *mfdata, int mfindex, int nr);
+int test_index_face(struct MFace *mface, struct CustomData *mfdata, int mfindex, int nr);
struct Mesh *get_mesh(struct Object *ob);
void set_mesh(struct Object *ob, struct Mesh *me);
void mball_to_mesh(struct ListBase *lb, struct Mesh *me);
void nurbs_to_mesh(struct Object *ob);
void free_dverts(struct MDeformVert *dvert, int totvert);
void copy_dverts(struct MDeformVert *dst, struct MDeformVert *src, int totvert); /* __NLA */
-int update_realtime_texture(struct MTFace *tface, double time);
void mesh_delete_material_index(struct Mesh *me, int index);
void mesh_set_smooth_flag(struct Object *meshOb, int enableSmooth);
@@ -93,6 +92,8 @@ float (*mesh_getRefKeyCos(struct Mesh *me, int *numVerts_r))[3];
/* UvVertMap */
+#define STD_UV_CONNECT_LIMIT 0.0001f
+
typedef struct UvVertMap {
struct UvMapVert **vert;
struct UvMapVert *buf;
@@ -101,7 +102,7 @@ typedef struct UvVertMap {
typedef struct UvMapVert {
struct UvMapVert *next;
unsigned int f;
- unsigned char tfindex, separate;
+ unsigned char tfindex, separate, flag;
} UvMapVert;
UvVertMap *make_uv_vert_map(struct MFace *mface, struct MTFace *tface, unsigned int totface, unsigned int totvert, int selected, float *limit);
diff --git a/source/blender/blenkernel/BKE_modifier.h b/source/blender/blenkernel/BKE_modifier.h
index 1b1b00372e7..a41716ed1ff 100644
--- a/source/blender/blenkernel/BKE_modifier.h
+++ b/source/blender/blenkernel/BKE_modifier.h
@@ -284,7 +284,9 @@ int modifiers_getCageIndex(struct Object *ob,
int *lastPossibleCageIndex_r);
int modifiers_isSoftbodyEnabled(struct Object *ob);
+int modifiers_isClothEnabled(struct Object *ob);
int modifiers_isParticleEnabled(struct Object *ob);
+
struct Object *modifiers_isDeformedByArmature(struct Object *ob);
struct Object *modifiers_isDeformedByLattice(struct Object *ob);
int modifiers_usesArmature(struct Object *ob, struct bArmature *arm);
diff --git a/source/blender/blenkernel/BKE_multires.h b/source/blender/blenkernel/BKE_multires.h
index 61eb796e53d..df565ddc7fe 100644
--- a/source/blender/blenkernel/BKE_multires.h
+++ b/source/blender/blenkernel/BKE_multires.h
@@ -61,7 +61,7 @@ void multires_load_cols(struct Mesh *me);
void multires_level_to_mesh(struct Object *ob, struct Mesh *me, const int render);
void multires_update_levels(struct Mesh *me, const int render);
void multires_update_first_level(struct Mesh *me, struct EditMesh *em);
-void multires_update_customdata(struct MultiresLevel *lvl1, struct CustomData *src,
+void multires_update_customdata(struct MultiresLevel *lvl1, struct EditMesh *em, struct CustomData *src,
struct CustomData *dst, const int type);
void multires_customdata_to_mesh(struct Mesh *me, struct EditMesh *em,
struct MultiresLevel *lvl, struct CustomData *src,
diff --git a/source/blender/blenkernel/BKE_node.h b/source/blender/blenkernel/BKE_node.h
index 2ffa1d205da..01c54663c6d 100644
--- a/source/blender/blenkernel/BKE_node.h
+++ b/source/blender/blenkernel/BKE_node.h
@@ -33,7 +33,8 @@
#ifndef BKE_NODE_H
#define BKE_NODE_H
-
+/* not very important, but the stack solver likes to know a maximum */
+#define MAX_SOCKET 64
struct ID;
struct bNodeTree;
@@ -46,6 +47,9 @@ struct rctf;
struct ListBase;
struct RenderData;
struct Scene;
+struct GPUMaterial;
+struct GPUNode;
+struct GPUNodeStack;
#define SOCK_IN 1
#define SOCK_OUT 2
@@ -87,8 +91,11 @@ typedef struct bNodeType {
/* for use with dynamic typedefs */
ID *id;
- void *script; /* holds pointer to python script */
- void *dict; /* holds pointer to python script dictionary (scope)*/
+ void *pynode; /* holds pointer to python script */
+ void *pydict; /* holds pointer to python script dictionary (scope)*/
+
+ /* gpu */
+ int (*gpufunc)(struct GPUMaterial *mat, struct bNode *node, struct GPUNodeStack *in, struct GPUNodeStack *out);
} bNodeType;
@@ -103,13 +110,14 @@ typedef struct bNodeType {
#define NODE_CLASS_INPUT 0
#define NODE_CLASS_OUTPUT 1
#define NODE_CLASS_OP_COLOR 3
-#define NODE_CLASS_OP_VECTOR 4
-#define NODE_CLASS_OP_FILTER 5
+#define NODE_CLASS_OP_VECTOR 4
+#define NODE_CLASS_OP_FILTER 5
#define NODE_CLASS_GROUP 6
#define NODE_CLASS_FILE 7
-#define NODE_CLASS_CONVERTOR 8
+#define NODE_CLASS_CONVERTOR 8
#define NODE_CLASS_MATTE 9
#define NODE_CLASS_DISTORT 10
+#define NODE_CLASS_OP_DYNAMIC 11
/* ************** GENERIC API, TREES *************** */
@@ -119,6 +127,7 @@ struct bNodeTree *ntreeAddTree(int type);
void ntreeInitTypes(struct bNodeTree *ntree);
void ntreeMakeOwnType(struct bNodeTree *ntree);
+void ntreeUpdateType(struct bNodeTree *ntree, struct bNodeType *ntype);
void ntreeFreeTree(struct bNodeTree *ntree);
struct bNodeTree *ntreeCopyTree(struct bNodeTree *ntree, int internal_select);
void ntreeMakeLocal(struct bNodeTree *ntree);
@@ -143,13 +152,21 @@ void nodeVerifyType(struct bNodeTree *ntree, struct bNode *node);
void nodeAddToPreview(struct bNode *, float *, int, int);
-struct bNode *nodeAddNodeType(struct bNodeTree *ntree, int type, struct bNodeTree *ngroup);
+void nodeUnlinkNode(struct bNodeTree *ntree, struct bNode *node);
+void nodeAddSockets(struct bNode *node, struct bNodeType *ntype);
+struct bNode *nodeAddNodeType(struct bNodeTree *ntree, int type, struct bNodeTree *ngroup, struct ID *id);
+void nodeRegisterType(struct ListBase *typelist, const struct bNodeType *ntype) ;
+void nodeUpdateType(struct bNodeTree *ntree, struct bNode* node, struct bNodeType *ntype);
+void nodeMakeDynamicType(struct bNode *node);
+int nodeDynamicUnlinkText(struct ID *txtid);
void nodeFreeNode(struct bNodeTree *ntree, struct bNode *node);
-struct bNode *nodeCopyNode(struct bNodeTree *ntree, struct bNode *node);
+struct bNode *nodeCopyNode(struct bNodeTree *ntree, struct bNode *node, int internal);
struct bNodeLink *nodeAddLink(struct bNodeTree *ntree, struct bNode *fromnode, struct bNodeSocket *fromsock, struct bNode *tonode, struct bNodeSocket *tosock);
void nodeRemLink(struct bNodeTree *ntree, struct bNodeLink *link);
+int nodeFindNode(struct bNodeTree *ntree, struct bNodeSocket *sock, struct bNode **nodep, int *sockindex);
+
struct bNodeLink *nodeFindLink(struct bNodeTree *ntree, struct bNodeSocket *from, struct bNodeSocket *to);
int nodeCountSocketLinks(struct bNodeTree *ntree, struct bNodeSocket *sock);
@@ -169,10 +186,13 @@ int nodeGroupUnGroup(struct bNodeTree *ntree, struct bNode *gnode);
void nodeVerifyGroup(struct bNodeTree *ngroup);
void nodeGroupSocketUseFlags(struct bNodeTree *ngroup);
+void nodeCopyGroup(struct bNode *gnode);
+
/* ************** COMMON NODES *************** */
#define NODE_GROUP 2
#define NODE_GROUP_MENU 1000
+#define NODE_DYNAMIC_MENU 4000
extern bNodeType node_group_typeinfo;
@@ -189,7 +209,7 @@ struct ShadeResult;
#define SH_NODE_OUTPUT 1
#define SH_NODE_MATERIAL 100
-#define SH_NODE_RGB 101
+#define SH_NODE_RGB 101
#define SH_NODE_VALUE 102
#define SH_NODE_MIX_RGB 103
#define SH_NODE_VALTORGB 104
@@ -209,12 +229,21 @@ struct ShadeResult;
#define SH_NODE_SEPRGB 120
#define SH_NODE_COMBRGB 121
#define SH_NODE_HUE_SAT 122
-
+#define NODE_DYNAMIC 123
/* custom defines options for Material node */
#define SH_NODE_MAT_DIFF 1
#define SH_NODE_MAT_SPEC 2
#define SH_NODE_MAT_NEG 4
+/* custom defines: states for Script node. These are bit indices */
+#define NODE_DYNAMIC_READY 0 /* 1 */
+#define NODE_DYNAMIC_LOADED 1 /* 2 */
+#define NODE_DYNAMIC_NEW 2 /* 4 */
+#define NODE_DYNAMIC_UPDATED 3 /* 8 */
+#define NODE_DYNAMIC_ADDEXIST 4 /* 16 */
+#define NODE_DYNAMIC_ERROR 5 /* 32 */
+#define NODE_DYNAMIC_REPARSE 6 /* 64 */
+#define NODE_DYNAMIC_SET 15 /* sign */
/* the type definitions array */
extern struct ListBase node_all_shaders;
@@ -229,25 +258,28 @@ void nodeShaderSynchronizeID(struct bNode *node, int copyto);
extern void (*node_shader_lamp_loop)(struct ShadeInput *, struct ShadeResult *);
void set_node_shader_lamp_loop(void (*lamp_loop_func)(struct ShadeInput *, struct ShadeResult *));
+void ntreeGPUMaterialNodes(struct bNodeTree *ntree, struct GPUMaterial *mat);
+
/* ************** COMPOSITE NODES *************** */
/* output socket defines */
-#define RRES_OUT_IMAGE 0
-#define RRES_OUT_ALPHA 1
-#define RRES_OUT_Z 2
-#define RRES_OUT_NORMAL 3
-#define RRES_OUT_UV 4
-#define RRES_OUT_VEC 5
-#define RRES_OUT_RGBA 6
-#define RRES_OUT_DIFF 7
-#define RRES_OUT_SPEC 8
-#define RRES_OUT_SHADOW 9
-#define RRES_OUT_AO 10
-#define RRES_OUT_REFLECT 11
-#define RRES_OUT_REFRACT 12
-#define RRES_OUT_RADIO 13
-#define RRES_OUT_INDEXOB 14
+#define RRES_OUT_IMAGE 0
+#define RRES_OUT_ALPHA 1
+#define RRES_OUT_Z 2
+#define RRES_OUT_NORMAL 3
+#define RRES_OUT_UV 4
+#define RRES_OUT_VEC 5
+#define RRES_OUT_RGBA 6
+#define RRES_OUT_DIFF 7
+#define RRES_OUT_SPEC 8
+#define RRES_OUT_SHADOW 9
+#define RRES_OUT_AO 10
+#define RRES_OUT_REFLECT 11
+#define RRES_OUT_REFRACT 12
+#define RRES_OUT_RADIO 13
+#define RRES_OUT_INDEXOB 14
+#define RRES_OUT_MIST 15
/* note: types are needed to restore callbacks, don't change values */
#define CMP_NODE_VIEWER 201
@@ -303,6 +335,9 @@ void set_node_shader_lamp_loop(void (*lamp_loop_func)(struct ShadeInput *, str
#define CMP_NODE_INVERT 251
#define CMP_NODE_NORMALIZE 252
#define CMP_NODE_CROP 253
+#define CMP_NODE_DBLUR 254
+#define CMP_NODE_BILATERALBLUR 255
+#define CMP_NODE_PREMULKEY 256
#define CMP_NODE_GLARE 301
#define CMP_NODE_TONEMAP 302
diff --git a/source/blender/blenkernel/BKE_object.h b/source/blender/blenkernel/BKE_object.h
index 69bdcf72550..a4a06b704bc 100644
--- a/source/blender/blenkernel/BKE_object.h
+++ b/source/blender/blenkernel/BKE_object.h
@@ -41,6 +41,7 @@ struct Camera;
struct BoundBox;
struct View3D;
struct SoftBody;
+struct BulletSoftBody;
struct Group;
struct bAction;
@@ -48,6 +49,12 @@ void clear_workob(void);
void copy_baseflags(void);
void copy_objectflags(void);
struct SoftBody *copy_softbody(struct SoftBody *sb);
+struct BulletSoftBody *copy_bulletsoftbody(struct BulletSoftBody *sb);
+void copy_object_particlesystems(struct Object *obn, struct Object *ob);
+void copy_object_softbody(struct Object *obn, struct Object *ob);
+void object_free_particlesystems(struct Object *ob);
+void object_free_softbody(struct Object *ob);
+void object_free_bulletsoftbody(struct Object *ob);
void update_base_layer(struct Object *ob);
void free_object(struct Object *ob);
@@ -81,6 +88,8 @@ void set_field_offs(float field);
void disable_speed_curve(int val);
float bsystem_time(struct Object *ob, float cfra, float ofs);
+void object_scale_to_mat3(struct Object *ob, float mat[][3]);
+void object_rot_to_mat3(struct Object *ob, float mat[][3]);
void object_to_mat3(struct Object *ob, float mat[][3]);
void object_to_mat4(struct Object *ob, float mat[][4]);
@@ -104,12 +113,14 @@ void object_boundbox_flag(struct Object *ob, int flag, int set);
void minmax_object(struct Object *ob, float *min, float *max);
void minmax_object_duplis(struct Object *ob, float *min, float *max);
void solve_tracking (struct Object *ob, float targetmat[][4]);
+int ray_hit_boundbox(struct BoundBox *bb, float ray_start[3], float ray_normal[3]);
void object_handle_update(struct Object *ob);
+float give_timeoffset(struct Object *ob);
+int give_obdata_texspace(struct Object *ob, int **texflag, float **loc, float **size, float **rot);
#ifdef __cplusplus
}
#endif
#endif
-
diff --git a/source/blender/blenkernel/BKE_particle.h b/source/blender/blenkernel/BKE_particle.h
index f64191f3e13..caba63ef8ce 100644
--- a/source/blender/blenkernel/BKE_particle.h
+++ b/source/blender/blenkernel/BKE_particle.h
@@ -38,6 +38,7 @@
struct ParticleSystemModifierData;
struct ParticleSystem;
struct ParticleKey;
+struct ParticleSettings;
struct HairKey;
struct Main;
@@ -46,6 +47,7 @@ struct Object;
struct DerivedMesh;
struct ModifierData;
struct MTFace;
+struct MCol;
struct MFace;
struct MVert;
struct IpoCurve;
@@ -71,6 +73,7 @@ typedef struct ParticleEffectorCache {
short type, psys_nbr;
struct Object obcopy; /* for restoring transformation data */
+ struct RNG *rng; /* random noise generator for e.g. wind */
} ParticleEffectorCache;
typedef struct ParticleReactEvent {
@@ -109,8 +112,8 @@ typedef struct ParticleSeam{
typedef struct ParticleCacheKey{
float co[3];
float vel[3];
- float col[3];
float rot[4];
+ float col[3];
int steps;
} ParticleCacheKey;
@@ -176,6 +179,7 @@ typedef struct ParticleThreadContext {
float *vg_length, *vg_clump, *vg_kink;
float *vg_rough1, *vg_rough2, *vg_roughe;
+ float *vg_effector;
} ParticleThreadContext;
typedef struct ParticleThread {
@@ -207,28 +211,32 @@ int psys_check_enabled(struct Object *ob, struct ParticleSystem *psys);
void psys_free_settings(struct ParticleSettings *part);
void free_child_path_cache(struct ParticleSystem *psys);
void psys_free_path_cache(struct ParticleSystem *psys);
-void free_hair(struct ParticleSystem *psys);
+void free_hair(struct ParticleSystem *psys, int softbody);
void free_keyed_keys(struct ParticleSystem *psys);
void psys_free(struct Object * ob, struct ParticleSystem * psys);
+void psys_free_children(struct ParticleSystem *psys);
-void psys_render_set(struct Object *ob, struct ParticleSystem *psys, float viewmat[][4], float winmat[][4], int winx, int winy);
+void psys_render_set(struct Object *ob, struct ParticleSystem *psys, float viewmat[][4], float winmat[][4], int winx, int winy, int timeoffset);
void psys_render_restore(struct Object *ob, struct ParticleSystem *psys);
int psys_render_simplify_distribution(struct ParticleThreadContext *ctx, int tot);
int psys_render_simplify_params(struct ParticleSystem *psys, struct ChildParticle *cpa, float *params);
-void clear_particles_from_cache(struct Object *ob, struct ParticleSystem *psys, int cfra);
-//void psys_remove_from_particle_list(struct Object *ob, short nbr, struct ParticleSystem *psys);
-
void psys_interpolate_uvs(struct MTFace *tface, int quad, float *uv, float *uvco);
+void psys_interpolate_mcol(struct MCol *mcol, int quad, float *uv, struct MCol *mc);
void copy_particle_key(struct ParticleKey *to, struct ParticleKey *from, int time);
-void psys_particle_on_emitter(struct Object *ob, struct ParticleSystemModifierData *psmd, int distr, int index, int index_dmcache, float *fuv, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor);
+void psys_particle_on_emitter(struct ParticleSystemModifierData *psmd, int distr, int index, int index_dmcache, float *fuv, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor);
struct ParticleSystemModifierData *psys_get_modifier(struct Object *ob, struct ParticleSystem *psys);
struct ParticleSettings *psys_new_settings(char *name, struct Main *main);
struct ParticleSettings *psys_copy_settings(struct ParticleSettings *part);
void psys_flush_settings(struct ParticleSettings *part, int event, int hair_recalc);
+void make_local_particlesettings(struct ParticleSettings *part);
+
+struct LinkNode *psys_using_settings(struct ParticleSettings *part, int flush_update);
+void psys_changed_type(struct ParticleSystem *psys);
+void psys_reset(struct ParticleSystem *psys, int mode);
void psys_find_parents(struct Object *ob, struct ParticleSystemModifierData *psmd, struct ParticleSystem *psys);
@@ -241,8 +249,10 @@ float psys_get_child_time(struct ParticleSystem *psys, struct ChildParticle *cpa
float psys_get_child_size(struct ParticleSystem *psys, struct ChildParticle *cpa, float cfra, float *pa_time);
void psys_get_particle_on_path(struct Object *ob, struct ParticleSystem *psys, int pa_num, struct ParticleKey *state, int vel);
int psys_get_particle_state(struct Object *ob, struct ParticleSystem *psys, int p, struct ParticleKey *state, int always);
+void psys_get_dupli_texture(struct Object *ob, struct ParticleSettings *part, struct ParticleSystemModifierData *psmd, struct ParticleData *pa, struct ChildParticle *cpa, float *uv, float *orco);
+void psys_get_dupli_path_transform(struct Object *ob, struct ParticleSystem *psys, struct ParticleSystemModifierData *psmd, struct ParticleData *pa, struct ChildParticle *cpa, struct ParticleCacheKey *cache, float mat[][4], float *scale);
-ParticleThread *psys_threads_create(struct Object *ob, struct ParticleSystem *psys, int totthread);
+ParticleThread *psys_threads_create(struct Object *ob, struct ParticleSystem *psys);
int psys_threads_init_distribution(ParticleThread *threads, struct DerivedMesh *dm, int from);
int psys_threads_init_path(ParticleThread *threads, float cfra, int editupdate);
void psys_threads_free(ParticleThread *threads);
@@ -274,19 +284,28 @@ void psys_mat_hair_to_orco(struct Object *ob, struct DerivedMesh *dm, short from
float *psys_cache_vgroup(struct DerivedMesh *dm, struct ParticleSystem *psys, int vgroup);
void psys_get_texture(struct Object *ob, struct Material *ma, struct ParticleSystemModifierData *psmd, struct ParticleSystem *psys, struct ParticleData *pa, struct ParticleTexture *ptex, int event);
void psys_interpolate_face(struct MVert *mvert, struct MFace *mface, struct MTFace *tface, float (*orcodata)[3], float *uv, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor);
+float psys_particle_value_from_verts(struct DerivedMesh *dm, short from, struct ParticleData *pa, float *values);
float psys_interpolate_value_from_verts(struct DerivedMesh *dm, short from, int index, float *fw, float *values);
void psys_get_from_key(struct ParticleKey *key, float *loc, float *vel, float *rot, float *time);
int psys_intersect_dm(struct Object *ob, struct DerivedMesh *dm, float *vert_cos, float *co1, float* co2, float *min_d, int *min_face, float *min_uv, float *face_minmax, float *pa_minmax, float radius, float *ipoint);
-void psys_particle_on_dm(struct Object *ob, struct DerivedMesh *dm, int from, int index, int index_dmcache, float *fw, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor);
+void psys_particle_on_dm(struct DerivedMesh *dm, int from, int index, int index_dmcache, float *fw, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor);
/* particle_system.c */
void initialize_particle(struct ParticleData *pa, int p, struct Object *ob, struct ParticleSystem *psys, struct ParticleSystemModifierData *psmd);
void reset_particle(struct ParticleData *pa, struct ParticleSystem *psys, struct ParticleSystemModifierData *psmd, struct Object *ob, float dtime, float cfra, float *vg_vel, float *vg_tan, float *vg_rot);
-void psys_calc_dmfaces(struct Object *ob, struct DerivedMesh *dm, struct ParticleSystem *psys);
+void do_effectors(int pa_no, struct ParticleData *pa, struct ParticleKey *state, struct Object *ob, struct ParticleSystem *psys, float *texco, float *force_field, float *vel,float framestep, float cfra);
+
+void psys_calc_dmcache(struct Object *ob, struct DerivedMesh *dm, struct ParticleSystem *psys);
int psys_particle_dm_face_lookup(struct Object *ob, struct DerivedMesh *dm, int index, float *fw, struct LinkNode *node);
+/* psys_reset */
+#define PSYS_RESET_ALL 1
+#define PSYS_RESET_DEPSGRAPH 2
+#define PSYS_RESET_CHILDREN 3
+#define PSYS_RESET_CACHE_MISS 4
+
/* ParticleEffectorCache->type */
#define PSYS_EC_EFFECTOR 1
#define PSYS_EC_DEFLECT 2
diff --git a/source/blender/blenkernel/BKE_plugin_types.h b/source/blender/blenkernel/BKE_plugin_types.h
index d6b91212d8f..fe5aafe5874 100644
--- a/source/blender/blenkernel/BKE_plugin_types.h
+++ b/source/blender/blenkernel/BKE_plugin_types.h
@@ -36,7 +36,8 @@
struct ImBuf;
-typedef int (*TexDoit)(int, void*, float*, float*, float*);
+typedef int (*TexDoitold)(int stype, void *cast, float *texvec, float *dxt, float *dyt);
+typedef int (*TexDoit)(int stype, void *cast, float *texvec, float *dxt, float *dyt, float *result );
typedef void (*SeqDoit)(void*, float, float, int, int,
struct ImBuf*, struct ImBuf*,
struct ImBuf*, struct ImBuf*);
@@ -60,7 +61,7 @@ typedef struct _PluginInfo {
void (*init)(void);
void (*callback)(int);
- TexDoit tex_doit;
+ void (*tex_doit)(void *);
SeqDoit seq_doit;
void (*instance_init)(void *);
} PluginInfo;
diff --git a/source/blender/blenkernel/BKE_pointcache.h b/source/blender/blenkernel/BKE_pointcache.h
index 52cc0ddcaa7..5bc467465a8 100644
--- a/source/blender/blenkernel/BKE_pointcache.h
+++ b/source/blender/blenkernel/BKE_pointcache.h
@@ -31,25 +31,84 @@
#include "DNA_ID.h"
-/* options for clearing pointcache - used for BKE_ptcache_id_clear
- Before and after are non inclusive (they wont remove the cfra) */
+/* Point cache clearing option, for BKE_ptcache_id_clear, before
+ * and after are non inclusive (they wont remove the cfra) */
#define PTCACHE_CLEAR_ALL 0
#define PTCACHE_CLEAR_FRAME 1
#define PTCACHE_CLEAR_BEFORE 2
#define PTCACHE_CLEAR_AFTER 3
+/* Point cache reset options */
+#define PTCACHE_RESET_DEPSGRAPH 0
+#define PTCACHE_RESET_BAKED 1
+#define PTCACHE_RESET_OUTDATED 2
+
/* Add the blendfile name after blendcache_ */
#define PTCACHE_EXT ".bphys"
-#define PTCACHE_PATH "//blendcache_"
+#define PTCACHE_PATH "blendcache_"
+
+/* File open options, for BKE_ptcache_file_open */
+#define PTCACHE_FILE_READ 0
+#define PTCACHE_FILE_WRITE 1
+
+/* PTCacheID types */
+#define PTCACHE_TYPE_SOFTBODY 0
+#define PTCACHE_TYPE_PARTICLES 1
+#define PTCACHE_TYPE_CLOTH 2
+
+/* Structs */
+struct Object;
+struct SoftBody;
+struct ParticleSystem;
+struct ClothModifierData;
+struct PointCache;
+struct ListBase;
+
+typedef struct PTCacheFile {
+ FILE *fp;
+} PTCacheFile;
+
+typedef struct PTCacheID {
+ struct PTCacheID *next, *prev;
+
+ struct Object *ob;
+ void *data;
+ int type;
+ int stack_index;
+
+ struct PointCache *cache;
+} PTCacheID;
+
+/* Creating ID's */
+void BKE_ptcache_id_from_softbody(PTCacheID *pid, struct Object *ob, struct SoftBody *sb);
+void BKE_ptcache_id_from_particles(PTCacheID *pid, struct Object *ob, struct ParticleSystem *psys);
+void BKE_ptcache_id_from_cloth(PTCacheID *pid, struct Object *ob, struct ClothModifierData *clmd);
+
+void BKE_ptcache_ids_from_object(struct ListBase *lb, struct Object *ob);
/* Global funcs */
-/* void BKE_ptcache_clean(void); - not implimented yet! */
+void BKE_ptcache_remove(void);
+
+/* ID specific functions */
+void BKE_ptcache_id_clear(PTCacheID *id, int mode, int cfra);
+int BKE_ptcache_id_exist(PTCacheID *id, int cfra);
+int BKE_ptcache_id_reset(PTCacheID *id, int mode);
+void BKE_ptcache_id_time(PTCacheID *pid, float cfra, int *startframe, int *endframe, float *timescale);
+int BKE_ptcache_object_reset(struct Object *ob, int mode);
+
+/* File reading/writing */
+PTCacheFile *BKE_ptcache_file_open(PTCacheID *id, int mode, int cfra);
+void BKE_ptcache_file_close(PTCacheFile *pf);
+int BKE_ptcache_file_read_floats(PTCacheFile *pf, float *f, int tot);
+int BKE_ptcache_file_write_floats(PTCacheFile *pf, float *f, int tot);
+/* Continue physics */
+void BKE_ptcache_set_continue_physics(int enable);
+int BKE_ptcache_get_continue_physics(void);
-/* Object spesific funcs */
-int BKE_ptcache_id_filename(struct ID *id, char *filename, int cfra, int stack_index, short do_path, short do_ext);
-FILE * BKE_ptcache_id_fopen(struct ID *id, char mode, int cfra, int stack_index);
-void BKE_ptcache_id_clear(struct ID *id, char mode, int cfra, int stack_index);
-int BKE_ptcache_id_exist(struct ID *id, int cfra, int stack_index);
+/* Point Cache */
+struct PointCache *BKE_ptcache_add(void);
+void BKE_ptcache_free(struct PointCache *cache);
+struct PointCache *BKE_ptcache_copy(struct PointCache *cache);
#endif
diff --git a/source/blender/blenkernel/BKE_property.h b/source/blender/blenkernel/BKE_property.h
index f1587790c4a..6af1deda727 100644
--- a/source/blender/blenkernel/BKE_property.h
+++ b/source/blender/blenkernel/BKE_property.h
@@ -41,7 +41,8 @@ struct bProperty *copy_property(struct bProperty *prop);
void copy_properties(struct ListBase *lbn, struct ListBase *lbo);
void init_property(struct bProperty *prop);
struct bProperty *new_property(int type);
-struct bProperty *get_property(struct Object *ob, char *name);
+struct bProperty *get_ob_property(struct Object *ob, char *name);
+void set_ob_property(struct Object *ob, struct bProperty *propc);
int compare_property(struct bProperty *prop, char *str);
void set_property(struct bProperty *prop, char *str);
void add_property(struct bProperty *prop, char *str);
diff --git a/source/blender/blenkernel/BKE_scene.h b/source/blender/blenkernel/BKE_scene.h
index bdc98f2817b..35168cb65f2 100644
--- a/source/blender/blenkernel/BKE_scene.h
+++ b/source/blender/blenkernel/BKE_scene.h
@@ -31,11 +31,14 @@
#ifndef BKE_SCENE_H
#define BKE_SCENE_H
+struct bglMats;
struct Scene;
struct Object;
struct Base;
struct AviCodecData;
struct QuicktimeCodecData;
+struct SculptData;
+struct RenderData;
/* sequence related defines */
@@ -51,7 +54,7 @@ struct QuicktimeCodecData;
}
/* note; doesn't work when scene is empty */
-#define SETLOOPER(s, b) sce= s, b= sce->base.first; b; b= (b->next?b->next:sce->set?(sce=sce->set)->base.first:NULL)
+#define SETLOOPER(s, b) sce= s, b= (Base*)sce->base.first; b; b= (Base*)(b->next?b->next:sce->set?(sce=sce->set)->base.first:NULL)
void free_avicodecdata(struct AviCodecData *acd);
@@ -78,5 +81,11 @@ void scene_update_for_newframe(struct Scene *sce, unsigned int lay);
void scene_add_render_layer(struct Scene *sce);
+/* render profile */
+int get_render_subsurf_level(struct RenderData *r, int level);
+int get_render_child_particle_number(struct RenderData *r, int num);
+int get_render_shadow_samples(struct RenderData *r, int samples);
+float get_render_aosss_error(struct RenderData *r, float error);
+
#endif
diff --git a/source/blender/blenkernel/BKE_screen.h b/source/blender/blenkernel/BKE_screen.h
index ebaf85a58f9..129093f6078 100644
--- a/source/blender/blenkernel/BKE_screen.h
+++ b/source/blender/blenkernel/BKE_screen.h
@@ -8,7 +8,7 @@
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
+ * of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
diff --git a/source/blender/blenkernel/BKE_sculpt.h b/source/blender/blenkernel/BKE_sculpt.h
index d539bcf5e8c..5d7ed28f561 100644
--- a/source/blender/blenkernel/BKE_sculpt.h
+++ b/source/blender/blenkernel/BKE_sculpt.h
@@ -31,30 +31,11 @@
#define BKE_SCULPT_H
struct NumInput;
+struct RadialControl;
struct Scene;
struct SculptData;
struct SculptSession;
-typedef enum PropsetMode {
- PropsetNone = 0,
- PropsetSize,
- PropsetStrength,
- PropsetTexRot
-} PropsetMode;
-
-typedef struct PropsetData {
- PropsetMode mode;
- unsigned int tex;
- short origloc[2];
- float *texdata;
-
- short origsize;
- char origstrength;
- float origtexrot;
-
- struct NumInput *num;
-} PropsetData;
-
typedef struct SculptSession {
struct ProjVert *projverts;
@@ -76,11 +57,8 @@ typedef struct SculptSession {
/* Used to cache the render of the active texture */
unsigned int texcache_w, texcache_h, *texcache;
- struct PropsetData *propset;
+ struct RadialControl *radialcontrol;
- /* For rotating around a pivot point */
- vec3f pivot;
-
struct SculptStroke *stroke;
} SculptSession;
diff --git a/source/blender/blenkernel/BKE_shrinkwrap.h b/source/blender/blenkernel/BKE_shrinkwrap.h
new file mode 100644
index 00000000000..eed22ff9d8e
--- /dev/null
+++ b/source/blender/blenkernel/BKE_shrinkwrap.h
@@ -0,0 +1,150 @@
+/**
+ * BKE_shrinkwrap.h
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef BKE_SHRINKWRAP_H
+#define BKE_SHRINKWRAP_H
+
+/* mesh util */
+//TODO: move this somewhere else
+#include "BKE_customdata.h"
+struct DerivedMesh;
+struct Object;
+struct DerivedMesh *object_get_derived_final(struct Object *ob, CustomDataMask dataMask);
+
+
+/* SpaceTransform stuff */
+/*
+ * TODO: move this somewhere else
+ *
+ * this structs encapsulates all needed data to convert between 2 coordinate spaces
+ * (where conversion can be represented by a matrix multiplication)
+ *
+ * This is used to reduce the number of arguments to pass to functions that need to perform
+ * this kind of operation and make it easier for the coder, as he/she doenst needs to recode
+ * the matrix calculation.
+ *
+ * A SpaceTransform is initialized using:
+ * space_transform_setup( &data, ob1, ob2 )
+ *
+ * After that the following calls can be used:
+ * space_transform_apply (&data, co); //converts a coordinate in ob1 coords space to the corresponding ob2 coords
+ * space_transform_invert(&data, co); //converts a coordinate in ob2 coords space to the corresponding ob1 coords
+ *
+ * //Same Concept as space_transform_apply and space_transform_invert, but no is normalized after conversion
+ * space_transform_apply_normal (&data, &no);
+ * space_transform_invert_normal(&data, &no);
+ *
+ */
+struct Object;
+
+typedef struct SpaceTransform
+{
+ float local2target[4][4];
+ float target2local[4][4];
+
+} SpaceTransform;
+
+void space_transform_from_matrixs(SpaceTransform *data, float local[][4], float target[][4]);
+#define space_transform_setup(data, local, target) space_transform_from_matrixs(data, (local)->obmat, (target)->obmat)
+
+void space_transform_apply (const SpaceTransform *data, float *co);
+void space_transform_invert(const SpaceTransform *data, float *co);
+
+void space_transform_apply_normal (const SpaceTransform *data, float *no);
+void space_transform_invert_normal(const SpaceTransform *data, float *no);
+
+/* Shrinkwrap stuff */
+#include "BKE_bvhutils.h"
+
+/*
+ * Shrinkwrap is composed by a set of functions and options that define the type of shrink.
+ *
+ * 3 modes are available:
+ * - Nearest vertex
+ * - Nearest surface
+ * - Normal projection
+ *
+ * ShrinkwrapCalcData encapsulates all needed data for shrinkwrap functions.
+ * (So that you dont have to pass an enormous ammount of arguments to functions)
+ */
+
+struct Object;
+struct DerivedMesh;
+struct ShrinkwrapModifierData;
+struct MDeformVert;
+struct BVHTree;
+
+
+typedef struct ShrinkwrapCalcData
+{
+ ShrinkwrapModifierData *smd; //shrinkwrap modifier data
+
+ struct Object *ob; //object we are applying shrinkwrap to
+ struct DerivedMesh *original; //mesh before shrinkwrap
+
+ float (*vertexCos)[3]; //vertexs being shrinkwraped
+ int numVerts;
+
+ struct MDeformVert* dvert; //Pointer to mdeform array
+ int vgroup; //Vertex group num
+
+ struct DerivedMesh *target; //mesh we are shrinking to
+ SpaceTransform local2target; //transform to move bettwem local and target space
+
+ float keepDist; //Distance to kept from target (units are in local space)
+
+} ShrinkwrapCalcData;
+
+void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *data);
+void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *data);
+void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *data);
+
+void shrinkwrapModifier_deform(struct ShrinkwrapModifierData *smd, struct Object *ob, struct DerivedMesh *dm, float (*vertexCos)[3], int numVerts);
+
+/*
+ * This function casts a ray in the given BVHTree.. but it takes into consideration the space_transform, that is:
+ *
+ * if transf was configured with "space_transform_setup( &transf, ob1, ob2 )"
+ * then the input (vert, dir, BVHTreeRayHit) must be defined in ob1 coordinates space
+ * and the BVHTree must be built in ob2 coordinate space.
+ *
+ * Thus it provides an easy way to cast the same ray across several trees (where each tree was built on its own coords space)
+ */
+int normal_projection_project_vertex(char options, const float *vert, const float *dir, const SpaceTransform *transf, BVHTree *tree, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata);
+
+/*
+ * NULL initializers to local data
+ */
+#define NULL_ShrinkwrapCalcData {NULL, }
+#define NULL_BVHTreeFromMesh {NULL, }
+#define NULL_BVHTreeRayHit {NULL, }
+#define NULL_BVHTreeNearest {0, }
+
+
+#endif
+
diff --git a/source/blender/blenkernel/BKE_simple_deform.h b/source/blender/blenkernel/BKE_simple_deform.h
new file mode 100644
index 00000000000..161871a64bc
--- /dev/null
+++ b/source/blender/blenkernel/BKE_simple_deform.h
@@ -0,0 +1,39 @@
+/**
+ * BKE_shrinkwrap.h
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef BKE_SIMPLE_DEFORM_H
+#define BKE_SIMPLE_DEFORM_H
+
+struct Object;
+struct DerivedMesh;
+struct SimpleDeformModifierData;
+
+void SimpleDeformModifier_do(SimpleDeformModifierData *smd, struct Object *ob, struct DerivedMesh *dm, float (*vertexCos)[3], int numVerts);
+
+#endif
+
diff --git a/source/blender/blenkernel/BKE_softbody.h b/source/blender/blenkernel/BKE_softbody.h
index b11585b47fb..1756734813b 100644
--- a/source/blender/blenkernel/BKE_softbody.h
+++ b/source/blender/blenkernel/BKE_softbody.h
@@ -38,8 +38,9 @@ typedef struct BodyPoint {
float origS[3], origE[3], origT[3], pos[3], vec[3], force[3];
float goal;
float prevpos[3], prevvec[3], prevdx[3], prevdv[3]; /* used for Heun integration */
+ float impdv[3],impdx[3];
int nofsprings; int *springs;
- float choke;
+ float choke,choke2,frozen;
float colball;
short flag;
char octantflag;
@@ -51,7 +52,8 @@ extern struct SoftBody *sbNew(void);
/* frees internal data and softbody itself */
extern void sbFree(struct SoftBody *sb);
-extern void softbody_clear_cache(struct Object *ob, float framenr);
+/* frees simulation data to reset simulation */
+extern void sbFreeSimulation(struct SoftBody *sb);
/* do one simul step, reading and writing vertex locs from given array */
extern void sbObjectStep(struct Object *ob, float framnr, float (*vertexCos)[3], int numVerts);
@@ -63,6 +65,8 @@ extern void sbObjectToSoftbody(struct Object *ob);
/* pass NULL to unlink again */
extern void sbSetInterruptCallBack(int (*f)(void));
+/* writing to cache for bake editing */
+extern void sbWriteCache(struct Object *ob, int framenr);
#endif
diff --git a/source/blender/blenkernel/BKE_suggestions.h b/source/blender/blenkernel/BKE_suggestions.h
new file mode 100644
index 00000000000..d58b8f58bf5
--- /dev/null
+++ b/source/blender/blenkernel/BKE_suggestions.h
@@ -0,0 +1,93 @@
+/**
+ * $Id: $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2008, Blender Foundation
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef BKE_SUGGESTIONS_H
+#define BKE_SUGGESTIONS_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* ****************************************************************************
+Suggestions should be added in sorted order although a linear sorting method is
+implemented. The list is then divided up based on the prefix provided by
+update_suggestions:
+
+Example:
+ Prefix: ab
+ aaa <-- first
+ aab
+ aba <-- firstmatch
+ abb <-- lastmatch
+ baa
+ bab <-- last
+**************************************************************************** */
+
+struct Text;
+
+typedef struct SuggItem {
+ struct SuggItem *prev, *next;
+ char *name;
+ char type;
+} SuggItem;
+
+typedef struct SuggList {
+ SuggItem *first, *last;
+ SuggItem *firstmatch, *lastmatch;
+ SuggItem *selected;
+ int top;
+} SuggList;
+
+/* Free all text tool memory */
+void free_texttools();
+
+/* Used to identify which Text object the current tools should appear against */
+void texttool_text_set_active(Text *text);
+void texttool_text_clear();
+short texttool_text_is_active(Text *text);
+
+/* Suggestions */
+void texttool_suggest_add(const char *name, char type);
+void texttool_suggest_prefix(const char *prefix);
+void texttool_suggest_clear();
+SuggItem *texttool_suggest_first();
+SuggItem *texttool_suggest_last();
+void texttool_suggest_select(SuggItem *sel);
+SuggItem *texttool_suggest_selected();
+int *texttool_suggest_top();
+
+/* Documentation */
+void texttool_docs_show(const char *docs);
+char *texttool_docs_get();
+void texttool_docs_clear();
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/source/blender/blenkernel/BKE_text.h b/source/blender/blenkernel/BKE_text.h
index 370a19304fe..002c804f17f 100644
--- a/source/blender/blenkernel/BKE_text.h
+++ b/source/blender/blenkernel/BKE_text.h
@@ -52,20 +52,24 @@ void txt_free_cut_buffer (void);
char* txt_to_buf (struct Text *text);
void txt_clean_text (struct Text *text);
void txt_order_cursors (struct Text *text);
-int txt_find_string (struct Text *text, char *findstr);
+int txt_find_string (struct Text *text, char *findstr, int wrap);
int txt_has_sel (struct Text *text);
int txt_get_span (struct TextLine *from, struct TextLine *to);
void txt_move_up (struct Text *text, short sel);
void txt_move_down (struct Text *text, short sel);
void txt_move_left (struct Text *text, short sel);
void txt_move_right (struct Text *text, short sel);
+void txt_jump_left (struct Text *text, short sel);
+void txt_jump_right (struct Text *text, short sel);
void txt_move_bof (struct Text *text, short sel);
void txt_move_eof (struct Text *text, short sel);
void txt_move_bol (struct Text *text, short sel);
void txt_move_eol (struct Text *text, short sel);
void txt_move_toline (struct Text *text, unsigned int line, short sel);
+void txt_move_to (struct Text *text, unsigned int line, unsigned int ch, short sel);
void txt_pop_sel (struct Text *text);
void txt_delete_char (struct Text *text);
+void txt_delete_word (struct Text *text);
void txt_copy_sel (struct Text *text);
void txt_sel_all (struct Text *text);
void txt_sel_line (struct Text *text);
@@ -80,8 +84,10 @@ void txt_do_undo (struct Text *text);
void txt_do_redo (struct Text *text);
void txt_split_curline (struct Text *text);
void txt_backspace_char (struct Text *text);
+void txt_backspace_word (struct Text *text);
int txt_add_char (struct Text *text, char add);
-void txt_find_panel (struct SpaceText *st, int again);
+int txt_replace_char (struct Text *text, char add);
+void find_and_replace (struct SpaceText *st, short mode);
void run_python_script (struct SpaceText *st);
int jumptoline_interactive (struct SpaceText *st);
void txt_export_to_object (struct Text *text);
@@ -92,6 +98,18 @@ void indent (struct Text *text);
void uncomment (struct Text *text);
int setcurr_tab (struct Text *text);
void convert_tabs (struct SpaceText *st, int tab);
+void txt_copy_clipboard (struct Text *text);
+void txt_paste_clipboard (struct Text *text);
+
+void txt_add_marker (struct Text *text, struct TextLine *line, int start, int end, char color[4], int group, int flags);
+short txt_clear_marker_region (struct Text *text, struct TextLine *line, int start, int end, int group, int flags);
+short txt_clear_markers (struct Text *text, int group, int flags);
+struct TextMarker *txt_find_marker (struct Text *text, struct TextLine *line, int curs, int group, int flags);
+struct TextMarker *txt_find_marker_region (struct Text *text, struct TextLine *line, int start, int end, int group, int flags);
+struct TextMarker *txt_prev_marker (struct Text *text, struct TextMarker *marker);
+struct TextMarker *txt_next_marker (struct Text *text, struct TextMarker *marker);
+struct TextMarker *txt_prev_marker_color (struct Text *text, struct TextMarker *marker);
+struct TextMarker *txt_next_marker_color (struct Text *text, struct TextMarker *marker);
/* Undo opcodes */
@@ -134,6 +152,14 @@ void convert_tabs (struct SpaceText *st, int tab);
#define UNDO_COMMENT 034
#define UNDO_UNCOMMENT 035
+/* Find and replace flags */
+#define TXT_FIND_WRAP 0x01
+#define TXT_FIND_ALLTEXTS 0x02
+
+/* Marker flags */
+#define TMARK_TEMP 0x01 /* Remove on non-editing events, don't save */
+#define TMARK_EDITALL 0x02 /* Edit all markers of the same group as one */
+
#ifdef __cplusplus
}
#endif
diff --git a/source/blender/blenkernel/BKE_texture.h b/source/blender/blenkernel/BKE_texture.h
index 78a8f60caeb..cfcae3c44bc 100644
--- a/source/blender/blenkernel/BKE_texture.h
+++ b/source/blender/blenkernel/BKE_texture.h
@@ -53,6 +53,7 @@ void free_plugin_tex(struct PluginTex *pit);
void init_colorband(struct ColorBand *coba, int rangetype);
struct ColorBand *add_colorband(int rangetype);
int do_colorband(struct ColorBand *coba, float in, float out[4]);
+void colorband_table_RGBA(struct ColorBand *coba, float **array, int *size);
void default_tex(struct Tex *tex);
struct Tex *add_texture(char *name);
@@ -62,6 +63,7 @@ struct Tex *copy_texture(struct Tex *tex);
void make_local_texture(struct Tex *tex);
void autotexname(struct Tex *tex);
struct Tex *give_current_texture(struct Object *ob, int act);
+struct Tex *give_current_world_texture(void);
struct TexMapping *add_mapping(void);
void init_mapping(struct TexMapping *texmap);
@@ -72,6 +74,7 @@ void BKE_free_envmap(struct EnvMap *env);
struct EnvMap *BKE_add_envmap(void);
struct EnvMap *BKE_copy_envmap(struct EnvMap *env);
+int BKE_texture_dependsOnTime(const struct Tex *texture);
#endif
diff --git a/source/blender/blenkernel/BKE_utildefines.h b/source/blender/blenkernel/BKE_utildefines.h
index 50e3f487171..6584af085cd 100644
--- a/source/blender/blenkernel/BKE_utildefines.h
+++ b/source/blender/blenkernel/BKE_utildefines.h
@@ -55,6 +55,8 @@
#define ELEM7(a, b, c, d, e, f, g, h) ( ELEM3(a, b, c, d) || ELEM4(a, e, f, g, h) )
#define ELEM8(a, b, c, d, e, f, g, h, i) ( ELEM4(a, b, c, d, e) || ELEM4(a, f, g, h, i) )
#define ELEM9(a, b, c, d, e, f, g, h, i, j) ( ELEM4(a, b, c, d, e) || ELEM5(a, f, g, h, i, j) )
+#define ELEM10(a, b, c, d, e, f, g, h, i, j, k) ( ELEM4(a, b, c, d, e) || ELEM6(a, f, g, h, i, j, k) )
+#define ELEM11(a, b, c, d, e, f, g, h, i, j, k, l) ( ELEM4(a, b, c, d, e) || ELEM7(a, f, g, h, i, j, k, l) )
/* shift around elements */
#define SHIFT3(type, a, b, c) { type tmp; tmp = a; a = c; c = b; b = tmp; }
@@ -98,6 +100,10 @@
#define ABS(a) ( (a)<0 ? (-(a)) : (a) )
+#define AVG2(x, y) ( 0.5 * ((x) + (y)) )
+
+#define FTOCHAR(val) ((val)<=0.0f)? 0 : (((val)>(1.0f-0.5f/255.0f))? 255 : (char)((255.0f*(val))+0.5f))
+
#define VECCOPY(v1,v2) {*(v1)= *(v2); *(v1+1)= *(v2+1); *(v1+2)= *(v2+2);}
#define VECCOPY2D(v1,v2) {*(v1)= *(v2); *(v1+1)= *(v2+1);}
#define QUATCOPY(v1,v2) {*(v1)= *(v2); *(v1+1)= *(v2+1); *(v1+2)= *(v2+2); *(v1+3)= *(v2+3);}
@@ -106,7 +112,9 @@
#define VECADD(v1,v2,v3) {*(v1)= *(v2) + *(v3); *(v1+1)= *(v2+1) + *(v3+1); *(v1+2)= *(v2+2) + *(v3+2);}
#define VECSUB(v1,v2,v3) {*(v1)= *(v2) - *(v3); *(v1+1)= *(v2+1) - *(v3+1); *(v1+2)= *(v2+2) - *(v3+2);}
+#define VECSUB2D(v1,v2,v3) {*(v1)= *(v2) - *(v3); *(v1+1)= *(v2+1) - *(v3+1);}
#define VECADDFAC(v1,v2,v3,fac) {*(v1)= *(v2) + *(v3)*(fac); *(v1+1)= *(v2+1) + *(v3+1)*(fac); *(v1+2)= *(v2+2) + *(v3+2)*(fac);}
+#define QUATADDFAC(v1,v2,v3,fac) {*(v1)= *(v2) + *(v3)*(fac); *(v1+1)= *(v2+1) + *(v3+1)*(fac); *(v1+2)= *(v2+2) + *(v3+2)*(fac); *(v1+3)= *(v2+3) + *(v3+3)*(fac);}
#define INPR(v1, v2) ( (v1)[0]*(v2)[0] + (v1)[1]*(v2)[1] + (v1)[2]*(v2)[2] )
@@ -129,7 +137,7 @@
#endif
/* INTEGER CODES */
-#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
+#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__hppa__) || defined (__BIG_ENDIAN__)
/* Big Endian */
#define MAKE_ID(a,b,c,d) ( (int)(a)<<24 | (int)(b)<<16 | (c)<<8 | (d) )
#else
@@ -165,20 +173,22 @@
/* This one rotates the bytes in an int */
#define SWITCH_INT(a) { \
- char s_i, *p_i; \
- p_i= (char *)&(a); \
- s_i=p_i[0]; p_i[0]=p_i[3]; p_i[3]=s_i; \
- s_i=p_i[1]; p_i[1]=p_i[2]; p_i[2]=s_i; }
+ char s_i, *p_i; \
+ p_i= (char *)&(a); \
+ s_i=p_i[0]; p_i[0]=p_i[3]; p_i[3]=s_i; \
+ s_i=p_i[1]; p_i[1]=p_i[2]; p_i[2]=s_i; }
#define SWITCH_SHORT(a) { \
- char s_i, *p_i; \
- p_i= (char *)&(a); \
- s_i=p_i[0]; p_i[0]=p_i[1]; p_i[1]=s_i; }
+ char s_i, *p_i; \
+ p_i= (char *)&(a); \
+ s_i=p_i[0]; p_i[0]=p_i[1]; p_i[1]=s_i; }
/* Bit operations */
-#define BTST(a,b) ( ( (a) & 1<<(b) )!=0 )
-#define BSET(a,b) ( (a) | 1<<(b) )
+#define BTST(a,b) ( ( (a) & 1<<(b) )!=0 )
+#define BNTST(a,b) ( ( (a) & 1<<(b) )==0 )
+#define BTST2(a,b,c) ( BTST( (a), (b) ) || BTST( (a), (c) ) )
+#define BSET(a,b) ( (a) | 1<<(b) )
#define BCLR(a,b) ( (a) & ~(1<<(b)) )
/* bit-row */
#define BROW(min, max) (((max)>=31? 0xFFFFFFFF: (1<<(max+1))-1) - ((min)? ((1<<(min))-1):0) )
@@ -189,5 +199,10 @@
#endif
#define GS(a) (*((short *)(a)))
+/* Warning-free macros for storing ints in pointers. Use these _only_
+ * for storing an int in a pointer, not a pointer in an int (64bit)! */
+#define SET_INT_IN_POINTER(i) ((void*)(intptr_t)(i))
+#define GET_INT_FROM_POINTER(i) ((int)(intptr_t)(i))
+
#endif
diff --git a/source/blender/blenkernel/BKE_writeffmpeg.h b/source/blender/blenkernel/BKE_writeffmpeg.h
index eccc02af1b1..02f7ba6f860 100644
--- a/source/blender/blenkernel/BKE_writeffmpeg.h
+++ b/source/blender/blenkernel/BKE_writeffmpeg.h
@@ -42,20 +42,16 @@ extern "C" {
#define FFMPEG_DV 5
#define FFMPEG_H264 6
#define FFMPEG_XVID 7
-
-#define FFMPEG_CODEC_MPEG1 0
-#define FFMPEG_CODEC_MPEG2 1
-#define FFMPEG_CODEC_MPEG4 2
-#define FFMPEG_CODEC_HUFFYUV 3
-#define FFMPEG_CODEC_DV 4
-#define FFMPEG_CODEC_H264 5
-#define FFMPEG_CODEC_XVID 6
+#define FFMPEG_FLV 8
+#define FFMPEG_MKV 9
+#define FFMPEG_OGG 10
#define FFMPEG_PRESET_NONE 0
#define FFMPEG_PRESET_DVD 1
#define FFMPEG_PRESET_SVCD 2
#define FFMPEG_PRESET_VCD 3
#define FFMPEG_PRESET_DV 4
+#define FFMPEG_PRESET_H264 5
struct RenderData;
diff --git a/source/blender/blenkernel/BKE_writeframeserver.h b/source/blender/blenkernel/BKE_writeframeserver.h
index a6ece63bc56..4774906a2fa 100644
--- a/source/blender/blenkernel/BKE_writeframeserver.h
+++ b/source/blender/blenkernel/BKE_writeframeserver.h
@@ -37,7 +37,7 @@ struct RenderData;
extern void start_frameserver(struct RenderData *rd, int rectx, int recty);
extern void end_frameserver(void);
extern void append_frameserver(int frame, int *pixels, int rectx, int recty);
-extern int frameserver_loop();
+extern int frameserver_loop(void);
#ifdef __cplusplus
}
diff --git a/source/blender/blenkernel/CMakeLists.txt b/source/blender/blenkernel/CMakeLists.txt
index 214af30f3c3..4c6d5717591 100644
--- a/source/blender/blenkernel/CMakeLists.txt
+++ b/source/blender/blenkernel/CMakeLists.txt
@@ -27,14 +27,15 @@
FILE(GLOB SRC intern/*.c)
SET(INC
- . ../../../intern/guardedalloc ../include ../blenlib ../makesdna
+ . ../../../intern/guardedalloc ../editors/include ../blenlib ../makesdna
../python ../render/extern/include ../../../intern/decimation/extern
- ../imbuf ../avi ../../../intern/elbeem/extern
+ ../imbuf ../avi ../../../intern/elbeem/extern ../../../intern/opennl/extern
../../../intern/iksolver/extern ../blenloader ../quicktime
- ../../../intern/bmfont
- ../nodes ../editors/include
+ ../../../intern/bmfont ../../../extern/bullet2/src
+ ../nodes ../../../extern/glew/include ../gpu
${SDL_INC}
${ZLIB_INC}
+ ${PYTHON_INC}
)
IF(WITH_VERSE)
@@ -46,6 +47,10 @@ IF(WITH_OPENEXR)
ADD_DEFINITIONS(-DWITH_OPENEXR)
ENDIF(WITH_OPENEXR)
+IF(WITH_DDS)
+ ADD_DEFINITIONS(-DWITH_DDS)
+ENDIF(WITH_DDS)
+
IF(WITH_QUICKTIME)
SET(INC ${INC} ${QUICKTIME_INC})
ADD_DEFINITIONS(-DWITH_QUICKTIME)
@@ -72,3 +77,6 @@ IF(WITH_INTERNATIONAL)
ADD_DEFINITIONS(-DWITH_FREETYPE2)
ENDIF(WITH_INTERNATIONAL)
+IF(NOT WITH_ELBEEM)
+ ADD_DEFINITIONS(-DDISABLE_ELBEEM)
+ENDIF(NOT WITH_ELBEEM)
diff --git a/source/blender/blenkernel/SConscript b/source/blender/blenkernel/SConscript
index 96ec8c3fff2..071fd5d82d9 100644
--- a/source/blender/blenkernel/SConscript
+++ b/source/blender/blenkernel/SConscript
@@ -4,19 +4,33 @@ Import ('env')
sources = env.Glob('intern/*.c')
incs = '. #/intern/guardedalloc ../editors/include ../blenlib ../makesdna'
-incs += ' ../python ../render/extern/include #/intern/decimation/extern'
+incs += ' ../render/extern/include #/intern/decimation/extern'
incs += ' ../imbuf ../avi #/intern/elbeem/extern ../nodes'
-incs += ' #/intern/iksolver/extern ../blenloader ../quicktime'
+incs += ' #/intern/iksolver/extern ../blenloader'
+incs += ' #/extern/bullet2/src'
incs += ' #/intern/bmfont'
+incs += ' #/intern/opennl/extern'
+incs += ' ../gpu #/extern/glew/include'
incs += ' ' + env['BF_OPENGL_INC']
incs += ' ' + env['BF_ZLIB_INC']
-incs += ' ' + env['BF_SDL_INC']
defs = ''
+if not env['WITH_BF_PYTHON']:
+ defs += 'DISABLE_PYTHON'
+else:
+ incs += ' ../python'
+ incs += ' ' + env['BF_PYTHON_INC']
+
+if env['WITH_BF_QUICKTIME']:
+ incs += ' ../quicktime'
+
+if env['WITH_BF_SDL']:
+ incs += ' ' + env['BF_SDL_INC']
+
if env['WITH_BF_INTERNATIONAL']:
- defs += 'WITH_FREETYPE2'
+ defs += ' WITH_FREETYPE2'
if env['WITH_BF_VERSE']:
defs += ' WITH_VERSE'
@@ -25,23 +39,24 @@ if env['WITH_BF_VERSE']:
if env['WITH_BF_VERSE']:
defs += ' WITH_VERSE'
-if env['WITH_BF_OPENEXR'] == 1:
- defs += ' WITH_OPENEXR'
+if env['WITH_BF_OPENEXR']:
+ defs += ' WITH_OPENEXR'
-if env['WITH_BF_DDS'] == 1:
- defs += ' WITH_DDS'
+if env['WITH_BF_DDS']:
+ defs += ' WITH_DDS'
-if env['WITH_BF_FFMPEG'] == 1:
- defs += ' WITH_FFMPEG'
- incs += ' ' + env['BF_FFMPEG_INC']
+if env['WITH_BF_FFMPEG']:
+ defs += ' WITH_FFMPEG'
+ incs += ' ' + env['BF_FFMPEG_INC']
-if env['WITH_BF_QUICKTIME'] == 1:
- defs += ' WITH_QUICKTIME'
- incs += ' ' + env['BF_QUICKTIME_INC']
+if env['WITH_BF_QUICKTIME']:
+ defs += ' WITH_QUICKTIME'
+ incs += ' ' + env['BF_QUICKTIME_INC']
-defs += ' WITH_CCGSUBSURF'
+if env['BF_NO_ELBEEM']:
+ defs += ' DISABLE_ELBEEM'
if env['WITH_BF_PLAYER']:
- SConscript(['bad_level_call_stubs/SConscript'])
+ SConscript(['bad_level_call_stubs/SConscript'])
-env.BlenderLib ( libname = 'bf_blenkernel', sources = sources, includes = Split(incs), defines = Split(defs), libtype=['core','player'], priority = [75, 10] )
+env.BlenderLib ( libname = 'bf_blenkernel', sources = sources, includes = Split(incs), defines = Split(defs), libtype=['core','player'], priority = [65, 20] )
diff --git a/source/blender/blenkernel/depsgraph_private.h b/source/blender/blenkernel/depsgraph_private.h
index adcb63b3d3a..78717393baf 100644
--- a/source/blender/blenkernel/depsgraph_private.h
+++ b/source/blender/blenkernel/depsgraph_private.h
@@ -51,6 +51,7 @@ typedef struct DagAdjList
short type;
int count; // number of identical arcs
unsigned int lay; // for flushing redraw/rebuild events
+ char *name;
struct DagAdjList *next;
} DagAdjList;
@@ -114,7 +115,7 @@ DagNode * dag_find_node (DagForest *forest,void * fob);
DagNode * dag_add_node (DagForest *forest,void * fob);
DagNode * dag_get_node (DagForest *forest,void * fob);
DagNode * dag_get_sub_node (DagForest *forest,void * fob);
-void dag_add_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel);
+void dag_add_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel, char *name);
void graph_bfs(void);
diff --git a/source/blender/blenkernel/intern/BME_Customdata.c b/source/blender/blenkernel/intern/BME_Customdata.c
new file mode 100644
index 00000000000..1fc8a4071dc
--- /dev/null
+++ b/source/blender/blenkernel/intern/BME_Customdata.c
@@ -0,0 +1,199 @@
+/**
+ * BME_customdata.c jan 2007
+ *
+ * Custom Data functions for Bmesh
+ *
+ * $Id: BKE_bmesh.h,v 1.00 2007/01/17 17:42:01 Briggs Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2004 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Geoffrey Bantle, Brecht Van Lommel, Ben Batt
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+
+#include "BKE_bmesh.h"
+#include "BKE_bmeshCustomData.h"
+#include "bmesh_private.h"
+#include <string.h>
+#include "MEM_guardedalloc.h"
+#include "BLI_mempool.h"
+
+/********************* Layer type information **********************/
+typedef struct BME_LayerTypeInfo {
+ int size;
+ char *defaultname;
+ void (*copy)(const void *source, void *dest, int count);
+ void (*free)(void *data, int count, int size);
+ void (*interp)(void **sources, float *weights, float *sub_weights, int count, void *dest);
+ void (*set_default)(void *data, int count);
+} BME_LayerTypeInfo;
+const BME_LayerTypeInfo BMELAYERTYPEINFO[BME_CD_NUMTYPES] = {
+ {sizeof(BME_facetex), "TexFace", NULL, NULL, NULL, NULL},
+ {sizeof(BME_looptex), "UV", NULL, NULL, NULL, NULL},
+ {sizeof(BME_loopcol), "VCol", NULL, NULL, NULL, NULL},
+ {sizeof(BME_DeformVert), "Group", NULL, NULL, NULL, NULL}
+};
+static const BME_LayerTypeInfo *BME_layerType_getInfo(int type)
+{
+ if(type < 0 || type >= CD_NUMTYPES) return NULL;
+
+ return &BMELAYERTYPEINFO[type];
+}
+void BME_CD_Create(BME_CustomData *data, BME_CustomDataInit *init, int initalloc)
+{
+ int i, j, offset=0;
+ const BME_LayerTypeInfo *info;
+
+ /*initialize data members*/
+ data->layers = NULL;
+ data->pool = NULL;
+ data->totlayer = 0;
+ data->totsize = 0;
+
+ /*first count how many layers to alloc*/
+ for(i=0; i < BME_CD_NUMTYPES; i++){
+ info = BME_layerType_getInfo(i);
+ data->totlayer += init->layout[i];
+ data->totsize += (init->layout[i] * info->size);
+ }
+ /*alloc our layers*/
+ if(data->totlayer){
+ /*alloc memory*/
+ data->layers = MEM_callocN(sizeof(BME_CustomDataLayer)*data->totlayer, "BMesh Custom Data Layers");
+ data->pool = BLI_mempool_create(data->totsize, initalloc, initalloc);
+ /*initialize layer data*/
+ for(i=0; i < BME_CD_NUMTYPES; i++){
+ if(init->layout[i]){
+ info = BME_layerType_getInfo(i);
+ for(j=0; j < init->layout[i]; j++){
+ if(j==0) data->layers[j+i].active = init->active[i];
+ data->layers[j+i].type = i;
+ data->layers[j+i].offset = offset;
+ strcpy(data->layers[j+i].name, &(init->nametemplate[j+i]));
+ offset += info->size;
+ }
+ }
+ }
+ }
+}
+
+void BME_CD_Free(BME_CustomData *data)
+{
+ if(data->pool) BLI_mempool_destroy(data->pool);
+}
+
+/*Block level ops*/
+void BME_CD_free_block(BME_CustomData *data, void **block)
+{
+ const BME_LayerTypeInfo *typeInfo;
+ int i;
+
+ if(!*block) return;
+ for(i = 0; i < data->totlayer; ++i) {
+ typeInfo = BME_layerType_getInfo(data->layers[i].type);
+ if(typeInfo->free) {
+ int offset = data->layers[i].offset;
+ typeInfo->free((char*)*block + offset, 1, typeInfo->size);
+ }
+ }
+ BLI_mempool_free(data->pool, *block);
+ *block = NULL;
+}
+
+
+static void BME_CD_alloc_block(BME_CustomData *data, void **block)
+{
+
+ if (*block) BME_CD_free_block(data, block); //if we copy layers that have their own free functions like deformverts
+
+ if (data->totsize > 0)
+ *block = BLI_mempool_alloc(data->pool);
+ else
+ *block = NULL;
+}
+
+void BME_CD_copy_data(const BME_CustomData *source, BME_CustomData *dest,
+ void *src_block, void **dest_block)
+{
+ const BME_LayerTypeInfo *typeInfo;
+ int dest_i, src_i;
+
+ if (!*dest_block) /*for addXXXlist functions!*/
+ BME_CD_alloc_block(dest, dest_block);
+
+ /* copies a layer at a time */
+ dest_i = 0;
+ for(src_i = 0; src_i < source->totlayer; ++src_i) {
+
+ /* find the first dest layer with type >= the source type
+ * (this should work because layers are ordered by type)
+ */
+ while(dest_i < dest->totlayer
+ && dest->layers[dest_i].type < source->layers[src_i].type)
+ ++dest_i;
+
+ /* if there are no more dest layers, we're done */
+ if(dest_i >= dest->totlayer) return;
+
+ /* if we found a matching layer, copy the data */
+ if(dest->layers[dest_i].type == source->layers[src_i].type &&
+ strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
+ char *src_data = (char*)src_block + source->layers[src_i].offset;
+ char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
+
+ typeInfo = BME_layerType_getInfo(source->layers[src_i].type);
+
+ if(typeInfo->copy)
+ typeInfo->copy(src_data, dest_data, 1);
+ else
+ memcpy(dest_data, src_data, typeInfo->size);
+
+ /* if there are multiple source & dest layers of the same type,
+ * we don't want to copy all source layers to the same dest, so
+ * increment dest_i
+ */
+ ++dest_i;
+ }
+ }
+}
+void BME_CD_set_default(BME_CustomData *data, void **block)
+{
+ const BME_LayerTypeInfo *typeInfo;
+ int i;
+
+ if (!*block)
+ BME_CD_alloc_block(data, block); //for addXXXlist functions...
+
+ for(i = 0; i < data->totlayer; ++i) {
+ int offset = data->layers[i].offset;
+
+ typeInfo = BME_layerType_getInfo(data->layers[i].type);
+
+ if(typeInfo->set_default)
+ typeInfo->set_default((char*)*block + offset, 1);
+ }
+}
diff --git a/source/blender/blenkernel/intern/BME_conversions.c b/source/blender/blenkernel/intern/BME_conversions.c
new file mode 100644
index 00000000000..2129042bdc2
--- /dev/null
+++ b/source/blender/blenkernel/intern/BME_conversions.c
@@ -0,0 +1,646 @@
+/**
+ * BME_mesh.c jan 2007
+ *
+ * BMesh mesh level functions.
+ *
+ * $Id: BME_eulers.c,v 1.00 2007/01/17 17:42:01 Briggs Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2007 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Geoffrey Bantle, Levi Schooley.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "MEM_guardedalloc.h"
+#include "BKE_customdata.h"
+
+#include "DNA_listBase.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_object_types.h"
+#include "DNA_scene_types.h"
+
+#include "BKE_utildefines.h"
+#include "BKE_mesh.h"
+#include "BKE_bmesh.h"
+#include "BKE_global.h"
+#include "BKE_DerivedMesh.h"
+#include "BKE_cdderivedmesh.h"
+
+#include "BLI_blenlib.h"
+#include "BLI_editVert.h"
+#include "BLI_edgehash.h"
+//XXX #include "BIF_editmesh.h"
+//XXX #include "editmesh.h"
+#include "bmesh_private.h"
+
+//XXX #include "BSE_edit.h"
+
+/*merge these functions*/
+static void BME_DMcorners_to_loops(BME_Mesh *bm, CustomData *facedata, int index, BME_Poly *f, int numCol, int numTex){
+ int i, j;
+ BME_Loop *l;
+ MTFace *texface;
+ MTexPoly *texpoly;
+ MCol *mcol;
+ MLoopCol *mloopcol;
+ MLoopUV *mloopuv;
+
+ for(i=0; i< numTex; i++){
+ texface = CustomData_get_layer_n(facedata, CD_MTFACE, i);
+ texpoly = CustomData_bmesh_get_n(&bm->pdata, f->data, CD_MTEXPOLY, i);
+
+ texpoly->tpage = texface[index].tpage;
+ texpoly->flag = texface[index].flag;
+ texpoly->transp = texface[index].transp;
+ texpoly->mode = texface[index].mode;
+ texpoly->tile = texface[index].tile;
+ texpoly->unwrap = texface[index].unwrap;
+
+ j = 0;
+ l = f->loopbase;
+ do{
+ mloopuv = CustomData_bmesh_get_n(&bm->ldata, l->data, CD_MLOOPUV, i);
+ mloopuv->uv[0] = texface[index].uv[j][0];
+ mloopuv->uv[1] = texface[index].uv[j][1];
+ j++;
+ l = l->next;
+ }while(l!=f->loopbase);
+ }
+
+ for(i=0; i < numCol; i++){
+ mcol = CustomData_get_layer_n(facedata, CD_MCOL, i);
+ j = 0;
+ l = f->loopbase;
+ do{
+ mloopcol = CustomData_bmesh_get_n(&bm->ldata, l->data, CD_MLOOPCOL, i);
+ mloopcol->r = mcol[(index*4)+j].r;
+ mloopcol->g = mcol[(index*4)+j].g;
+ mloopcol->b = mcol[(index*4)+j].b;
+ mloopcol->a = mcol[(index*4)+j].a;
+ j++;
+ l = l->next;
+ }while(l!=f->loopbase);
+ }
+}
+
+static void BME_DMloops_to_corners(BME_Mesh *bm, CustomData *facedata, int index, BME_Poly *f,int numCol, int numTex){
+ int i, j;
+ BME_Loop *l;
+ MTFace *texface;
+ MTexPoly *texpoly;
+ MCol *mcol;
+ MLoopCol *mloopcol;
+ MLoopUV *mloopuv;
+
+ for(i=0; i < numTex; i++){
+ texface = CustomData_get_layer_n(facedata, CD_MTFACE, i);
+ texpoly = CustomData_bmesh_get_n(&bm->pdata, f->data, CD_MTEXPOLY, i);
+
+ texface[index].tpage = texpoly->tpage;
+ texface[index].flag = texpoly->flag;
+ texface[index].transp = texpoly->transp;
+ texface[index].mode = texpoly->mode;
+ texface[index].tile = texpoly->tile;
+ texface[index].unwrap = texpoly->unwrap;
+
+ j = 0;
+ l = f->loopbase;
+ do{
+ mloopuv = CustomData_bmesh_get_n(&bm->ldata, l->data, CD_MLOOPUV, i);
+ texface[index].uv[j][0] = mloopuv->uv[0];
+ texface[index].uv[j][1] = mloopuv->uv[1];
+ j++;
+ l = l->next;
+ }while(l!=f->loopbase);
+
+ }
+ for(i=0; i < numCol; i++){
+ mcol = CustomData_get_layer_n(facedata,CD_MCOL, i);
+ j = 0;
+ l = f->loopbase;
+ do{
+ mloopcol = CustomData_bmesh_get_n(&bm->ldata, l->data, CD_MLOOPCOL, i);
+ mcol[(index*4) + j].r = mloopcol->r;
+ mcol[(index*4) + j].g = mloopcol->g;
+ mcol[(index*4) + j].b = mloopcol->b;
+ mcol[(index*4) + j].a = mloopcol->a;
+ j++;
+ l = l->next;
+ }while(l!=f->loopbase);
+ }
+}
+
+
+static void BME_corners_to_loops(BME_Mesh *bm, CustomData *facedata, void *face_block, BME_Poly *f,int numCol, int numTex){
+ int i, j;
+ BME_Loop *l;
+ MTFace *texface;
+ MTexPoly *texpoly;
+ MCol *mcol;
+ MLoopCol *mloopcol;
+ MLoopUV *mloopuv;
+
+ for(i=0; i < numTex; i++){
+ texface = CustomData_em_get_n(facedata, face_block, CD_MTFACE, i);
+ texpoly = CustomData_bmesh_get_n(&bm->pdata, f->data, CD_MTEXPOLY, i);
+
+ texpoly->tpage = texface->tpage;
+ texpoly->flag = texface->flag;
+ texpoly->transp = texface->transp;
+ texpoly->mode = texface->mode;
+ texpoly->tile = texface->tile;
+ texpoly->unwrap = texface->unwrap;
+
+ j = 0;
+ l = f->loopbase;
+ do{
+ mloopuv = CustomData_bmesh_get_n(&bm->ldata, l->data, CD_MLOOPUV, i);
+ mloopuv->uv[0] = texface->uv[j][0];
+ mloopuv->uv[1] = texface->uv[j][1];
+ j++;
+ l = l->next;
+ }while(l!=f->loopbase);
+
+ }
+ for(i=0; i < numCol; i++){
+ mcol = CustomData_em_get_n(facedata, face_block, CD_MCOL, i);
+ j = 0;
+ l = f->loopbase;
+ do{
+ mloopcol = CustomData_bmesh_get_n(&bm->ldata, l->data, CD_MLOOPCOL, i);
+ mloopcol->r = mcol[j].r;
+ mloopcol->g = mcol[j].g;
+ mloopcol->b = mcol[j].b;
+ mloopcol->a = mcol[j].a;
+ j++;
+ l = l->next;
+ }while(l!=f->loopbase);
+ }
+}
+
+static void BME_loops_to_corners(BME_Mesh *bm, CustomData *facedata, void *face_block, BME_Poly *f,int numCol, int numTex){
+ int i, j;
+ BME_Loop *l;
+ MTFace *texface;
+ MTexPoly *texpoly;
+ MCol *mcol;
+ MLoopCol *mloopcol;
+ MLoopUV *mloopuv;
+
+ for(i=0; i < numTex; i++){
+ texface = CustomData_em_get_n(facedata, face_block, CD_MTFACE, i);
+ texpoly = CustomData_bmesh_get_n(&bm->pdata, f->data, CD_MTEXPOLY, i);
+
+ texface->tpage = texpoly->tpage;
+ texface->flag = texpoly->flag;
+ texface->transp = texpoly->transp;
+ texface->mode = texpoly->mode;
+ texface->tile = texpoly->tile;
+ texface->unwrap = texpoly->unwrap;
+
+ j = 0;
+ l = f->loopbase;
+ do{
+ mloopuv = CustomData_bmesh_get_n(&bm->ldata, l->data, CD_MLOOPUV, i);
+ texface->uv[j][0] = mloopuv->uv[0];
+ texface->uv[j][1] = mloopuv->uv[1];
+ j++;
+ l = l->next;
+ }while(l!=f->loopbase);
+
+ }
+ for(i=0; i < numCol; i++){
+ mcol = CustomData_em_get_n(facedata, face_block, CD_MCOL, i);
+ j = 0;
+ l = f->loopbase;
+ do{
+ mloopcol = CustomData_bmesh_get_n(&bm->ldata, l->data, CD_MLOOPCOL, i);
+ mcol[j].r = mloopcol->r;
+ mcol[j].g = mloopcol->g;
+ mcol[j].b = mloopcol->b;
+ mcol[j].a = mloopcol->a;
+ j++;
+ l = l->next;
+ }while(l!=f->loopbase);
+ }
+}
+/*move the EditMesh conversion functions to editmesh_tools.c*/
+BME_Mesh *BME_editmesh_to_bmesh(EditMesh *em) {
+ BME_Mesh *bm;
+ int allocsize[4] = {512,512,2048,512}, numTex, numCol;
+ BME_Vert *v1, *v2;
+ BME_Edge *e, *edar[4];
+ BME_Poly *f;
+
+ EditVert *eve;
+ EditEdge *eed;
+ EditFace *efa;
+
+ int len;
+ bm = BME_make_mesh(allocsize);
+
+ /*copy custom data layout*/
+ CustomData_copy(&em->vdata, &bm->vdata, CD_MASK_BMESH, CD_CALLOC, 0);
+ CustomData_copy(&em->edata, &bm->edata, CD_MASK_BMESH, CD_CALLOC, 0);
+ CustomData_copy(&em->fdata, &bm->pdata, CD_MASK_BMESH, CD_CALLOC, 0);
+
+ /*copy face corner data*/
+ CustomData_to_bmeshpoly(&em->fdata, &bm->pdata, &bm->ldata);
+ /*initialize memory pools*/
+ CustomData_bmesh_init_pool(&bm->vdata, allocsize[0]);
+ CustomData_bmesh_init_pool(&bm->edata, allocsize[1]);
+ CustomData_bmesh_init_pool(&bm->ldata, allocsize[2]);
+ CustomData_bmesh_init_pool(&bm->pdata, allocsize[3]);
+ /*needed later*/
+ numTex = CustomData_number_of_layers(&bm->pdata, CD_MTEXPOLY);
+ numCol = CustomData_number_of_layers(&bm->ldata, CD_MLOOPCOL);
+
+ BME_model_begin(bm);
+ /*add verts*/
+ eve= em->verts.first;
+ while(eve) {
+ v1 = BME_MV(bm,eve->co);
+ VECCOPY(v1->no,eve->no);
+ v1->flag = eve->f;
+ v1->h = eve->h;
+ v1->bweight = eve->bweight;
+ /*Copy Custom Data*/
+ CustomData_bmesh_copy_data(&em->vdata, &bm->vdata, eve->data, &v1->data);
+ eve->tmp.v = (EditVert*)v1;
+ eve = eve->next;
+ }
+
+ /*add edges*/
+ eed= em->edges.first;
+ while(eed) {
+ v1 = (BME_Vert*)eed->v1->tmp.v;
+ v2 = (BME_Vert*)eed->v2->tmp.v;
+ e = BME_ME(bm, v1, v2);
+ e->crease = eed->crease;
+ e->bweight = eed->bweight;
+ e->flag = eed->f & SELECT;
+ if(eed->sharp) e->flag |= ME_SHARP;
+ if(eed->seam) e->flag |= ME_SEAM;
+ //XXX if(eed->h & EM_FGON) e->flag |= ME_FGON;
+ if(eed->h & 1) e->flag |= ME_HIDE;
+ eed->tmp.e = (EditEdge*)e;
+ CustomData_bmesh_copy_data(&em->edata, &bm->edata, eed->data, &e->data);
+ eed = eed->next;
+ }
+ /*add faces.*/
+ efa= em->faces.first;
+ while(efa) {
+ if(efa->v4) len = 4;
+ else len = 3;
+
+ edar[0] = (BME_Edge*)efa->e1->tmp.e;
+ edar[1] = (BME_Edge*)efa->e2->tmp.e;
+ edar[2] = (BME_Edge*)efa->e3->tmp.e;
+ if(len == 4){
+ edar[3] = (BME_Edge*)efa->e4->tmp.e;
+ }
+
+ /*find v1 and v2*/
+ v1 = (BME_Vert*)efa->v1->tmp.v;
+ v2 = (BME_Vert*)efa->v2->tmp.v;
+
+ f = BME_MF(bm,v1,v2,edar,len);
+ f->mat_nr = efa->mat_nr;
+ f->flag = efa->flag;
+ if(efa->h) {
+ f->flag |= ME_HIDE;
+ f->flag &= ~ME_FACE_SEL;
+ }
+ else {
+ if(efa->f & 1) f->flag |= ME_FACE_SEL;
+ else f->flag &= ~ME_FACE_SEL;
+ }
+ CustomData_bmesh_copy_data(&em->fdata, &bm->pdata, efa->data, &f->data);
+ BME_corners_to_loops(bm, &em->fdata, efa->data, f,numCol,numTex);
+ efa = efa->next;
+ }
+ BME_model_end(bm);
+ return bm;
+}
+/* adds the geometry in the bmesh to G.editMesh (does not free G.editMesh)
+ * if td != NULL, the transdata will be mapped to the EditVert's co */
+EditMesh *BME_bmesh_to_editmesh(BME_Mesh *bm, BME_TransData_Head *td) {
+ BME_Vert *v1;
+ BME_Edge *e;
+ BME_Poly *f;
+
+ BME_TransData *vtd;
+
+ EditMesh *em;
+ EditVert *eve1, *eve2, *eve3, *eve4, **evlist;
+ EditEdge *eed;
+ EditFace *efa;
+
+ int totvert, len, i, numTex, numCol;
+
+ em = G.editMesh;
+
+ if (em == NULL) return NULL;
+
+
+ CustomData_copy(&bm->vdata, &em->vdata, CD_MASK_BMESH, CD_CALLOC, 0);
+ CustomData_copy(&bm->edata, &em->edata, CD_MASK_BMESH, CD_CALLOC, 0);
+ CustomData_copy(&bm->pdata, &em->fdata, CD_MASK_BMESH, CD_CALLOC, 0);
+ CustomData_from_bmeshpoly(&em->fdata, &bm->pdata, &bm->ldata,0);
+ numTex = CustomData_number_of_layers(&bm->pdata, CD_MTEXPOLY);
+ numCol = CustomData_number_of_layers(&bm->ldata, CD_MLOOPCOL);
+
+
+ /* convert to EditMesh */
+ /* make editverts */
+ totvert = BLI_countlist(&(bm->verts));
+ evlist= (EditVert **)MEM_mallocN(totvert*sizeof(void *),"evlist");
+ for (i=0,v1=bm->verts.first;v1;v1=v1->next,i++) {
+ v1->tflag1 = i;
+ eve1 = NULL; //XXX addvertlist(v1->co,NULL);
+ if (td && (vtd = BME_get_transdata(td,v1))) {
+ vtd->loc = eve1->co;
+ }
+ eve1->keyindex = i;
+ evlist[i]= eve1;
+ eve1->f = (unsigned char)v1->flag;
+ eve1->h = (unsigned char)v1->h;
+ eve1->bweight = v1->bweight;
+ CustomData_em_copy_data(&bm->vdata, &em->vdata, v1->data, &eve1->data);
+ }
+
+ /* make edges */
+ for (e=bm->edges.first;e;e=e->next) {
+ if(0) { //XXX if(!(findedgelist(evlist[e->v1->tflag1], evlist[e->v2->tflag1]))){
+ eed= NULL; //XXX addedgelist(evlist[e->v1->tflag1], evlist[e->v2->tflag1], NULL);
+ eed->crease = e->crease;
+ eed->bweight = e->bweight;
+ if(e->flag & ME_SEAM) eed->seam = 1;
+ if(e->flag & ME_SHARP) eed->sharp = 1;
+ if(e->flag & SELECT) eed->f |= SELECT;
+ //XXX if(e->flag & ME_FGON) eed->h= EM_FGON; // 2 different defines!
+ if(e->flag & ME_HIDE) eed->h |= 1;
+ if(G.scene->selectmode==SCE_SELECT_EDGE)
+ ; //XXX EM_select_edge(eed, eed->f & SELECT);
+
+ CustomData_em_copy_data(&bm->edata, &em->edata, e->data, &eed->data);
+ }
+ }
+
+ /* make faces */
+ for (f=bm->polys.first;f;f=f->next) {
+ len = BME_cycle_length(f->loopbase);
+ if (len==3 || len==4) {
+ eve1= evlist[f->loopbase->v->tflag1];
+ eve2= evlist[f->loopbase->next->v->tflag1];
+ eve3= evlist[f->loopbase->next->next->v->tflag1];
+ if (len == 4) {
+ eve4= evlist[f->loopbase->prev->v->tflag1];
+ }
+ else {
+ eve4= NULL;
+ }
+
+ efa = NULL; //XXX addfacelist(eve1, eve2, eve3, eve4, NULL, NULL);
+ efa->mat_nr = (unsigned char)f->mat_nr;
+ efa->flag= f->flag & ~ME_HIDE;
+ if(f->flag & ME_FACE_SEL) {
+ efa->f |= SELECT;
+ }
+ if(f->flag & ME_HIDE) efa->h= 1;
+ if((G.f & G_FACESELECT) && (efa->f & SELECT))
+ ; //XXX EM_select_face(efa, 1); /* flush down */
+ CustomData_em_copy_data(&bm->pdata, &em->fdata, f->data, &efa->data);
+ BME_loops_to_corners(bm, &em->fdata, efa->data, f,numCol,numTex);
+ }
+ }
+
+ MEM_freeN(evlist);
+
+ //XXX countall();
+
+ return em;
+}
+
+/* Adds the geometry found in dm to bm
+ */
+BME_Mesh *BME_derivedmesh_to_bmesh(DerivedMesh *dm)
+{
+
+ BME_Mesh *bm;
+ int allocsize[4] = {512,512,2048,512};
+ MVert *mvert, *mv;
+ MEdge *medge, *me;
+ MFace *mface, *mf;
+ int totface,totedge,totvert,i,len, numTex, numCol;
+ BME_Vert *v1=NULL,*v2=NULL, **vert_array;
+ BME_Edge *e=NULL;
+ BME_Poly *f=NULL;
+
+ EdgeHash *edge_hash = BLI_edgehash_new();
+
+ bm = BME_make_mesh(allocsize);
+ /*copy custom data layout*/
+ CustomData_copy(&dm->vertData, &bm->vdata, CD_MASK_BMESH, CD_CALLOC, 0);
+ CustomData_copy(&dm->edgeData, &bm->edata, CD_MASK_BMESH, CD_CALLOC, 0);
+ CustomData_copy(&dm->faceData, &bm->pdata, CD_MASK_BMESH, CD_CALLOC, 0);
+
+ /*copy face corner data*/
+ CustomData_to_bmeshpoly(&dm->faceData, &bm->pdata, &bm->ldata);
+ /*initialize memory pools*/
+ CustomData_bmesh_init_pool(&bm->vdata, allocsize[0]);
+ CustomData_bmesh_init_pool(&bm->edata, allocsize[1]);
+ CustomData_bmesh_init_pool(&bm->ldata, allocsize[2]);
+ CustomData_bmesh_init_pool(&bm->pdata, allocsize[3]);
+ /*needed later*/
+ numTex = CustomData_number_of_layers(&bm->pdata, CD_MTEXPOLY);
+ numCol = CustomData_number_of_layers(&bm->ldata, CD_MLOOPCOL);
+
+ totvert = dm->getNumVerts(dm);
+ totedge = dm->getNumEdges(dm);
+ totface = dm->getNumFaces(dm);
+ mvert = dm->getVertArray(dm);
+ medge = dm->getEdgeArray(dm);
+ mface = dm->getFaceArray(dm);
+
+ vert_array = MEM_mallocN(sizeof(*vert_array)*totvert,"BME_derivedmesh_to_bmesh BME_Vert* array");
+
+ BME_model_begin(bm);
+ /*add verts*/
+ for(i=0,mv = mvert; i < totvert;i++,mv++){
+ v1 = BME_MV(bm,mv->co);
+ vert_array[i] = v1;
+ v1->flag = mv->flag;
+ v1->bweight = mv->bweight/255.0f;
+ CustomData_to_bmesh_block(&dm->vertData, &bm->vdata, i, &v1->data);
+ }
+ /*add edges*/
+ for(i=0,me = medge; i < totedge;i++,me++){
+ v1 = vert_array[me->v1];
+ v2 = vert_array[me->v2];
+ e = BME_ME(bm, v1, v2);
+ e->crease = me->crease/255.0f;
+ e->bweight = me->bweight/255.0f;
+ e->flag = (unsigned char)me->flag;
+ BLI_edgehash_insert(edge_hash,me->v1,me->v2,e);
+ CustomData_to_bmesh_block(&dm->edgeData, &bm->edata, i, &e->data);
+ }
+ /*add faces.*/
+ for(i=0,mf = mface; i < totface;i++,mf++){
+ BME_Edge *edar[4];
+ if(mf->v4) len = 4;
+ else len = 3;
+
+ edar[0] = BLI_edgehash_lookup(edge_hash,mf->v1,mf->v2);
+ edar[1] = BLI_edgehash_lookup(edge_hash,mf->v2,mf->v3);
+ if(len == 4){
+ edar[2] = BLI_edgehash_lookup(edge_hash,mf->v3,mf->v4);
+ edar[3] = BLI_edgehash_lookup(edge_hash,mf->v4,mf->v1);
+ }
+ else
+ edar[2] = BLI_edgehash_lookup(edge_hash,mf->v3,mf->v1);
+
+ /*find v1 and v2*/
+ v1 = vert_array[mf->v1];
+ v2 = vert_array[mf->v2];
+
+ f = BME_MF(bm,v1,v2,edar,len);
+ f->mat_nr = mf->mat_nr;
+ f->flag = mf->flag;
+ CustomData_to_bmesh_block(&dm->faceData,&bm->pdata,i,&f->data);
+ BME_DMcorners_to_loops(bm, &dm->faceData,i,f, numCol,numTex);
+ }
+
+ BME_model_end(bm);
+ BLI_edgehash_free(edge_hash, NULL);
+ MEM_freeN(vert_array);
+ return bm;
+}
+
+DerivedMesh *BME_bmesh_to_derivedmesh(BME_Mesh *bm, DerivedMesh *dm)
+{
+ MFace *mface, *mf;
+ MEdge *medge, *me;
+ MVert *mvert, *mv;
+ int totface,totedge,totvert,i,bmeshok,len, numTex, numCol;
+
+ BME_Vert *v1=NULL;
+ BME_Edge *e=NULL, *oe=NULL;
+ BME_Poly *f=NULL;
+
+ DerivedMesh *result;
+ EdgeHash *edge_hash = BLI_edgehash_new();
+
+ totvert = BLI_countlist(&(bm->verts));
+ totedge = 0;
+
+ /*we cannot have double edges in a derived mesh!*/
+ for(i=0, v1=bm->verts.first; v1; v1=v1->next, i++) v1->tflag1 = i;
+ for(e=bm->edges.first; e; e=e->next){
+ oe = BLI_edgehash_lookup(edge_hash,e->v1->tflag1, e->v2->tflag1);
+ if(!oe){
+ totedge++;
+ BLI_edgehash_insert(edge_hash,e->v1->tflag1,e->v2->tflag1,e);
+ e->tflag2 = 1;
+ }
+ else{
+ e->tflag2 = 0;
+ }
+ }
+
+ /*count quads and tris*/
+ totface = 0;
+ bmeshok = 1;
+ for(f=bm->polys.first;f;f=f->next){
+ len = BME_cycle_length(f->loopbase);
+ if(len == 3 || len == 4) totface++;
+ }
+
+ /*convert back to mesh*/
+ result = CDDM_from_template(dm,totvert,totedge,totface);
+ CustomData_merge(&bm->vdata, &result->vertData, CD_MASK_BMESH, CD_CALLOC, totvert);
+ CustomData_merge(&bm->edata, &result->edgeData, CD_MASK_BMESH, CD_CALLOC, totedge);
+ CustomData_merge(&bm->pdata, &result->faceData, CD_MASK_BMESH, CD_CALLOC, totface);
+ CustomData_from_bmeshpoly(&result->faceData, &bm->pdata, &bm->ldata,totface);
+ numTex = CustomData_number_of_layers(&bm->pdata, CD_MTEXPOLY);
+ numCol = CustomData_number_of_layers(&bm->ldata, CD_MLOOPCOL);
+
+
+ /*Make Verts*/
+ mvert = CDDM_get_verts(result);
+ for(i=0,v1=bm->verts.first,mv=mvert;v1;v1=v1->next,i++,mv++){
+ VECCOPY(mv->co,v1->co);
+ mv->flag = (unsigned char)v1->flag;
+ mv->bweight = (char)(255.0*v1->bweight);
+ CustomData_from_bmesh_block(&bm->vdata, &result->vertData, &v1->data, i);
+ }
+ medge = CDDM_get_edges(result);
+ i=0;
+ for(e=bm->edges.first,me=medge;e;e=e->next){
+ if(e->tflag2){
+ if(e->v1->tflag1 < e->v2->tflag1){
+ me->v1 = e->v1->tflag1;
+ me->v2 = e->v2->tflag1;
+ }
+ else{
+ me->v1 = e->v2->tflag1;
+ me->v2 = e->v1->tflag1;
+ }
+
+ me->crease = (char)(255.0*e->crease);
+ me->bweight = (char)(255.0*e->bweight);
+ me->flag = e->flag;
+ CustomData_from_bmesh_block(&bm->edata, &result->edgeData, &e->data, i);
+ me++;
+ i++;
+ }
+ }
+ if(totface){
+ mface = CDDM_get_faces(result);
+ /*make faces*/
+ for(i=0,f=bm->polys.first;f;f=f->next){
+ mf = &mface[i];
+ len = BME_cycle_length(f->loopbase);
+ if(len==3 || len==4){
+ mf->v1 = f->loopbase->v->tflag1;
+ mf->v2 = f->loopbase->next->v->tflag1;
+ mf->v3 = f->loopbase->next->next->v->tflag1;
+ if(len == 4){
+ mf->v4 = f->loopbase->prev->v->tflag1;
+ }
+ /* test and rotate indexes if necessary so that verts 3 and 4 aren't index 0 */
+ if(mf->v3 == 0 || (len == 4 && mf->v4 == 0)){
+ test_index_face(mf, NULL, i, len);
+ }
+ mf->mat_nr = (unsigned char)f->mat_nr;
+ mf->flag = (unsigned char)f->flag;
+ CustomData_from_bmesh_block(&bm->pdata, &result->faceData, &f->data, i);
+ BME_DMloops_to_corners(bm, &result->faceData, i, f,numCol,numTex);
+ i++;
+ }
+ }
+ }
+ BLI_edgehash_free(edge_hash, NULL);
+ return result;
+}
diff --git a/source/blender/blenkernel/intern/BME_eulers.c b/source/blender/blenkernel/intern/BME_eulers.c
new file mode 100644
index 00000000000..801e0b8bdec
--- /dev/null
+++ b/source/blender/blenkernel/intern/BME_eulers.c
@@ -0,0 +1,977 @@
+/**
+ * BME_eulers.c jan 2007
+ *
+ * BMesh Euler construction API.
+ *
+ * $Id: BME_eulers.c,v 1.00 2007/01/17 17:42:01 Briggs Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2004 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Geoffrey Bantle.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_listBase.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_mesh_types.h"
+
+#include "BKE_utildefines.h"
+#include "BKE_customdata.h"
+#include "BKE_bmesh.h"
+
+#include "BLI_blenlib.h"
+#include "bmesh_private.h"
+#include "BLI_ghash.h"
+
+/*********************************************************
+ * "Euler API" *
+ * *
+ * *
+ * Primitive construction operators for mesh tools. *
+ * *
+ **********************************************************/
+
+
+/*
+ The functions in this file represent the 'primitive' or 'atomic' operators that
+ mesh tools use to manipulate the topology of the structure.* The purpose of these
+ functions is to provide a trusted set of operators to manipulate the mesh topology
+ and which can also be combined together like building blocks to create more
+ sophisticated tools. It needs to be stressed that NO manipulation of an existing
+ mesh structure should be done outside of these functions.
+
+ In the BMesh system, each euler is named by an ancronym which describes what it actually does.
+ Furthermore each Euler has a logical inverse. An important design criteria of all Eulers is that
+ through a Euler's logical inverse you can 'undo' an operation. (Special note should
+ be taken of BME_loop_reverse, which is its own inverse).
+
+ BME_MF/KF: Make Face and Kill Face
+ BME_ME/KE: Make Edge and Kill Edge
+ BME_MV/KV: Make Vert and Kill Vert
+ BME_SEMV/JEKV: Split Edge, Make Vert and Join Edge, Kill Vert
+ BME_SFME/JFKE: Split Face, Make Edge and Join Face, Kill Edge
+ BME_loop_reverse: Reverse a Polygon's loop cycle. (used for flip normals for one)
+
+ Using a combination of these eleven eulers any non-manifold modelling operation can be achieved.
+ Each Euler operator has a detailed explanation of what is does in the comments preceding its
+ code.
+
+ *The term "Euler Operator" is actually a misnomer when referring to a non-manifold
+ data structure. Its use is in keeping with the convention established by others.
+
+ TODO:
+ -Finish inserting 'strict' validation in all Eulers
+*/
+
+void *BME_exit(char *s) {
+ if (s) printf("%s\n",s);
+ return NULL;
+}
+
+#define RETCLEAR(bm) {bm->rval->v = bm->rval->e = bm->rval->f = bm->rva->l = NULL;}
+/*MAKE Eulers*/
+
+/**
+ * BME_MV
+ *
+ * MAKE VERT EULER:
+ *
+ * Makes a single loose vertex.
+ *
+ * Returns -
+ * A BME_Vert pointer.
+ */
+
+BME_Vert *BME_MV(BME_Mesh *bm, float *vec){
+ BME_Vert *v = BME_addvertlist(bm, NULL);
+ VECCOPY(v->co,vec);
+ return v;
+}
+
+/**
+ * BME_ME
+ *
+ * MAKE EDGE EULER:
+ *
+ * Makes a single wire edge between two vertices.
+ * If the caller does not want there to be duplicate
+ * edges between the vertices, it is up to them to check
+ * for this condition beforehand.
+ *
+ * Returns -
+ * A BME_Edge pointer.
+ */
+
+BME_Edge *BME_ME(BME_Mesh *bm, BME_Vert *v1, BME_Vert *v2){
+ BME_Edge *e=NULL;
+ BME_CycleNode *d1=NULL, *d2=NULL;
+ int valance1=0, valance2=0, edok;
+
+ /*edge must be between two distinct vertices...*/
+ if(v1 == v2) return NULL;
+
+ #ifndef BME_FASTEULER
+ /*count valance of v1*/
+ if(v1->edge){
+ d1 = BME_disk_getpointer(v1->edge,v1);
+ if(d1) valance1 = BME_cycle_length(d1);
+ else BME_error();
+ }
+ if(v2->edge){
+ d2 = BME_disk_getpointer(v2->edge,v2);
+ if(d2) valance2 = BME_cycle_length(d2);
+ else BME_error();
+ }
+ #endif
+
+ /*go ahead and add*/
+ e = BME_addedgelist(bm, v1, v2, NULL);
+ BME_disk_append_edge(e, e->v1);
+ BME_disk_append_edge(e, e->v2);
+
+ #ifndef BME_FASTEULER
+ /*verify disk cycle lengths*/
+ d1 = BME_disk_getpointer(e, e->v1);
+ edok = BME_cycle_validate(valance1+1, d1);
+ if(!edok) BME_error();
+ d2 = BME_disk_getpointer(e, e->v2);
+ edok = BME_cycle_validate(valance2+1, d2);
+ if(!edok) BME_error();
+
+ /*verify that edge actually made it into the cycle*/
+ edok = BME_disk_hasedge(v1, e);
+ if(!edok) BME_error();
+ edok = BME_disk_hasedge(v2, e);
+ if(!edok) BME_error();
+ #endif
+ return e;
+}
+
+
+
+/**
+ * BME_MF
+ *
+ * MAKE FACE EULER:
+ * Takes a list of edge pointers which form a closed loop and makes a face
+ * from them. The first edge in elist is considered to be the start of the
+ * polygon, and v1 and v2 are its vertices and determine the winding of the face
+ * Other than the first edge, no other assumptions are made about the order of edges
+ * in the elist array. To verify that it is a single closed loop and derive the correct
+ * order a simple series of verifications is done and all elements are visited.
+ *
+ * Returns -
+ * A BME_Poly pointer
+ */
+
+#define MF_CANDIDATE 1
+#define MF_VISITED 2
+#define MF_TAKEN 4
+
+BME_Poly *BME_MF(BME_Mesh *bm, BME_Vert *v1, BME_Vert *v2, BME_Edge **elist, int len)
+{
+ BME_Poly *f = NULL;
+ BME_Edge *curedge;
+ BME_Vert *curvert, *tv, **vlist;
+ int i, j, done, cont, edok;
+
+ if(len < 2) return NULL;
+
+ /*make sure that v1 and v2 are in elist[0]*/
+ if(BME_verts_in_edge(v1,v2,elist[0]) == 0) return NULL;
+
+ /*clear euler flags*/
+ for(i=0;i<len;i++) elist[i]->eflag1=elist[i]->eflag2 = 0;
+ for(i=0;i<len;i++){
+ elist[i]->eflag1 |= MF_CANDIDATE;
+
+ /*if elist[i] has a loop, count its radial length*/
+ if(elist[i]->loop) elist[i]->eflag2 = BME_cycle_length(&(elist[i]->loop->radial));
+ else elist[i]->eflag2 = 0;
+ }
+
+ /* For each vertex in each edge, it must have exactly two MF_CANDIDATE edges attached to it
+ Note that this does not gauruntee that face is a single closed loop. At best it gauruntees
+ that elist contains a finite number of seperate closed loops.
+ */
+ for(i=0; i<len; i++){
+ edok = BME_disk_count_edgeflag(elist[i]->v1, MF_CANDIDATE, 0);
+ if(edok != 2) return NULL;
+ edok = BME_disk_count_edgeflag(elist[i]->v2, MF_CANDIDATE, 0);
+ if(edok != 2) return NULL;
+ }
+
+ /*set start edge, start vert and target vert for our loop traversal*/
+ curedge = elist[0];
+ tv = v1;
+ curvert = v2;
+
+ if(bm->vtarlen < len){
+ MEM_freeN(bm->vtar);
+ bm->vtar = MEM_callocN(sizeof(BME_Vert *)* len, "BMesh Vert pointer array");
+ bm->vtarlen = len;
+ }
+ /*insert tv into vlist since its the first vertex in face*/
+ i=0;
+ vlist=bm->vtar;
+ vlist[i] = tv;
+
+ /* Basic procedure: Starting with curv we find the edge in it's disk cycle which hasn't
+ been visited yet. When we do, we put curv in a linked list and find the next MF_CANDIDATE
+ edge, loop until we find TV. We know TV is reachable because of test we did earlier.
+ */
+ done=0;
+ while(!done){
+ /*add curvert to vlist*/
+ /*insert some error cheking here for overflows*/
+ i++;
+ vlist[i] = curvert;
+
+ /*mark curedge as visited*/
+ curedge->eflag1 |= MF_VISITED;
+
+ /*find next edge and vert*/
+ curedge = BME_disk_next_edgeflag(curedge, curvert, MF_CANDIDATE, 0);
+ curvert = BME_edge_getothervert(curedge, curvert);
+ if(curvert == tv){
+ curedge->eflag1 |= MF_VISITED;
+ done=1;
+ }
+ }
+
+ /* Verify that all edges have been visited It's possible that we did reach tv
+ from sv, but that several unconnected loops were passed in via elist.
+ */
+ cont=1;
+ for(i=0; i<len; i++){
+ if((elist[i]->eflag1 & MF_VISITED) == 0) cont = 0;
+ }
+
+ /*if we get this far, its ok to allocate the face and add the loops*/
+ if(cont){
+ BME_Loop *l;
+ BME_Edge *e;
+ f = BME_addpolylist(bm, NULL);
+ f->len = len;
+ for(i=0;i<len;i++){
+ curvert = vlist[i];
+ l = BME_create_loop(bm,curvert,NULL,f,NULL);
+ if(!(f->loopbase)) f->loopbase = l;
+ BME_cycle_append(f->loopbase, l);
+ }
+
+ /*take care of edge pointers and radial cycle*/
+ for(i=0, l = f->loopbase; i<len; i++, l=l->next){
+ e = NULL;
+ if(l == f->loopbase) e = elist[0]; /*first edge*/
+
+ else{/*search elist for others*/
+ for(j=1; j<len; j++){
+ edok = BME_verts_in_edge(l->v, l->next->v, elist[j]);
+ if(edok){
+ e = elist[j];
+ break;
+ }
+ }
+ }
+ l->e = e; /*set pointer*/
+ BME_radial_append(e, l); /*append into radial*/
+ }
+
+ f->len = len;
+
+ /*Validation Loop cycle*/
+ edok = BME_cycle_validate(len, f->loopbase);
+ if(!edok) BME_error();
+ for(i=0, l = f->loopbase; i<len; i++, l=l->next){
+ /*validate loop vert pointers*/
+ edok = BME_verts_in_edge(l->v, l->next->v, l->e);
+ if(!edok) BME_error();
+ /*validate the radial cycle of each edge*/
+ edok = BME_cycle_length(&(l->radial));
+ if(edok != (l->e->eflag2 + 1)) BME_error();
+ }
+ }
+ return f;
+}
+
+/* KILL Eulers */
+
+/**
+ * BME_KV
+ *
+ * KILL VERT EULER:
+ *
+ * Kills a single loose vertex.
+ *
+ * Returns -
+ * 1 for success, 0 for failure.
+ */
+
+int BME_KV(BME_Mesh *bm, BME_Vert *v){
+ if(v->edge == NULL){
+ BLI_remlink(&(bm->verts), v);
+ BME_free_vert(bm,v);
+ return 1;
+ }
+ return 0;
+}
+
+/**
+ * BME_KE
+ *
+ * KILL EDGE EULER:
+ *
+ * Kills a wire edge.
+ *
+ * Returns -
+ * 1 for success, 0 for failure.
+ */
+
+int BME_KE(BME_Mesh *bm, BME_Edge *e){
+ int edok;
+
+ /*Make sure that no faces!*/
+ if(e->loop == NULL){
+ BME_disk_remove_edge(e, e->v1);
+ BME_disk_remove_edge(e, e->v2);
+
+ /*verify that edge out of disk*/
+ edok = BME_disk_hasedge(e->v1, e);
+ if(edok) BME_error();
+ edok = BME_disk_hasedge(e->v2, e);
+ if(edok) BME_error();
+
+ /*remove and deallocate*/
+ BLI_remlink(&(bm->edges), e);
+ BME_free_edge(bm, e);
+ return 1;
+ }
+ return 0;
+}
+
+/**
+ * BME_KF
+ *
+ * KILL FACE EULER:
+ *
+ * The logical inverse of BME_MF.
+ * Kills a face and removes each of its loops from the radial that it belongs to.
+ *
+ * Returns -
+ * 1 for success, 0 for failure.
+*/
+
+int BME_KF(BME_Mesh *bm, BME_Poly *bply){
+ BME_Loop *newbase,*oldbase, *curloop;
+ int i,len=0;
+
+ /*add validation to make sure that radial cycle is cleaned up ok*/
+ /*deal with radial cycle first*/
+ len = BME_cycle_length(bply->loopbase);
+ for(i=0, curloop=bply->loopbase; i < len; i++, curloop = curloop->next)
+ BME_radial_remove_loop(curloop, curloop->e);
+
+ /*now deallocate the editloops*/
+ for(i=0; i < len; i++){
+ newbase = bply->loopbase->next;
+ oldbase = bply->loopbase;
+ BME_cycle_remove(oldbase, oldbase);
+ BME_free_loop(bm, oldbase);
+ bply->loopbase = newbase;
+ }
+
+ BLI_remlink(&(bm->polys), bply);
+ BME_free_poly(bm, bply);
+ return 1;
+}
+
+/*SPLIT Eulers*/
+
+/**
+ * BME_SEMV
+ *
+ * SPLIT EDGE MAKE VERT:
+ * Takes a given edge and splits it into two, creating a new vert.
+ *
+ *
+ * Before: OV---------TV
+ * After: OV----NV---TV
+ *
+ * Returns -
+ * BME_Vert pointer.
+ *
+*/
+
+BME_Vert *BME_SEMV(BME_Mesh *bm, BME_Vert *tv, BME_Edge *e, BME_Edge **re){
+ BME_Vert *nv, *ov;
+ BME_CycleNode *diskbase;
+ BME_Edge *ne;
+ int i, edok, valance1=0, valance2=0;
+
+ if(BME_vert_in_edge(e,tv) == 0) return NULL;
+ ov = BME_edge_getothervert(e,tv);
+ //v2 = tv;
+
+ /*count valance of v1*/
+ diskbase = BME_disk_getpointer(e, ov);
+ valance1 = BME_cycle_length(diskbase);
+ /*count valance of v2*/
+ diskbase = BME_disk_getpointer(e, tv);
+ valance2 = BME_cycle_length(diskbase);
+
+ nv = BME_addvertlist(bm, tv);
+ ne = BME_addedgelist(bm, nv, tv, e);
+
+ //e->v2 = nv;
+ /*remove e from v2's disk cycle*/
+ BME_disk_remove_edge(e, tv);
+ /*swap out tv for nv in e*/
+ BME_edge_swapverts(e, tv, nv);
+ /*add e to nv's disk cycle*/
+ BME_disk_append_edge(e, nv);
+ /*add ne to nv's disk cycle*/
+ BME_disk_append_edge(ne, nv);
+ /*add ne to tv's disk cycle*/
+ BME_disk_append_edge(ne, tv);
+ /*verify disk cycles*/
+ diskbase = BME_disk_getpointer(ov->edge,ov);
+ edok = BME_cycle_validate(valance1, diskbase);
+ if(!edok) BME_error();
+ diskbase = BME_disk_getpointer(tv->edge,tv);
+ edok = BME_cycle_validate(valance2, diskbase);
+ if(!edok) BME_error();
+ diskbase = BME_disk_getpointer(nv->edge,nv);
+ edok = BME_cycle_validate(2, diskbase);
+ if(!edok) BME_error();
+
+ /*Split the radial cycle if present*/
+ if(e->loop){
+ BME_Loop *nl,*l;
+ BME_CycleNode *radEBase=NULL, *radNEBase=NULL;
+ int radlen = BME_cycle_length(&(e->loop->radial));
+ /*Take the next loop. Remove it from radial. Split it. Append to appropriate radials.*/
+ while(e->loop){
+ l=e->loop;
+ l->f->len++;
+ BME_radial_remove_loop(l,e);
+
+ nl = BME_create_loop(bm,NULL,NULL,l->f,l);
+ nl->prev = l;
+ nl->next = l->next;
+ nl->prev->next = nl;
+ nl->next->prev = nl;
+ nl->v = nv;
+
+ /*assign the correct edge to the correct loop*/
+ if(BME_verts_in_edge(nl->v, nl->next->v, e)){
+ nl->e = e;
+ l->e = ne;
+
+ /*append l into ne's rad cycle*/
+ if(!radNEBase){
+ radNEBase = &(l->radial);
+ radNEBase->next = NULL;
+ radNEBase->prev = NULL;
+ }
+
+ if(!radEBase){
+ radEBase = &(nl->radial);
+ radEBase->next = NULL;
+ radEBase->prev = NULL;
+ }
+
+ BME_cycle_append(radEBase,&(nl->radial));
+ BME_cycle_append(radNEBase,&(l->radial));
+
+ }
+ else if(BME_verts_in_edge(nl->v,nl->next->v,ne)){
+ nl->e = ne;
+ l->e = e;
+
+ if(!radNEBase){
+ radNEBase = &(nl->radial);
+ radNEBase->next = NULL;
+ radNEBase->prev = NULL;
+ }
+ if(!radEBase){
+ radEBase = &(l->radial);
+ radEBase->next = NULL;
+ radEBase->prev = NULL;
+ }
+ BME_cycle_append(radEBase,&(l->radial));
+ BME_cycle_append(radNEBase,&(nl->radial));
+ }
+
+ }
+
+ e->loop = radEBase->data;
+ ne->loop = radNEBase->data;
+
+ /*verify length of radial cycle*/
+ edok = BME_cycle_validate(radlen,&(e->loop->radial));
+ if(!edok) BME_error();
+ edok = BME_cycle_validate(radlen,&(ne->loop->radial));
+ if(!edok) BME_error();
+
+ /*verify loop->v and loop->next->v pointers for e*/
+ for(i=0,l=e->loop; i < radlen; i++, l = l->radial.next->data){
+ if(!(l->e == e)) BME_error();
+ if(!(l->radial.data == l)) BME_error();
+ if(l->prev->e != ne && l->next->e != ne) BME_error();
+ edok = BME_verts_in_edge(l->v, l->next->v, e);
+ if(!edok) BME_error();
+ if(l->v == l->next->v) BME_error();
+ if(l->e == l->next->e) BME_error();
+ /*verify loop cycle for kloop->f*/
+ edok = BME_cycle_validate(l->f->len, l->f->loopbase);
+ if(!edok) BME_error();
+ }
+ /*verify loop->v and loop->next->v pointers for ne*/
+ for(i=0,l=ne->loop; i < radlen; i++, l = l->radial.next->data){
+ if(!(l->e == ne)) BME_error();
+ if(!(l->radial.data == l)) BME_error();
+ if(l->prev->e != e && l->next->e != e) BME_error();
+ edok = BME_verts_in_edge(l->v, l->next->v, ne);
+ if(!edok) BME_error();
+ if(l->v == l->next->v) BME_error();
+ if(l->e == l->next->e) BME_error();
+ /*verify loop cycle for kloop->f. Redundant*/
+ edok = BME_cycle_validate(l->f->len, l->f->loopbase);
+ if(!edok) BME_error();
+ }
+ }
+
+ if(re) *re = ne;
+ return nv;
+}
+
+/**
+ * BME_SFME
+ *
+ * SPLIT FACE MAKE EDGE:
+ *
+ * Takes as input two vertices in a single face. An edge is created which divides the original face
+ * into two distinct regions. One of the regions is assigned to the original face and it is closed off.
+ * The second region has a new face assigned to it.
+ *
+ * Examples:
+ *
+ * Before: After:
+ * ---------- ----------
+ * | | | |
+ * | | | f1 |
+ * v1 f1 v2 v1======v2
+ * | | | f2 |
+ * | | | |
+ * ---------- ----------
+ *
+ * Note that the input vertices can be part of the same edge. This will result in a two edged face.
+ * This is desirable for advanced construction tools and particularly essential for edge bevel. Because
+ * of this it is up to the caller to decide what to do with the extra edge.
+ *
+ * Returns -
+ * A BME_Poly pointer
+ */
+BME_Poly *BME_SFME(BME_Mesh *bm, BME_Poly *f, BME_Vert *v1, BME_Vert *v2, BME_Loop **rl){
+
+ BME_Poly *f2;
+ BME_Loop *v1loop = NULL, *v2loop = NULL, *curloop, *f1loop=NULL, *f2loop=NULL;
+ BME_Edge *e;
+ int i, len, f1len, f2len;
+
+
+ /*verify that v1 and v2 are in face.*/
+ len = BME_cycle_length(f->loopbase);
+ for(i = 0, curloop = f->loopbase; i < len; i++, curloop = curloop->next){
+ if(curloop->v == v1) v1loop = curloop;
+ else if(curloop->v == v2) v2loop = curloop;
+ }
+
+ if(!v1loop || !v2loop) return NULL;
+
+ /*allocate new edge between v1 and v2*/
+ e = BME_addedgelist(bm, v1, v2,NULL);
+ BME_disk_append_edge(e, v1);
+ BME_disk_append_edge(e, v2);
+
+ f2 = BME_addpolylist(bm,f);
+ f1loop = BME_create_loop(bm,v2,e,f,v2loop);
+ f2loop = BME_create_loop(bm,v1,e,f2,v1loop);
+
+ f1loop->prev = v2loop->prev;
+ f2loop->prev = v1loop->prev;
+ v2loop->prev->next = f1loop;
+ v1loop->prev->next = f2loop;
+
+ f1loop->next = v1loop;
+ f2loop->next = v2loop;
+ v1loop->prev = f1loop;
+ v2loop->prev = f2loop;
+
+ f2->loopbase = f2loop;
+ f->loopbase = f1loop;
+
+ /*validate both loops*/
+ /*I dont know how many loops are supposed to be in each face at this point! FIXME!*/
+
+ /*go through all of f2's loops and make sure they point to it properly.*/
+ f2len = BME_cycle_length(f2->loopbase);
+ for(i=0, curloop = f2->loopbase; i < f2len; i++, curloop = curloop->next) curloop->f = f2;
+
+ /*link up the new loops into the new edges radial*/
+ BME_radial_append(e, f1loop);
+ BME_radial_append(e, f2loop);
+
+
+ f2->len = f2len;
+
+ f1len = BME_cycle_length(f->loopbase);
+ f->len = f1len;
+
+ if(rl) *rl = f2loop;
+ return f2;
+}
+
+
+/**
+ * BME_JEKV
+ *
+ * JOIN EDGE KILL VERT:
+ * Takes a an edge and pointer to one of its vertices and collapses
+ * the edge on that vertex.
+ *
+ * Before: OE KE
+ * ------- -------
+ * | || |
+ * OV KV TV
+ *
+ *
+ * After: OE
+ * ---------------
+ * | |
+ * OV TV
+ *
+ *
+ * Restrictions:
+ * KV is a vertex that must have a valance of exactly two. Furthermore
+ * both edges in KV's disk cycle (OE and KE) must be unique (no double
+ * edges).
+ *
+ * It should also be noted that this euler has the possibility of creating
+ * faces with just 2 edges. It is up to the caller to decide what to do with
+ * these faces.
+ *
+ * Returns -
+ * 1 for success, 0 for failure.
+ */
+int BME_JEKV(BME_Mesh *bm, BME_Edge *ke, BME_Vert *kv)
+{
+ BME_Edge *oe;
+ BME_Vert *ov, *tv;
+ BME_CycleNode *diskbase;
+ BME_Loop *killoop,*nextl;
+ int len,radlen=0, halt = 0, i, valance1, valance2,edok;
+
+ if(BME_vert_in_edge(ke,kv) == 0) return 0;
+ diskbase = BME_disk_getpointer(kv->edge, kv);
+ len = BME_cycle_length(diskbase);
+
+ if(len == 2){
+ oe = BME_disk_nextedge(ke, kv);
+ tv = BME_edge_getothervert(ke, kv);
+ ov = BME_edge_getothervert(oe, kv);
+ halt = BME_verts_in_edge(kv, tv, oe); //check for double edges
+
+ if(halt) return 0;
+ else{
+
+ /*For verification later, count valance of ov and tv*/
+ diskbase = BME_disk_getpointer(ov->edge, ov);
+ valance1 = BME_cycle_length(diskbase);
+ diskbase = BME_disk_getpointer(tv->edge, tv);
+ valance2 = BME_cycle_length(diskbase);
+
+ /*remove oe from kv's disk cycle*/
+ BME_disk_remove_edge(oe,kv);
+ /*relink oe->kv to be oe->tv*/
+ BME_edge_swapverts(oe, kv, tv);
+ /*append oe to tv's disk cycle*/
+ BME_disk_append_edge(oe, tv);
+ /*remove ke from tv's disk cycle*/
+ BME_disk_remove_edge(ke, tv);
+
+
+
+ /*deal with radial cycle of ke*/
+ if(ke->loop){
+ /*first step, fix the neighboring loops of all loops in ke's radial cycle*/
+ radlen = BME_cycle_length(&(ke->loop->radial));
+ for(i=0,killoop = ke->loop; i<radlen; i++, killoop = BME_radial_nextloop(killoop)){
+ /*relink loops and fix vertex pointer*/
+ killoop->next->prev = killoop->prev;
+ killoop->prev->next = killoop->next;
+ if(killoop->next->v == kv) killoop->next->v = tv;
+
+ /*fix len attribute of face*/
+ killoop->f->len--;
+ if(killoop->f->loopbase == killoop) killoop->f->loopbase = killoop->next;
+ }
+ /*second step, remove all the hanging loops attached to ke*/
+ killoop = ke->loop;
+ radlen = BME_cycle_length(&(ke->loop->radial));
+ /*make sure we have enough room in bm->lpar*/
+ if(bm->lparlen < radlen){
+ MEM_freeN(bm->lpar);
+ bm->lpar = MEM_callocN(sizeof(BME_Loop *)* radlen, "BMesh Loop pointer array");
+ bm->lparlen = bm->lparlen * radlen;
+ }
+ /*this should be wrapped into a bme_free_radial function to be used by BME_KF as well...*/
+ i=0;
+ while(i<radlen){
+ bm->lpar[i] = killoop;
+ killoop = killoop->radial.next->data;
+ i++;
+ }
+ i=0;
+ while(i<radlen){
+ BME_free_loop(bm,bm->lpar[i]);
+ i++;
+ }
+ /*Validate radial cycle of oe*/
+ edok = BME_cycle_validate(radlen,&(oe->loop->radial));
+
+ }
+
+
+ /*Validate disk cycles*/
+ diskbase = BME_disk_getpointer(ov->edge,ov);
+ edok = BME_cycle_validate(valance1, diskbase);
+ if(!edok) BME_error();
+ diskbase = BME_disk_getpointer(tv->edge,tv);
+ edok = BME_cycle_validate(valance2, diskbase);
+ if(!edok) BME_error();
+
+ /*Validate loop cycle of all faces attached to oe*/
+ for(i=0,nextl = oe->loop; i<radlen; i++, nextl = BME_radial_nextloop(nextl)){
+ edok = BME_cycle_validate(nextl->f->len,nextl->f->loopbase);
+ if(!edok) BME_error();
+ }
+ /*deallocate edge*/
+ BLI_remlink(&(bm->edges), ke);
+ BME_free_edge(bm, ke);
+ /*deallocate vertex*/
+ BLI_remlink(&(bm->verts), kv);
+ BME_free_vert(bm, kv);
+ return 1;
+ }
+ }
+ return 0;
+}
+
+
+/**
+ * BME_loop_reverse
+ *
+ * FLIP FACE EULER
+ *
+ * Changes the winding order of a face from CW to CCW or vice versa.
+ * This euler is a bit peculiar in compairson to others as it is its
+ * own inverse.
+ *
+ * TODO: reinsert validation code.
+ *
+ * Returns -
+ * 1 for success, 0 for failure.
+ */
+
+int BME_loop_reverse(BME_Mesh *bm, BME_Poly *f){
+ BME_Loop *l = f->loopbase, *curloop, *oldprev, *oldnext;
+ int i, j, edok, len = 0;
+
+ len = BME_cycle_length(l);
+ if(bm->edarlen < len){
+ MEM_freeN(bm->edar);
+ bm->edar = MEM_callocN(sizeof(BME_Edge *)* len, "BMesh Edge pointer array");
+ bm->edarlen = len;
+ }
+
+ for(i=0, curloop = l; i< len; i++, curloop=curloop->next){
+ curloop->e->eflag1 = 0;
+ curloop->e->eflag2 = BME_cycle_length(&curloop->radial);
+ BME_radial_remove_loop(curloop, curloop->e);
+ /*in case of border edges we HAVE to zero out curloop->radial Next/Prev*/
+ curloop->radial.next = curloop->radial.prev = NULL;
+ bm->edar[i] = curloop->e;
+ }
+
+ /*actually reverse the loop. This belongs in BME_cycle_reverse!*/
+ for(i=0, curloop = l; i < len; i++){
+ oldnext = curloop->next;
+ oldprev = curloop->prev;
+ curloop->next = oldprev;
+ curloop->prev = oldnext;
+ curloop = oldnext;
+ }
+
+ if(len == 2){ //two edged face
+ //do some verification here!
+ l->e = bm->edar[1];
+ l->next->e = bm->edar[0];
+ }
+ else{
+ for(i=0, curloop = l; i < len; i++, curloop = curloop->next){
+ edok = 0;
+ for(j=0; j < len; j++){
+ edok = BME_verts_in_edge(curloop->v, curloop->next->v, bm->edar[j]);
+ if(edok){
+ curloop->e = bm->edar[j];
+ break;
+ }
+ }
+ }
+ }
+ /*rebuild radial*/
+ for(i=0, curloop = l; i < len; i++, curloop = curloop->next) BME_radial_append(curloop->e, curloop);
+
+ /*validate radial*/
+ for(i=0, curloop = l; i < len; i++, curloop = curloop->next){
+ edok = BME_cycle_validate(curloop->e->eflag2, &(curloop->radial));
+ if(!edok){
+ BME_error();
+ }
+ }
+ return 1;
+}
+
+/**
+ * BME_JFKE
+ *
+ * JOIN FACE KILL EDGE:
+ *
+ * Takes two faces joined by a single 2-manifold edge and fuses them togather.
+ * The edge shared by the faces must not be connected to any other edges which have
+ * Both faces in its radial cycle
+ *
+ * Examples:
+ *
+ * A B
+ * ---------- ----------
+ * | | | |
+ * | f1 | | f1 |
+ * v1========v2 = Ok! v1==V2==v3 == Wrong!
+ * | f2 | | f2 |
+ * | | | |
+ * ---------- ----------
+ *
+ * In the example A, faces f1 and f2 are joined by a single edge, and the euler can safely be used.
+ * In example B however, f1 and f2 are joined by multiple edges and will produce an error. The caller
+ * in this case should call BME_JEKV on the extra edges before attempting to fuse f1 and f2.
+ *
+ * Also note that the order of arguments decides whether or not certain per-face attributes are present
+ * in the resultant face. For instance vertex winding, material index, smooth flags, ect are inherited
+ * from f1, not f2.
+ *
+ * Returns -
+ * A BME_Poly pointer
+*/
+
+BME_Poly *BME_JFKE(BME_Mesh *bm, BME_Poly *f1, BME_Poly *f2, BME_Edge *e)
+{
+
+ BME_Loop *curloop, *f1loop=NULL, *f2loop=NULL;
+ int loopok = 0, newlen = 0,i, f1len=0, f2len=0, radlen=0, edok;
+
+ if(f1 == f2) return NULL; //can't join a face to itself
+ /*verify that e is in both f1 and f2*/
+ f1len = BME_cycle_length(f1->loopbase);
+ f2len = BME_cycle_length(f2->loopbase);
+ for(i=0, curloop = f1->loopbase; i < f1len; i++, curloop = curloop->next){
+ if(curloop->e == e){
+ f1loop = curloop;
+ break;
+ }
+ }
+ for(i=0, curloop = f2->loopbase; i < f2len; i++, curloop = curloop->next){
+ if(curloop->e==e){
+ f2loop = curloop;
+ break;
+ }
+ }
+ if(!(f1loop && f2loop)) return NULL;
+
+ /*validate that edge is 2-manifold edge*/
+ radlen = BME_cycle_length(&(f1loop->radial));
+ if(radlen != 2) return NULL;
+
+ /*validate direction of f2's loop cycle is compatible.*/
+ if(f1loop->v == f2loop->v) return NULL;
+
+ /*
+ Finally validate that for each face, each vertex has another edge in its disk cycle that is
+ not e, and not shared.
+ */
+ if(BME_radial_find_face(f1loop->next->e,f2)) return NULL;
+ if(BME_radial_find_face(f1loop->prev->e,f2)) return NULL;
+ if(BME_radial_find_face(f2loop->next->e,f1)) return NULL;
+ if(BME_radial_find_face(f2loop->prev->e,f1)) return NULL;
+
+ /*join the two loops*/
+ f1loop->prev->next = f2loop->next;
+ f2loop->next->prev = f1loop->prev;
+
+ f1loop->next->prev = f2loop->prev;
+ f2loop->prev->next = f1loop->next;
+
+ /*if f1loop was baseloop, give f1loop->next the base.*/
+ if(f1->loopbase == f1loop) f1->loopbase = f1loop->next;
+
+ /*validate the new loop*/
+ loopok = BME_cycle_validate((f1len+f2len)-2, f1->loopbase);
+ if(!loopok) BME_error();
+
+ /*make sure each loop points to the proper face*/
+ newlen = BME_cycle_length(f1->loopbase);
+ for(i = 0, curloop = f1->loopbase; i < newlen; i++, curloop = curloop->next) curloop->f = f1;
+
+ f1->len = newlen;
+
+ edok = BME_cycle_validate(f1->len, f1->loopbase);
+ if(!edok) BME_error();
+
+ /*remove edge from the disk cycle of its two vertices.*/
+ BME_disk_remove_edge(f1loop->e, f1loop->e->v1);
+ BME_disk_remove_edge(f1loop->e, f1loop->e->v2);
+
+ /*deallocate edge and its two loops as well as f2*/
+ BLI_remlink(&(bm->edges), f1loop->e);
+ BLI_remlink(&(bm->polys), f2);
+ BME_free_edge(bm, f1loop->e);
+ BME_free_loop(bm, f1loop);
+ BME_free_loop(bm, f2loop);
+ BME_free_poly(bm, f2);
+ return f1;
+}
diff --git a/source/blender/blenkernel/intern/BME_mesh.c b/source/blender/blenkernel/intern/BME_mesh.c
new file mode 100644
index 00000000000..ad46a7c1eb7
--- /dev/null
+++ b/source/blender/blenkernel/intern/BME_mesh.c
@@ -0,0 +1,285 @@
+/**
+ * BME_mesh.c jan 2007
+ *
+ * BMesh mesh level functions.
+ *
+ * $Id: BME_eulers.c,v 1.00 2007/01/17 17:42:01 Briggs Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2007 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Geoffrey Bantle.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+
+#include "MEM_guardedalloc.h"
+#include "DNA_listBase.h"
+#include "BLI_blenlib.h"
+#include "BKE_utildefines.h"
+#include "BKE_bmesh.h"
+#include "bmesh_private.h"
+
+
+/*
+ * BME MAKE MESH
+ *
+ * Allocates a new BME_Mesh structure.
+ * Returns -
+ * Pointer to a Bmesh
+ *
+*/
+
+BME_Mesh *BME_make_mesh(int allocsize[4])
+{
+ /*allocate the structure*/
+ BME_Mesh *bm = MEM_callocN(sizeof(BME_Mesh),"BMesh");
+ /*allocate the memory pools for the mesh elements*/
+ bm->vpool = BLI_mempool_create(sizeof(BME_Vert), allocsize[0], allocsize[0]);
+ bm->epool = BLI_mempool_create(sizeof(BME_Edge), allocsize[1], allocsize[1]);
+ bm->lpool = BLI_mempool_create(sizeof(BME_Loop), allocsize[2], allocsize[2]);
+ bm->ppool = BLI_mempool_create(sizeof(BME_Poly), allocsize[3], allocsize[3]);
+ return bm;
+}
+/*
+ * BME FREE MESH
+ *
+ * Frees a BME_Mesh structure.
+*/
+
+void BME_free_mesh(BME_Mesh *bm)
+{
+ BME_Vert *v;
+ BME_Edge *e;
+ BME_Loop *l;
+ BME_Poly *f;
+
+ for(v=bm->verts.first; v; v=v->next) CustomData_bmesh_free_block(&bm->vdata, &v->data);
+ for(e=bm->edges.first; e; e=e->next) CustomData_bmesh_free_block(&bm->edata, &e->data);
+ for(f=bm->polys.first; f; f=f->next){
+ CustomData_bmesh_free_block(&bm->pdata, &f->data);
+ l = f->loopbase;
+ do{
+ CustomData_bmesh_free_block(&bm->ldata, &l->data);
+ l = l->next;
+ }while(l!=f->loopbase);
+ }
+
+ /*Free custom data pools, This should probably go in CustomData_free?*/
+ if(bm->vdata.totlayer) BLI_mempool_destroy(bm->vdata.pool);
+ if(bm->edata.totlayer) BLI_mempool_destroy(bm->edata.pool);
+ if(bm->ldata.totlayer) BLI_mempool_destroy(bm->ldata.pool);
+ if(bm->pdata.totlayer) BLI_mempool_destroy(bm->pdata.pool);
+
+ /*free custom data*/
+ CustomData_free(&bm->vdata,0);
+ CustomData_free(&bm->edata,0);
+ CustomData_free(&bm->ldata,0);
+ CustomData_free(&bm->pdata,0);
+
+ /*destroy element pools*/
+ BLI_mempool_destroy(bm->vpool);
+ BLI_mempool_destroy(bm->epool);
+ BLI_mempool_destroy(bm->ppool);
+ BLI_mempool_destroy(bm->lpool);
+
+ MEM_freeN(bm);
+}
+
+/*
+ * BME MODEL BEGIN AND END
+ *
+ * These two functions represent the 'point of entry' for tools. Every BMesh tool
+ * must begin with a call to BME_model_end() and finish with a call to BME_model_end().
+ * No modification of mesh data is allowed except in between these two calls.
+ *
+ * The purpose of these calls is allow for housekeeping tasks to be performed,
+ * such as allocating/freeing scratch arrays or performing debug validation of
+ * the mesh structure.
+ *
+ * Returns -
+ * Nothing
+ *
+*/
+
+int BME_model_begin(BME_Mesh *bm){
+ /*Initialize some scratch pointer arrays used by eulers*/
+ bm->vtar = MEM_callocN(sizeof(BME_Vert *) * 1024, "BMesh scratch vert array");
+ bm->edar = MEM_callocN(sizeof(BME_Edge *) * 1024, "BMesh scratch edge array");
+ bm->lpar = MEM_callocN(sizeof(BME_Loop *) * 1024, "BMesh scratch loop array");
+ bm->plar = MEM_callocN(sizeof(BME_Poly *) * 1024, "BMesh scratch poly array");
+
+ bm->vtarlen = bm->edarlen = bm->lparlen = bm->plarlen = 1024;
+
+ return 1;
+}
+
+void BME_model_end(BME_Mesh *bm){
+ int meshok, totvert, totedge, totpoly;
+
+ totvert = BLI_countlist(&(bm->verts));
+ totedge = BLI_countlist(&(bm->edges));
+ totpoly = BLI_countlist(&(bm->polys));
+
+ if(bm->vtar) MEM_freeN(bm->vtar);
+ if(bm->edar) MEM_freeN(bm->edar);
+ if(bm->lpar) MEM_freeN(bm->lpar);
+ if(bm->plar) MEM_freeN(bm->plar);
+
+ bm->vtar = NULL;
+ bm->edar = NULL;
+ bm->lpar = NULL;
+ bm->plar = NULL;
+ bm->vtarlen = bm->edarlen = bm->lparlen = bm->plarlen = 0;
+
+
+ if(bm->totvert!=totvert || bm->totedge!=totedge || bm->totpoly!=totpoly)
+ BME_error();
+
+ meshok = BME_validate_mesh(bm, 1);
+ if(!meshok){
+ BME_error();
+ }
+}
+
+/*
+ * BME VALIDATE MESH
+ *
+ * There are several levels of validation for meshes. At the
+ * Euler level, some basic validation is done to local topology.
+ * To catch more subtle problems however, BME_validate_mesh() is
+ * called by BME_model_end() whenever a tool is done executing.
+ * The purpose of this function is to insure that during the course
+ * of tool execution that nothing has been done to invalidate the
+ * structure, and if it has, provide a way of reporting that so that
+ * we can restore the proper structure from a backup. Since a full mesh
+ * validation would be too expensive, this is presented as a compromise.
+ *
+ * TODO
+ *
+ * -Make this only part of debug builds
+ */
+
+#define VHALT(halt) {BME_error(); if(halt) return 0;}
+
+int BME_validate_mesh(struct BME_Mesh *bm, int halt)
+{
+ BME_Vert *v;
+ BME_Edge *e;
+ BME_Poly *f;
+ BME_Loop *l;
+ BME_CycleNode *diskbase;
+ int i, ok;
+
+ /*Simple edge verification*/
+ for(e=bm->edges.first; e; e=e->next){
+ if(e->v1 == e->v2) VHALT(halt);
+ /*validate e->d1.data and e->d2.data*/
+ if(e->d1.data != e || e->d2.data != e) VHALT(halt);
+ /*validate e->loop->e*/
+ if(e->loop){
+ if(e->loop->e != e) VHALT(halt);
+ }
+ }
+
+ /*calculate disk cycle lengths*/
+ for(v=bm->verts.first; v; v=v->next) v->tflag1 = v->tflag2 = 0;
+ for(e=bm->edges.first; e; e=e->next){
+ e->v1->tflag1++;
+ e->v2->tflag1++;
+ }
+ /*Validate vertices and disk cycle*/
+ for(v=bm->verts.first; v; v=v->next){
+ /*validate v->edge pointer*/
+ if(v->tflag1){
+ if(v->edge){
+ ok = BME_vert_in_edge(v->edge,v);
+ if(!ok) VHALT(halt);
+ /*validate length of disk cycle*/
+ diskbase = BME_disk_getpointer(v->edge, v);
+ ok = BME_cycle_validate(v->tflag1, diskbase);
+ if(!ok) VHALT(halt);
+ /*validate that each edge in disk cycle contains V*/
+ for(i=0, e=v->edge; i < v->tflag1; i++, e = BME_disk_nextedge(e,v)){
+ ok = BME_vert_in_edge(e, v);
+ if(!ok) VHALT(halt);
+ }
+ }
+ else VHALT(halt);
+ }
+ }
+ /*validate edges*/
+ for(e=bm->edges.first; e; e=e->next){
+ /*seperate these into BME_disk_hasedge (takes pointer to edge)*/
+ /*search v1 disk cycle for edge*/
+ ok = BME_disk_hasedge(e->v1,e);
+ if(!ok) VHALT(halt);
+ /*search v2 disk cycle for edge*/
+ ok = BME_disk_hasedge(e->v2,e);
+ if(!ok) VHALT(halt);
+ }
+
+ for(e=bm->edges.first; e; e=e->next) e->tflag2 = 0; //store incident faces
+ /*Validate the loop cycle integrity.*/
+ for(f=bm->polys.first; f; f=f->next){
+ ok = BME_cycle_length(f->loopbase);
+ if(ok > 1){
+ f->tflag1 = ok;
+ }
+ else VHALT(halt);
+ for(i=0, l=f->loopbase; i < f->tflag1; i++, l=l->next){
+ /*verify loop->v pointers*/
+ ok = BME_verts_in_edge(l->v, l->next->v, l->e);
+ if(!ok) VHALT(halt);
+ /*verify radial node data pointer*/
+ if(l->radial.data != l) VHALT(halt);
+ /*validate l->e->loop poitner*/
+ if(l->e->loop == NULL) VHALT(halt);
+ /*validate l->f pointer*/
+ if(l->f != f) VHALT(halt);
+ /*see if l->e->loop is actually in radial cycle*/
+
+ l->e->tflag2++;
+ }
+ }
+
+ /*validate length of radial cycle*/
+ for(e=bm->edges.first; e; e=e->next){
+ if(e->loop){
+ ok = BME_cycle_validate(e->tflag2,&(e->loop->radial));
+ if(!ok) VHALT(halt);
+ }
+ }
+
+ /*validate that EIDs are within range... if not indicates corrupted mem*/
+
+ /*if we get this far, pretty safe to return 1*/
+ return 1;
+}
+
+/* Currently just a convient place for a breakpoint.
+ Probably should take an error string
+*/
+void BME_error(void){
+ printf("BME modelling error!");
+}
diff --git a/source/blender/blenkernel/intern/BME_structure.c b/source/blender/blenkernel/intern/BME_structure.c
new file mode 100644
index 00000000000..ca27f5efd10
--- /dev/null
+++ b/source/blender/blenkernel/intern/BME_structure.c
@@ -0,0 +1,627 @@
+/**
+ * BME_structure.c jan 2007
+ *
+ * Low level routines for manipulating the BMesh structure.
+ *
+ * $Id: BME_structure.c,v 1.00 2007/01/17 17:42:01 Briggs Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2007 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Geoffrey Bantle.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include <limits.h>
+#include "MEM_guardedalloc.h"
+
+#include "DNA_listBase.h"
+#include "BKE_utildefines.h"
+#include "BKE_bmesh.h"
+#include "BLI_blenlib.h"
+#include "BLI_linklist.h"
+#include "BLI_ghash.h"
+/**
+ * MISC utility functions.
+ *
+ */
+
+int BME_vert_in_edge(BME_Edge *e, BME_Vert *v){
+ if(e->v1 == v || e->v2 == v) return 1;
+ return 0;
+}
+int BME_verts_in_edge(BME_Vert *v1, BME_Vert *v2, BME_Edge *e){
+ if(e->v1 == v1 && e->v2 == v2) return 1;
+ else if(e->v1 == v2 && e->v2 == v1) return 1;
+ return 0;
+}
+
+BME_Vert *BME_edge_getothervert(BME_Edge *e, BME_Vert *v){
+ if(e->v1 == v) return e->v2;
+ else if(e->v2 == v) return e->v1;
+ return NULL;
+}
+
+int BME_edge_swapverts(BME_Edge *e, BME_Vert *orig, BME_Vert *new){
+ if(e->v1 == orig){
+ e->v1 = new;
+ e->d1.next = NULL;
+ e->d1.prev = NULL;
+ return 1;
+ }
+ else if(e->v2 == orig){
+ e->v2 = new;
+ e->d2.next = NULL;
+ e->d2.prev = NULL;
+ return 1;
+ }
+ return 0;
+}
+
+/**
+ * ALLOCATION/DEALLOCATION FUNCTIONS
+ */
+
+BME_Vert *BME_addvertlist(BME_Mesh *bm, BME_Vert *example){
+ BME_Vert *v=NULL;
+ v = BLI_mempool_alloc(bm->vpool);
+ v->next = v->prev = NULL;
+ v->EID = bm->nextv;
+ v->co[0] = v->co[1] = v->co[2] = 0.0f;
+ v->no[0] = v->no[1] = v->no[2] = 0.0f;
+ v->edge = NULL;
+ v->data = NULL;
+ v->eflag1 = v->eflag2 = v->tflag1 = v->tflag2 = 0;
+ v->flag = v->h = 0;
+ v->bweight = 0.0f;
+ BLI_addtail(&(bm->verts), v);
+ bm->nextv++;
+ bm->totvert++;
+
+ if(example){
+ VECCOPY(v->co,example->co);
+ CustomData_bmesh_copy_data(&bm->vdata, &bm->vdata, example->data, &v->data);
+ }
+ else
+ CustomData_bmesh_set_default(&bm->vdata, &v->data);
+
+ return v;
+}
+BME_Edge *BME_addedgelist(BME_Mesh *bm, BME_Vert *v1, BME_Vert *v2, BME_Edge *example){
+ BME_Edge *e=NULL;
+ e = BLI_mempool_alloc(bm->epool);
+ e->next = e->prev = NULL;
+ e->EID = bm->nexte;
+ e->v1 = v1;
+ e->v2 = v2;
+ e->d1.next = e->d1.prev = e->d2.next = e->d2.prev = NULL;
+ e->d1.data = e;
+ e->d2.data = e;
+ e->loop = NULL;
+ e->data = NULL;
+ e->eflag1 = e->eflag2 = e->tflag1 = e->tflag2 = 0;
+ e->flag = e->h = 0;
+ e->crease = e->bweight = 0.0f;
+ bm->nexte++;
+ bm->totedge++;
+ BLI_addtail(&(bm->edges), e);
+
+ if(example)
+ CustomData_bmesh_copy_data(&bm->edata, &bm->edata, example->data, &e->data);
+ else
+ CustomData_bmesh_set_default(&bm->edata, &e->data);
+
+
+ return e;
+}
+BME_Loop *BME_create_loop(BME_Mesh *bm, BME_Vert *v, BME_Edge *e, BME_Poly *f, BME_Loop *example){
+ BME_Loop *l=NULL;
+ l = BLI_mempool_alloc(bm->lpool);
+ l->next = l->prev = NULL;
+ l->EID = bm->nextl;
+ l->radial.next = l->radial.prev = NULL;
+ l->radial.data = l;
+ l->v = v;
+ l->e = e;
+ l->f = f;
+ l->data = NULL;
+ l->eflag1 = l->eflag2 = l->tflag1 = l->tflag2 = 0;
+ l->flag = l->h = 0; //stupid waste!
+ bm->nextl++;
+ bm->totloop++;
+
+ if(example)
+ CustomData_bmesh_copy_data(&bm->ldata, &bm->ldata, example->data, &l->data);
+ else
+ CustomData_bmesh_set_default(&bm->ldata, &l->data);
+
+ return l;
+}
+
+BME_Poly *BME_addpolylist(BME_Mesh *bm, BME_Poly *example){
+ BME_Poly *f = NULL;
+ f = BLI_mempool_alloc(bm->ppool);
+ f->next = f->prev = NULL;
+ f->EID = bm->nextp;
+ f->loopbase = NULL;
+ f->len = 0;
+ f->data = NULL;
+ f->eflag1 = f->eflag2 = f->tflag1 = f->tflag2 = 0;
+ f->flag = f->h = f->mat_nr;
+ BLI_addtail(&(bm->polys),f);
+ bm->nextp++;
+ bm->totpoly++;
+
+ if(example)
+ CustomData_bmesh_copy_data(&bm->pdata, &bm->pdata, example->data, &f->data);
+ else
+ CustomData_bmesh_set_default(&bm->pdata, &f->data);
+
+
+ return f;
+}
+
+/* free functions dont do much *yet*. When per-vertex, per-edge and per-face/faceloop
+ data is added though these will be needed.
+*/
+void BME_free_vert(BME_Mesh *bm, BME_Vert *v){
+ bm->totvert--;
+ CustomData_bmesh_free_block(&bm->vdata, &v->data);
+ BLI_mempool_free(bm->vpool, v);
+}
+void BME_free_edge(BME_Mesh *bm, BME_Edge *e){
+ bm->totedge--;
+ CustomData_bmesh_free_block(&bm->edata, &e->data);
+ BLI_mempool_free(bm->epool, e);
+}
+void BME_free_poly(BME_Mesh *bm, BME_Poly *f){
+ bm->totpoly--;
+ CustomData_bmesh_free_block(&bm->pdata, &f->data);
+ BLI_mempool_free(bm->ppool, f);
+}
+void BME_free_loop(BME_Mesh *bm, BME_Loop *l){
+ bm->totloop--;
+ CustomData_bmesh_free_block(&bm->ldata, &l->data);
+ BLI_mempool_free(bm->lpool, l);
+}
+/**
+ * BMESH CYCLES
+ *
+ * Cycles are circular doubly linked lists that form the basis of adjacency
+ * information in the BME modeller. Full adjacency relations can be derived
+ * from examining these cycles very quickly. Although each cycle is a double
+ * circular linked list, each one is considered to have a 'base' or 'head',
+ * and care must be taken by Euler code when modifying the contents of a cycle.
+ *
+ * The contents of this file are split into two parts. First there are the
+ * BME_cycle family of functions which are generic circular double linked list
+ * procedures. The second part contains higher level procedures for supporting
+ * modification of specific cycle types.
+ *
+ * The three cycles explicitly stored in the BMesh data structure are as follows:
+ *
+ * 1: The Disk Cycle - A circle of edges around a vertex
+ * Base: vertex->edge pointer.
+ *
+ * This cycle is the most complicated in terms of its structure. Each BME_Edge contains
+ * two BME_CycleNode structures to keep track of that edge's membership in the disk cycle
+ * of each of its vertices. However for any given vertex it may be the first in some edges
+ * in its disk cycle and the second for others. The BME_disk_XXX family of functions contain
+ * some nice utilities for navigating disk cycles in a way that hides this detail from the
+ * tool writer.
+ *
+ * Note that the disk cycle is completley independant from face data. One advantage of this
+ * is that wire edges are fully integrated into the topology database. Another is that the
+ * the disk cycle has no problems dealing with non-manifold conditions involving faces.
+ *
+ * Functions relating to this cycle:
+ *
+ * BME_disk_append_edge
+ * BME_disk_remove_edge
+ * BME_disk_nextedge
+ * BME_disk_getpointer
+ *
+ * 2: The Radial Cycle - A circle of face edges (BME_Loop) around an edge
+ * Base: edge->loop->radial structure.
+ *
+ * The radial cycle is similar to the radial cycle in the radial edge data structure.*
+ * Unlike the radial edge however, the radial cycle does not require a large amount of memory
+ * to store non-manifold conditions since BMesh does not keep track of region/shell
+ * information.
+ *
+ * Functions relating to this cycle:
+ *
+ * BME_radial_append
+ * BME_radial_remove_loop
+ * BME_radial_nextloop
+ * BME_radial_find_face
+ *
+ *
+ * 3: The Loop Cycle - A circle of face edges around a polygon.
+ * Base: polygon->loopbase.
+ *
+ * The loop cycle keeps track of a faces vertices and edges. It should be noted that the
+ * direction of a loop cycle is either CW or CCW depending on the face normal, and is
+ * not oriented to the faces editedges.
+ *
+ * Functions relating to this cycle:
+ *
+ * BME_cycle_XXX family of functions.
+ *
+ *
+ * Note that the order of elements in all cycles except the loop cycle is undefined. This
+ * leads to slightly increased seek time for deriving some adjacency relations, however the
+ * advantage is that no intrinsic properties of the data structures are dependant upon the
+ * cycle order and all non-manifold conditions are represented trivially.
+ *
+*/
+
+
+void BME_cycle_append(void *h, void *nt)
+{
+ BME_CycleNode *oldtail, *head, *newtail;
+
+ head = (BME_CycleNode*)h;
+ newtail = (BME_CycleNode*)nt;
+
+ if(head->next == NULL){
+ head->next = newtail;
+ head->prev = newtail;
+ newtail->next = head;
+ newtail->prev = head;
+ }
+ else{
+ oldtail = head->prev;
+ oldtail->next = newtail;
+ newtail->next = head;
+ newtail->prev = oldtail;
+ head->prev = newtail;
+
+ }
+}
+
+/**
+ * BME_cycle_length
+ *
+ * Count the nodes in a cycle.
+ *
+ * Returns -
+ * Integer
+ */
+
+int BME_cycle_length(void *h){
+
+ int len = 0;
+ BME_CycleNode *head, *curnode;
+ head = (BME_CycleNode*)h;
+
+ if(head){
+ len = 1;
+ for(curnode = head->next; curnode != head; curnode=curnode->next){
+ if(len == INT_MAX){ //check for infinite loop/corrupted cycle
+ return -1;
+ }
+ len++;
+ }
+ }
+ return len;
+}
+
+
+/**
+ * BME_cycle_remove
+ *
+ * Removes a node from a cycle.
+ *
+ * Returns -
+ * 1 for success, 0 for failure.
+ */
+
+int BME_cycle_remove(void *h, void *remn)
+{
+ int i, len;
+ BME_CycleNode *head, *remnode, *curnode;
+
+ head = (BME_CycleNode*)h;
+ remnode = (BME_CycleNode*)remn;
+ len = BME_cycle_length(h);
+
+ if(len == 1 && head == remnode){
+ head->next = NULL;
+ head->prev = NULL;
+ return 1;
+ }
+ else{
+ for(i=0, curnode = head; i < len; curnode = curnode->next){
+ if(curnode == remnode){
+ remnode->prev->next = remnode->next;
+ remnode->next->prev = remnode->prev;
+ /*zero out remnode pointers, important!*/
+ //remnode->next = NULL;
+ //remnode->prev = NULL;
+ return 1;
+
+ }
+ }
+ }
+ return 0;
+}
+
+/**
+ * BME_cycle_validate
+ *
+ * Validates a cycle. Takes as an argument the expected length of the cycle and
+ * a pointer to the cycle head or base.
+ *
+ *
+ * Returns -
+ * 1 for success, 0 for failure.
+ */
+
+int BME_cycle_validate(int len, void *h){
+ int i;
+ BME_CycleNode *curnode, *head;
+ head = (BME_CycleNode*)h;
+
+ /*forward validation*/
+ for(i = 0, curnode = head; i < len; i++, curnode = curnode->next);
+ if(curnode != head) return 0;
+
+ /*reverse validation*/
+ for(i = 0, curnode = head; i < len; i++, curnode = curnode->prev);
+ if(curnode != head) return 0;
+
+ return 1;
+}
+
+/*Begin Disk Cycle routines*/
+
+/**
+ * BME_disk_nextedge
+ *
+ * Find the next edge in a disk cycle
+ *
+ * Returns -
+ * Pointer to the next edge in the disk cycle for the vertex v.
+ */
+
+BME_Edge *BME_disk_nextedge(BME_Edge *e, BME_Vert *v)
+{
+ if(BME_vert_in_edge(e, v)){
+ if(e->v1 == v) return e->d1.next->data;
+ else if(e->v2 == v) return e->d2.next->data;
+ }
+ return NULL;
+}
+
+/**
+ * BME_disk_getpointer
+ *
+ * Given an edge and one of its vertices, find the apporpriate CycleNode
+ *
+ * Returns -
+ * Pointer to BME_CycleNode.
+ */
+BME_CycleNode *BME_disk_getpointer(BME_Edge *e, BME_Vert *v){
+ /*returns pointer to the cycle node for the appropriate vertex in this disk*/
+ if(e->v1 == v) return &(e->d1);
+ else if (e->v2 == v) return &(e->d2);
+ return NULL;
+}
+
+/**
+ * BME_disk_append_edge
+ *
+ * Appends edge to the end of a vertex disk cycle.
+ *
+ * Returns -
+ * 1 for success, 0 for failure
+ */
+
+int BME_disk_append_edge(BME_Edge *e, BME_Vert *v)
+{
+
+ BME_CycleNode *base, *tail;
+
+ if(BME_vert_in_edge(e, v) == 0) return 0; /*check to make sure v is in e*/
+
+ /*check for loose vert first*/
+ if(v->edge == NULL){
+ v->edge = e;
+ base = tail = BME_disk_getpointer(e, v);
+ BME_cycle_append(base, tail); /*circular reference is ok!*/
+ return 1;
+ }
+
+ /*insert e at the end of disk cycle and make it the new v->edge*/
+ base = BME_disk_getpointer(v->edge, v);
+ tail = BME_disk_getpointer(e, v);
+ BME_cycle_append(base, tail);
+ return 1;
+}
+
+/**
+ * BME_disk_remove_edge
+ *
+ * Removes an edge from a disk cycle. If the edge to be removed is
+ * at the base of the cycle, the next edge becomes the new base.
+ *
+ *
+ * Returns -
+ * Nothing
+ */
+
+void BME_disk_remove_edge(BME_Edge *e, BME_Vert *v)
+{
+ BME_CycleNode *base, *remnode;
+ BME_Edge *newbase;
+ int len;
+
+ base = BME_disk_getpointer(v->edge, v);
+ remnode = BME_disk_getpointer(e, v);
+
+ /*first deal with v->edge pointer...*/
+ len = BME_cycle_length(base);
+ if(len == 1) newbase = NULL;
+ else if(v->edge == e) newbase = base->next-> data;
+ else newbase = v->edge;
+
+ /*remove and rebase*/
+ BME_cycle_remove(base, remnode);
+ v->edge = newbase;
+}
+
+/**
+ * BME_disk_next_edgeflag
+ *
+ * Searches the disk cycle of v, starting with e, for the
+ * next edge that has either eflag or tflag.
+ *
+ * BME_Edge pointer.
+ */
+
+BME_Edge *BME_disk_next_edgeflag(BME_Edge *e, BME_Vert *v, int eflag, int tflag){
+
+ BME_CycleNode *diskbase;
+ BME_Edge *curedge;
+ int len, ok;
+
+ if(eflag && tflag) return NULL;
+
+ ok = BME_vert_in_edge(e,v);
+ if(ok){
+ diskbase = BME_disk_getpointer(e, v);
+ len = BME_cycle_length(diskbase);
+ curedge = BME_disk_nextedge(e,v);
+ while(curedge != e){
+ if(tflag){
+ if(curedge->tflag1 == tflag) return curedge;
+ }
+ else if(eflag){
+ if(curedge->eflag1 == eflag) return curedge;
+ }
+ curedge = BME_disk_nextedge(curedge, v);
+ }
+ }
+ return NULL;
+}
+
+/**
+ * BME_disk_count_edgeflag
+ *
+ * Counts number of edges in this verts disk cycle which have
+ * either eflag or tflag (but not both!)
+ *
+ * Returns -
+ * Integer.
+ */
+
+int BME_disk_count_edgeflag(BME_Vert *v, int eflag, int tflag){
+ BME_CycleNode *diskbase;
+ BME_Edge *curedge;
+ int i, len=0, count=0;
+
+ if(v->edge){
+ if(eflag && tflag) return 0; /*tflag and eflag are reserved for different functions!*/
+ diskbase = BME_disk_getpointer(v->edge, v);
+ len = BME_cycle_length(diskbase);
+
+ for(i = 0, curedge=v->edge; i<len; i++){
+ if(tflag){
+ if(curedge->tflag1 == tflag) count++;
+ }
+ else if(eflag){
+ if(curedge->eflag1 == eflag) count++;
+ }
+ curedge = BME_disk_nextedge(curedge, v);
+ }
+ }
+ return count;
+}
+
+int BME_disk_hasedge(BME_Vert *v, BME_Edge *e){
+ BME_CycleNode *diskbase;
+ BME_Edge *curedge;
+ int i, len=0;
+
+ if(v->edge){
+ diskbase = BME_disk_getpointer(v->edge,v);
+ len = BME_cycle_length(diskbase);
+
+ for(i = 0, curedge=v->edge; i<len; i++){
+ if(curedge == e) return 1;
+ else curedge=BME_disk_nextedge(curedge, v);
+ }
+ }
+ return 0;
+}
+/*end disk cycle routines*/
+
+BME_Loop *BME_radial_nextloop(BME_Loop *l){
+ return (BME_Loop*)(l->radial.next->data);
+}
+
+void BME_radial_append(BME_Edge *e, BME_Loop *l){
+ if(e->loop == NULL) e->loop = l;
+ BME_cycle_append(&(e->loop->radial), &(l->radial));
+}
+
+void BME_radial_remove_loop(BME_Loop *l, BME_Edge *e)
+{
+ BME_Loop *newbase;
+ int len;
+
+ /*deal with edge->loop pointer*/
+ len = BME_cycle_length(&(e->loop->radial));
+ if(len == 1) newbase = NULL;
+ else if(e->loop == l) newbase = e->loop->radial.next->data;
+ else newbase = e->loop;
+
+ /*remove and rebase*/
+ BME_cycle_remove(&(e->loop->radial), &(l->radial));
+ e->loop = newbase;
+}
+
+int BME_radial_find_face(BME_Edge *e,BME_Poly *f)
+{
+
+ BME_Loop *curloop;
+ int i, len;
+
+ len = BME_cycle_length(&(e->loop->radial));
+ for(i = 0, curloop = e->loop; i < len; i++, curloop = curloop->radial.next->data){
+ if(curloop->f == f) return 1;
+ }
+ return 0;
+}
+
+struct BME_Loop *BME_loop_find_loop(struct BME_Poly *f, struct BME_Vert *v) {
+ BME_Loop *l;
+ int i, len;
+
+ len = BME_cycle_length(f->loopbase);
+ for (i = 0, l=f->loopbase; i < len; i++, l=l->next) {
+ if (l->v == v) return l;
+ }
+ return NULL;
+}
diff --git a/source/blender/blenkernel/intern/BME_tools.c b/source/blender/blenkernel/intern/BME_tools.c
new file mode 100644
index 00000000000..8aaa7aca023
--- /dev/null
+++ b/source/blender/blenkernel/intern/BME_tools.c
@@ -0,0 +1,1323 @@
+/**
+ * BME_tools.c jan 2007
+ *
+ * Functions for changing the topology of a mesh.
+ *
+ * $Id: BME_eulers.c,v 1.00 2007/01/17 17:42:01 Briggs Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2004 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Geoffrey Bantle and Levi Schooley.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include <math.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_listBase.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_mesh_types.h"
+#include "DNA_object_types.h"
+
+#include "BKE_utildefines.h"
+#include "BKE_bmesh.h"
+#include "BLI_arithb.h"
+#include "BLI_blenlib.h"
+
+/*split this all into a seperate bevel.c file in src*/
+
+/* ------- Bevel code starts here -------- */
+
+BME_TransData_Head *BME_init_transdata(int bufsize) {
+ BME_TransData_Head *td;
+
+ td = MEM_callocN(sizeof(BME_TransData_Head), "BMesh transdata header");
+ td->gh = BLI_ghash_new(BLI_ghashutil_ptrhash,BLI_ghashutil_ptrcmp);
+ td->ma = BLI_memarena_new(bufsize);
+ BLI_memarena_use_calloc(td->ma);
+
+ return td;
+}
+
+void BME_free_transdata(BME_TransData_Head *td) {
+ BLI_ghash_free(td->gh,NULL,NULL);
+ BLI_memarena_free(td->ma);
+ MEM_freeN(td);
+}
+
+BME_TransData *BME_assign_transdata(BME_TransData_Head *td, BME_Mesh *bm, BME_Vert *v,
+ float *co, float *org, float *vec, float *loc,
+ float factor, float weight, float maxfactor, float *max) {
+ BME_TransData *vtd;
+ int is_new = 0;
+
+ if (v == NULL) return NULL;
+
+ if ((vtd = BLI_ghash_lookup(td->gh, v)) == NULL && bm != NULL) {
+ vtd = BLI_memarena_alloc(td->ma, sizeof(*vtd));
+ BLI_ghash_insert(td->gh, v, vtd);
+ td->len++;
+ is_new = 1;
+ }
+
+ vtd->bm = bm;
+ vtd->v = v;
+ if (co != NULL) VECCOPY(vtd->co,co);
+ if (org == NULL && is_new) { VECCOPY(vtd->org,v->co); } /* default */
+ else if (org != NULL) VECCOPY(vtd->org,org);
+ if (vec != NULL) {
+ VECCOPY(vtd->vec,vec);
+ Normalize(vtd->vec);
+ }
+ vtd->loc = loc;
+
+ vtd->factor = factor;
+ vtd->weight = weight;
+ vtd->maxfactor = maxfactor;
+ vtd->max = max;
+
+ return vtd;
+}
+
+BME_TransData *BME_get_transdata(BME_TransData_Head *td, BME_Vert *v) {
+ BME_TransData *vtd;
+ vtd = BLI_ghash_lookup(td->gh, v);
+ return vtd;
+}
+
+/* a hack (?) to use the transdata memarena to allocate floats for use with the max limits */
+float *BME_new_transdata_float(BME_TransData_Head *td) {
+ return BLI_memarena_alloc(td->ma, sizeof(float));
+}
+
+static int BME_is_nonmanifold_vert(BME_Mesh *bm, BME_Vert *v) {
+ BME_Edge *e, *oe;
+ BME_Loop *l;
+ int len, count, flag;
+
+ if (v->edge == NULL) {
+ /* loose vert */
+ return 1;
+ }
+
+ /* count edges while looking for non-manifold edges */
+ oe = v->edge;
+ for (len=0,e=v->edge; e != oe || (e == oe && len == 0); len++,e=BME_disk_nextedge(e,v)) {
+ if (e->loop == NULL) {
+ /* loose edge */
+ return 1;
+ }
+
+ if (BME_cycle_length(&(e->loop->radial)) > 2) {
+ /* edge shared by more than two faces */
+ return 1;
+ }
+ }
+
+ count = 1;
+ flag = 1;
+ e = NULL;
+ oe = v->edge;
+ l = oe->loop;
+ while(e != oe) {
+ if (l->v == v) l = l->prev;
+ else l = l->next;
+ e = l->e;
+ count++; /* count the edges */
+
+ if (flag && l->radial.next->data == l) {
+ /* we've hit the edge of an open mesh, reset once */
+ flag = 0;
+ count = 1;
+ oe = e;
+ e = NULL;
+ l = oe->loop;
+ }
+ else if (l->radial.next->data == l) {
+ /* break the loop */
+ e = oe;
+ }
+ else {
+ l = l->radial.next->data;
+ }
+ }
+
+ if (count < len) {
+ /* vert shared by multiple regions */
+ return 1;
+ }
+
+ return 0;
+}
+
+/* a wrapper for BME_JFKE that [for now just] checks to
+ * make sure loop directions are compatible */
+static BME_Poly *BME_JFKE_safe(BME_Mesh *bm, BME_Poly *f1, BME_Poly *f2, BME_Edge *e) {
+ BME_Loop *l1, *l2;
+
+ l1 = e->loop;
+ l2 = l1->radial.next->data;
+ if (l1->v == l2->v) {
+ BME_loop_reverse(bm, f2);
+ }
+
+ return BME_JFKE(bm, f1, f2, e);
+}
+
+/* a wrapper for BME_SFME that transfers element flags */
+static BME_Poly *BME_split_face(BME_Mesh *bm, BME_Poly *f, BME_Vert *v1, BME_Vert *v2, BME_Loop **nl, BME_Edge *example) {
+ BME_Poly *nf;
+ nf = BME_SFME(bm,f,v1,v2,nl);
+ nf->flag = f->flag;
+ /* if the edge was selected, select this face, too */
+ if (example->flag & SELECT) f->flag |= ME_FACE_SEL;
+ nf->h = f->h;
+ nf->mat_nr = f->mat_nr;
+ if (nl && example) {
+ (*nl)->e->flag = example->flag;
+ (*nl)->e->h = example->h;
+ (*nl)->e->crease = example->crease;
+ (*nl)->e->bweight = example->bweight;
+ }
+
+ return nf;
+}
+
+
+static void BME_data_interp_from_verts(BME_Mesh *bm, BME_Vert *v1, BME_Vert *v2, BME_Vert *v, float fac)
+{
+ void *src[2];
+ float w[2];
+ if (v1->data && v2->data) {
+ src[0]= v1->data;
+ src[1]= v2->data;
+ w[0] = 1.0f-fac;
+ w[1] = fac;
+ CustomData_bmesh_interp(&bm->vdata, src, w, NULL, 2, v->data);
+ }
+}
+
+
+static void BME_data_facevert_edgesplit(BME_Mesh *bm, BME_Vert *v1, BME_Vert *v2, BME_Vert *v, BME_Edge *e1, float fac){
+ void *src[2];
+ float w[2];
+ BME_Loop *l=NULL, *v1loop = NULL, *vloop = NULL, *v2loop = NULL;
+
+ w[0] = 1.0f - fac;
+ w[1] = fac;
+
+ if(!e1->loop) return;
+ l = e1->loop;
+ do{
+ if(l->v == v1){
+ v1loop = l;
+ vloop = v1loop->next;
+ v2loop = vloop->next;
+ }else if(l->v == v){
+ v1loop = l->next;
+ vloop = l;
+ v2loop = l->prev;
+
+ }
+
+ src[0] = v1loop->data;
+ src[1] = v2loop->data;
+
+ CustomData_bmesh_interp(&bm->ldata, src,w, NULL, 2, vloop->data);
+ l = l->radial.next->data;
+ }while(l!=e1->loop);
+}
+
+
+/* a wrapper for BME_SEMV that transfers element flags */ /*add custom data interpolation in here!*/
+static BME_Vert *BME_split_edge(BME_Mesh *bm, BME_Vert *v, BME_Edge *e, BME_Edge **ne, float percent) {
+ BME_Vert *nv, *v2;
+ float len;
+
+ v2 = BME_edge_getothervert(e,v);
+ nv = BME_SEMV(bm,v,e,ne);
+ if (nv == NULL) return NULL;
+ VECSUB(nv->co,v2->co,v->co);
+ len = VecLength(nv->co);
+ VECADDFAC(nv->co,v->co,nv->co,len*percent);
+ nv->flag = v->flag;
+ nv->bweight = v->bweight;
+ if (ne) {
+ (*ne)->flag = e->flag;
+ (*ne)->h = e->h;
+ (*ne)->crease = e->crease;
+ (*ne)->bweight = e->bweight;
+ }
+ /*v->nv->v2*/
+ BME_data_facevert_edgesplit(bm,v2, v, nv, e, 0.75);
+ return nv;
+}
+
+static void BME_collapse_vert(BME_Mesh *bm, BME_Edge *ke, BME_Vert *kv, float fac){
+ void *src[2];
+ float w[2];
+ BME_Loop *l=NULL, *kvloop=NULL, *tvloop=NULL;
+ BME_Vert *tv = BME_edge_getothervert(ke,kv);
+
+ w[0] = 1.0f - fac;
+ w[1] = fac;
+
+ if(ke->loop){
+ l = ke->loop;
+ do{
+ if(l->v == tv && l->next->v == kv){
+ tvloop = l;
+ kvloop = l->next;
+
+ src[0] = kvloop->data;
+ src[1] = tvloop->data;
+ CustomData_bmesh_interp(&bm->ldata, src,w, NULL, 2, kvloop->data);
+ }
+ l=l->radial.next->data;
+ }while(l!=ke->loop);
+ }
+ BME_JEKV(bm,ke,kv);
+}
+
+
+
+static int BME_bevel_is_split_vert(BME_Loop *l) {
+ /* look for verts that have already been added to the edge when
+ * beveling other polys; this can be determined by testing the
+ * vert and the edges around it for originality
+ */
+ if ((l->v->tflag1 & BME_BEVEL_ORIG)==0
+ && (l->e->tflag1 & BME_BEVEL_ORIG)
+ && (l->prev->e->tflag1 & BME_BEVEL_ORIG))
+ {
+ return 1;
+ }
+ return 0;
+}
+
+/* get a vector, vec, that points from v1->co to wherever makes sense to
+ * the bevel operation as a whole based on the relationship between v1 and v2
+ * (won't necessarily be a vec from v1->co to v2->co, though it probably will be);
+ * the return value is -1 for failure, 0 if we used vert co's, and 1 if we used transform origins */
+static int BME_bevel_get_vec(float *vec, BME_Vert *v1, BME_Vert *v2, BME_TransData_Head *td) {
+ BME_TransData *vtd1, *vtd2;
+
+ vtd1 = BME_get_transdata(td,v1);
+ vtd2 = BME_get_transdata(td,v2);
+ if (!vtd1 || !vtd2) {
+ //printf("BME_bevel_get_vec() got called without proper BME_TransData\n");
+ return -1;
+ }
+
+ /* compare the transform origins to see if we can use the vert co's;
+ * if they belong to different origins, then we will use the origins to determine
+ * the vector */
+ if (VecCompare(vtd1->org,vtd2->org,0.000001f)) {
+ VECSUB(vec,v2->co,v1->co);
+ if (VecLength(vec) < 0.000001f) {
+ VecMulf(vec,0);
+ }
+ return 0;
+ }
+ else {
+ VECSUB(vec,vtd2->org,vtd1->org);
+ if (VecLength(vec) < 0.000001f) {
+ VecMulf(vec,0);
+ }
+ return 1;
+ }
+}
+
+/* "Projects" a vector perpendicular to vec2 against vec1, such that
+ * the projected vec1 + vec2 has a min distance of 1 from the "edge" defined by vec2.
+ * note: the direction, is_forward, is used in conjunction with up_vec to determine
+ * whether this is a convex or concave corner. If it is a concave corner, it will
+ * be projected "backwards." If vec1 is before vec2, is_forward should be 0 (we are projecting backwards).
+ * vec1 is the vector to project onto (expected to be normalized)
+ * vec2 is the direction of projection (pointing away from vec1)
+ * up_vec is used for orientation (expected to be normalized)
+ * returns the length of the projected vector that lies along vec1 */
+static float BME_bevel_project_vec(float *vec1, float *vec2, float *up_vec, int is_forward, BME_TransData_Head *td) {
+ float factor, vec3[3], tmp[3],c1,c2;
+
+ Crossf(tmp,vec1,vec2);
+ Normalize(tmp);
+ factor = Inpf(up_vec,tmp);
+ if ((factor > 0 && is_forward) || (factor < 0 && !is_forward)) {
+ Crossf(vec3,vec2,tmp); /* hmm, maybe up_vec should be used instead of tmp */
+ }
+ else {
+ Crossf(vec3,tmp,vec2); /* hmm, maybe up_vec should be used instead of tmp */
+ }
+ Normalize(vec3);
+ c1 = Inpf(vec3,vec1);
+ c2 = Inpf(vec1,vec1);
+ if (fabs(c1) < 0.000001f || fabs(c2) < 0.000001f) {
+ factor = 0.0f;
+ }
+ else {
+ factor = c2/c1;
+ }
+
+ return factor;
+}
+
+/* BME_bevel_split_edge() is the main math work-house; its responsibilities are:
+ * using the vert and the loop passed, get or make the split vert, set its coordinates
+ * and transform properties, and set the max limits.
+ * Finally, return the split vert. */
+static BME_Vert *BME_bevel_split_edge(BME_Mesh *bm, BME_Vert *v, BME_Vert *v1, BME_Loop *l, float *up_vec, float value, BME_TransData_Head *td) {
+ BME_TransData *vtd, *vtd1, *vtd2;
+ BME_Vert *sv, *v2, *v3, *ov;
+ BME_Loop *lv1, *lv2;
+ BME_Edge *ne, *e1, *e2;
+ float maxfactor, scale, len, dis, vec1[3], vec2[3], t_up_vec[3];
+ int is_edge, forward, is_split_vert;
+
+ if (l == NULL) {
+ /* what you call operator overloading in C :)
+ * I wanted to use the same function for both wire edges and poly loops
+ * so... here we walk around edges to find the needed verts */
+ forward = 1;
+ is_split_vert = 0;
+ if (v->edge == NULL) {
+ //printf("We can't split a loose vert's edge!\n");
+ return NULL;
+ }
+ e1 = v->edge; /* we just use the first two edges */
+ e2 = BME_disk_nextedge(v->edge, v);
+ if (e1 == e2) {
+ //printf("You need at least two edges to use BME_bevel_split_edge()\n");
+ return NULL;
+ }
+ v2 = BME_edge_getothervert(e1, v);
+ v3 = BME_edge_getothervert(e2, v);
+ if (v1 != v2 && v1 != v3) {
+ //printf("Error: more than 2 edges in v's disk cycle, or v1 does not share an edge with v\n");
+ return NULL;
+ }
+ if (v1 == v2) {
+ v2 = v3;
+ }
+ else {
+ e1 = e2;
+ }
+ ov = BME_edge_getothervert(e1,v);
+ sv = BME_split_edge(bm,v,e1,&ne,0);
+ //BME_data_interp_from_verts(bm, v, ov, sv, 0.25); /*this is technically wrong...*/
+ //BME_data_interp_from_faceverts(bm, v, ov, sv, 0.25);
+ //BME_data_interp_from_faceverts(bm, ov, v, sv, 0.25);
+ BME_assign_transdata(td, bm, sv, sv->co, sv->co, NULL, sv->co, 0, -1, -1, NULL); /* quick default */
+ sv->tflag1 |= BME_BEVEL_BEVEL;
+ ne->tflag1 = BME_BEVEL_ORIG; /* mark edge as original, even though it isn't */
+ BME_bevel_get_vec(vec1,v1,v,td);
+ BME_bevel_get_vec(vec2,v2,v,td);
+ Crossf(t_up_vec,vec1,vec2);
+ Normalize(t_up_vec);
+ up_vec = t_up_vec;
+ }
+ else {
+ /* establish loop direction */
+ if (l->v == v) {
+ forward = 1;
+ lv1 = l->next;
+ lv2 = l->prev;
+ v1 = l->next->v;
+ v2 = l->prev->v;
+ }
+ else if (l->next->v == v) {
+ forward = 0;
+ lv1 = l;
+ lv2 = l->next->next;
+ v1 = l->v;
+ v2 = l->next->next->v;
+ }
+ else {
+ //printf("ERROR: BME_bevel_split_edge() - v must be adjacent to l\n");
+ return NULL;
+ }
+
+ if (BME_bevel_is_split_vert(lv1)) {
+ is_split_vert = 1;
+ sv = v1;
+ if (forward) v1 = l->next->next->v;
+ else v1 = l->prev->v;
+ }
+ else {
+ is_split_vert = 0;
+ ov = BME_edge_getothervert(l->e,v);
+ sv = BME_split_edge(bm,v,l->e,&ne,0);
+ //BME_data_interp_from_verts(bm, v, ov, sv, 0.25); /*this is technically wrong...*/
+ //BME_data_interp_from_faceverts(bm, v, ov, sv, 0.25);
+ //BME_data_interp_from_faceverts(bm, ov, v, sv, 0.25);
+ BME_assign_transdata(td, bm, sv, sv->co, sv->co, NULL, sv->co, 0, -1, -1, NULL); /* quick default */
+ sv->tflag1 |= BME_BEVEL_BEVEL;
+ ne->tflag1 = BME_BEVEL_ORIG; /* mark edge as original, even though it isn't */
+ }
+
+ if (BME_bevel_is_split_vert(lv2)) {
+ if (forward) v2 = lv2->prev->v;
+ else v2 = lv2->next->v;
+ }
+ }
+
+ is_edge = BME_bevel_get_vec(vec1,v,v1,td); /* get the vector we will be projecting onto */
+ BME_bevel_get_vec(vec2,v,v2,td); /* get the vector we will be projecting parallel to */
+ len = VecLength(vec1);
+ Normalize(vec1);
+
+ vtd = BME_get_transdata(td, sv);
+ vtd1 = BME_get_transdata(td, v);
+ vtd2 = BME_get_transdata(td,v1);
+
+ if (vtd1->loc == NULL) {
+ /* this is a vert with data only for calculating initial weights */
+ if (vtd1->weight < 0) {
+ vtd1->weight = 0;
+ }
+ scale = vtd1->weight/vtd1->factor;
+ if (!vtd1->max) {
+ vtd1->max = BME_new_transdata_float(td);
+ *vtd1->max = -1;
+ }
+ }
+ else {
+ scale = vtd1->weight;
+ }
+ vtd->max = vtd1->max;
+
+ if (is_edge && vtd1->loc != NULL) {
+ maxfactor = vtd1->maxfactor;
+ }
+ else {
+ maxfactor = scale*BME_bevel_project_vec(vec1,vec2,up_vec,forward,td);
+ if (vtd->maxfactor > 0 && vtd->maxfactor < maxfactor) {
+ maxfactor = vtd->maxfactor;
+ }
+ }
+
+ dis = (v1->tflag1 & BME_BEVEL_ORIG)? len/3 : len/2;
+ if (is_edge || dis > maxfactor*value) {
+ dis = maxfactor*value;
+ }
+ VECADDFAC(sv->co,v->co,vec1,dis);
+ VECSUB(vec1,sv->co,vtd1->org);
+ dis = VecLength(vec1);
+ Normalize(vec1);
+ BME_assign_transdata(td, bm, sv, vtd1->org, vtd1->org, vec1, sv->co, dis, scale, maxfactor, vtd->max);
+
+ return sv;
+}
+
+static float BME_bevel_set_max(BME_Vert *v1, BME_Vert *v2, float value, BME_TransData_Head *td) {
+ BME_TransData *vtd1, *vtd2;
+ float max, fac1, fac2, vec1[3], vec2[3], vec3[3];
+
+ BME_bevel_get_vec(vec1,v1,v2,td);
+ vtd1 = BME_get_transdata(td,v1);
+ vtd2 = BME_get_transdata(td,v2);
+
+ if (vtd1->loc == NULL) {
+ fac1 = 0;
+ }
+ else {
+ VECCOPY(vec2,vtd1->vec);
+ VecMulf(vec2,vtd1->factor);
+ if (Inpf(vec1, vec1)) {
+ Projf(vec2,vec2,vec1);
+ fac1 = VecLength(vec2)/value;
+ }
+ else {
+ fac1 = 0;
+ }
+ }
+
+ if (vtd2->loc == NULL) {
+ fac2 = 0;
+ }
+ else {
+ VECCOPY(vec3,vtd2->vec);
+ VecMulf(vec3,vtd2->factor);
+ if (Inpf(vec1, vec1)) {
+ Projf(vec2,vec3,vec1);
+ fac2 = VecLength(vec2)/value;
+ }
+ else {
+ fac2 = 0;
+ }
+ }
+
+ if (fac1 || fac2) {
+ max = VecLength(vec1)/(fac1 + fac2);
+ if (vtd1->max && (*vtd1->max < 0 || max < *vtd1->max)) {
+ *vtd1->max = max;
+ }
+ if (vtd2->max && (*vtd2->max < 0 || max < *vtd2->max)) {
+ *vtd2->max = max;
+ }
+ }
+ else {
+ max = -1;
+ }
+
+ return max;
+}
+
+static BME_Vert *BME_bevel_wire(BME_Mesh *bm, BME_Vert *v, float value, int res, int options, BME_TransData_Head *td) {
+ BME_Vert *ov1, *ov2, *v1, *v2;
+
+ ov1 = BME_edge_getothervert(v->edge, v);
+ ov2 = BME_edge_getothervert(BME_disk_nextedge(v->edge, v), v);
+
+ /* split the edges */
+ v1 = BME_bevel_split_edge(bm,v,ov1,NULL,NULL,value,td);
+ v1->tflag1 |= BME_BEVEL_NONMAN;
+ v2 = BME_bevel_split_edge(bm,v,ov2,NULL,NULL,value,td);
+ v2->tflag1 |= BME_BEVEL_NONMAN;
+
+ if (value > 0.5) {
+ BME_bevel_set_max(v1,ov1,value,td);
+ BME_bevel_set_max(v2,ov2,value,td);
+ }
+
+ /* remove the original vert */
+ if (res) {
+ BME_JEKV(bm,v->edge,v);
+ }
+
+ return v1;
+}
+
+static BME_Loop *BME_bevel_edge(BME_Mesh *bm, BME_Loop *l, float value, int options, float *up_vec, BME_TransData_Head *td) {
+ BME_Vert *v1, *v2, *kv;
+ BME_Loop *kl=NULL, *nl;
+ BME_Edge *e;
+ BME_Poly *f;
+
+ f = l->f;
+ e = l->e;
+
+ if ((l->e->tflag1 & BME_BEVEL_BEVEL) == 0
+ && ((l->v->tflag1 & BME_BEVEL_BEVEL) || (l->next->v->tflag1 & BME_BEVEL_BEVEL)))
+ { /* sanity check */
+ return l;
+ }
+
+ /* checks and operations for prev edge */
+ /* first, check to see if this edge was inset previously */
+ if ((l->prev->e->tflag1 & BME_BEVEL_ORIG) == 0
+ && (l->v->tflag1 & BME_BEVEL_NONMAN) == 0) {
+ kl = l->prev->radial.next->data;
+ if (kl->v == l->v) kl = kl->prev;
+ else kl = kl->next;
+ kv = l->v;
+ }
+ else {
+ kv = NULL;
+ }
+ /* get/make the first vert to be used in SFME */
+ if (l->v->tflag1 & BME_BEVEL_NONMAN){
+ v1 = l->v;
+ }
+ else { /* we'll need to split the previous edge */
+ v1 = BME_bevel_split_edge(bm,l->v,NULL,l->prev,up_vec,value,td);
+ }
+ /* if we need to clean up geometry... */
+ if (kv) {
+ l = l->next;
+ if (kl->v == kv) {
+ BME_split_face(bm,kl->f,kl->prev->v,kl->next->v,&nl,kl->prev->e);
+ BME_JFKE(bm,((BME_Loop*)kl->prev->radial.next->data)->f,kl->f,kl->prev->e);
+ BME_collapse_vert(bm, kl->e, kv, 1.0);
+ //BME_JEKV(bm,kl->e,kv);
+
+ }
+ else {
+ BME_split_face(bm,kl->f,kl->next->next->v,kl->v,&nl,kl->next->e);
+ BME_JFKE(bm,((BME_Loop*)kl->next->radial.next->data)->f,kl->f,kl->next->e);
+ BME_collapse_vert(bm, kl->e, kv, 1.0);
+ //BME_JEKV(bm,kl->e,kv);
+ }
+ l = l->prev;
+ }
+
+ /* checks and operations for the next edge */
+ /* first, check to see if this edge was inset previously */
+ if ((l->next->e->tflag1 & BME_BEVEL_ORIG) == 0
+ && (l->next->v->tflag1 & BME_BEVEL_NONMAN) == 0) {
+ kl = l->next->radial.next->data;
+ if (kl->v == l->next->v) kl = kl->prev;
+ else kl = kl->next;
+ kv = l->next->v;
+ }
+ else {
+ kv = NULL;
+ }
+ /* get/make the second vert to be used in SFME */
+ if (l->next->v->tflag1 & BME_BEVEL_NONMAN) {
+ v2 = l->next->v;
+ }
+ else { /* we'll need to split the next edge */
+ v2 = BME_bevel_split_edge(bm,l->next->v,NULL,l->next,up_vec,value,td);
+ }
+ /* if we need to clean up geometry... */
+ if (kv) {
+ if (kl->v == kv) {
+ BME_split_face(bm,kl->f,kl->prev->v,kl->next->v,&nl,kl->prev->e);
+ BME_JFKE(bm,((BME_Loop*)kl->prev->radial.next->data)->f,kl->f,kl->prev->e);
+ BME_collapse_vert(bm, kl->e, kv, 1.0);
+ //BME_JEKV(bm,kl->e,kv);
+ }
+ else {
+ BME_split_face(bm,kl->f,kl->next->next->v,kl->v,&nl,kl->next->e);
+ BME_JFKE(bm,((BME_Loop*)kl->next->radial.next->data)->f,kl->f,kl->next->e);
+ BME_collapse_vert(bm, kl->e, kv, 1.0);
+ //BME_JEKV(bm,kl->e,kv);
+ }
+ }
+
+ if ((v1->tflag1 & BME_BEVEL_NONMAN)==0 || (v2->tflag1 & BME_BEVEL_NONMAN)==0) {
+ BME_split_face(bm,f,v2,v1,&l,e);
+ l->e->tflag1 = BME_BEVEL_BEVEL;
+ l = l->radial.next->data;
+ }
+
+ if (l->f != f){
+ //printf("Whoops! You got something out of order in BME_bevel_edge()!\n");
+ }
+
+ return l;
+}
+
+static BME_Loop *BME_bevel_vert(BME_Mesh *bm, BME_Loop *l, float value, int options, float *up_vec, BME_TransData_Head *td) {
+ BME_Vert *v1, *v2;
+ BME_Poly *f;
+
+ /* get/make the first vert to be used in SFME */
+ /* may need to split the previous edge */
+ v1 = BME_bevel_split_edge(bm,l->v,NULL,l->prev,up_vec,value,td);
+
+ /* get/make the second vert to be used in SFME */
+ /* may need to split this edge (so move l) */
+ l = l->prev;
+ v2 = BME_bevel_split_edge(bm,l->next->v,NULL,l->next,up_vec,value,td);
+ l = l->next->next;
+
+ /* "cut off" this corner */
+ f = BME_split_face(bm,l->f,v2,v1,NULL,l->e);
+
+ return l;
+}
+
+/**
+ * BME_bevel_poly
+ *
+ * Polygon inset tool:
+ *
+ * Insets a polygon/face based on the tflag1's of its vertices
+ * and edges. Used by the bevel tool only, for now.
+ * The parameter "value" is the distance to inset (should be negative).
+ * The parameter "options" is not currently used.
+ *
+ * Returns -
+ * A BME_Poly pointer to the resulting inner face.
+*/
+static BME_Poly *BME_bevel_poly(BME_Mesh *bm, BME_Poly *f, float value, int options, BME_TransData_Head *td) {
+ BME_Loop *l, *ol;
+ BME_TransData *vtd1, *vtd2;
+ float up_vec[3], vec1[3], vec2[3], vec3[3], fac1, fac2, max = -1;
+ int len, i;
+
+ up_vec[0] = 0.0f;
+ up_vec[1] = 0.0f;
+ up_vec[2] = 0.0f;
+ /* find a good normal for this face (there's better ways, I'm sure) */
+ ol = f->loopbase;
+ l = ol->next;
+ for (i=0,ol=f->loopbase,l=ol->next; l->next!=ol; l=l->next) {
+ BME_bevel_get_vec(vec1,l->next->v,ol->v,td);
+ BME_bevel_get_vec(vec2,l->v,ol->v,td);
+ Crossf(vec3,vec2,vec1);
+ VECADD(up_vec,up_vec,vec3);
+ i++;
+ }
+ VecMulf(up_vec,1.0f/i);
+ Normalize(up_vec);
+
+ for (i=0,len=f->len; i<len; i++,l=l->next) {
+ if ((l->e->tflag1 & BME_BEVEL_BEVEL) && (l->e->tflag1 & BME_BEVEL_ORIG)) {
+ max = 1.0f;
+ l = BME_bevel_edge(bm, l, value, options, up_vec, td);
+ }
+ else if ((l->v->tflag1 & BME_BEVEL_BEVEL) && (l->v->tflag1 & BME_BEVEL_ORIG) && (l->prev->e->tflag1 & BME_BEVEL_BEVEL) == 0) {
+ max = 1.0f;
+ l = BME_bevel_vert(bm, l, value, options, up_vec, td);
+ }
+ }
+
+ /* max pass */
+ if (value > 0.5 && max > 0) {
+ max = -1;
+ for (i=0,len=f->len; i<len; i++,l=l->next) {
+ if ((l->e->tflag1 & BME_BEVEL_BEVEL) || (l->e->tflag1 & BME_BEVEL_ORIG)) {
+ BME_bevel_get_vec(vec1,l->v,l->next->v,td);
+ vtd1 = BME_get_transdata(td,l->v);
+ vtd2 = BME_get_transdata(td,l->next->v);
+ if (vtd1->loc == NULL) {
+ fac1 = 0;
+ }
+ else {
+ VECCOPY(vec2,vtd1->vec);
+ VecMulf(vec2,vtd1->factor);
+ if (Inpf(vec1, vec1)) {
+ Projf(vec2,vec2,vec1);
+ fac1 = VecLength(vec2)/value;
+ }
+ else {
+ fac1 = 0;
+ }
+ }
+ if (vtd2->loc == NULL) {
+ fac2 = 0;
+ }
+ else {
+ VECCOPY(vec3,vtd2->vec);
+ VecMulf(vec3,vtd2->factor);
+ if (Inpf(vec1, vec1)) {
+ Projf(vec2,vec3,vec1);
+ fac2 = VecLength(vec2)/value;
+ }
+ else {
+ fac2 = 0;
+ }
+ }
+ if (fac1 || fac2) {
+ max = VecLength(vec1)/(fac1 + fac2);
+ if (vtd1->max && (*vtd1->max < 0 || max < *vtd1->max)) {
+ *vtd1->max = max;
+ }
+ if (vtd2->max && (*vtd2->max < 0 || max < *vtd2->max)) {
+ *vtd2->max = max;
+ }
+ }
+ }
+ }
+ }
+
+ return l->f;
+}
+
+static void BME_bevel_add_vweight(BME_TransData_Head *td, BME_Mesh *bm, BME_Vert *v, float weight, float factor, int options) {
+ BME_TransData *vtd;
+
+ if (v->tflag1 & BME_BEVEL_NONMAN) return;
+ v->tflag1 |= BME_BEVEL_BEVEL;
+ if ( (vtd = BME_get_transdata(td, v)) ) {
+ if (options & BME_BEVEL_EMIN) {
+ vtd->factor = 1.0;
+ if (vtd->weight < 0 || weight < vtd->weight) {
+ vtd->weight = weight;
+ }
+ }
+ else if (options & BME_BEVEL_EMAX) {
+ vtd->factor = 1.0;
+ if (weight > vtd->weight) {
+ vtd->weight = weight;
+ }
+ }
+ else if (vtd->weight < 0) {
+ vtd->factor = factor;
+ vtd->weight = weight;
+ }
+ else {
+ vtd->factor += factor; /* increment number of edges with weights (will be averaged) */
+ vtd->weight += weight; /* accumulate all the weights */
+ }
+ }
+ else {
+ /* we'll use vtd->loc == NULL to mark that this vert is not moving */
+ vtd = BME_assign_transdata(td, bm, v, v->co, NULL, NULL, NULL, factor, weight, -1, NULL);
+ }
+}
+
+static float BME_bevel_get_angle(BME_Mesh *bm, BME_Edge *e, BME_Vert *v) {
+ BME_Vert *v1, *v2;
+ BME_Loop *l1, *l2;
+ float vec1[3], vec2[3], vec3[3], vec4[3];
+
+ l1 = e->loop;
+ l2 = e->loop->radial.next->data;
+ if (l1->v == v) {
+ v1 = l1->prev->v;
+ v2 = l1->next->v;
+ }
+ else {
+ v1 = l1->next->next->v;
+ v2 = l1->v;
+ }
+ VECSUB(vec1,v1->co,v->co);
+ VECSUB(vec2,v2->co,v->co);
+ Crossf(vec3,vec1,vec2);
+
+ l1 = l2;
+ if (l1->v == v) {
+ v1 = l1->prev->v;
+ v2 = l1->next->v;
+ }
+ else {
+ v1 = l1->next->next->v;
+ v2 = l1->v;
+ }
+ VECSUB(vec1,v1->co,v->co);
+ VECSUB(vec2,v2->co,v->co);
+ Crossf(vec4,vec2,vec1);
+
+ Normalize(vec3);
+ Normalize(vec4);
+
+ return Inpf(vec3,vec4);
+}
+static int BME_face_sharededges(BME_Poly *f1, BME_Poly *f2){
+ BME_Loop *l;
+ int count = 0;
+
+ l = f1->loopbase;
+ do{
+ if(BME_radial_find_face(l->e,f2)) count++;
+ l = l->next;
+ }while(l != f1->loopbase);
+
+ return count;
+}
+/**
+ * BME_bevel_initialize
+ *
+ * Prepare the mesh for beveling:
+ *
+ * Sets the tflag1's of the mesh elements based on the options passed.
+ *
+ * Returns -
+ * A BME_Mesh pointer to the BMesh passed as a parameter.
+*/
+static BME_Mesh *BME_bevel_initialize(BME_Mesh *bm, int options, int defgrp_index, float angle, BME_TransData_Head *td) {
+ BME_Vert *v;
+ BME_Edge *e;
+ BME_Poly *f;
+ BME_TransData *vtd;
+ MDeformVert *dvert;
+ MDeformWeight *dw;
+ int len;
+ float weight, threshold;
+
+ /* vert pass */
+ for (v=bm->verts.first; v; v=v->next) {
+ dvert = NULL;
+ dw = NULL;
+ v->tflag1 = BME_BEVEL_ORIG;
+ /* originally coded, a vertex gets tagged with BME_BEVEL_BEVEL in this pass if
+ * the vert is manifold (or is shared by only two edges - wire bevel)
+ * BME_BEVEL_SELECT is passed and the vert has v->flag&SELECT or
+ * BME_BEVEL_VWEIGHT is passed, and the vert has a defgrp and weight
+ * BME_BEVEL_ANGLE is not passed
+ * BME_BEVEL_EWEIGHT is not passed
+ */
+ /* originally coded, a vertex gets tagged with BME_BEVEL_NONMAN in this pass if
+ * the vert is loose, shared by multiple regions, or is shared by wire edges
+ * note: verts belonging to edges of open meshes are not tagged with BME_BEVEL_NONMAN
+ */
+ /* originally coded, a vertex gets a transform weight set in this pass if
+ * BME_BEVEL_VWEIGHT is passed, and the vert has a defgrp and weight
+ */
+
+ /* get disk cycle length */
+ if (v->edge == NULL) {
+ len = 0;
+ }
+ else {
+ len = BME_cycle_length(BME_disk_getpointer(v->edge,v));
+ /* we'll assign a default transform data to every vert (except the loose ones) */
+ vtd = BME_assign_transdata(td, bm, v, v->co, v->co, NULL, NULL, 0, -1, -1, NULL);
+ }
+
+ /* check for non-manifold vert */
+ if (BME_is_nonmanifold_vert(bm,v)) {
+ v->tflag1 |= BME_BEVEL_NONMAN;
+ }
+
+ /* BME_BEVEL_BEVEL tests */
+ if ((v->tflag1 & BME_BEVEL_NONMAN) == 0 || len == 2) { /* either manifold vert, or wire vert */
+ if (((options & BME_BEVEL_SELECT) && (v->flag & SELECT))
+ || ((options & BME_BEVEL_WEIGHT) && (options & BME_BEVEL_VERT)) /* use weights for verts */
+ || ((options & BME_BEVEL_ANGLE) == 0
+ && (options & BME_BEVEL_SELECT) == 0
+ && (options & BME_BEVEL_WEIGHT) == 0))
+ {
+ if (options & BME_BEVEL_WEIGHT) {
+ /* do vert weight stuff */
+ //~ dvert = CustomData_em_get(&bm->vdata,v->data,CD_MDEFORMVERT);
+ //~ if (!dvert) continue;
+ //~ for (i = 0; i < dvert->totweight; ++i) {
+ //~ if(dvert->dw[i].def_nr == defgrp_index) {
+ //~ dw = &dvert->dw[i];
+ //~ break;
+ //~ }
+ //~ }
+ //~ if (!dw || dw->weight == 0.0) continue;
+ if (v->bweight == 0.0) continue;
+ vtd = BME_assign_transdata(td, bm, v, v->co, v->co, NULL, NULL, 1.0, v->bweight, -1, NULL);
+ v->tflag1 |= BME_BEVEL_BEVEL;
+ }
+ else {
+ vtd = BME_assign_transdata(td, bm, v, v->co, v->co, NULL, NULL, 1.0, 1.0, -1, NULL);
+ v->tflag1 |= BME_BEVEL_BEVEL;
+ }
+ }
+ }
+ }
+
+ /* edge pass */
+ threshold = (float)cos((angle + 0.00001) * M_PI / 180.0);
+ for (e=bm->edges.first; e; e=e->next) {
+ e->tflag1 = BME_BEVEL_ORIG;
+ weight = 0.0;
+ /* originally coded, an edge gets tagged with BME_BEVEL_BEVEL in this pass if
+ * BME_BEVEL_VERT is not set
+ * the edge is manifold (shared by exactly two faces)
+ * BME_BEVEL_SELECT is passed and the edge has e->flag&SELECT or
+ * BME_BEVEL_EWEIGHT is passed, and the edge has the crease set or
+ * BME_BEVEL_ANGLE is passed, and the edge is sharp enough
+ * BME_BEVEL_VWEIGHT is passed, and both verts are set for bevel
+ */
+ /* originally coded, a vertex gets tagged with BME_BEVEL_BEVEL in this pass if
+ * the vert belongs to the edge
+ * the vert is not tagged with BME_BEVEL_NONMAN
+ * the edge is eligible for bevel (even if BME_BEVEL_VERT is set, or the edge is shared by less than 2 faces)
+ */
+ /* originally coded, a vertex gets a transform weight set in this pass if
+ * the vert belongs to the edge
+ * the edge has a weight
+ */
+ /* note: edge weights are cumulative at the verts,
+ * i.e. the vert's weight is the average of the weights of its weighted edges
+ */
+
+ if (e->loop == NULL) {
+ len = 0;
+ e->v1->tflag1 |= BME_BEVEL_NONMAN;
+ e->v2->tflag1 |= BME_BEVEL_NONMAN;
+ }
+ else {
+ len = BME_cycle_length(&(e->loop->radial));
+ }
+
+ if (len > 2) {
+ /* non-manifold edge of the worst kind */
+ continue;
+ }
+
+ if ((options & BME_BEVEL_SELECT) && (e->flag & SELECT)) {
+ weight = 1.0;
+ /* stupid editmode doesn't always flush selections, or something */
+ e->v1->flag |= SELECT;
+ e->v2->flag |= SELECT;
+ }
+ else if ((options & BME_BEVEL_WEIGHT) && (options & BME_BEVEL_VERT) == 0) {
+ weight = e->bweight;
+ }
+ else if (options & BME_BEVEL_ANGLE) {
+ if ((e->v1->tflag1 & BME_BEVEL_NONMAN) == 0 && BME_bevel_get_angle(bm,e,e->v1) < threshold) {
+ e->tflag1 |= BME_BEVEL_BEVEL;
+ e->v1->tflag1 |= BME_BEVEL_BEVEL;
+ BME_bevel_add_vweight(td, bm, e->v1, 1.0, 1.0, options);
+ }
+ else {
+ BME_bevel_add_vweight(td, bm, e->v1, 0.0, 1.0, options);
+ }
+ if ((e->v2->tflag1 & BME_BEVEL_NONMAN) == 0 && BME_bevel_get_angle(bm,e,e->v2) < threshold) {
+ e->tflag1 |= BME_BEVEL_BEVEL;
+ e->v2->tflag1 |= BME_BEVEL_BEVEL;
+ BME_bevel_add_vweight(td, bm, e->v2, 1.0, 1.0, options);
+ }
+ else {
+ BME_bevel_add_vweight(td, bm, e->v2, 0.0, 1.0, options);
+ }
+ }
+ //~ else if ((options & BME_BEVEL_VWEIGHT) && (options & BME_BEVEL_VERT) == 0) {
+ //~ if ((e->v1->tflag1 & BME_BEVEL_BEVEL) && (e->v2->tflag1 & BME_BEVEL_BEVEL)) {
+ //~ e->tflag1 |= BME_BEVEL_BEVEL;
+ //~ }
+ //~ }
+ else if ((options & BME_BEVEL_SELECT) == 0
+ && (options & BME_BEVEL_VERT) == 0)
+ {
+ weight = 1.0;
+ }
+
+ if (weight > 0.0) {
+ e->tflag1 |= BME_BEVEL_BEVEL;
+ BME_bevel_add_vweight(td, bm, e->v1, weight, 1.0, options);
+ BME_bevel_add_vweight(td, bm, e->v2, weight, 1.0, options);
+ }
+
+ if (len != 2 || options & BME_BEVEL_VERT) {
+ e->tflag1 &= ~BME_BEVEL_BEVEL;
+ }
+ }
+
+ /* face pass */
+ for (f=bm->polys.first; f; f=f->next) f->tflag1 = BME_BEVEL_ORIG;
+
+ /*clean up edges with 2 faces that share more than one edge*/
+ for (e=bm->edges.first; e; e=e->next){
+ if(e->tflag1 & BME_BEVEL_BEVEL){
+ int count = 0;
+ count = BME_face_sharededges(e->loop->f, ((BME_Loop*)e->loop->radial.next->data)->f);
+ if(count > 1){
+ e->tflag1 &= ~BME_BEVEL_BEVEL;
+ }
+ }
+ }
+
+ return bm;
+}
+
+/* tags all elements as originals */
+static BME_Mesh *BME_bevel_reinitialize(BME_Mesh *bm) {
+ BME_Vert *v;
+ BME_Edge *e;
+ BME_Poly *f;
+
+ for (v = bm->verts.first; v; v=v->next) {
+ v->tflag1 |= BME_BEVEL_ORIG;
+ }
+
+ for (e=bm->edges.first; e; e=e->next) {
+ e->tflag1 |= BME_BEVEL_ORIG;
+ }
+
+ for (f=bm->polys.first; f; f=f->next) {
+ f->tflag1 |= BME_BEVEL_ORIG;
+ }
+
+ return bm;
+}
+
+/**
+ * BME_bevel_mesh
+ *
+ * Mesh beveling tool:
+ *
+ * Bevels an entire mesh. It currently uses the tflag1's of
+ * its vertices and edges to track topological changes.
+ * The parameter "value" is the distance to inset (should be negative).
+ * The parameter "options" is not currently used.
+ *
+ * Returns -
+ * A BME_Mesh pointer to the BMesh passed as a parameter.
+*/
+
+static void bmesh_dissolve_disk(BME_Mesh *bm, BME_Vert *v){
+ BME_Poly *f;
+ BME_Edge *e;
+ int done, len;
+
+ if(v->edge){
+ done = 0;
+ while(!done){
+ done = 1;
+ e = v->edge; /*loop the edge looking for a edge to dissolve*/
+ do{
+ f = NULL;
+ len = BME_cycle_length(&(e->loop->radial));
+ if(len == 2){
+ f = BME_JFKE_safe(bm,e->loop->f, ((BME_Loop*)(e->loop->radial.next->data))->f, e);
+ }
+ if(f){
+ done = 0;
+ break;
+ }
+ e = BME_disk_nextedge(e,v);
+ }while(e != v->edge);
+ }
+ BME_collapse_vert(bm, v->edge, v, 1.0);
+ //BME_JEKV(bm,v->edge,v);
+ }
+}
+static BME_Mesh *BME_bevel_mesh(BME_Mesh *bm, float value, int res, int options, int defgrp_index, BME_TransData_Head *td) {
+ BME_Vert *v, *nv;
+ BME_Edge *e, *oe;
+ BME_Loop *l, *l2;
+ BME_Poly *f;
+ unsigned int i, len;
+
+ for (f=bm->polys.first; f; f=f->next) {
+ if(f->tflag1 & BME_BEVEL_ORIG) {
+ BME_bevel_poly(bm,f,value,options,td);
+ }
+ }
+
+ /* here we will loop through all the verts to clean up the left over geometry */
+ /* crazy idea. when res == 0, don't remove the original geometry */
+ for (v = bm->verts.first; v; /* we may kill v, so increment in-loop */) {
+ nv = v->next;
+ if ((v->tflag1 & BME_BEVEL_NONMAN) && (v->tflag1 & BME_BEVEL_BEVEL) && (v->tflag1 & BME_BEVEL_ORIG)) {
+ v = BME_bevel_wire(bm, v, value, res, options, td);
+ }
+ else if (res && ((v->tflag1 & BME_BEVEL_BEVEL) && (v->tflag1 & BME_BEVEL_ORIG))) {
+ int count = 0;
+ /* first, make sure we're not sitting on an edge to be removed */
+ oe = v->edge;
+ e = BME_disk_nextedge(oe,v);
+ while ((e->tflag1 & BME_BEVEL_BEVEL) && (e->tflag1 & BME_BEVEL_ORIG)) {
+ e = BME_disk_nextedge(e,v);
+ if (e == oe) {
+ //printf("Something's wrong! We can't remove every edge here!\n");
+ break;
+ }
+ }
+ /* look for original edges, and remove them */
+ oe = e;
+ while ( (e = BME_disk_next_edgeflag(oe, v, 0, BME_BEVEL_ORIG | BME_BEVEL_BEVEL)) ) {
+ count++;
+ /* join the faces (we'll split them later) */
+ f = BME_JFKE_safe(bm,e->loop->f,((BME_Loop*)e->loop->radial.next->data)->f,e);
+ if (!f){
+ //printf("Non-manifold geometry not getting tagged right?\n");
+ }
+ }
+
+ /*need to do double check *before* you bevel to make sure that manifold edges are for two faces that share only *one* edge to make sure it doesnt hang here!*/
+
+
+ /* all original edges marked to be beveled have been removed;
+ * now we need to link up the edges for this "corner" */
+ len = BME_cycle_length(BME_disk_getpointer(v->edge, v));
+ for (i=0,e=v->edge; i < len; i++,e=BME_disk_nextedge(e,v)) {
+ l = e->loop;
+ l2 = l->radial.next->data;
+ if (l->v != v) l = l->next;
+ if (l2->v != v) l2 = l2->next;
+ /* look for faces that have had the original edges removed via JFKE */
+ if (l->f->len > 3) {
+ BME_split_face(bm,l->f,l->next->v,l->prev->v,&l,l->e); /* clip this corner off */
+ if (len > 2) {
+ l->e->tflag1 |= BME_BEVEL_BEVEL;
+ }
+ }
+ if (l2->f->len > 3) {
+ BME_split_face(bm,l2->f,l2->next->v,l2->prev->v,&l,l2->e); /* clip this corner off */
+ if (len > 2) {
+ l->e->tflag1 |= BME_BEVEL_BEVEL;
+ }
+ }
+ }
+ bmesh_dissolve_disk(bm, v);
+ }
+ v = nv;
+ }
+
+ return bm;
+}
+
+static BME_Mesh *BME_tesselate(BME_Mesh *bm) {
+ BME_Loop *l, *nextloop;
+ BME_Poly *f;
+
+ for (f=bm->polys.first; f; f=f->next) {
+ l = f->loopbase;
+ while (l->f->len > 4) {
+ nextloop = l->next->next->next;
+ /* make a quad */
+ BME_split_face(bm,l->f,l->v,nextloop->v,NULL,l->e);
+ l = nextloop;
+ }
+ }
+ return bm;
+}
+
+
+/*Main bevel function:
+ Should be only one exported
+
+*/
+
+/* options that can be passed:
+ * BME_BEVEL_VWEIGHT <---- v, Look at vertex weights; use defgrp_index if option is present
+ * BME_BEVEL_SELECT <---- v,e, check selection for verts and edges
+ * BME_BEVEL_ANGLE <---- v,e, don't bevel-tag verts - tag verts per edge
+ * BME_BEVEL_VERT <---- e, don't tag edges
+ * BME_BEVEL_EWEIGHT <---- e, use crease flag for now
+ * BME_BEVEL_PERCENT <---- Will need to think about this one; will probably need to incorporate into actual bevel routine
+ * BME_BEVEL_RADIUS <---- Will need to think about this one; will probably need to incorporate into actual bevel routine
+ * All weights/limits are stored per-vertex
+ */
+BME_Mesh *BME_bevel(BME_Mesh *bm, float value, int res, int options, int defgrp_index, float angle, BME_TransData_Head **rtd) {
+ BME_Vert *v;
+ BME_TransData_Head *td;
+ BME_TransData *vtd;
+ int i;
+ float fac=1, d;
+
+ td = BME_init_transdata(BLI_MEMARENA_STD_BUFSIZE);
+
+ BME_bevel_initialize(bm, options, defgrp_index, angle, td);
+
+ /* recursion math courtesy of Martin Poirier (theeth) */
+ for (i=0; i<res-1; i++) {
+ if (i==0) fac += 1.0f/3.0f; else fac += 1.0f/(3 * i * 2.0f);
+ }
+ d = 1.0f/fac;
+ /* crazy idea. if res == 0, don't remove original geometry */
+ for (i=0; i<res || (res==0 && i==0); i++) {
+ if (i != 0) BME_bevel_reinitialize(bm);
+ BME_model_begin(bm);
+ BME_bevel_mesh(bm,d,res,options,defgrp_index,td);
+ BME_model_end(bm);
+ if (i==0) d /= 3; else d /= 2;
+ }
+
+ BME_tesselate(bm);
+
+ if (rtd) {
+ *rtd = td;
+ return bm;
+ }
+
+ /* transform pass */
+ for (v = bm->verts.first; v; v=v->next) {
+ if ( (vtd = BME_get_transdata(td, v)) ) {
+ if (vtd->max && (*vtd->max > 0 && value > *vtd->max)) {
+ d = *vtd->max;
+ }
+ else {
+ d = value;
+ }
+ VECADDFAC(v->co,vtd->org,vtd->vec,vtd->factor*d);
+ }
+ v->tflag1 = 0;
+ }
+
+ BME_free_transdata(td);
+ return bm;
+}
diff --git a/source/blender/blenkernel/intern/CCGSubSurf.c b/source/blender/blenkernel/intern/CCGSubSurf.c
index 4e00e29029c..cee032f364e 100644
--- a/source/blender/blenkernel/intern/CCGSubSurf.c
+++ b/source/blender/blenkernel/intern/CCGSubSurf.c
@@ -7,6 +7,8 @@
#include "CCGSubSurf.h"
+#include "BLO_sys_types.h" // for intptr_t support
+
/***/
typedef unsigned char byte;
@@ -35,7 +37,7 @@ typedef struct _EHash {
#define EHASH_alloc(eh, nb) ((eh)->allocatorIFC.alloc((eh)->allocator, nb))
#define EHASH_free(eh, ptr) ((eh)->allocatorIFC.free((eh)->allocator, ptr))
-#define EHASH_hash(eh, item) (((unsigned long) (item))%((unsigned int) (eh)->curSize))
+#define EHASH_hash(eh, item) (((uintptr_t) (item))%((unsigned int) (eh)->curSize))
static EHash *_ehash_new(int estimatedNumEntries, CCGAllocatorIFC *allocatorIFC, CCGAllocatorHDL allocator) {
EHash *eh = allocatorIFC->alloc(allocator, sizeof(*eh));
@@ -199,21 +201,21 @@ static CCGAllocatorIFC *_getStandardAllocatorIFC(void) {
static int VertDataEqual(float *a, float *b) {
return a[0]==b[0] && a[1]==b[1] && a[2]==b[2];
}
-#define VertDataZero(av) { float *a = (float*) av; a[0] = a[1] = a[2] = 0.0f; }
-#define VertDataCopy(av, bv) { float *a = (float*) av, *b = (float*) bv; a[0] =b[0]; a[1] =b[1]; a[2] =b[2]; }
-#define VertDataAdd(av, bv) { float *a = (float*) av, *b = (float*) bv; a[0]+=b[0]; a[1]+=b[1]; a[2]+=b[2]; }
-#define VertDataSub(av, bv) { float *a = (float*) av, *b = (float*) bv; a[0]-=b[0]; a[1]-=b[1]; a[2]-=b[2]; }
-#define VertDataMulN(av, n) { float *a = (float*) av; a[0]*=n; a[1]*=n; a[2]*=n; }
+#define VertDataZero(av) { float *_a = (float*) av; _a[0] = _a[1] = _a[2] = 0.0f; }
+#define VertDataCopy(av, bv) { float *_a = (float*) av, *_b = (float*) bv; _a[0] =_b[0]; _a[1] =_b[1]; _a[2] =_b[2]; }
+#define VertDataAdd(av, bv) { float *_a = (float*) av, *_b = (float*) bv; _a[0]+=_b[0]; _a[1]+=_b[1]; _a[2]+=_b[2]; }
+#define VertDataSub(av, bv) { float *_a = (float*) av, *_b = (float*) bv; _a[0]-=_b[0]; _a[1]-=_b[1]; _a[2]-=_b[2]; }
+#define VertDataMulN(av, n) { float *_a = (float*) av; _a[0]*=n; _a[1]*=n; _a[2]*=n; }
#define VertDataAvg4(tv, av, bv, cv, dv) \
{ \
- float *t = (float*) tv, *a = (float*) av, *b = (float*) bv, *c = (float*) cv, *d = (float*) dv; \
- t[0] = (a[0]+b[0]+c[0]+d[0])*.25; \
- t[1] = (a[1]+b[1]+c[1]+d[1])*.25; \
- t[2] = (a[2]+b[2]+c[2]+d[2])*.25; \
+ float *_t = (float*) tv, *_a = (float*) av, *_b = (float*) bv, *_c = (float*) cv, *_d = (float*) dv; \
+ _t[0] = (_a[0]+_b[0]+_c[0]+_d[0])*.25; \
+ _t[1] = (_a[1]+_b[1]+_c[1]+_d[1])*.25; \
+ _t[2] = (_a[2]+_b[2]+_c[2]+_d[2])*.25; \
}
-#define NormZero(av) { float *a = (float*) av; a[0] = a[1] = a[2] = 0.0f; }
-#define NormCopy(av, bv) { float *a = (float*) av, *b = (float*) bv; a[0] =b[0]; a[1] =b[1]; a[2] =b[2]; }
-#define NormAdd(av, bv) { float *a = (float*) av, *b = (float*) bv; a[0]+=b[0]; a[1]+=b[1]; a[2]+=b[2]; }
+#define NormZero(av) { float *_a = (float*) av; _a[0] = _a[1] = _a[2] = 0.0f; }
+#define NormCopy(av, bv) { float *_a = (float*) av, *_b = (float*) bv; _a[0] =_b[0]; _a[1] =_b[1]; _a[2] =_b[2]; }
+#define NormAdd(av, bv) { float *_a = (float*) av, *_b = (float*) bv; _a[0]+=_b[0]; _a[1]+=_b[1]; _a[2]+=_b[2]; }
static int _edge_isBoundary(CCGEdge *e);
@@ -328,7 +330,7 @@ struct _CCGSubSurf {
/***/
-static CCGVert *_vert_new(CCGVertHDL vHDL, int levels, int dataSize, CCGSubSurf *ss) {
+static CCGVert *_vert_new(CCGVertHDL vHDL, CCGSubSurf *ss) {
CCGVert *v = CCGSUBSURF_alloc(ss, sizeof(CCGVert) + ss->meshIFC.vertDataSize * (ss->subdivLevels+1) + ss->meshIFC.vertUserSize);
byte *userData;
@@ -344,7 +346,7 @@ static CCGVert *_vert_new(CCGVertHDL vHDL, int levels, int dataSize, CCGSubSurf
return v;
}
-static void _vert_remEdge(CCGVert *v, CCGEdge *e, CCGSubSurf *ss) {
+static void _vert_remEdge(CCGVert *v, CCGEdge *e) {
int i;
for (i=0; i<v->numEdges; i++) {
if (v->edges[i]==e) {
@@ -353,7 +355,7 @@ static void _vert_remEdge(CCGVert *v, CCGEdge *e, CCGSubSurf *ss) {
}
}
}
-static void _vert_remFace(CCGVert *v, CCGFace *f, CCGSubSurf *ss) {
+static void _vert_remFace(CCGVert *v, CCGFace *f) {
int i;
for (i=0; i<v->numFaces; i++) {
if (v->faces[i]==f) {
@@ -401,13 +403,13 @@ static void _vert_free(CCGVert *v, CCGSubSurf *ss) {
CCGSUBSURF_free(ss, v);
}
-static int VERT_seam(CCGVert *v, CCGSubSurf *ss) {
+static int VERT_seam(CCGVert *v) {
return ((v->flags & Vert_eSeam) != 0);
}
/***/
-static CCGEdge *_edge_new(CCGEdgeHDL eHDL, CCGVert *v0, CCGVert *v1, float crease, int levels, int dataSize, CCGSubSurf *ss) {
+static CCGEdge *_edge_new(CCGEdgeHDL eHDL, CCGVert *v0, CCGVert *v1, float crease, CCGSubSurf *ss) {
CCGEdge *e = CCGSUBSURF_alloc(ss, sizeof(CCGEdge) + ss->meshIFC.vertDataSize *((ss->subdivLevels+1) + (1<<(ss->subdivLevels+1))-1) + ss->meshIFC.edgeUserSize);
byte *userData;
@@ -427,7 +429,7 @@ static CCGEdge *_edge_new(CCGEdgeHDL eHDL, CCGVert *v0, CCGVert *v1, float creas
return e;
}
-static void _edge_remFace(CCGEdge *e, CCGFace *f, CCGSubSurf *ss) {
+static void _edge_remFace(CCGEdge *e, CCGFace *f) {
int i;
for (i=0; i<e->numFaces; i++) {
if (e->faces[i]==f) {
@@ -476,8 +478,8 @@ static void _edge_free(CCGEdge *e, CCGSubSurf *ss) {
CCGSUBSURF_free(ss, e);
}
static void _edge_unlinkMarkAndFree(CCGEdge *e, CCGSubSurf *ss) {
- _vert_remEdge(e->v0, e, ss);
- _vert_remEdge(e->v1, e, ss);
+ _vert_remEdge(e->v0, e);
+ _vert_remEdge(e->v1, e);
e->v0->flags |= Vert_eEffected;
e->v1->flags |= Vert_eEffected;
_edge_free(e, ss);
@@ -494,7 +496,7 @@ static float EDGE_getSharpness(CCGEdge *e, int lvl) {
return e->crease - lvl;
}
-static CCGFace *_face_new(CCGFaceHDL fHDL, CCGVert **verts, CCGEdge **edges, int numVerts, int levels, int dataSize, CCGSubSurf *ss) {
+static CCGFace *_face_new(CCGFaceHDL fHDL, CCGVert **verts, CCGEdge **edges, int numVerts, CCGSubSurf *ss) {
int maxGridSize = 1 + (1<<(ss->subdivLevels-1));
CCGFace *f = CCGSUBSURF_alloc(ss, sizeof(CCGFace) + sizeof(CCGVert*)*numVerts + sizeof(CCGEdge*)*numVerts + ss->meshIFC.vertDataSize *(1 + numVerts*maxGridSize + numVerts*maxGridSize*maxGridSize) + ss->meshIFC.faceUserSize);
byte *userData;
@@ -608,8 +610,8 @@ static void _face_free(CCGFace *f, CCGSubSurf *ss) {
static void _face_unlinkMarkAndFree(CCGFace *f, CCGSubSurf *ss) {
int j;
for (j=0; j<f->numVerts; j++) {
- _vert_remFace(FACE_getVerts(f)[j], f, ss);
- _edge_remFace(FACE_getEdges(f)[j], f, ss);
+ _vert_remFace(FACE_getVerts(f)[j], f);
+ _edge_remFace(FACE_getEdges(f)[j], f);
FACE_getVerts(f)[j]->flags |= Vert_eEffected;
}
_face_free(f, ss);
@@ -882,7 +884,7 @@ CCGError ccgSubSurf_syncVert(CCGSubSurf *ss, CCGVertHDL vHDL, void *vertData, in
if (ss->syncState==eSyncState_Partial) {
v = _ehash_lookupWithPrev(ss->vMap, vHDL, &prevp);
if (!v) {
- v = _vert_new(vHDL, ss->subdivLevels, ss->meshIFC.vertDataSize, ss);
+ v = _vert_new(vHDL, ss);
VertDataCopy(_vert_getCo(v,0,ss->meshIFC.vertDataSize), vertData);
_ehash_insert(ss->vMap, (EHEntry*) v);
v->flags = Vert_eEffected|seamflag;
@@ -911,7 +913,7 @@ CCGError ccgSubSurf_syncVert(CCGSubSurf *ss, CCGVertHDL vHDL, void *vertData, in
v = _ehash_lookupWithPrev(ss->oldVMap, vHDL, &prevp);
if (!v) {
- v = _vert_new(vHDL, ss->subdivLevels, ss->meshIFC.vertDataSize, ss);
+ v = _vert_new(vHDL, ss);
VertDataCopy(_vert_getCo(v,0,ss->meshIFC.vertDataSize), vertData);
_ehash_insert(ss->vMap, (EHEntry*) v);
v->flags = Vert_eEffected|seamflag;
@@ -941,7 +943,7 @@ CCGError ccgSubSurf_syncEdge(CCGSubSurf *ss, CCGEdgeHDL eHDL, CCGVertHDL e_vHDL0
CCGVert *v0 = _ehash_lookup(ss->vMap, e_vHDL0);
CCGVert *v1 = _ehash_lookup(ss->vMap, e_vHDL1);
- eNew = _edge_new(eHDL, v0, v1, crease, ss->subdivLevels, ss->meshIFC.vertDataSize, ss);
+ eNew = _edge_new(eHDL, v0, v1, crease, ss);
if (e) {
*prevp = eNew;
@@ -966,7 +968,7 @@ CCGError ccgSubSurf_syncEdge(CCGSubSurf *ss, CCGEdgeHDL eHDL, CCGVertHDL e_vHDL0
if (!e || e->v0->vHDL!=e_vHDL0 || e->v1->vHDL!=e_vHDL1|| e->crease!=crease) {
CCGVert *v0 = _ehash_lookup(ss->vMap, e_vHDL0);
CCGVert *v1 = _ehash_lookup(ss->vMap, e_vHDL1);
- e = _edge_new(eHDL, v0, v1, crease, ss->subdivLevels, ss->meshIFC.vertDataSize, ss);
+ e = _edge_new(eHDL, v0, v1, crease, ss);
_ehash_insert(ss->eMap, (EHEntry*) e);
e->v0->flags |= Vert_eEffected;
e->v1->flags |= Vert_eEffected;
@@ -1015,7 +1017,7 @@ CCGError ccgSubSurf_syncFace(CCGSubSurf *ss, CCGFaceHDL fHDL, int numVerts, CCGV
}
if (!f || topologyChanged) {
- fNew = _face_new(fHDL, ss->tempVerts, ss->tempEdges, numVerts, ss->subdivLevels, ss->meshIFC.vertDataSize, ss);
+ fNew = _face_new(fHDL, ss->tempVerts, ss->tempEdges, numVerts, ss);
if (f) {
ss->numGrids += numVerts - f->numVerts;
@@ -1052,7 +1054,7 @@ CCGError ccgSubSurf_syncFace(CCGSubSurf *ss, CCGFaceHDL fHDL, int numVerts, CCGV
if (!ss->tempEdges[k]) {
if (ss->allowEdgeCreation) {
- CCGEdge *e = ss->tempEdges[k] = _edge_new((CCGEdgeHDL) -1, ss->tempVerts[k], ss->tempVerts[(k+1)%numVerts], ss->defaultCreaseValue, ss->subdivLevels, ss->meshIFC.vertDataSize, ss);
+ CCGEdge *e = ss->tempEdges[k] = _edge_new((CCGEdgeHDL) -1, ss->tempVerts[k], ss->tempVerts[(k+1)%numVerts], ss->defaultCreaseValue, ss);
_ehash_insert(ss->eMap, (EHEntry*) e);
e->v0->flags |= Vert_eEffected;
e->v1->flags |= Vert_eEffected;
@@ -1073,7 +1075,7 @@ CCGError ccgSubSurf_syncFace(CCGSubSurf *ss, CCGFaceHDL fHDL, int numVerts, CCGV
}
if (!f || topologyChanged) {
- f = _face_new(fHDL, ss->tempVerts, ss->tempEdges, numVerts, ss->subdivLevels, ss->meshIFC.vertDataSize, ss);
+ f = _face_new(fHDL, ss->tempVerts, ss->tempEdges, numVerts, ss);
_ehash_insert(ss->fMap, (EHEntry*) f);
ss->numGrids += numVerts;
@@ -1226,7 +1228,7 @@ static void ccgSubSurf__sync(CCGSubSurf *ss) {
void *nCo = VERT_getCo(v, nextLvl);
int sharpCount = 0, allSharp = 1;
float avgSharpness = 0.0;
- int seam = VERT_seam(v, ss), seamEdges = 0;
+ int seam = VERT_seam(v), seamEdges = 0;
for (i=0; i<v->numEdges; i++) {
CCGEdge *e = v->edges[i];
@@ -1243,9 +1245,11 @@ static void ccgSubSurf__sync(CCGSubSurf *ss) {
}
}
- avgSharpness /= sharpCount;
- if (avgSharpness>1.0) {
- avgSharpness = 1.0;
+ if(sharpCount) {
+ avgSharpness /= sharpCount;
+ if (avgSharpness>1.0) {
+ avgSharpness = 1.0;
+ }
}
if (seam && seamEdges < 2)
@@ -1293,7 +1297,7 @@ static void ccgSubSurf__sync(CCGSubSurf *ss) {
VertDataMulN(nCo, 1.0f/numEdges);
}
- if ((sharpCount>1 && v->numFaces) || seam) {
+ if (sharpCount>1 || seam) {
VertDataZero(q);
if (seam) {
@@ -1524,7 +1528,7 @@ static void ccgSubSurf__sync(CCGSubSurf *ss) {
void *nCo = VERT_getCo(v, nextLvl);
int sharpCount = 0, allSharp = 1;
float avgSharpness = 0.0;
- int seam = VERT_seam(v, ss), seamEdges = 0;
+ int seam = VERT_seam(v), seamEdges = 0;
for (i=0; i<v->numEdges; i++) {
CCGEdge *e = v->edges[i];
@@ -1541,9 +1545,11 @@ static void ccgSubSurf__sync(CCGSubSurf *ss) {
}
}
- avgSharpness /= sharpCount;
- if (avgSharpness>1.0) {
- avgSharpness = 1.0;
+ if(sharpCount) {
+ avgSharpness /= sharpCount;
+ if (avgSharpness>1.0) {
+ avgSharpness = 1.0;
+ }
}
if (seam && seamEdges < 2)
@@ -2069,7 +2075,7 @@ int ccgSubSurf_getGridLevelSize(CCGSubSurf *ss, int level) {
/* Vert accessors */
-CCGVertHDL ccgSubSurf_getVertVertHandle(CCGSubSurf *ss, CCGVert *v) {
+CCGVertHDL ccgSubSurf_getVertVertHandle(CCGVert *v) {
return v->vHDL;
}
int ccgSubSurf_getVertAge(CCGSubSurf *ss, CCGVert *v) {
@@ -2083,20 +2089,20 @@ int ccgSubSurf_getVertAge(CCGSubSurf *ss, CCGVert *v) {
void *ccgSubSurf_getVertUserData(CCGSubSurf *ss, CCGVert *v) {
return VERT_getLevelData(v) + ss->meshIFC.vertDataSize*(ss->subdivLevels+1);
}
-int ccgSubSurf_getVertNumFaces(CCGSubSurf *ss, CCGVert *v) {
+int ccgSubSurf_getVertNumFaces(CCGVert *v) {
return v->numFaces;
}
-CCGFace *ccgSubSurf_getVertFace(CCGSubSurf *ss, CCGVert *v, int index) {
+CCGFace *ccgSubSurf_getVertFace(CCGVert *v, int index) {
if (index<0 || index>=v->numFaces) {
return NULL;
} else {
return v->faces[index];
}
}
-int ccgSubSurf_getVertNumEdges(CCGSubSurf *ss, CCGVert *v) {
+int ccgSubSurf_getVertNumEdges(CCGVert *v) {
return v->numEdges;
}
-CCGEdge *ccgSubSurf_getVertEdge(CCGSubSurf *ss, CCGVert *v, int index) {
+CCGEdge *ccgSubSurf_getVertEdge(CCGVert *v, int index) {
if (index<0 || index>=v->numEdges) {
return NULL;
} else {
@@ -2116,7 +2122,7 @@ void *ccgSubSurf_getVertLevelData(CCGSubSurf *ss, CCGVert *v, int level) {
/* Edge accessors */
-CCGEdgeHDL ccgSubSurf_getEdgeEdgeHandle(CCGSubSurf *ss, CCGEdge *e) {
+CCGEdgeHDL ccgSubSurf_getEdgeEdgeHandle(CCGEdge *e) {
return e->eHDL;
}
int ccgSubSurf_getEdgeAge(CCGSubSurf *ss, CCGEdge *e) {
@@ -2130,20 +2136,20 @@ int ccgSubSurf_getEdgeAge(CCGSubSurf *ss, CCGEdge *e) {
void *ccgSubSurf_getEdgeUserData(CCGSubSurf *ss, CCGEdge *e) {
return EDGE_getLevelData(e) + ss->meshIFC.vertDataSize *((ss->subdivLevels+1) + (1<<(ss->subdivLevels+1))-1);
}
-int ccgSubSurf_getEdgeNumFaces(CCGSubSurf *ss, CCGEdge *e) {
+int ccgSubSurf_getEdgeNumFaces(CCGEdge *e) {
return e->numFaces;
}
-CCGFace *ccgSubSurf_getEdgeFace(CCGSubSurf *ss, CCGEdge *e, int index) {
+CCGFace *ccgSubSurf_getEdgeFace(CCGEdge *e, int index) {
if (index<0 || index>=e->numFaces) {
return NULL;
} else {
return e->faces[index];
}
}
-CCGVert *ccgSubSurf_getEdgeVert0(CCGSubSurf *ss, CCGEdge *e) {
+CCGVert *ccgSubSurf_getEdgeVert0(CCGEdge *e) {
return e->v0;
}
-CCGVert *ccgSubSurf_getEdgeVert1(CCGSubSurf *ss, CCGEdge *e) {
+CCGVert *ccgSubSurf_getEdgeVert1(CCGEdge *e) {
return e->v1;
}
void *ccgSubSurf_getEdgeDataArray(CCGSubSurf *ss, CCGEdge *e) {
@@ -2159,7 +2165,7 @@ void *ccgSubSurf_getEdgeLevelData(CCGSubSurf *ss, CCGEdge *e, int x, int level)
return _edge_getCo(e, level, x, ss->meshIFC.vertDataSize);
}
}
-float ccgSubSurf_getEdgeCrease(CCGSubSurf *ss, CCGEdge *e) {
+float ccgSubSurf_getEdgeCrease(CCGEdge *e) {
return e->crease;
}
@@ -2180,7 +2186,7 @@ void *ccgSubSurf_getFaceUserData(CCGSubSurf *ss, CCGFace *f) {
int maxGridSize = 1 + (1<<(ss->subdivLevels-1));
return FACE_getCenterData(f) + ss->meshIFC.vertDataSize *(1 + f->numVerts*maxGridSize + f->numVerts*maxGridSize*maxGridSize);
}
-int ccgSubSurf_getFaceNumVerts(CCGSubSurf *ss, CCGFace *f) {
+int ccgSubSurf_getFaceNumVerts(CCGFace *f) {
return f->numVerts;
}
CCGVert *ccgSubSurf_getFaceVert(CCGSubSurf *ss, CCGFace *f, int index) {
@@ -2197,7 +2203,7 @@ CCGEdge *ccgSubSurf_getFaceEdge(CCGSubSurf *ss, CCGFace *f, int index) {
return FACE_getEdges(f)[index];
}
}
-int ccgSubSurf_getFaceEdgeIndex(CCGSubSurf *ss, CCGFace *f, CCGEdge *e) {
+int ccgSubSurf_getFaceEdgeIndex(CCGFace *f, CCGEdge *e) {
int i;
for (i=0; i<f->numVerts; i++)
@@ -2206,7 +2212,7 @@ int ccgSubSurf_getFaceEdgeIndex(CCGSubSurf *ss, CCGFace *f, CCGEdge *e) {
return -1;
}
-void *ccgSubSurf_getFaceCenterData(CCGSubSurf *ss, CCGFace *f) {
+void *ccgSubSurf_getFaceCenterData(CCGFace *f) {
return FACE_getCenterData(f);
}
void *ccgSubSurf_getFaceGridEdgeDataArray(CCGSubSurf *ss, CCGFace *f, int gridIndex) {
diff --git a/source/blender/blenkernel/intern/CCGSubSurf.h b/source/blender/blenkernel/intern/CCGSubSurf.h
index 91f3ffab43b..fbd0aecc0a5 100644
--- a/source/blender/blenkernel/intern/CCGSubSurf.h
+++ b/source/blender/blenkernel/intern/CCGSubSurf.h
@@ -82,11 +82,11 @@ int ccgSubSurf_getGridSize (CCGSubSurf *ss);
int ccgSubSurf_getGridLevelSize (CCGSubSurf *ss, int level);
CCGVert* ccgSubSurf_getVert (CCGSubSurf *ss, CCGVertHDL v);
-CCGVertHDL ccgSubSurf_getVertVertHandle (CCGSubSurf *ss, CCGVert *v);
-int ccgSubSurf_getVertNumFaces (CCGSubSurf *ss, CCGVert *v);
-CCGFace* ccgSubSurf_getVertFace (CCGSubSurf *ss, CCGVert *v, int index);
-int ccgSubSurf_getVertNumEdges (CCGSubSurf *ss, CCGVert *v);
-CCGEdge* ccgSubSurf_getVertEdge (CCGSubSurf *ss, CCGVert *v, int index);
+CCGVertHDL ccgSubSurf_getVertVertHandle (CCGVert *v);
+int ccgSubSurf_getVertNumFaces (CCGVert *v);
+CCGFace* ccgSubSurf_getVertFace (CCGVert *v, int index);
+int ccgSubSurf_getVertNumEdges (CCGVert *v);
+CCGEdge* ccgSubSurf_getVertEdge (CCGVert *v, int index);
int ccgSubSurf_getVertAge (CCGSubSurf *ss, CCGVert *v);
void* ccgSubSurf_getVertUserData (CCGSubSurf *ss, CCGVert *v);
@@ -94,12 +94,12 @@ void* ccgSubSurf_getVertData (CCGSubSurf *ss, CCGVert *v);
void* ccgSubSurf_getVertLevelData (CCGSubSurf *ss, CCGVert *v, int level);
CCGEdge* ccgSubSurf_getEdge (CCGSubSurf *ss, CCGEdgeHDL e);
-CCGEdgeHDL ccgSubSurf_getEdgeEdgeHandle (CCGSubSurf *ss, CCGEdge *e);
-int ccgSubSurf_getEdgeNumFaces (CCGSubSurf *ss, CCGEdge *e);
-CCGFace* ccgSubSurf_getEdgeFace (CCGSubSurf *ss, CCGEdge *e, int index);
-CCGVert* ccgSubSurf_getEdgeVert0 (CCGSubSurf *ss, CCGEdge *e);
-CCGVert* ccgSubSurf_getEdgeVert1 (CCGSubSurf *ss, CCGEdge *e);
-float ccgSubSurf_getEdgeCrease (CCGSubSurf *ss, CCGEdge *e);
+CCGEdgeHDL ccgSubSurf_getEdgeEdgeHandle (CCGEdge *e);
+int ccgSubSurf_getEdgeNumFaces (CCGEdge *e);
+CCGFace* ccgSubSurf_getEdgeFace (CCGEdge *e, int index);
+CCGVert* ccgSubSurf_getEdgeVert0 (CCGEdge *e);
+CCGVert* ccgSubSurf_getEdgeVert1 (CCGEdge *e);
+float ccgSubSurf_getEdgeCrease (CCGEdge *e);
int ccgSubSurf_getEdgeAge (CCGSubSurf *ss, CCGEdge *e);
void* ccgSubSurf_getEdgeUserData (CCGSubSurf *ss, CCGEdge *e);
@@ -109,14 +109,14 @@ void* ccgSubSurf_getEdgeLevelData (CCGSubSurf *ss, CCGEdge *e, int x, int lev
CCGFace* ccgSubSurf_getFace (CCGSubSurf *ss, CCGFaceHDL f);
CCGFaceHDL ccgSubSurf_getFaceFaceHandle (CCGSubSurf *ss, CCGFace *f);
-int ccgSubSurf_getFaceNumVerts (CCGSubSurf *ss, CCGFace *f);
+int ccgSubSurf_getFaceNumVerts (CCGFace *f);
CCGVert* ccgSubSurf_getFaceVert (CCGSubSurf *ss, CCGFace *f, int index);
CCGEdge* ccgSubSurf_getFaceEdge (CCGSubSurf *ss, CCGFace *f, int index);
-int ccgSubSurf_getFaceEdgeIndex (CCGSubSurf *ss, CCGFace *f, CCGEdge *e);
+int ccgSubSurf_getFaceEdgeIndex (CCGFace *f, CCGEdge *e);
int ccgSubSurf_getFaceAge (CCGSubSurf *ss, CCGFace *f);
void* ccgSubSurf_getFaceUserData (CCGSubSurf *ss, CCGFace *f);
-void* ccgSubSurf_getFaceCenterData (CCGSubSurf *ss, CCGFace *f);
+void* ccgSubSurf_getFaceCenterData (CCGFace *f);
void* ccgSubSurf_getFaceGridEdgeDataArray (CCGSubSurf *ss, CCGFace *f, int gridIndex);
void* ccgSubSurf_getFaceGridEdgeData (CCGSubSurf *ss, CCGFace *f, int gridIndex, int x);
void* ccgSubSurf_getFaceGridDataArray (CCGSubSurf *ss, CCGFace *f, int gridIndex);
diff --git a/source/blender/blenkernel/intern/DerivedMesh.c b/source/blender/blenkernel/intern/DerivedMesh.c
index 473c64f58f2..aab39a099bf 100644
--- a/source/blender/blenkernel/intern/DerivedMesh.c
+++ b/source/blender/blenkernel/intern/DerivedMesh.c
@@ -33,8 +33,6 @@
#include <config.h>
#endif
-#include <zlib.h>
-
#include "PIL_time.h"
#include "MEM_guardedalloc.h"
@@ -59,6 +57,7 @@
#include "BLI_edgehash.h"
#include "BLI_editVert.h"
#include "BLI_linklist.h"
+#include "BLI_memarena.h"
#include "BKE_cdderivedmesh.h"
#include "BKE_customdata.h"
@@ -66,17 +65,21 @@
#include "BKE_deform.h"
#include "BKE_displist.h"
#include "BKE_effect.h"
+#include "BKE_fluidsim.h"
#include "BKE_global.h"
#include "BKE_key.h"
#include "BKE_material.h"
#include "BKE_modifier.h"
#include "BKE_mesh.h"
+#include "BKE_multires.h"
#include "BKE_object.h"
#include "BKE_subsurf.h"
#include "BKE_texture.h"
#include "BKE_utildefines.h"
#include "BKE_particle.h"
+#include "BLO_sys_types.h" // for intptr_t support
+
#ifdef WITH_VERSE
#include "BKE_verse.h"
#endif
@@ -85,16 +88,15 @@
#include "BIF_glutil.h"
//XXX #include "multires.h"
-
-// headers for fluidsim bobj meshes
-#include <stdlib.h>
-#include "LBM_fluidsim.h"
-#include "elbeem.h"
+//
+#include "GPU_draw.h"
+#include "GPU_extensions.h"
+#include "GPU_material.h"
///////////////////////////////////
///////////////////////////////////
-MVert *dm_getVertArray(DerivedMesh *dm)
+static MVert *dm_getVertArray(DerivedMesh *dm)
{
MVert *mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
@@ -108,7 +110,7 @@ MVert *dm_getVertArray(DerivedMesh *dm)
return mvert;
}
-MEdge *dm_getEdgeArray(DerivedMesh *dm)
+static MEdge *dm_getEdgeArray(DerivedMesh *dm)
{
MEdge *medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
@@ -122,7 +124,7 @@ MEdge *dm_getEdgeArray(DerivedMesh *dm)
return medge;
}
-MFace *dm_getFaceArray(DerivedMesh *dm)
+static MFace *dm_getFaceArray(DerivedMesh *dm)
{
MFace *mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
@@ -136,7 +138,7 @@ MFace *dm_getFaceArray(DerivedMesh *dm)
return mface;
}
-MVert *dm_dupVertArray(DerivedMesh *dm)
+static MVert *dm_dupVertArray(DerivedMesh *dm)
{
MVert *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumVerts(dm),
"dm_dupVertArray tmp");
@@ -146,7 +148,7 @@ MVert *dm_dupVertArray(DerivedMesh *dm)
return tmp;
}
-MEdge *dm_dupEdgeArray(DerivedMesh *dm)
+static MEdge *dm_dupEdgeArray(DerivedMesh *dm)
{
MEdge *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumEdges(dm),
"dm_dupEdgeArray tmp");
@@ -156,7 +158,7 @@ MEdge *dm_dupEdgeArray(DerivedMesh *dm)
return tmp;
}
-MFace *dm_dupFaceArray(DerivedMesh *dm)
+static MFace *dm_dupFaceArray(DerivedMesh *dm)
{
MFace *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumFaces(dm),
"dm_dupFaceArray tmp");
@@ -187,10 +189,6 @@ void DM_init_funcs(DerivedMesh *dm)
void DM_init(DerivedMesh *dm,
int numVerts, int numEdges, int numFaces)
{
- CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, numVerts);
- CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
- CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, numFaces);
-
dm->numVertData = numVerts;
dm->numEdgeData = numEdges;
dm->numFaceData = numFaces;
@@ -413,39 +411,20 @@ void DM_swap_face_data(DerivedMesh *dm, int index, int *corner_indices)
CustomData_swap(&dm->faceData, index, corner_indices);
}
+///
+
static DerivedMesh *getMeshDerivedMesh(Mesh *me, Object *ob, float (*vertCos)[3])
{
DerivedMesh *dm = CDDM_from_mesh(me, ob);
- int i, dofluidsim;
-
- dofluidsim = ((ob->fluidsimFlag & OB_FLUIDSIM_ENABLE) &&
- (ob->fluidsimSettings->type & OB_FLUIDSIM_DOMAIN)&&
- (ob->fluidsimSettings->meshSurface) &&
- (1) && (!give_parteff(ob)) && // doesnt work together with particle systems!
- (me->totvert == ((Mesh *)(ob->fluidsimSettings->meshSurface))->totvert));
-
- if (vertCos && !dofluidsim)
+
+ if(!dm)
+ return NULL;
+
+ if (vertCos)
CDDM_apply_vert_coords(dm, vertCos);
CDDM_calc_normals(dm);
- /* apply fluidsim normals */
- if (dofluidsim) {
- // use normals from readBobjgz
- // TODO? check for modifiers!?
- MVert *fsvert = ob->fluidsimSettings->meshSurfNormals;
- short (*normals)[3] = MEM_mallocN(sizeof(short)*3*me->totvert, "fluidsim nor");
-
- for (i=0; i<me->totvert; i++) {
- VECCOPY(normals[i], fsvert[i].no);
- //mv->no[0]= 30000; mv->no[1]= mv->no[2]= 0; // DEBUG fixed test normals
- }
-
- CDDM_apply_vert_normals(dm, normals);
-
- MEM_freeN(normals);
- }
-
return dm;
}
@@ -484,7 +463,7 @@ static void emDM_foreachMappedEdge(DerivedMesh *dm, void (*func)(void *userData,
EditVert *eve;
for (i=0,eve=emdm->em->verts.first; eve; eve= eve->next)
- eve->tmp.l = (long) i++;
+ eve->tmp.l = (intptr_t) i++;
for(i=0,eed= emdm->em->edges.first; eed; i++,eed= eed->next)
func(userData, i, emdm->vertexCos[(int) eed->v1->tmp.l], emdm->vertexCos[(int) eed->v2->tmp.l]);
} else {
@@ -502,7 +481,7 @@ static void emDM_drawMappedEdges(DerivedMesh *dm, int (*setDrawOptions)(void *us
EditVert *eve;
for (i=0,eve=emdm->em->verts.first; eve; eve= eve->next)
- eve->tmp.l = (long) i++;
+ eve->tmp.l = (intptr_t) i++;
glBegin(GL_LINES);
for(i=0,eed= emdm->em->edges.first; eed; i++,eed= eed->next) {
@@ -537,7 +516,7 @@ static void emDM_drawMappedEdgesInterp(DerivedMesh *dm, int (*setDrawOptions)(vo
EditVert *eve;
for (i=0,eve=emdm->em->verts.first; eve; eve= eve->next)
- eve->tmp.l = (long) i++;
+ eve->tmp.l = (intptr_t) i++;
glBegin(GL_LINES);
for (i=0,eed= emdm->em->edges.first; eed; i++,eed= eed->next) {
@@ -624,7 +603,7 @@ static void emDM_foreachMappedFaceCenter(DerivedMesh *dm, void (*func)(void *use
if (emdm->vertexCos) {
for (i=0,eve=emdm->em->verts.first; eve; eve= eve->next)
- eve->tmp.l = (long) i++;
+ eve->tmp.l = (intptr_t) i++;
}
for(i=0,efa= emdm->em->faces.first; efa; i++,efa= efa->next) {
@@ -634,7 +613,6 @@ static void emDM_foreachMappedFaceCenter(DerivedMesh *dm, void (*func)(void *use
}
static void emDM_drawMappedFaces(DerivedMesh *dm, int (*setDrawOptions)(void *userData, int index, int *drawSmooth_r), void *userData, int useColors)
{
- GLubyte act_face_stipple[32*32/8] = DM_FACE_STIPPLE;
EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
EditFace *efa;
int i, draw;
@@ -643,7 +621,7 @@ static void emDM_drawMappedFaces(DerivedMesh *dm, int (*setDrawOptions)(void *us
EditVert *eve;
for (i=0,eve=emdm->em->verts.first; eve; eve= eve->next)
- eve->tmp.l = (long) i++;
+ eve->tmp.l = (intptr_t) i++;
for (i=0,efa= emdm->em->faces.first; efa; i++,efa= efa->next) {
int drawSmooth = (efa->flag & ME_SMOOTH);
@@ -651,7 +629,7 @@ static void emDM_drawMappedFaces(DerivedMesh *dm, int (*setDrawOptions)(void *us
if(draw) {
if (draw==2) { /* enabled with stipple */
glEnable(GL_POLYGON_STIPPLE);
- glPolygonStipple(act_face_stipple);
+ glPolygonStipple(0); //XXX stipple_quarttone);
}
glShadeModel(drawSmooth?GL_SMOOTH:GL_FLAT);
@@ -688,7 +666,7 @@ static void emDM_drawMappedFaces(DerivedMesh *dm, int (*setDrawOptions)(void *us
if(draw) {
if (draw==2) { /* enabled with stipple */
glEnable(GL_POLYGON_STIPPLE);
- glPolygonStipple(act_face_stipple);
+ glPolygonStipple(0); //XXX stipple_quarttone);
}
glShadeModel(drawSmooth?GL_SMOOTH:GL_FLAT);
@@ -732,11 +710,14 @@ static void emDM_drawFacesTex_common(DerivedMesh *dm,
EditFace *efa;
int i;
+ /* always use smooth shading even for flat faces, else vertex colors wont interpolate */
+ glShadeModel(GL_SMOOTH);
+
if (vertexCos) {
EditVert *eve;
for (i=0,eve=em->verts.first; eve; eve= eve->next)
- eve->tmp.l = (long) i++;
+ eve->tmp.l = (intptr_t) i++;
for (i=0,efa= em->faces.first; efa; i++,efa= efa->next) {
MTFace *tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
@@ -753,11 +734,16 @@ static void emDM_drawFacesTex_common(DerivedMesh *dm,
flag= 1;
if(flag != 0) { /* flag 0 == the face is hidden or invisible */
- if (flag==1 && mcol)
- cp= (unsigned char*)mcol;
-
- glShadeModel(drawSmooth?GL_SMOOTH:GL_FLAT);
-
+
+ /* we always want smooth here since otherwise vertex colors dont interpolate */
+ if (mcol) {
+ if (flag==1) {
+ cp= (unsigned char*)mcol;
+ }
+ } else {
+ glShadeModel(drawSmooth?GL_SMOOTH:GL_FLAT);
+ }
+
glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
if (!drawSmooth) {
glNormal3fv(emdm->faceNos[i]);
@@ -821,10 +807,14 @@ static void emDM_drawFacesTex_common(DerivedMesh *dm,
flag= 1;
if(flag != 0) { /* flag 0 == the face is hidden or invisible */
- if (flag==1 && mcol)
- cp= (unsigned char*)mcol;
-
- glShadeModel(drawSmooth?GL_SMOOTH:GL_FLAT);
+ /* we always want smooth here since otherwise vertex colors dont interpolate */
+ if (mcol) {
+ if (flag==1) {
+ cp= (unsigned char*)mcol;
+ }
+ } else {
+ glShadeModel(drawSmooth?GL_SMOOTH:GL_FLAT);
+ }
glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
if (!drawSmooth) {
@@ -886,6 +876,162 @@ static void emDM_drawMappedFacesTex(DerivedMesh *dm, int (*setDrawOptions)(void
emDM_drawFacesTex_common(dm, NULL, setDrawOptions, userData);
}
+static void emDM_drawMappedFacesGLSL(DerivedMesh *dm,
+ int (*setMaterial)(int, void *attribs),
+ int (*setDrawOptions)(void *userData, int index), void *userData)
+{
+ EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
+ EditMesh *em= emdm->em;
+ float (*vertexCos)[3]= emdm->vertexCos;
+ float (*vertexNos)[3]= emdm->vertexNos;
+ EditVert *eve;
+ EditFace *efa;
+ DMVertexAttribs attribs;
+ GPUVertexAttribs gattribs;
+ MTFace *tf;
+ int transp, new_transp, orig_transp, tfoffset;
+ int i, b, matnr, new_matnr, dodraw, layer;
+
+ dodraw = 0;
+ matnr = -1;
+
+ transp = GPU_get_material_blend_mode();
+ orig_transp = transp;
+ layer = CustomData_get_layer_index(&em->fdata, CD_MTFACE);
+ tfoffset = (layer == -1)? -1: em->fdata.layers[layer].offset;
+
+ memset(&attribs, 0, sizeof(attribs));
+
+ /* always use smooth shading even for flat faces, else vertex colors wont interpolate */
+ glShadeModel(GL_SMOOTH);
+
+ for (i=0,eve=em->verts.first; eve; eve= eve->next)
+ eve->tmp.l = (long) i++;
+
+#define PASSATTRIB(efa, eve, vert) { \
+ if(attribs.totorco) { \
+ float *orco = attribs.orco.array[eve->tmp.l]; \
+ glVertexAttrib3fvARB(attribs.orco.glIndex, orco); \
+ } \
+ for(b = 0; b < attribs.tottface; b++) { \
+ MTFace *_tf = (MTFace*)((char*)efa->data + attribs.tface[b].emOffset); \
+ glVertexAttrib2fvARB(attribs.tface[b].glIndex, _tf->uv[vert]); \
+ } \
+ for(b = 0; b < attribs.totmcol; b++) { \
+ MCol *cp = (MCol*)((char*)efa->data + attribs.mcol[b].emOffset); \
+ GLubyte col[4]; \
+ col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a; \
+ glVertexAttrib4ubvARB(attribs.mcol[b].glIndex, col); \
+ } \
+ if(attribs.tottang) { \
+ float *tang = attribs.tang.array[i*4 + vert]; \
+ glVertexAttrib3fvARB(attribs.tang.glIndex, tang); \
+ } \
+}
+
+ for (i=0,efa= em->faces.first; efa; i++,efa= efa->next) {
+ int drawSmooth= (efa->flag & ME_SMOOTH);
+
+ if(setDrawOptions && !setDrawOptions(userData, i))
+ continue;
+
+ new_matnr = efa->mat_nr + 1;
+ if(new_matnr != matnr) {
+ dodraw = setMaterial(matnr = new_matnr, &gattribs);
+ if(dodraw)
+ DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
+ }
+
+ if(tfoffset != -1) {
+ tf = (MTFace*)((char*)efa->data)+tfoffset;
+ new_transp = tf->transp;
+
+ if(new_transp != transp) {
+ if(new_transp == GPU_BLEND_SOLID && orig_transp != GPU_BLEND_SOLID)
+ GPU_set_material_blend_mode(orig_transp);
+ else
+ GPU_set_material_blend_mode(new_transp);
+ transp = new_transp;
+ }
+ }
+
+ if(dodraw) {
+ glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
+ if (!drawSmooth) {
+ if(vertexCos) glNormal3fv(emdm->faceNos[i]);
+ else glNormal3fv(efa->n);
+
+ PASSATTRIB(efa, efa->v1, 0);
+ if(vertexCos) glVertex3fv(vertexCos[(int) efa->v1->tmp.l]);
+ else glVertex3fv(efa->v1->co);
+
+ PASSATTRIB(efa, efa->v2, 1);
+ if(vertexCos) glVertex3fv(vertexCos[(int) efa->v2->tmp.l]);
+ else glVertex3fv(efa->v2->co);
+
+ PASSATTRIB(efa, efa->v3, 2);
+ if(vertexCos) glVertex3fv(vertexCos[(int) efa->v3->tmp.l]);
+ else glVertex3fv(efa->v3->co);
+
+ if(efa->v4) {
+ PASSATTRIB(efa, efa->v4, 3);
+ if(vertexCos) glVertex3fv(vertexCos[(int) efa->v4->tmp.l]);
+ else glVertex3fv(efa->v4->co);
+ }
+ } else {
+ PASSATTRIB(efa, efa->v1, 0);
+ if(vertexCos) {
+ glNormal3fv(vertexNos[(int) efa->v1->tmp.l]);
+ glVertex3fv(vertexCos[(int) efa->v1->tmp.l]);
+ }
+ else {
+ glNormal3fv(efa->v1->no);
+ glVertex3fv(efa->v1->co);
+ }
+
+ PASSATTRIB(efa, efa->v2, 1);
+ if(vertexCos) {
+ glNormal3fv(vertexNos[(int) efa->v2->tmp.l]);
+ glVertex3fv(vertexCos[(int) efa->v2->tmp.l]);
+ }
+ else {
+ glNormal3fv(efa->v2->no);
+ glVertex3fv(efa->v2->co);
+ }
+
+ PASSATTRIB(efa, efa->v3, 2);
+ if(vertexCos) {
+ glNormal3fv(vertexNos[(int) efa->v3->tmp.l]);
+ glVertex3fv(vertexCos[(int) efa->v3->tmp.l]);
+ }
+ else {
+ glNormal3fv(efa->v3->no);
+ glVertex3fv(efa->v3->co);
+ }
+
+ if(efa->v4) {
+ PASSATTRIB(efa, efa->v4, 3);
+ if(vertexCos) {
+ glNormal3fv(vertexNos[(int) efa->v4->tmp.l]);
+ glVertex3fv(vertexCos[(int) efa->v4->tmp.l]);
+ }
+ else {
+ glNormal3fv(efa->v4->no);
+ glVertex3fv(efa->v4->co);
+ }
+ }
+ }
+ glEnd();
+ }
+ }
+}
+
+static void emDM_drawFacesGLSL(DerivedMesh *dm,
+ int (*setMaterial)(int, void *attribs))
+{
+ dm->drawMappedFacesGLSL(dm, setMaterial, NULL, NULL);
+}
+
static void emDM_getMinMax(DerivedMesh *dm, float min_r[3], float max_r[3])
{
EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
@@ -925,7 +1071,7 @@ static int emDM_getNumFaces(DerivedMesh *dm)
return BLI_countlist(&emdm->em->faces);
}
-void emDM_getVert(DerivedMesh *dm, int index, MVert *vert_r)
+static void emDM_getVert(DerivedMesh *dm, int index, MVert *vert_r)
{
EditVert *ev = ((EditMeshDerivedMesh *)dm)->em->verts.first;
int i;
@@ -940,9 +1086,10 @@ void emDM_getVert(DerivedMesh *dm, int index, MVert *vert_r)
/* TODO what to do with vert_r->flag and vert_r->mat_nr? */
vert_r->mat_nr = 0;
+ vert_r->bweight = (unsigned char) (ev->bweight*255.0f);
}
-void emDM_getEdge(DerivedMesh *dm, int index, MEdge *edge_r)
+static void emDM_getEdge(DerivedMesh *dm, int index, MEdge *edge_r)
{
EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
EditEdge *ee = em->edges.first;
@@ -952,6 +1099,7 @@ void emDM_getEdge(DerivedMesh *dm, int index, MEdge *edge_r)
for(i = 0; i < index; ++i) ee = ee->next;
edge_r->crease = (unsigned char) (ee->crease*255.0f);
+ edge_r->bweight = (unsigned char) (ee->bweight*255.0f);
/* TODO what to do with edge_r->flag? */
edge_r->flag = ME_EDGEDRAW|ME_EDGERENDER;
if (ee->seam) edge_r->flag |= ME_SEAM;
@@ -976,7 +1124,7 @@ void emDM_getEdge(DerivedMesh *dm, int index, MEdge *edge_r)
}
}
-void emDM_getFace(DerivedMesh *dm, int index, MFace *face_r)
+static void emDM_getFace(DerivedMesh *dm, int index, MFace *face_r)
{
EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
EditFace *ef = em->faces.first;
@@ -1018,7 +1166,7 @@ void emDM_getFace(DerivedMesh *dm, int index, MFace *face_r)
test_index_face(face_r, NULL, 0, ef->v4?4:3);
}
-void emDM_copyVertArray(DerivedMesh *dm, MVert *vert_r)
+static void emDM_copyVertArray(DerivedMesh *dm, MVert *vert_r)
{
EditVert *ev = ((EditMeshDerivedMesh *)dm)->em->verts.first;
@@ -1032,10 +1180,11 @@ void emDM_copyVertArray(DerivedMesh *dm, MVert *vert_r)
/* TODO what to do with vert_r->flag and vert_r->mat_nr? */
vert_r->mat_nr = 0;
vert_r->flag = 0;
+ vert_r->bweight = (unsigned char) (ev->bweight*255.0f);
}
}
-void emDM_copyEdgeArray(DerivedMesh *dm, MEdge *edge_r)
+static void emDM_copyEdgeArray(DerivedMesh *dm, MEdge *edge_r)
{
EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
EditEdge *ee = em->edges.first;
@@ -1044,10 +1193,11 @@ void emDM_copyEdgeArray(DerivedMesh *dm, MEdge *edge_r)
/* store vertex indices in tmp union */
for(ev = em->verts.first, i = 0; ev; ev = ev->next, ++i)
- ev->tmp.l = (long) i++;
+ ev->tmp.l = (intptr_t) i;
for( ; ee; ee = ee->next, ++edge_r) {
edge_r->crease = (unsigned char) (ee->crease*255.0f);
+ edge_r->bweight = (unsigned char) (ee->bweight*255.0f);
/* TODO what to do with edge_r->flag? */
edge_r->flag = ME_EDGEDRAW|ME_EDGERENDER;
if (ee->seam) edge_r->flag |= ME_SEAM;
@@ -1062,7 +1212,7 @@ void emDM_copyEdgeArray(DerivedMesh *dm, MEdge *edge_r)
}
}
-void emDM_copyFaceArray(DerivedMesh *dm, MFace *face_r)
+static void emDM_copyFaceArray(DerivedMesh *dm, MFace *face_r)
{
EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
EditFace *ef = em->faces.first;
@@ -1071,7 +1221,7 @@ void emDM_copyFaceArray(DerivedMesh *dm, MFace *face_r)
/* store vertexes indices in tmp union */
for(ev = em->verts.first, i = 0; ev; ev = ev->next, ++i)
- ev->tmp.l = (long) i;
+ ev->tmp.l = (intptr_t) i;
for( ; ef; ef = ef->next, ++face_r) {
face_r->mat_nr = ef->mat_nr;
@@ -1087,6 +1237,43 @@ void emDM_copyFaceArray(DerivedMesh *dm, MFace *face_r)
}
}
+static void *emDM_getFaceDataArray(DerivedMesh *dm, int type)
+{
+ EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
+ EditMesh *em= emdm->em;
+ EditFace *efa;
+ char *data, *emdata;
+ void *datalayer;
+ int index, offset, size;
+
+ datalayer = DM_get_face_data_layer(dm, type);
+ if(datalayer)
+ return datalayer;
+
+ /* layers are store per face for editmesh, we convert to a temporary
+ * data layer array in the derivedmesh when these are requested */
+ if(type == CD_MTFACE || type == CD_MCOL) {
+ index = CustomData_get_layer_index(&em->fdata, type);
+
+ if(index != -1) {
+ offset = em->fdata.layers[index].offset;
+ size = CustomData_sizeof(type);
+
+ DM_add_face_layer(dm, type, CD_CALLOC, NULL);
+ index = CustomData_get_layer_index(&dm->faceData, type);
+ dm->faceData.layers[index].flag |= CD_FLAG_TEMPORARY;
+
+ data = datalayer = DM_get_face_data_layer(dm, type);
+ for(efa=em->faces.first; efa; efa=efa->next, data+=size) {
+ emdata = CustomData_em_get(&em->fdata, efa->data, type);
+ memcpy(data, emdata, size);
+ }
+ }
+ }
+
+ return datalayer;
+}
+
static void emDM_release(DerivedMesh *dm)
{
EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
@@ -1122,6 +1309,7 @@ static DerivedMesh *getEditMeshDerivedMesh(EditMesh *em, Object *ob,
emdm->dm.copyVertArray = emDM_copyVertArray;
emdm->dm.copyEdgeArray = emDM_copyEdgeArray;
emdm->dm.copyFaceArray = emDM_copyFaceArray;
+ emdm->dm.getFaceDataArray = emDM_getFaceDataArray;
emdm->dm.foreachMappedVert = emDM_foreachMappedVert;
emdm->dm.foreachMappedEdge = emDM_foreachMappedEdge;
@@ -1132,7 +1320,9 @@ static DerivedMesh *getEditMeshDerivedMesh(EditMesh *em, Object *ob,
emdm->dm.drawMappedEdgesInterp = emDM_drawMappedEdgesInterp;
emdm->dm.drawMappedFaces = emDM_drawMappedFaces;
emdm->dm.drawMappedFacesTex = emDM_drawMappedFacesTex;
+ emdm->dm.drawMappedFacesGLSL = emDM_drawMappedFacesGLSL;
emdm->dm.drawFacesTex = emDM_drawFacesTex;
+ emdm->dm.drawFacesGLSL = emDM_drawFacesGLSL;
emdm->dm.drawUVEdges = emDM_drawUVEdges;
emdm->dm.release = emDM_release;
@@ -1158,7 +1348,7 @@ static DerivedMesh *getEditMeshDerivedMesh(EditMesh *em, Object *ob,
int i;
for (i=0,eve=em->verts.first; eve; eve= eve->next)
- eve->tmp.l = (long) i++;
+ eve->tmp.l = (intptr_t) i++;
emdm->vertexNos = MEM_callocN(sizeof(*emdm->vertexNos)*i, "emdm_vno");
emdm->faceNos = MEM_mallocN(sizeof(*emdm->faceNos)*totface, "emdm_vno");
@@ -1316,6 +1506,7 @@ void vDM_getEdge(DerivedMesh *dm, int index, MEdge *edge_r)
/* not supported yet */
edge_r->flag = 0;
edge_r->crease = 0;
+ edge_r->bweight = 0;
break;
}
}
@@ -1422,6 +1613,7 @@ void vDM_copyEdgeArray(DerivedMesh *dm, MEdge *edge_r)
/* not supported yet */
edge_r->flag = 0;
edge_r->crease = 0;
+ edge_r->bweight = 0;
}
}
}
@@ -1560,7 +1752,7 @@ static void vDM_drawUVEdges(DerivedMesh *dm)
}
/* draw all VerseFaces */
-static void vDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int))
+static void vDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int, void *attribs))
{
VDerivedMesh *vdm = (VDerivedMesh*)dm;
struct VerseFace *vface;
@@ -1660,6 +1852,8 @@ static void vDM_drawMappedFacesTex(
int (*setDrawParams)(void *userData, int index),
void *userData)
{
+ /* not supported yet */
+ vDM_drawFacesTex(dm, NULL);
}
/**/
@@ -1801,19 +1995,23 @@ CustomDataMask get_viewedit_datamask()
ScrArea *sa;
/* check if we need tfaces & mcols due to face select or texture paint */
- if(FACESEL_PAINT_TEST || G.f & G_TEXTUREPAINT) {
+ if(FACESEL_PAINT_TEST || G.f & G_TEXTUREPAINT)
mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
- } else {
- /* check if we need tfaces & mcols due to view mode */
- for(sa = G.curscreen->areabase.first; sa; sa = sa->next) {
- if(sa->spacetype == SPACE_VIEW3D) {
- View3D *view = sa->spacedata.first;
- if(view->drawtype == OB_SHADED) {
- /* this includes normals for mesh_create_shadedColors */
- mask |= CD_MASK_MTFACE | CD_MASK_MCOL | CD_MASK_NORMAL | CD_MASK_ORCO;
- }
- if((view->drawtype == OB_TEXTURE) || ((view->drawtype == OB_SOLID) && (view->flag2 & V3D_SOLID_TEX))) {
- mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
+
+ /* check if we need tfaces & mcols due to view mode */
+ for(sa = G.curscreen->areabase.first; sa; sa = sa->next) {
+ if(sa->spacetype == SPACE_VIEW3D) {
+ View3D *view = sa->spacedata.first;
+ if(view->drawtype == OB_SHADED) {
+ /* this includes normals for mesh_create_shadedColors */
+ mask |= CD_MASK_MTFACE | CD_MASK_MCOL | CD_MASK_NORMAL | CD_MASK_ORCO;
+ }
+ if((view->drawtype == OB_TEXTURE) || ((view->drawtype == OB_SOLID) && (view->flag2 & V3D_SOLID_TEX))) {
+ mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
+
+ if((G.fileflags & G_FILE_GAME_MAT) &&
+ (G.fileflags & G_FILE_GAME_MAT_GLSL)) {
+ mask |= CD_MASK_ORCO;
}
}
}
@@ -1826,13 +2024,41 @@ CustomDataMask get_viewedit_datamask()
return mask;
}
-static DerivedMesh *create_orco_dm(Object *ob, Mesh *me)
+static float *get_editmesh_orco_verts(EditMesh *em)
+{
+ EditVert *eve;
+ float *orco;
+ int a, totvert;
+
+ /* these may not really be the orco's, but it's only for preview.
+ * could be solver better once, but isn't simple */
+
+ totvert= 0;
+ for(eve=em->verts.first; eve; eve=eve->next)
+ totvert++;
+
+ orco = MEM_mallocN(sizeof(float)*3*totvert, "EditMesh Orco");
+
+ for(a=0, eve=em->verts.first; eve; eve=eve->next, a+=3)
+ VECCOPY(orco+a, eve->co);
+
+ return orco;
+}
+
+static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, EditMesh *em)
{
DerivedMesh *dm;
float (*orco)[3];
- dm= CDDM_from_mesh(me, ob);
- orco= (float(*)[3])get_mesh_orco_verts(ob);
+ if(em) {
+ dm= CDDM_from_editmesh(em, me);
+ orco= (float(*)[3])get_editmesh_orco_verts(em);
+ }
+ else {
+ dm= CDDM_from_mesh(me, ob);
+ orco= (float(*)[3])get_mesh_orco_verts(ob);
+ }
+
CDDM_apply_vert_coords(dm, orco);
CDDM_calc_normals(dm);
MEM_freeN(orco);
@@ -1840,7 +2066,7 @@ static DerivedMesh *create_orco_dm(Object *ob, Mesh *me)
return dm;
}
-static void add_orco_dm(Object *ob, DerivedMesh *dm, DerivedMesh *orcodm)
+static void add_orco_dm(Object *ob, EditMesh *em, DerivedMesh *dm, DerivedMesh *orcodm)
{
float (*orco)[3], (*layerorco)[3];
int totvert;
@@ -1855,8 +2081,10 @@ static void add_orco_dm(Object *ob, DerivedMesh *dm, DerivedMesh *orcodm)
else
dm->getVertCos(dm, orco);
}
- else
- orco= (float(*)[3])get_mesh_orco_verts(ob);
+ else {
+ if(em) orco= (float(*)[3])get_editmesh_orco_verts(em);
+ else orco= (float(*)[3])get_mesh_orco_verts(ob);
+ }
transform_mesh_orco_verts(ob->data, orco, totvert, 0);
@@ -1871,7 +2099,7 @@ static void add_orco_dm(Object *ob, DerivedMesh *dm, DerivedMesh *orcodm)
static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
DerivedMesh **deform_r, DerivedMesh **final_r,
int useRenderParams, int useDeform,
- int needMapping, CustomDataMask dataMask)
+ int needMapping, CustomDataMask dataMask, int index)
{
Mesh *me = ob->data;
ModifierData *firstmd, *md;
@@ -1880,7 +2108,6 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
float (*deformedVerts)[3] = NULL;
DerivedMesh *dm, *orcodm, *finaldm;
int numVerts = me->totvert;
- int fluidsimMeshUsed = 0;
int required_mode;
md = firstmd = modifiers_getVirtualModifierList(ob);
@@ -1896,22 +2123,6 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
if(deform_r) *deform_r = NULL;
*final_r = NULL;
- /* replace original mesh by fluidsim surface mesh for fluidsim
- * domain objects
- */
- if((G.obedit!=ob) && !needMapping) {
- if((ob->fluidsimFlag & OB_FLUIDSIM_ENABLE) &&
- (1) && (!give_parteff(ob)) ) { // doesnt work together with particle systems!
- if(ob->fluidsimSettings->type & OB_FLUIDSIM_DOMAIN) {
- loadFluidsimMesh(ob,useRenderParams);
- fluidsimMeshUsed = 1;
- /* might have changed... */
- me = ob->data;
- numVerts = me->totvert;
- }
- }
- }
-
if(useRenderParams) required_mode = eModifierMode_Render;
else required_mode = eModifierMode_Realtime;
@@ -1920,7 +2131,7 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
deformedVerts = mesh_getVertexCos(me, &numVerts);
/* Apply all leading deforming modifiers */
- for(; md; md = md->next, curr = curr->next) {
+ for(;md; md = md->next, curr = curr->next) {
ModifierTypeInfo *mti = modifierType_getInfo(md->type);
if((md->mode & required_mode) != required_mode) continue;
@@ -1934,6 +2145,10 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
} else {
break;
}
+
+ /* grab modifiers until index i */
+ if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
+ break;
}
/* Result of all leading deforming modifiers is cached for
@@ -1959,18 +2174,11 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
#endif
}
} else {
- if(!fluidsimMeshUsed) {
- /* default behaviour for meshes */
- if(inputVertexCos)
- deformedVerts = inputVertexCos;
- else
- deformedVerts = mesh_getRefKeyCos(me, &numVerts);
- } else {
- /* the fluid sim mesh might have more vertices than the original
- * one, so inputVertexCos shouldnt be used
- */
- deformedVerts = mesh_getVertexCos(me, &numVerts);
- }
+ /* default behaviour for meshes */
+ if(inputVertexCos)
+ deformedVerts = inputVertexCos;
+ else
+ deformedVerts = mesh_getRefKeyCos(me, &numVerts);
}
@@ -1987,14 +2195,13 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
if(me->vnode) dm = derivedmesh_from_versemesh(me->vnode, deformedVerts);
#endif
- for(; md; md = md->next, curr = curr->next) {
+ for(;md; md = md->next, curr = curr->next) {
ModifierTypeInfo *mti = modifierType_getInfo(md->type);
if((md->mode & required_mode) != required_mode) continue;
if(mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue;
if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
- modifier_setError(md, "Internal error, modifier requires "
- "original data (bad stack position).");
+ modifier_setError(md, "Modifier requires original data, bad stack position.");
continue;
}
if(mti->isDisabled && mti->isDisabled(md)) continue;
@@ -2004,7 +2211,7 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
if(dm && mti->requiredDataMask) {
mask = mti->requiredDataMask(md);
if(mask & CD_MASK_ORCO)
- add_orco_dm(ob, dm, orcodm);
+ add_orco_dm(ob, NULL, dm, orcodm);
}
/* How to apply modifier depends on (a) what we already have as
@@ -2057,7 +2264,7 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
mask= (CustomDataMask)curr->link;
if(mask & CD_MASK_ORCO) {
if(!orcodm)
- orcodm= create_orco_dm(ob, me);
+ orcodm= create_orco_dm(ob, me, NULL);
mask &= ~CD_MASK_ORCO;
DM_set_only_copy(orcodm, mask);
@@ -2094,6 +2301,10 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
}
}
}
+
+ /* grab modifiers until index i */
+ if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
+ break;
}
for(md=firstmd; md; md=md->next)
@@ -2133,8 +2344,12 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
}
/* add an orco layer if needed */
- if(dataMask & CD_MASK_ORCO)
- add_orco_dm(ob, finaldm, orcodm);
+ if(dataMask & CD_MASK_ORCO) {
+ add_orco_dm(ob, NULL, finaldm, orcodm);
+
+ if(deform_r && *deform_r)
+ add_orco_dm(ob, NULL, *deform_r, NULL);
+ }
*final_r = finaldm;
@@ -2145,9 +2360,6 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
MEM_freeN(deformedVerts);
BLI_linklist_free(datamasks, NULL);
-
- /* restore mesh in any case */
- if(fluidsimMeshUsed) ob->data = ob->fluidsimSettings->orgMesh;
}
static float (*editmesh_getVertexCos(EditMesh *em, int *numVerts_r))[3]
@@ -2171,8 +2383,7 @@ static int editmesh_modifier_is_enabled(ModifierData *md, DerivedMesh *dm)
if((md->mode & required_mode) != required_mode) return 0;
if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
- modifier_setError(md, "Internal error, modifier requires"
- "original data (bad stack position).");
+ modifier_setError(md, "Modifier requires original data, bad stack position.");
return 0;
}
if(mti->isDisabled && mti->isDisabled(md)) return 0;
@@ -2190,7 +2401,8 @@ static void editmesh_calc_modifiers(DerivedMesh **cage_r,
EditMesh *em = G.editMesh;
ModifierData *md;
float (*deformedVerts)[3] = NULL;
- DerivedMesh *dm;
+ CustomDataMask mask;
+ DerivedMesh *dm, *orcodm = NULL;
int i, numVerts = 0, cageIndex = modifiers_getCageIndex(ob, NULL);
LinkNode *datamasks, *curr;
@@ -2215,6 +2427,13 @@ static void editmesh_calc_modifiers(DerivedMesh **cage_r,
if(!editmesh_modifier_is_enabled(md, dm))
continue;
+ /* add an orco layer if needed by this modifier */
+ if(dm && mti->requiredDataMask) {
+ mask = mti->requiredDataMask(md);
+ if(mask & CD_MASK_ORCO)
+ add_orco_dm(ob, em, dm, orcodm);
+ }
+
/* How to apply modifier depends on (a) what we already have as
* a result of previous modifiers (could be a DerivedMesh or just
* deformed vertices) and (b) what type the modifier is.
@@ -2265,6 +2484,23 @@ static void editmesh_calc_modifiers(DerivedMesh **cage_r,
}
}
+ /* create an orco derivedmesh in parallel */
+ mask= (CustomDataMask)curr->link;
+ if(mask & CD_MASK_ORCO) {
+ if(!orcodm)
+ orcodm= create_orco_dm(ob, ob->data, em);
+
+ mask &= ~CD_MASK_ORCO;
+ DM_set_only_copy(orcodm, mask);
+ ndm = mti->applyModifierEM(md, ob, em, orcodm);
+
+ if(ndm) {
+ /* if the modifier returned a new dm, release the old one */
+ if(orcodm && orcodm != ndm) orcodm->release(orcodm);
+ orcodm = ndm;
+ }
+ }
+
/* set the DerivedMesh to only copy needed data */
DM_set_only_copy(dm, (CustomDataMask)curr->link);
@@ -2323,6 +2559,13 @@ static void editmesh_calc_modifiers(DerivedMesh **cage_r,
deformedVerts = NULL;
}
+ /* add an orco layer if needed */
+ if(dataMask & CD_MASK_ORCO)
+ add_orco_dm(ob, em, *final_r, orcodm);
+
+ if(orcodm)
+ orcodm->release(orcodm);
+
if(deformedVerts)
MEM_freeN(deformedVerts);
}
@@ -2460,21 +2703,26 @@ static void mesh_build_data(Object *ob, CustomDataMask dataMask)
if( (G.f & G_WEIGHTPAINT) && ob==obact ) {
MCol *wpcol = (MCol*)calc_weightpaint_colors(ob);
int layernum = CustomData_number_of_layers(&me->fdata, CD_MCOL);
+ int prevactive = CustomData_get_active_layer(&me->fdata, CD_MCOL);
+ int prevrender = CustomData_get_render_layer(&me->fdata, CD_MCOL);
/* ugly hack here, we temporarily add a new active mcol layer with
weightpaint colors in it, that is then duplicated in CDDM_from_mesh */
CustomData_add_layer(&me->fdata, CD_MCOL, CD_ASSIGN, wpcol, me->totface);
CustomData_set_layer_active(&me->fdata, CD_MCOL, layernum);
+ CustomData_set_layer_render(&me->fdata, CD_MCOL, layernum);
mesh_calc_modifiers(ob, NULL, &ob->derivedDeform,
&ob->derivedFinal, 0, 1,
- needMapping, dataMask);
+ needMapping, dataMask, -1);
CustomData_free_layer_active(&me->fdata, CD_MCOL, me->totface);
+ CustomData_set_layer_active(&me->fdata, CD_MCOL, prevactive);
+ CustomData_set_layer_render(&me->fdata, CD_MCOL, prevrender);
} else {
mesh_calc_modifiers(ob, NULL, &ob->derivedDeform,
- &ob->derivedFinal, 0, 1,
- needMapping, dataMask);
+ &ob->derivedFinal, G.rendering, 1,
+ needMapping, dataMask, -1);
}
INIT_MINMAX(min, max);
@@ -2532,14 +2780,7 @@ void makeDerivedMesh(Object *ob, CustomDataMask dataMask)
if (ob==G.obedit) {
editmesh_build_data(dataMask);
} else {
- PartEff *paf= give_parteff(ob);
-
mesh_build_data(ob, dataMask);
-
- if(paf) {
- if((paf->flag & PAF_STATIC) || (ob->recalc & OB_RECALC_TIME)==0)
- build_particle_system(ob);
- }
}
}
@@ -2572,7 +2813,7 @@ float *multires_render_pin(Object *ob, Mesh *me, int *orig_lvl)
{
float *vert_copy= NULL;
- if(me->mr) {
+ if(me->mr && !(me->mr->flag & MULTIRES_NO_RENDER)) {
MultiresLevel *lvl= NULL;
int i;
@@ -2598,16 +2839,22 @@ float *multires_render_pin(Object *ob, Mesh *me, int *orig_lvl)
void multires_render_final(Object *ob, Mesh *me, DerivedMesh **dm, float *vert_copy,
const int orig_lvl, CustomDataMask dataMask)
{
- if(me->mr) {
+ if(me->mr && !(me->mr->flag & MULTIRES_NO_RENDER)) {
if((*dm)->getNumVerts(*dm) == me->totvert &&
(*dm)->getNumFaces(*dm) == me->totface) {
//XXX MultiresLevel *lvl= multires_level_n(me->mr, BLI_countlist(&me->mr->levels));
DerivedMesh *old= NULL;
+ MVert *vertdup= NULL;
int i;
- (*dm)->copyVertArray(*dm, me->mvert);
+ /* Copy the verts into the mesh */
+ vertdup= (*dm)->dupVertArray(*dm);
(*dm)->release(*dm);
-
+ for(i=0; i<me->totvert; ++i)
+ me->mvert[i]= vertdup[i];
+ /* Free vertdup after use*/
+ MEM_freeN(vertdup);
+ /* Go to the render level */
me->mr->newlvl= me->mr->renderlvl;
//XXX multires_set_level(ob, me, 1);
(*dm)= getMeshDerivedMesh(me, ob, NULL);
@@ -2618,7 +2865,7 @@ void multires_render_final(Object *ob, Mesh *me, DerivedMesh **dm, float *vert_c
old->release(old);
if(dataMask & CD_MASK_ORCO)
- add_orco_dm(ob, *dm, NULL);
+ add_orco_dm(ob, NULL, *dm, NULL);
/* Restore the original verts */
me->mr->newlvl= BLI_countlist(&me->mr->levels);
@@ -2646,7 +2893,21 @@ DerivedMesh *mesh_create_derived_render(Object *ob, CustomDataMask dataMask)
int orig_lvl= 0;
vert_copy= multires_render_pin(ob, me, &orig_lvl);
- mesh_calc_modifiers(ob, NULL, NULL, &final, 1, 1, 0, dataMask);
+ mesh_calc_modifiers(ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1);
+ multires_render_final(ob, me, &final, vert_copy, orig_lvl, dataMask);
+
+ return final;
+}
+
+DerivedMesh *mesh_create_derived_index_render(Object *ob, CustomDataMask dataMask, int index)
+{
+ DerivedMesh *final;
+ Mesh *me= get_mesh(ob);
+ float *vert_copy= NULL;
+ int orig_lvl= 0;
+
+ vert_copy= multires_render_pin(ob, me, &orig_lvl);
+ mesh_calc_modifiers(ob, NULL, NULL, &final, 1, 1, 0, dataMask, index);
multires_render_final(ob, me, &final, vert_copy, orig_lvl, dataMask);
return final;
@@ -2656,7 +2917,7 @@ DerivedMesh *mesh_create_derived_view(Object *ob, CustomDataMask dataMask)
{
DerivedMesh *final;
- mesh_calc_modifiers(ob, NULL, NULL, &final, 0, 1, 0, dataMask);
+ mesh_calc_modifiers(ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1);
return final;
}
@@ -2666,7 +2927,7 @@ DerivedMesh *mesh_create_derived_no_deform(Object *ob, float (*vertCos)[3],
{
DerivedMesh *final;
- mesh_calc_modifiers(ob, vertCos, NULL, &final, 0, 0, 0, dataMask);
+ mesh_calc_modifiers(ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1);
return final;
}
@@ -2681,7 +2942,7 @@ DerivedMesh *mesh_create_derived_no_deform_render(Object *ob,
int orig_lvl= 0;
vert_copy= multires_render_pin(ob, me, &orig_lvl);
- mesh_calc_modifiers(ob, vertCos, NULL, &final, 1, 0, 0, dataMask);
+ mesh_calc_modifiers(ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1);
multires_render_final(ob, me, &final, vert_copy, orig_lvl, dataMask);
return final;
@@ -2833,580 +3094,211 @@ int editmesh_get_first_deform_matrices(float (**deformmats)[3][3], float (**defo
return numleft;
}
-/* ************************* fluidsim bobj file handling **************************** */
-
-#ifndef DISABLE_ELBEEM
-
-#ifdef WIN32
-#ifndef snprintf
-#define snprintf _snprintf
-#endif
-#endif
+/* ******************* GLSL ******************** */
-/* write .bobj.gz file for a mesh object */
-void writeBobjgz(char *filename, struct Object *ob, int useGlobalCoords, int append, float time)
+void DM_add_tangent_layer(DerivedMesh *dm)
{
- char debugStrBuffer[256];
- int wri,i,j,totvert,totface;
- float wrf;
- gzFile gzf;
- DerivedMesh *dm;
- float vec[3];
- float rotmat[3][3];
- MVert *mvert;
- MFace *mface;
- //if(append)return; // DEBUG
-
- if(!ob->data || (ob->type!=OB_MESH)) {
- snprintf(debugStrBuffer,256,"Writing GZ_BOBJ Invalid object %s ...\n", ob->id.name);
- elbeemDebugOut(debugStrBuffer);
- return;
- }
- if((ob->size[0]<0.0) || (ob->size[0]<0.0) || (ob->size[0]<0.0) ) {
- snprintf(debugStrBuffer,256,"\nfluidSim::writeBobjgz:: Warning object %s has negative scaling - check triangle ordering...?\n\n", ob->id.name);
- elbeemDebugOut(debugStrBuffer);
- }
+ /* mesh vars */
+ MTFace *mtface, *tf;
+ MFace *mface, *mf;
+ MVert *mvert, *v1, *v2, *v3, *v4;
+ MemArena *arena= NULL;
+ VertexTangent **vtangents= NULL;
+ float (*orco)[3]= NULL, (*tangent)[3];
+ float *uv1, *uv2, *uv3, *uv4, *vtang;
+ float fno[3], tang[3], uv[4][2];
+ int i, j, len, mf_vi[4], totvert, totface;
- snprintf(debugStrBuffer,256,"Writing GZ_BOBJ '%s' ... ",filename); elbeemDebugOut(debugStrBuffer);
- if(append) gzf = gzopen(filename, "a+b9");
- else gzf = gzopen(filename, "wb9");
- if (!gzf) {
- snprintf(debugStrBuffer,256,"writeBobjgz::error - Unable to open file for writing '%s'\n", filename);
- elbeemDebugOut(debugStrBuffer);
+ if(CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
return;
- }
- dm = mesh_create_derived_render(ob, CD_MASK_BAREMESH);
- //dm = mesh_create_derived_no_deform(ob,NULL);
+ /* check we have all the needed layers */
+ totvert= dm->getNumVerts(dm);
+ totface= dm->getNumFaces(dm);
- mvert = dm->getVertArray(dm);
- mface = dm->getFaceArray(dm);
- totvert = dm->getNumVerts(dm);
- totface = dm->getNumFaces(dm);
+ mvert= dm->getVertArray(dm);
+ mface= dm->getFaceArray(dm);
+ mtface= dm->getFaceDataArray(dm, CD_MTFACE);
- // write time value for appended anim mesh
- if(append) {
- gzwrite(gzf, &time, sizeof(time));
+ if(!mtface) {
+ orco= dm->getVertDataArray(dm, CD_ORCO);
+ if(!orco)
+ return;
}
-
- // continue with verts/norms
- if(sizeof(wri)!=4) { snprintf(debugStrBuffer,256,"Writing GZ_BOBJ, Invalid int size %d...\n", wri); elbeemDebugOut(debugStrBuffer); return; } // paranoia check
- wri = dm->getNumVerts(dm);
- mvert = dm->getVertArray(dm);
- gzwrite(gzf, &wri, sizeof(wri));
- for(i=0; i<wri;i++) {
- VECCOPY(vec, mvert[i].co);
- if(useGlobalCoords) { Mat4MulVecfl(ob->obmat, vec); }
- for(j=0; j<3; j++) {
- wrf = vec[j];
- gzwrite(gzf, &wrf, sizeof( wrf ));
+
+ /* create tangent layer */
+ DM_add_face_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
+ tangent= DM_get_face_data_layer(dm, CD_TANGENT);
+
+ /* allocate some space */
+ arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
+ BLI_memarena_use_calloc(arena);
+ vtangents= MEM_callocN(sizeof(VertexTangent*)*totvert, "VertexTangent");
+
+ /* sum tangents at connected vertices */
+ for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++) {
+ v1= &mvert[mf->v1];
+ v2= &mvert[mf->v2];
+ v3= &mvert[mf->v3];
+
+ if (mf->v4) {
+ v4= &mvert[mf->v4];
+ CalcNormFloat4(v4->co, v3->co, v2->co, v1->co, fno);
}
- }
-
- // should be the same as Vertices.size
- wri = totvert;
- gzwrite(gzf, &wri, sizeof(wri));
- EulToMat3(ob->rot, rotmat);
- for(i=0; i<wri;i++) {
- VECCOPY(vec, mvert[i].no);
- Normalize(vec);
- if(useGlobalCoords) { Mat3MulVecfl(rotmat, vec); }
- for(j=0; j<3; j++) {
- wrf = vec[j];
- gzwrite(gzf, &wrf, sizeof( wrf ));
+ else {
+ v4= NULL;
+ CalcNormFloat(v3->co, v2->co, v1->co, fno);
}
- }
-
- // append only writes verts&norms
- if(!append) {
- //float side1[3],side2[3],norm1[3],norm2[3];
- //float inpf;
-
- // compute no. of triangles
- wri = 0;
- for(i=0; i<totface; i++) {
- wri++;
- if(mface[i].v4) { wri++; }
+
+ if(mtface) {
+ uv1= tf->uv[0];
+ uv2= tf->uv[1];
+ uv3= tf->uv[2];
+ uv4= tf->uv[3];
}
- gzwrite(gzf, &wri, sizeof(wri));
- for(i=0; i<totface; i++) {
-
- int face[4];
- face[0] = mface[i].v1;
- face[1] = mface[i].v2;
- face[2] = mface[i].v3;
- face[3] = mface[i].v4;
- //snprintf(debugStrBuffer,256,"F %s %d = %d,%d,%d,%d \n",ob->id.name, i, face[0],face[1],face[2],face[3] ); elbeemDebugOut(debugStrBuffer);
- //VecSubf(side1, mvert[face[1]].co,mvert[face[0]].co);
- //VecSubf(side2, mvert[face[2]].co,mvert[face[0]].co);
- //Crossf(norm1,side1,side2);
- gzwrite(gzf, &(face[0]), sizeof( face[0] ));
- gzwrite(gzf, &(face[1]), sizeof( face[1] ));
- gzwrite(gzf, &(face[2]), sizeof( face[2] ));
- if(face[3]) {
- //VecSubf(side1, mvert[face[2]].co,mvert[face[0]].co);
- //VecSubf(side2, mvert[face[3]].co,mvert[face[0]].co);
- //Crossf(norm2,side1,side2);
- //inpf = Inpf(norm1,norm2);
- //if(inpf>0.) {
- gzwrite(gzf, &(face[0]), sizeof( face[0] ));
- gzwrite(gzf, &(face[2]), sizeof( face[2] ));
- gzwrite(gzf, &(face[3]), sizeof( face[3] ));
- //} else {
- //gzwrite(gzf, &(face[0]), sizeof( face[0] ));
- //gzwrite(gzf, &(face[3]), sizeof( face[3] ));
- //gzwrite(gzf, &(face[2]), sizeof( face[2] ));
- //}
- } // quad
+ else {
+ uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
+ spheremap(orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2], &uv[0][0], &uv[0][1]);
+ spheremap(orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2], &uv[1][0], &uv[1][1]);
+ spheremap(orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2], &uv[2][0], &uv[2][1]);
+ if(v4)
+ spheremap(orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2], &uv[3][0], &uv[3][1]);
}
- }
-
- snprintf(debugStrBuffer,256,"Done. #Vertices: %d, #Triangles: %d\n", totvert, totface );
- elbeemDebugOut(debugStrBuffer);
-
- gzclose( gzf );
- dm->release(dm);
-}
-
-void initElbeemMesh(struct Object *ob,
- int *numVertices, float **vertices,
- int *numTriangles, int **triangles,
- int useGlobalCoords)
-{
- DerivedMesh *dm = NULL;
- MVert *mvert;
- MFace *mface;
- int countTris=0, i, totvert, totface;
- float *verts;
- int *tris;
-
- dm = mesh_create_derived_render(ob, CD_MASK_BAREMESH);
- //dm = mesh_create_derived_no_deform(ob,NULL);
-
- mvert = dm->getVertArray(dm);
- mface = dm->getFaceArray(dm);
- totvert = dm->getNumVerts(dm);
- totface = dm->getNumFaces(dm);
-
- *numVertices = totvert;
- verts = MEM_callocN( totvert*3*sizeof(float), "elbeemmesh_vertices");
- for(i=0; i<totvert; i++) {
- VECCOPY( &verts[i*3], mvert[i].co);
- if(useGlobalCoords) { Mat4MulVecfl(ob->obmat, &verts[i*3]); }
- }
- *vertices = verts;
-
- for(i=0; i<totface; i++) {
- countTris++;
- if(mface[i].v4) { countTris++; }
- }
- *numTriangles = countTris;
- tris = MEM_callocN( countTris*3*sizeof(int), "elbeemmesh_triangles");
- countTris = 0;
- for(i=0; i<totface; i++) {
- int face[4];
- face[0] = mface[i].v1;
- face[1] = mface[i].v2;
- face[2] = mface[i].v3;
- face[3] = mface[i].v4;
-
- tris[countTris*3+0] = face[0];
- tris[countTris*3+1] = face[1];
- tris[countTris*3+2] = face[2];
- countTris++;
- if(face[3]) {
- tris[countTris*3+0] = face[0];
- tris[countTris*3+1] = face[2];
- tris[countTris*3+2] = face[3];
- countTris++;
+
+ tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, fno, tang);
+ sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
+ sum_or_add_vertex_tangent(arena, &vtangents[mf->v2], tang, uv2);
+ sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
+
+ if(mf->v4) {
+ v4= &mvert[mf->v4];
+
+ tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, fno, tang);
+ sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
+ sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
+ sum_or_add_vertex_tangent(arena, &vtangents[mf->v4], tang, uv4);
}
}
- *triangles = tris;
-
- dm->release(dm);
-}
-
-/* read .bobj.gz file into a fluidsimDerivedMesh struct */
-Mesh* readBobjgz(char *filename, Mesh *orgmesh, float* bbstart, float *bbsize) //, fluidsimDerivedMesh *fsdm)
-{
- int wri,i,j;
- char debugStrBuffer[256];
- float wrf;
- Mesh *newmesh;
- const int debugBobjRead = 1;
- // init data from old mesh (materials,flags)
- MFace *origMFace = &((MFace*) orgmesh->mface)[0];
- int mat_nr = -1;
- int flag = -1;
- MFace *fsface = NULL;
- int gotBytes;
- gzFile gzf;
-
- if(!orgmesh) return NULL;
- if(!origMFace) return NULL;
- mat_nr = origMFace->mat_nr;
- flag = origMFace->flag;
-
- // similar to copy_mesh
- newmesh = MEM_dupallocN(orgmesh);
- newmesh->mat= orgmesh->mat;
-
- newmesh->mvert= NULL;
- newmesh->medge= NULL;
- newmesh->mface= NULL;
- newmesh->mtface= NULL;
-
- newmesh->dvert = NULL;
-
- newmesh->mcol= NULL;
- newmesh->msticky= NULL;
- newmesh->texcomesh= NULL;
- memset(&newmesh->vdata, 0, sizeof(newmesh->vdata));
- memset(&newmesh->edata, 0, sizeof(newmesh->edata));
- memset(&newmesh->fdata, 0, sizeof(newmesh->fdata));
-
- newmesh->key= NULL;
- newmesh->totface = 0;
- newmesh->totvert = 0;
- newmesh->totedge = 0;
- newmesh->medge = NULL;
-
-
- snprintf(debugStrBuffer,256,"Reading '%s' GZ_BOBJ... ",filename); elbeemDebugOut(debugStrBuffer);
- gzf = gzopen(filename, "rb");
- // gzf = fopen(filename, "rb");
- // debug: fread(b,c,1,a) = gzread(a,b,c)
- if (!gzf) {
- //snprintf(debugStrBuffer,256,"readBobjgz::error - Unable to open file for reading '%s'\n", filename); // DEBUG
- MEM_freeN(newmesh);
- return NULL;
- }
-
- //if(sizeof(wri)!=4) { snprintf(debugStrBuffer,256,"Reading GZ_BOBJ, Invalid int size %d...\n", wri); return NULL; } // paranoia check
- gotBytes = gzread(gzf, &wri, sizeof(wri));
- newmesh->totvert = wri;
- newmesh->mvert = CustomData_add_layer(&newmesh->vdata, CD_MVERT, CD_CALLOC, NULL, newmesh->totvert);
- if(debugBobjRead){ snprintf(debugStrBuffer,256,"#vertices %d ", newmesh->totvert); elbeemDebugOut(debugStrBuffer); } //DEBUG
- for(i=0; i<newmesh->totvert;i++) {
- //if(debugBobjRead) snprintf(debugStrBuffer,256,"V %d = ",i);
- for(j=0; j<3; j++) {
- gotBytes = gzread(gzf, &wrf, sizeof( wrf ));
- newmesh->mvert[i].co[j] = wrf;
- //if(debugBobjRead) snprintf(debugStrBuffer,256,"%25.20f ", wrf);
+
+ /* write tangent to layer */
+ for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++, tangent+=4) {
+ len= (mf->v4)? 4 : 3;
+
+ if(mtface) {
+ uv1= tf->uv[0];
+ uv2= tf->uv[1];
+ uv3= tf->uv[2];
+ uv4= tf->uv[3];
}
- //if(debugBobjRead) snprintf(debugStrBuffer,256,"\n");
- }
-
- // should be the same as Vertices.size
- gotBytes = gzread(gzf, &wri, sizeof(wri));
- if(wri != newmesh->totvert) {
- // complain #vertices has to be equal to #normals, reset&abort
- CustomData_free_layer_active(&newmesh->vdata, CD_MVERT, newmesh->totvert);
- MEM_freeN(newmesh);
- snprintf(debugStrBuffer,256,"Reading GZ_BOBJ, #normals=%d, #vertices=%d, aborting...\n", wri,newmesh->totvert );
- return NULL;
- }
- for(i=0; i<newmesh->totvert;i++) {
- for(j=0; j<3; j++) {
- gotBytes = gzread(gzf, &wrf, sizeof( wrf ));
- newmesh->mvert[i].no[j] = (short)(wrf*32767.0f);
- //newmesh->mvert[i].no[j] = 0.5; // DEBUG tst
+ else {
+ uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
+ spheremap(orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2], &uv[0][0], &uv[0][1]);
+ spheremap(orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2], &uv[1][0], &uv[1][1]);
+ spheremap(orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2], &uv[2][0], &uv[2][1]);
+ if(len==4)
+ spheremap(orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2], &uv[3][0], &uv[3][1]);
}
- //fprintf(stderr," DEBDPCN nm%d, %d = %d,%d,%d \n",
- //(int)(newmesh->mvert), i, newmesh->mvert[i].no[0], newmesh->mvert[i].no[1], newmesh->mvert[i].no[2]);
- }
- //fprintf(stderr," DPCN 0 = %d,%d,%d \n", newmesh->mvert[0].no[0], newmesh->mvert[0].no[1], newmesh->mvert[0].no[2]);
+
+ mf_vi[0]= mf->v1;
+ mf_vi[1]= mf->v2;
+ mf_vi[2]= mf->v3;
+ mf_vi[3]= mf->v4;
+
+ for(j=0; j<len; j++) {
+ vtang= find_vertex_tangent(vtangents[mf_vi[j]], mtface ? tf->uv[j] : uv[j]);
-
- /* compute no. of triangles */
- gotBytes = gzread(gzf, &wri, sizeof(wri));
- newmesh->totface = wri;
- newmesh->mface = CustomData_add_layer(&newmesh->fdata, CD_MFACE, CD_CALLOC, NULL, newmesh->totface);
- if(debugBobjRead){ snprintf(debugStrBuffer,256,"#faces %d ", newmesh->totface); elbeemDebugOut(debugStrBuffer); } //DEBUG
- fsface = newmesh->mface;
- for(i=0; i<newmesh->totface; i++) {
- int face[4];
-
- gotBytes = gzread(gzf, &(face[0]), sizeof( face[0] ));
- gotBytes = gzread(gzf, &(face[1]), sizeof( face[1] ));
- gotBytes = gzread(gzf, &(face[2]), sizeof( face[2] ));
- face[3] = 0;
-
- fsface[i].v1 = face[0];
- fsface[i].v2 = face[1];
- fsface[i].v3 = face[2];
- fsface[i].v4 = face[3];
- }
-
- // correct triangles with v3==0 for blender, cycle verts
- for(i=0; i<newmesh->totface; i++) {
- if(!fsface[i].v3) {
- int temp = fsface[i].v1;
- fsface[i].v1 = fsface[i].v2;
- fsface[i].v2 = fsface[i].v3;
- fsface[i].v3 = temp;
+ VECCOPY(tangent[j], vtang);
+ Normalize(tangent[j]);
}
}
- gzclose( gzf );
- for(i=0;i<newmesh->totface;i++) {
- fsface[i].mat_nr = mat_nr;
- fsface[i].flag = flag;
- fsface[i].edcode = ME_V1V2 | ME_V2V3 | ME_V3V1;
- //snprintf(debugStrBuffer,256,"%d : %d,%d,%d\n", i,fsface[i].mat_nr, fsface[i].flag, fsface[i].edcode );
- }
-
- snprintf(debugStrBuffer,256," (%d,%d) done\n", newmesh->totvert,newmesh->totface); elbeemDebugOut(debugStrBuffer); //DEBUG
- return newmesh;
-}
-
-/* read zipped fluidsim velocities into the co's of the fluidsimsettings normals struct */
-void readVelgz(char *filename, Object *srcob)
-{
- char debugStrBuffer[256];
- int wri, i, j;
- float wrf;
- gzFile gzf;
- MVert *vverts = srcob->fluidsimSettings->meshSurfNormals;
- int len = strlen(filename);
- Mesh *mesh = srcob->data;
- // mesh and vverts have to be valid from loading...
-
- // clean up in any case
- for(i=0; i<mesh->totvert;i++) {
- for(j=0; j<3; j++) {
- vverts[i].co[j] = 0.;
- }
- }
- if(srcob->fluidsimSettings->domainNovecgen>0) return;
-
- if(len<7) {
- //printf("readVelgz Eror: invalid filename '%s'\n",filename); // DEBUG
- return;
- }
-
- // .bobj.gz , correct filename
- // 87654321
- filename[len-6] = 'v';
- filename[len-5] = 'e';
- filename[len-4] = 'l';
-
- snprintf(debugStrBuffer,256,"Reading '%s' GZ_VEL... ",filename); elbeemDebugOut(debugStrBuffer);
- gzf = gzopen(filename, "rb");
- if (!gzf) {
- //printf("readVelgz Eror: unable to open file '%s'\n",filename); // DEBUG
- return;
- }
-
- gzread(gzf, &wri, sizeof( wri ));
- if(wri != mesh->totvert) {
- //printf("readVelgz Eror: invalid no. of velocities %d vs. %d aborting.\n" ,wri ,mesh->totvert ); // DEBUG
- return;
- }
-
- for(i=0; i<mesh->totvert;i++) {
- for(j=0; j<3; j++) {
- gzread(gzf, &wrf, sizeof( wrf ));
- vverts[i].co[j] = wrf;
- }
- //if(i<20) fprintf(stderr, "GZ_VELload %d = %f,%f,%f \n",i,vverts[i].co[0],vverts[i].co[1],vverts[i].co[2]); // DEBUG
- }
-
- gzclose(gzf);
+ BLI_memarena_free(arena);
+ MEM_freeN(vtangents);
}
-
-/* ***************************** fluidsim derived mesh ***************************** */
-
-/* check which file to load, and replace old mesh of the object with it */
-/* this replacement is undone at the end of mesh_calc_modifiers */
-void loadFluidsimMesh(Object *srcob, int useRenderParams)
+void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
{
- Mesh *mesh = NULL;
- float *bbStart = NULL, *bbSize = NULL;
- float lastBB[3];
- int displaymode = 0;
- int curFrame = G.scene->r.cfra - 1 /*G.scene->r.sfra*/; /* start with 0 at start frame */
- char targetDir[FILE_MAXFILE+FILE_MAXDIR], targetFile[FILE_MAXFILE+FILE_MAXDIR];
- char debugStrBuffer[256];
- //snprintf(debugStrBuffer,256,"loadFluidsimMesh call (obid '%s', rp %d)\n", srcob->id.name, useRenderParams); // debug
+ CustomData *vdata, *fdata, *tfdata = NULL;
+ int a, b, layer;
- if((!srcob)||(!srcob->fluidsimSettings)) {
- snprintf(debugStrBuffer,256,"DEBUG - Invalid loadFluidsimMesh call, rp %d, dm %d)\n", useRenderParams, displaymode); // debug
- elbeemDebugOut(debugStrBuffer); // debug
- return;
- }
- // make sure the original mesh data pointer is stored
- if(!srcob->fluidsimSettings->orgMesh) {
- srcob->fluidsimSettings->orgMesh = srcob->data;
- }
+ /* From the layers requested by the GLSL shader, figure out which ones are
+ * actually available for this derivedmesh, and retrieve the pointers */
- // free old mesh, if there is one (todo, check if it's still valid?)
- if(srcob->fluidsimSettings->meshSurface) {
- Mesh *freeFsMesh = srcob->fluidsimSettings->meshSurface;
+ memset(attribs, 0, sizeof(DMVertexAttribs));
- // similar to free_mesh(...) , but no things like unlink...
- CustomData_free(&freeFsMesh->vdata, freeFsMesh->totvert);
- CustomData_free(&freeFsMesh->edata, freeFsMesh->totedge);
- CustomData_free(&freeFsMesh->fdata, freeFsMesh->totface);
- MEM_freeN(freeFsMesh);
-
- if(srcob->data == srcob->fluidsimSettings->meshSurface)
- srcob->data = srcob->fluidsimSettings->orgMesh;
- srcob->fluidsimSettings->meshSurface = NULL;
-
- if(srcob->fluidsimSettings->meshSurfNormals) MEM_freeN(srcob->fluidsimSettings->meshSurfNormals);
- srcob->fluidsimSettings->meshSurfNormals = NULL;
- }
-
- // init bounding box
- bbStart = srcob->fluidsimSettings->bbStart;
- bbSize = srcob->fluidsimSettings->bbSize;
- lastBB[0] = bbSize[0]; // TEST
- lastBB[1] = bbSize[1];
- lastBB[2] = bbSize[2];
- fluidsimGetAxisAlignedBB(srcob->fluidsimSettings->orgMesh, srcob->obmat, bbStart, bbSize, &srcob->fluidsimSettings->meshBB);
- // check free fsmesh... TODO
-
- if(!useRenderParams) {
- displaymode = srcob->fluidsimSettings->guiDisplayMode;
- } else {
- displaymode = srcob->fluidsimSettings->renderDisplayMode;
- }
-
- snprintf(debugStrBuffer,256,"loadFluidsimMesh call (obid '%s', rp %d, dm %d), curFra=%d, sFra=%d #=%d \n",
- srcob->id.name, useRenderParams, displaymode, G.scene->r.cfra, G.scene->r.sfra, curFrame ); // debug
- elbeemDebugOut(debugStrBuffer); // debug
-
- strncpy(targetDir, srcob->fluidsimSettings->surfdataPath, FILE_MAXDIR);
- // use preview or final mesh?
- if(displaymode==1) {
- // just display original object
- srcob->data = srcob->fluidsimSettings->orgMesh;
- return;
- } else if(displaymode==2) {
- strcat(targetDir,"fluidsurface_preview_#");
- } else { // 3
- strcat(targetDir,"fluidsurface_final_#");
- }
- BLI_convertstringcode(targetDir, G.sce, curFrame); // fixed #frame-no
- strcpy(targetFile,targetDir);
- strcat(targetFile, ".bobj.gz");
+ vdata = &dm->vertData;
+ fdata = &dm->faceData;
- snprintf(debugStrBuffer,256,"loadFluidsimMesh call (obid '%s', rp %d, dm %d) '%s' \n", srcob->id.name, useRenderParams, displaymode, targetFile); // debug
- elbeemDebugOut(debugStrBuffer); // debug
+ /* ugly hack, editmesh derivedmesh doesn't copy face data, this way we
+ * can use offsets instead */
+ if(dm->release == emDM_release)
+ tfdata = &((EditMeshDerivedMesh*)dm)->em->fdata;
+ else
+ tfdata = fdata;
+
+ /* add a tangent layer if necessary */
+ for(b = 0; b < gattribs->totlayer; b++)
+ if(gattribs->layer[b].type == CD_TANGENT)
+ if(CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
+ DM_add_tangent_layer(dm);
+
+ for(b = 0; b < gattribs->totlayer; b++) {
+ if(gattribs->layer[b].type == CD_MTFACE) {
+ /* uv coordinates */
+ if(gattribs->layer[b].name[0])
+ layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
+ gattribs->layer[b].name);
+ else
+ layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
- if(displaymode!=2) { // dont add bounding box for final
- mesh = readBobjgz(targetFile, srcob->fluidsimSettings->orgMesh ,NULL,NULL);
- } else {
- mesh = readBobjgz(targetFile, srcob->fluidsimSettings->orgMesh, bbSize,bbSize );
- }
- if(!mesh) {
- // switch, abort background rendering when fluidsim mesh is missing
- const char *strEnvName2 = "BLENDER_ELBEEMBOBJABORT"; // from blendercall.cpp
- if(G.background==1) {
- if(getenv(strEnvName2)) {
- int elevel = atoi(getenv(strEnvName2));
- if(elevel>0) {
- printf("Env. var %s set, fluid sim mesh '%s' not found, aborting render...\n",strEnvName2, targetFile);
- exit(1);
- }
+ if(layer != -1) {
+ a = attribs->tottface++;
+
+ attribs->tface[a].array = tfdata->layers[layer].data;
+ attribs->tface[a].emOffset = tfdata->layers[layer].offset;
+ attribs->tface[a].glIndex = gattribs->layer[b].glindex;
}
}
-
- // display org. object upon failure
- srcob->data = srcob->fluidsimSettings->orgMesh;
- return;
- }
+ else if(gattribs->layer[b].type == CD_MCOL) {
+ /* vertex colors */
+ if(gattribs->layer[b].name[0])
+ layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
+ gattribs->layer[b].name);
+ else
+ layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
- if((mesh)&&(mesh->totvert>0)) {
- make_edges(mesh, 0); // 0 = make all edges draw
- }
- srcob->fluidsimSettings->meshSurface = mesh;
- srcob->data = mesh;
- srcob->fluidsimSettings->meshSurfNormals = MEM_dupallocN(mesh->mvert);
+ if(layer != -1) {
+ a = attribs->totmcol++;
- // load vertex velocities, if they exist...
- // TODO? use generate flag as loading flag as well?
- // warning, needs original .bobj.gz mesh loading filename
- if(displaymode==3) {
- readVelgz(targetFile, srcob);
- } else {
- // no data for preview, only clear...
- int i,j;
- for(i=0; i<mesh->totvert;i++) { for(j=0; j<3; j++) { srcob->fluidsimSettings->meshSurfNormals[i].co[j] = 0.; }}
- }
+ attribs->mcol[a].array = tfdata->layers[layer].data;
+ attribs->mcol[a].emOffset = tfdata->layers[layer].offset;
+ attribs->mcol[a].glIndex = gattribs->layer[b].glindex;
+ }
+ }
+ else if(gattribs->layer[b].type == CD_TANGENT) {
+ /* tangents */
+ layer = CustomData_get_layer_index(fdata, CD_TANGENT);
- //fprintf(stderr,"LOADFLM DEBXHCH fs=%d 3:%d,%d,%d \n", (int)mesh, ((Mesh *)(srcob->fluidsimSettings->meshSurface))->mvert[3].no[0], ((Mesh *)(srcob->fluidsimSettings->meshSurface))->mvert[3].no[1], ((Mesh *)(srcob->fluidsimSettings->meshSurface))->mvert[3].no[2]);
- return;
-}
+ if(layer != -1) {
+ attribs->tottang = 1;
-/* helper function */
-/* init axis aligned BB for mesh object */
-void fluidsimGetAxisAlignedBB(struct Mesh *mesh, float obmat[][4],
- /*RET*/ float start[3], /*RET*/ float size[3], /*RET*/ struct Mesh **bbmesh )
-{
- float bbsx=0.0, bbsy=0.0, bbsz=0.0;
- float bbex=1.0, bbey=1.0, bbez=1.0;
- int i;
- float vec[3];
-
- VECCOPY(vec, mesh->mvert[0].co);
- Mat4MulVecfl(obmat, vec);
- bbsx = vec[0]; bbsy = vec[1]; bbsz = vec[2];
- bbex = vec[0]; bbey = vec[1]; bbez = vec[2];
-
- for(i=1; i<mesh->totvert;i++) {
- VECCOPY(vec, mesh->mvert[i].co);
- Mat4MulVecfl(obmat, vec);
-
- if(vec[0] < bbsx){ bbsx= vec[0]; }
- if(vec[1] < bbsy){ bbsy= vec[1]; }
- if(vec[2] < bbsz){ bbsz= vec[2]; }
- if(vec[0] > bbex){ bbex= vec[0]; }
- if(vec[1] > bbey){ bbey= vec[1]; }
- if(vec[2] > bbez){ bbez= vec[2]; }
- }
-
- // return values...
- if(start) {
- start[0] = bbsx;
- start[1] = bbsy;
- start[2] = bbsz;
- }
- if(size) {
- size[0] = bbex-bbsx;
- size[1] = bbey-bbsy;
- size[2] = bbez-bbsz;
- }
-
- // init bounding box mesh?
- if(bbmesh) {
- int i,j;
- Mesh *newmesh = NULL;
- if(!(*bbmesh)) { newmesh = MEM_callocN(sizeof(Mesh), "fluidsimGetAxisAlignedBB_meshbb"); }
- else { newmesh = *bbmesh; }
-
- newmesh->totvert = 8;
- if(!newmesh->mvert)
- newmesh->mvert = CustomData_add_layer(&newmesh->vdata, CD_MVERT, CD_CALLOC, NULL, newmesh->totvert);
- for(i=0; i<8; i++) {
- for(j=0; j<3; j++) newmesh->mvert[i].co[j] = start[j];
+ attribs->tang.array = fdata->layers[layer].data;
+ attribs->tang.emOffset = fdata->layers[layer].offset;
+ attribs->tang.glIndex = gattribs->layer[b].glindex;
+ }
}
+ else if(gattribs->layer[b].type == CD_ORCO) {
+ /* original coordinates */
+ layer = CustomData_get_layer_index(vdata, CD_ORCO);
- newmesh->totface = 6;
- if(!newmesh->mface)
- newmesh->mface = CustomData_add_layer(&newmesh->fdata, CD_MFACE, CD_CALLOC, NULL, newmesh->totface);
+ if(layer != -1) {
+ attribs->totorco = 1;
- *bbmesh = newmesh;
+ attribs->orco.array = vdata->layers[layer].data;
+ attribs->orco.emOffset = vdata->layers[layer].offset;
+ attribs->orco.glIndex = gattribs->layer[b].glindex;
+ }
+ }
}
}
-#else // DISABLE_ELBEEM
-
-/* dummy for mesh_calc_modifiers */
-void loadFluidsimMesh(Object *srcob, int useRenderParams) {
-}
-
-#endif // DISABLE_ELBEEM
-
diff --git a/source/blender/blenkernel/intern/Makefile b/source/blender/blenkernel/intern/Makefile
index 94aa3db3f9e..4cfc8f91efe 100644
--- a/source/blender/blenkernel/intern/Makefile
+++ b/source/blender/blenkernel/intern/Makefile
@@ -36,6 +36,7 @@ include nan_compile.mk
CFLAGS += $(LEVEL_1_C_WARNINGS)
# OpenGL and Python
+CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(OPENGL_HEADERS)
CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION)
@@ -66,6 +67,7 @@ CPPFLAGS += $(NAN_SDLCFLAGS)
CPPFLAGS += -I$(NAN_IKSOLVER)/include
CPPFLAGS += -I$(NAN_DECIMATION)/include
CPPFLAGS += -I$(NAN_ELBEEM)/include
+CPPFLAGS += -I$(NAN_OPENNL)/include
# path to zlib
CPPFLAGS += -I$(NAN_ZLIB)/include
@@ -73,9 +75,15 @@ CPPFLAGS += -I$(NAN_ZLIB)/include
#path to nodes
CPPFLAGS += -I../../nodes
+#path to gpu
+CPPFLAGS += -I../../gpu
+
# path to our own external headerfiles
CPPFLAGS += -I..
+# path to bullet2, for cloth
+CPPFLAGS += -I../../../../extern/bullet2/src
+
ifeq ($(WITH_FREETYPE2), true)
CPPFLAGS += -DWITH_FREETYPE2
CPPFLAGS += -I$(NAN_FREETYPE)/include
diff --git a/source/blender/blenkernel/intern/action.c b/source/blender/blenkernel/intern/action.c
index 3011cc2f99b..1c720cea21f 100644
--- a/source/blender/blenkernel/intern/action.c
+++ b/source/blender/blenkernel/intern/action.c
@@ -62,6 +62,7 @@
#include "BLI_arithb.h"
#include "BLI_blenlib.h"
+#include "BLI_ghash.h"
//XXX #include "nla.h"
@@ -174,24 +175,51 @@ void free_action (bAction *act)
if (act->chanbase.first)
BLI_freelistN(&act->chanbase);
+
+ /* Free groups */
+ if (act->groups.first)
+ BLI_freelistN(&act->groups);
+
+ /* Free pose-references (aka local markers) */
+ if (act->markers.first)
+ BLI_freelistN(&act->markers);
}
bAction *copy_action (bAction *src)
{
bAction *dst = NULL;
bActionChannel *dchan, *schan;
+ bActionGroup *dgrp, *sgrp;
if (!src) return NULL;
dst= copy_libblock(src);
+
BLI_duplicatelist(&(dst->chanbase), &(src->chanbase));
+ BLI_duplicatelist(&(dst->groups), &(src->groups));
+ BLI_duplicatelist(&(dst->markers), &(src->markers));
- for (dchan=dst->chanbase.first, schan=src->chanbase.first; dchan; dchan=dchan->next, schan=schan->next){
+ for (dchan=dst->chanbase.first, schan=src->chanbase.first; dchan; dchan=dchan->next, schan=schan->next) {
+ for (dgrp=dst->groups.first, sgrp=src->groups.first; dgrp && sgrp; dgrp=dgrp->next, sgrp=sgrp->next) {
+ if (dchan->grp == sgrp) {
+ dchan->grp= dgrp;
+
+ if (dgrp->channels.first == schan)
+ dgrp->channels.first= dchan;
+ if (dgrp->channels.last == schan)
+ dgrp->channels.last= dchan;
+
+ break;
+ }
+ }
+
dchan->ipo = copy_ipo(dchan->ipo);
copy_constraint_channels(&dchan->constraintChannels, &schan->constraintChannels);
}
+
dst->id.flag |= LIB_FAKEUSER;
dst->id.us++;
+
return dst;
}
@@ -263,6 +291,12 @@ void copy_pose(bPose **dst, bPose *src, int copycon)
return;
}
+ if (*dst==src) {
+ printf("copy_pose source and target are the same\n");
+ *dst=NULL;
+ return;
+ }
+
outPose= MEM_callocN(sizeof(bPose), "pose");
BLI_duplicatelist (&outPose->chanbase, &src->chanbase);
@@ -282,13 +316,82 @@ void free_pose_channels(bPose *pose)
{
bPoseChannel *pchan;
- if (pose->chanbase.first){
+ if (pose->chanbase.first) {
for (pchan = pose->chanbase.first; pchan; pchan=pchan->next){
- if(pchan->path)
+ if (pchan->path)
MEM_freeN(pchan->path);
free_constraints(&pchan->constraints);
}
- BLI_freelistN (&pose->chanbase);
+ BLI_freelistN(&pose->chanbase);
+ }
+}
+
+void free_pose(bPose *pose)
+{
+ if (pose) {
+ /* free pose-channels */
+ free_pose_channels(pose);
+
+ /* free pose-groups */
+ if (pose->agroups.first)
+ BLI_freelistN(&pose->agroups);
+
+ /* free pose */
+ MEM_freeN(pose);
+ }
+}
+
+void game_copy_pose(bPose **dst, bPose *src)
+{
+ bPose *out;
+ bPoseChannel *pchan, *outpchan;
+ GHash *ghash;
+
+ /* the game engine copies the current armature pose and then swaps
+ * the object pose pointer. this makes it possible to change poses
+ * without affecting the original blender data. */
+
+ if (!src) {
+ *dst=NULL;
+ return;
+ }
+ else if (*dst==src) {
+ printf("copy_pose source and target are the same\n");
+ *dst=NULL;
+ return;
+ }
+
+ out= MEM_dupallocN(src);
+ out->agroups.first= out->agroups.last= NULL;
+ BLI_duplicatelist(&out->chanbase, &src->chanbase);
+
+ /* remap pointers */
+ ghash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
+
+ pchan= src->chanbase.first;
+ outpchan= out->chanbase.first;
+ for (; pchan; pchan=pchan->next, outpchan=outpchan->next)
+ BLI_ghash_insert(ghash, pchan, outpchan);
+
+ for (pchan=out->chanbase.first; pchan; pchan=pchan->next) {
+ pchan->parent= BLI_ghash_lookup(ghash, pchan->parent);
+ pchan->child= BLI_ghash_lookup(ghash, pchan->child);
+ pchan->path= NULL;
+ }
+
+ BLI_ghash_free(ghash, NULL, NULL);
+
+ *dst=out;
+}
+
+void game_free_pose(bPose *pose)
+{
+ if (pose) {
+ /* we don't free constraints, those are owned by the original pose */
+ if(pose->chanbase.first)
+ BLI_freelistN(&pose->chanbase);
+
+ MEM_freeN(pose);
}
}
@@ -299,16 +402,20 @@ static void copy_pose_channel_data(bPoseChannel *pchan, const bPoseChannel *chan
VECCOPY(pchan->loc, chan->loc);
VECCOPY(pchan->size, chan->size);
QUATCOPY(pchan->quat, chan->quat);
+ Mat4CpyMat4(pchan->chan_mat, (float(*)[4])chan->chan_mat);
+ Mat4CpyMat4(pchan->pose_mat, (float(*)[4])chan->pose_mat);
pchan->flag= chan->flag;
con= chan->constraints.first;
- for(pcon= pchan->constraints.first; pcon; pcon= pcon->next) {
+ for(pcon= pchan->constraints.first; pcon; pcon= pcon->next, con= con->next) {
pcon->enforce= con->enforce;
pcon->headtail= con->headtail;
}
}
-/* checks for IK constraint, can do more constraints flags later */
+/* checks for IK constraint, and also for Follow-Path constraint.
+ * can do more constraints flags later
+ */
/* pose should be entirely OK */
void update_pose_constraint_flags(bPose *pose)
{
@@ -316,13 +423,15 @@ void update_pose_constraint_flags(bPose *pose)
bConstraint *con;
/* clear */
- for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
+ for (pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
pchan->constflag= 0;
}
+ pose->flag &= ~POSE_CONSTRAINTS_TIMEDEPEND;
+
/* detect */
- for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
- for(con= pchan->constraints.first; con; con= con->next) {
- if(con->type==CONSTRAINT_TYPE_KINEMATIC) {
+ for (pchan= pose->chanbase.first; pchan; pchan=pchan->next) {
+ for (con= pchan->constraints.first; con; con= con->next) {
+ if (con->type==CONSTRAINT_TYPE_KINEMATIC) {
bKinematicConstraint *data = (bKinematicConstraint*)con->data;
pchan->constflag |= PCHAN_HAS_IK;
@@ -345,7 +454,20 @@ void update_pose_constraint_flags(bPose *pose)
}
}
}
- else pchan->constflag |= PCHAN_HAS_CONST;
+ else if (con->type == CONSTRAINT_TYPE_FOLLOWPATH) {
+ bFollowPathConstraint *data= (bFollowPathConstraint *)con->data;
+
+ /* for drawing constraint colors when color set allows this */
+ pchan->constflag |= PCHAN_HAS_CONST;
+
+ /* if we have a valid target, make sure that this will get updated on frame-change
+ * (needed for when there is no anim-data for this pose)
+ */
+ if ((data->tar) && (data->tar->type==OB_CURVE))
+ pose->flag |= POSE_CONSTRAINTS_TIMEDEPEND;
+ }
+ else
+ pchan->constflag |= PCHAN_HAS_CONST;
}
}
}
@@ -385,7 +507,7 @@ bActionChannel *get_action_channel(bAction *act, const char *name)
if (!act || !name)
return NULL;
- for (chan = act->chanbase.first; chan; chan=chan->next){
+ for (chan = act->chanbase.first; chan; chan=chan->next) {
if (!strcmp (chan->name, name))
return chan;
}
@@ -393,18 +515,16 @@ bActionChannel *get_action_channel(bAction *act, const char *name)
return NULL;
}
-/* returns existing channel, or adds new one. In latter case it doesnt activate it, context is required for that*/
+/* returns existing channel, or adds new one. In latter case it doesnt activate it, context is required for that */
bActionChannel *verify_action_channel(bAction *act, const char *name)
{
bActionChannel *chan;
chan= get_action_channel(act, name);
- if(chan==NULL) {
- if (!chan) {
- chan = MEM_callocN (sizeof(bActionChannel), "actionChannel");
- strncpy (chan->name, name, 31);
- BLI_addtail (&act->chanbase, chan);
- }
+ if (chan == NULL) {
+ chan = MEM_callocN (sizeof(bActionChannel), "actionChannel");
+ strncpy(chan->name, name, 31);
+ BLI_addtail(&act->chanbase, chan);
}
return chan;
}
@@ -432,8 +552,11 @@ static float get_actionstrip_frame(bActionStrip *strip, float cframe, int invert
{
float length, actlength, repeat, scale;
+ if (strip->repeat == 0.0f) strip->repeat = 1.0f;
repeat = (strip->flag & ACTSTRIP_USESTRIDE) ? (1.0f) : (strip->repeat);
- scale = abs(strip->scale); /* scale must be positive (for now) */
+
+ if (strip->scale == 0.0f) strip->scale= 1.0f;
+ scale = fabs(strip->scale); /* scale must be positive (for now) */
actlength = strip->actend-strip->actstart;
if (actlength == 0.0f) actlength = 1.0f;
@@ -680,6 +803,11 @@ void extract_pose_from_pose(bPose *pose, const bPose *src)
const bPoseChannel *schan;
bPoseChannel *pchan= pose->chanbase.first;
+ if (pose==src) {
+ printf("extract_pose_from_pose source and target are the same\n");
+ return;
+ }
+
for (schan=src->chanbase.first; schan; schan=schan->next, pchan= pchan->next) {
copy_pose_channel_data(pchan, schan);
}
@@ -757,6 +885,12 @@ void copy_pose_result(bPose *to, bPose *from)
return;
}
+ if (to==from) {
+ printf("copy_pose_result source and target are the same\n");
+ return;
+ }
+
+
for(pchanfrom= from->chanbase.first; pchanfrom; pchanfrom= pchanfrom->next) {
pchanto= get_pose_channel(to, pchanfrom->name);
if(pchanto) {
@@ -783,7 +917,7 @@ typedef struct NlaIpoChannel {
int type;
} NlaIpoChannel;
-static void extract_ipochannels_from_action(ListBase *lb, ID *id, bAction *act, char *name, float ctime)
+void extract_ipochannels_from_action(ListBase *lb, ID *id, bAction *act, const char *name, float ctime)
{
bActionChannel *achan= get_action_channel(act, name);
IpoCurve *icu;
@@ -876,15 +1010,18 @@ static void blend_ipochannels(ListBase *dst, ListBase *src, float srcweight, int
}
}
-static void execute_ipochannels(ListBase *lb)
+int execute_ipochannels(ListBase *lb)
{
NlaIpoChannel *nic;
+ int count = 0;
for(nic= lb->first; nic; nic= nic->next) {
if(nic->poin) {
write_ipo_poin(nic->poin, nic->type, nic->val);
+ count++;
}
}
+ return count;
}
/* nla timing */
@@ -901,11 +1038,7 @@ static float nla_time(float cfra, float unit)
/* global time */
cfra*= G.scene->r.framelen;
-
-
- /* decide later... */
-// if(no_speed_curve==0) if(ob && ob->ipo) cfra= calc_ipo_time(ob->ipo, cfra);
-
+
return cfra;
}
@@ -915,7 +1048,7 @@ static float nla_time(float cfra, float unit)
static float stridechannel_frame(Object *ob, float sizecorr, bActionStrip *strip, Path *path, float pathdist, float *stride_offset)
{
bAction *act= strip->act;
- char *name= strip->stridechannel;
+ const char *name= strip->stridechannel;
bActionChannel *achan= get_action_channel(act, name);
int stride_axis= strip->stride_axis;
@@ -1083,12 +1216,13 @@ void what_does_obaction (Object *ob, bAction *act, float cframe)
workob.constraints.first = ob->constraints.first;
workob.constraints.last = ob->constraints.last;
- strcpy(workob.parsubstr, ob->parsubstr);
+ strcpy(workob.parsubstr, ob->parsubstr);
+ strcpy(workob.id.name, ob->id.name);
/* extract_ipochannels_from_action needs id's! */
workob.action= act;
- extract_ipochannels_from_action(&tchanbase, &ob->id, act, "Object", bsystem_time(&workob, cframe, 0.0));
+ extract_ipochannels_from_action(&tchanbase, &workob.id, act, "Object", bsystem_time(&workob, cframe, 0.0));
if (tchanbase.first) {
execute_ipochannels(&tchanbase);
@@ -1308,10 +1442,8 @@ static void do_nla(Object *ob, int blocktype)
}
/* free */
- if (tpose){
- free_pose_channels(tpose);
- MEM_freeN(tpose);
- }
+ if (tpose)
+ free_pose(tpose);
if(chanbase.first)
BLI_freelistN(&chanbase);
}
diff --git a/source/blender/blenkernel/intern/anim.c b/source/blender/blenkernel/intern/anim.c
index 08648aa6e10..aeddabf8c1b 100644
--- a/source/blender/blenkernel/intern/anim.c
+++ b/source/blender/blenkernel/intern/anim.c
@@ -44,6 +44,7 @@
#include "DNA_key_types.h"
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
+#include "DNA_modifier_types.h"
#include "DNA_object_types.h"
#include "DNA_particle_types.h"
#include "DNA_scene_types.h"
@@ -51,6 +52,7 @@
#include "DNA_vfont_types.h"
#include "BKE_anim.h"
+#include "BKE_curve.h"
#include "BKE_DerivedMesh.h"
#include "BKE_displist.h"
#include "BKE_effect.h"
@@ -61,6 +63,7 @@
#include "BKE_key.h"
#include "BKE_lattice.h"
#include "BKE_main.h"
+#include "BKE_mesh.h"
#include "BKE_object.h"
#include "BKE_particle.h"
#include "BKE_utildefines.h"
@@ -69,6 +72,8 @@
#include <config.h>
#endif
+static void object_duplilist_recursive(ID *id, Object *ob, ListBase *duplilist, float par_space_mat[][4], int level, int animated);
+
void free_path(Path *path)
{
if(path->data) MEM_freeN(path->data);
@@ -112,7 +117,7 @@ void calc_curvepath(Object *ob)
path->len= tot+1;
/* exception: vector handle paths and polygon paths should be subdivided at least a factor resolu */
- if(path->len<nu->resolu*nu->pntsu) path->len= nu->resolu*nu->pntsu;
+ if(path->len<nu->resolu*SEGMENTSU(nu)) path->len= nu->resolu*SEGMENTSU(nu);
dist= (float *)MEM_mallocN((tot+1)*4, "calcpathdist");
@@ -275,7 +280,7 @@ int where_on_path(Object *ob, float ctime, float *vec, float *dir) /* returns OK
/* ****************** DUPLICATOR ************** */
-static DupliObject *new_dupli_object(ListBase *lb, Object *ob, float mat[][4], int lay, int index)
+static DupliObject *new_dupli_object(ListBase *lb, Object *ob, float mat[][4], int lay, int index, int type, int animated)
{
DupliObject *dob= MEM_callocN(sizeof(DupliObject), "dupliobject");
@@ -285,50 +290,66 @@ static DupliObject *new_dupli_object(ListBase *lb, Object *ob, float mat[][4], i
Mat4CpyMat4(dob->omat, ob->obmat);
dob->origlay= ob->lay;
dob->index= index;
+ dob->type= type;
+ dob->animated= (type == OB_DUPLIGROUP) && animated;
ob->lay= lay;
return dob;
}
-static void group_duplilist(ListBase *lb, Object *ob, int level)
+static void group_duplilist(ListBase *lb, Object *ob, int level, int animated)
{
DupliObject *dob;
Group *group;
GroupObject *go;
- float mat[4][4];
+ float mat[4][4], tmat[4][4];
if(ob->dup_group==NULL) return;
group= ob->dup_group;
/* simple preventing of too deep nested groups */
- if(level>4) return;
+ if(level>MAX_DUPLI_RECUR) return;
/* handles animated groups, and */
/* we need to check update for objects that are not in scene... */
group_handle_recalc_and_update(ob, group);
+ animated= animated || group_is_animated(ob, group);
for(go= group->gobject.first; go; go= go->next) {
/* note, if you check on layer here, render goes wrong... it still deforms verts and uses parent imat */
if(go->ob!=ob) {
- Mat4MulMat4(mat, go->ob->obmat, ob->obmat);
- dob= new_dupli_object(lb, go->ob, mat, ob->lay, 0);
+
+ /* Group Dupli Offset, should apply after everything else */
+ if (group->dupli_ofs[0] || group->dupli_ofs[1] || group->dupli_ofs[2]) {
+ Mat4CpyMat4(tmat, go->ob->obmat);
+ VecSubf(tmat[3], tmat[3], group->dupli_ofs);
+ Mat4MulMat4(mat, tmat, ob->obmat);
+ } else {
+ Mat4MulMat4(mat, go->ob->obmat, ob->obmat);
+ }
+
+ dob= new_dupli_object(lb, go->ob, mat, ob->lay, 0, OB_DUPLIGROUP, animated);
dob->no_draw= (dob->origlay & group->layer)==0;
- if(go->ob->dup_group && (go->ob->transflag & OB_DUPLIGROUP)) {
+ if(go->ob->transflag & OB_DUPLI) {
Mat4CpyMat4(dob->ob->obmat, dob->mat);
- group_duplilist(lb, go->ob, level+1);
+ object_duplilist_recursive((ID *)group, go->ob, lb, ob->obmat, level+1, animated);
Mat4CpyMat4(dob->ob->obmat, dob->omat);
}
}
}
}
-static void frames_duplilist(ListBase *lb, Object *ob)
+static void frames_duplilist(ListBase *lb, Object *ob, int level, int animated)
{
extern int enable_cu_speed; /* object.c */
Object copyob;
+ DupliObject *dob;
int cfrao, ok;
+ /* simple preventing of too deep nested groups */
+ if(level>MAX_DUPLI_RECUR) return;
+
cfrao= G.scene->r.cfra;
if(ob->parent==NULL && ob->track==NULL && ob->ipo==NULL && ob->constraints.first==NULL) return;
@@ -347,7 +368,8 @@ static void frames_duplilist(ListBase *lb, Object *ob)
if(ok) {
do_ob_ipo(ob);
where_is_object_time(ob, (float)G.scene->r.cfra);
- new_dupli_object(lb, ob, ob->obmat, ob->lay, G.scene->r.cfra);
+ dob= new_dupli_object(lb, ob, ob->obmat, ob->lay, G.scene->r.cfra, OB_DUPLIFRAMES, animated);
+ Mat4CpyMat4(dob->omat, copyob.obmat);
}
}
@@ -357,22 +379,28 @@ static void frames_duplilist(ListBase *lb, Object *ob)
}
struct vertexDupliData {
+ ID *id; /* scene or group, for recursive loops */
+ int level;
+ int animated;
ListBase *lb;
float pmat[4][4];
+ float obmat[4][4]; /* Only used for dupliverts inside dupligroups, where the ob->obmat is modified */
Object *ob, *par;
+ float (*orco)[3];
};
static void vertex_dupli__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
{
+ DupliObject *dob;
struct vertexDupliData *vdd= userData;
- float vec[3], *q2, mat[3][3], tmat[4][4], obmat[4][4];
+ float vec[3], q2[4], mat[3][3], tmat[4][4], obmat[4][4];
VECCOPY(vec, co);
Mat4MulVecfl(vdd->pmat, vec);
VecSubf(vec, vec, vdd->pmat[3]);
- VecAddf(vec, vec, vdd->ob->obmat[3]);
+ VecAddf(vec, vec, vdd->obmat[3]);
- Mat4CpyMat4(obmat, vdd->ob->obmat);
+ Mat4CpyMat4(obmat, vdd->obmat);
VECCOPY(obmat[3], vec);
if(vdd->par->transflag & OB_DUPLIROT) {
@@ -383,44 +411,98 @@ static void vertex_dupli__mapFunc(void *userData, int index, float *co, float *n
vec[0]= -no_s[0]; vec[1]= -no_s[1]; vec[2]= -no_s[2];
}
- q2= vectoquat(vec, vdd->ob->trackflag, vdd->ob->upflag);
+ vectoquat(vec, vdd->ob->trackflag, vdd->ob->upflag, q2);
QuatToMat3(q2, mat);
Mat4CpyMat4(tmat, obmat);
Mat4MulMat43(obmat, tmat, mat);
}
- new_dupli_object(vdd->lb, vdd->ob, obmat, vdd->par->lay, index);
+ dob= new_dupli_object(vdd->lb, vdd->ob, obmat, vdd->par->lay, index, OB_DUPLIVERTS, vdd->animated);
+ if(vdd->orco)
+ VECCOPY(dob->orco, vdd->orco[index]);
+
+ if(vdd->ob->transflag & OB_DUPLI) {
+ float tmpmat[4][4];
+ Mat4CpyMat4(tmpmat, vdd->ob->obmat);
+ Mat4CpyMat4(vdd->ob->obmat, obmat); /* pretend we are really this mat */
+ object_duplilist_recursive((ID *)vdd->id, vdd->ob, vdd->lb, obmat, vdd->level+1, vdd->animated);
+ Mat4CpyMat4(vdd->ob->obmat, tmpmat);
+ }
}
-static void vertex_duplilist(ListBase *lb, Scene *sce, Object *par)
+static void vertex_duplilist(ListBase *lb, ID *id, Object *par, float par_space_mat[][4], int level, int animated)
{
- Object *ob;
- Base *base;
+ Object *ob, *ob_iter;
+ Mesh *me;
+ Base *base = NULL;
float vec[3], no[3], pmat[4][4];
- int lay, totvert, a;
+ int lay, totvert, a, oblay;
DerivedMesh *dm;
+ struct vertexDupliData vdd;
+ Scene *sce = NULL;
+ Group *group = NULL;
+ GroupObject * go = NULL;
Mat4CpyMat4(pmat, par->obmat);
- lay= G.scene->lay;
-
+ /* simple preventing of too deep nested groups */
+ if(level>MAX_DUPLI_RECUR) return;
+
if(par==G.obedit)
dm= editmesh_get_derived_cage(CD_MASK_BAREMESH);
else
- dm = mesh_get_derived_deform(par, CD_MASK_BAREMESH);
+ dm= mesh_get_derived_deform(par, CD_MASK_BAREMESH);
+
+ if(G.rendering) {
+ me= par->data;
+ vdd.orco= (float(*)[3])get_mesh_orco_verts(par);
+ transform_mesh_orco_verts(me, vdd.orco, me->totvert, 0);
+ }
+ else
+ vdd.orco= NULL;
totvert = dm->getNumVerts(dm);
- base= sce->base.first;
- while(base) {
-
- if(base->object->type>0 && (lay & base->lay) && G.obedit!=base->object) {
- ob= base->object->parent;
+ /* having to loop on scene OR group objects is NOT FUN */
+ if (GS(id->name) == ID_SCE) {
+ sce = (Scene *)id;
+ lay= sce->lay;
+ base= sce->base.first;
+ } else {
+ group = (Group *)id;
+ lay= group->layer;
+ go = group->gobject.first;
+ }
+
+ /* Start looping on Scene OR Group objects */
+ while (base || go) {
+ if (sce) {
+ ob_iter= base->object;
+ oblay = base->lay;
+ } else {
+ ob_iter= go->ob;
+ oblay = ob_iter->lay;
+ }
+
+ if (lay & oblay && G.obedit!=ob_iter) {
+ ob=ob_iter->parent;
while(ob) {
if(ob==par) {
- struct vertexDupliData vdd;
+ ob = ob_iter;
+ /* End Scene/Group object loop, below is generic */
- ob= base->object;
+
+ /* par_space_mat - only used for groups so we can modify the space dupli's are in
+ when par_space_mat is NULL ob->obmat can be used instead of ob__obmat
+ */
+ if(par_space_mat)
+ Mat4MulMat4(vdd.obmat, ob->obmat, par_space_mat);
+ else
+ Mat4CpyMat4(vdd.obmat, ob->obmat);
+
+ vdd.id= id;
+ vdd.level= level;
+ vdd.animated= animated;
vdd.lb= lb;
vdd.ob= ob;
vdd.par= par;
@@ -446,26 +528,37 @@ static void vertex_duplilist(ListBase *lb, Scene *sce, Object *par)
ob= ob->parent;
}
}
- base= base->next;
+ if (sce) base= base->next; /* scene loop */
+ else go= go->next; /* group loop */
}
+ if(vdd.orco)
+ MEM_freeN(vdd.orco);
dm->release(dm);
}
-static void face_duplilist(ListBase *lb, Scene *sce, Object *par)
+static void face_duplilist(ListBase *lb, ID *id, Object *par, float par_space_mat[][4], int level, int animated)
{
- Object *ob;
- Base *base;
+ Object *ob, *ob_iter;
+ Base *base = NULL;
+ DupliObject *dob;
DerivedMesh *dm;
+ Mesh *me;
+ MTFace *mtface;
MFace *mface;
MVert *mvert;
- float pmat[4][4], imat[3][3];
- int lay, totface, a;
-
- Mat4CpyMat4(pmat, par->obmat);
+ float pmat[4][4], imat[3][3], (*orco)[3] = NULL, w;
+ int lay, oblay, totface, a;
+ Scene *sce = NULL;
+ Group *group = NULL;
+ GroupObject *go = NULL;
+ float ob__obmat[4][4]; /* needed for groups where the object matrix needs to be modified */
- lay= G.scene->lay;
+ /* simple preventing of too deep nested groups */
+ if(level>MAX_DUPLI_RECUR) return;
+ Mat4CpyMat4(pmat, par->obmat);
+
if(par==G.obedit) {
int totvert;
dm= editmesh_get_derived_cage(CD_MASK_BAREMESH);
@@ -484,26 +577,69 @@ static void face_duplilist(ListBase *lb, Scene *sce, Object *par)
mface= dm->getFaceArray(dm);
mvert= dm->getVertArray(dm);
}
+
+ if(G.rendering) {
+ me= (Mesh*)par->data;
+
+ orco= (float(*)[3])get_mesh_orco_verts(par);
+ transform_mesh_orco_verts(me, orco, me->totvert, 0);
+ mtface= me->mtface;
+ }
+ else {
+ orco= NULL;
+ mtface= NULL;
+ }
+ /* having to loop on scene OR group objects is NOT FUN */
+ if (GS(id->name) == ID_SCE) {
+ sce = (Scene *)id;
+ lay= sce->lay;
+ base= sce->base.first;
+ } else {
+ group = (Group *)id;
+ lay= group->layer;
+ go = group->gobject.first;
+ }
- for(base= sce->base.first; base; base= base->next) {
+ /* Start looping on Scene OR Group objects */
+ while (base || go) {
+ if (sce) {
+ ob_iter= base->object;
+ oblay = base->lay;
+ } else {
+ ob_iter= go->ob;
+ oblay = ob_iter->lay;
+ }
- if(base->object->type>0 && (lay & base->lay) && G.obedit!=base->object) {
- ob= base->object->parent;
+ if (lay & oblay && G.obedit!=ob_iter) {
+ ob=ob_iter->parent;
while(ob) {
if(ob==par) {
+ ob = ob_iter;
+ /* End Scene/Group object loop, below is generic */
- ob= base->object;
- Mat3CpyMat4(imat, ob->parentinv);
+ /* par_space_mat - only used for groups so we can modify the space dupli's are in
+ when par_space_mat is NULL ob->obmat can be used instead of ob__obmat
+ */
+ if(par_space_mat)
+ Mat4MulMat4(ob__obmat, ob->obmat, par_space_mat);
+ else
+ Mat4CpyMat4(ob__obmat, ob->obmat);
+ Mat3CpyMat4(imat, ob->parentinv);
+
/* mballs have a different dupli handling */
if(ob->type!=OB_MBALL) ob->flag |= OB_DONE; /* doesnt render */
for(a=0; a<totface; a++) {
- float *v1= mvert[ mface[a].v1 ].co;
- float *v2= mvert[ mface[a].v2 ].co;
- float *v3= mvert[ mface[a].v3 ].co;
- float *v4= mface[a].v4?mvert[ mface[a].v4 ].co:NULL;
+ int mv1 = mface[a].v1;
+ int mv2 = mface[a].v2;
+ int mv3 = mface[a].v3;
+ int mv4 = mface[a].v4;
+ float *v1= mvert[mv1].co;
+ float *v2= mvert[mv2].co;
+ float *v3= mvert[mv3].co;
+ float *v4= (mv4)? mvert[mv4].co: NULL;
float cent[3], quat[4], mat[3][3], mat3[3][3], tmat[4][4], obmat[4][4];
/* translation */
@@ -514,9 +650,10 @@ static void face_duplilist(ListBase *lb, Scene *sce, Object *par)
Mat4MulVecfl(pmat, cent);
VecSubf(cent, cent, pmat[3]);
- VecAddf(cent, cent, ob->obmat[3]);
+ VecAddf(cent, cent, ob__obmat[3]);
+
+ Mat4CpyMat4(obmat, ob__obmat);
- Mat4CpyMat4(obmat, ob->obmat);
VECCOPY(obmat[3], cent);
/* rotation */
@@ -536,8 +673,40 @@ static void face_duplilist(ListBase *lb, Scene *sce, Object *par)
Mat4CpyMat4(tmat, obmat);
Mat4MulMat43(obmat, tmat, mat);
- new_dupli_object(lb, ob, obmat, lay, a);
-
+ dob= new_dupli_object(lb, ob, obmat, lay, a, OB_DUPLIFACES, animated);
+ if(G.rendering) {
+ w= (mv4)? 0.25f: 1.0f/3.0f;
+
+ if(orco) {
+ VECADDFAC(dob->orco, dob->orco, orco[mv1], w);
+ VECADDFAC(dob->orco, dob->orco, orco[mv2], w);
+ VECADDFAC(dob->orco, dob->orco, orco[mv3], w);
+ if(mv4)
+ VECADDFAC(dob->orco, dob->orco, orco[mv4], w);
+ }
+
+ if(mtface) {
+ dob->uv[0] += w*mtface[a].uv[0][0];
+ dob->uv[1] += w*mtface[a].uv[0][1];
+ dob->uv[0] += w*mtface[a].uv[1][0];
+ dob->uv[1] += w*mtface[a].uv[1][1];
+ dob->uv[0] += w*mtface[a].uv[2][0];
+ dob->uv[1] += w*mtface[a].uv[2][1];
+
+ if(mv4) {
+ dob->uv[0] += w*mtface[a].uv[3][0];
+ dob->uv[1] += w*mtface[a].uv[3][1];
+ }
+ }
+ }
+
+ if(ob->transflag & OB_DUPLI) {
+ float tmpmat[4][4];
+ Mat4CpyMat4(tmpmat, ob->obmat);
+ Mat4CpyMat4(ob->obmat, obmat); /* pretend we are really this mat */
+ object_duplilist_recursive((ID *)id, ob, lb, ob->obmat, level+1, animated);
+ Mat4CpyMat4(ob->obmat, tmpmat);
+ }
}
break;
@@ -545,34 +714,51 @@ static void face_duplilist(ListBase *lb, Scene *sce, Object *par)
ob= ob->parent;
}
}
+ if (sce) base= base->next; /* scene loop */
+ else go= go->next; /* group loop */
}
if(par==G.obedit) {
MEM_freeN(mface);
MEM_freeN(mvert);
}
+
+ if(orco)
+ MEM_freeN(orco);
dm->release(dm);
}
-static void new_particle_duplilist(ListBase *lb, Scene *sce, Object *par, ParticleSystem *psys)
+static void new_particle_duplilist(ListBase *lb, ID *id, Object *par, float par_space_mat[][4], ParticleSystem *psys, int level, int animated)
{
GroupObject *go;
- Object *ob, **oblist=0;
+ Object *ob=0, **oblist=0, obcopy, *obcopylist=0;
+ DupliObject *dob;
ParticleSettings *part;
ParticleData *pa;
+ ChildParticle *cpa=0;
ParticleKey state;
- float ctime, pa_time;
- float tmat[4][4], mat[3][3], obrotmat[3][3], parotmat[3][3], size=0.0;
- float xvec[3] = {-1.0, 0.0, 0.0}, *q;
- int lay, a, k, step_nbr = 0, counter;
+ ParticleCacheKey *cache;
+ ParticleSystemModifierData *psmd;
+ float ctime, pa_time, scale = 1.0f;
+ float tmat[4][4], mat[4][4], pamat[4][4], size=0.0;
+ float (*obmat)[4], (*oldobmat)[4];
+ int lay, a, b, k, step_nbr = 0, counter, hair = 0;
int totpart, totchild, totgroup=0, pa_num;
if(psys==0) return;
+ /* simple preventing of too deep nested groups */
+ if(level>MAX_DUPLI_RECUR) return;
+
part=psys->part;
+ psmd= psys_get_modifier(par, psys);
+
+ if(part==0)
+ return;
- if(part==0) return;
+ if(!psys_check_enabled(par, psys))
+ return;
ctime = bsystem_time(par, (float)G.scene->r.cfra, 0.0);
@@ -580,7 +766,7 @@ static void new_particle_duplilist(ListBase *lb, Scene *sce, Object *par, Partic
totchild = psys->totchild;
BLI_srandom(31415926 + psys->seed);
-
+
lay= G.scene->lay;
if((part->draw_as == PART_DRAW_OB && part->dup_ob) ||
(part->draw_as == PART_DRAW_GR && part->dup_group && part->dup_group->gobject.first)) {
@@ -590,103 +776,171 @@ static void new_particle_duplilist(ListBase *lb, Scene *sce, Object *par, Partic
else
step_nbr = 0;
+ /* if we have a hair particle system, use the path cache */
+ if(part->type == PART_HAIR) {
+ if(psys->flag & PSYS_HAIR_DONE)
+ hair= (totchild == 0 || psys->childcache) && psys->pathcache;
+ if(!hair)
+ return;
+
+ /* we use cache, update totchild according to cached data */
+ totchild = psys->totchildcache;
+ totpart = psys->totcached;
+ }
+
psys->lattice = psys_get_lattice(par, psys);
+ /* gather list of objects or single object */
if(part->draw_as==PART_DRAW_GR) {
group_handle_recalc_and_update(par, part->dup_group);
- go= part->dup_group->gobject.first;
- while(go) {
- go=go->next;
+ for(go=part->dup_group->gobject.first; go; go=go->next)
totgroup++;
- }
- oblist= MEM_callocN(totgroup*sizeof(Object *), "dupgroup object list");
- go= part->dup_group->gobject.first;
- for(a=0; a<totgroup; a++, go=go->next)
- oblist[a]=go->ob;
+ /* we also copy the actual objects to restore afterwards, since
+ * where_is_object_time will change the object which breaks transform */
+ oblist = MEM_callocN(totgroup*sizeof(Object *), "dupgroup object list");
+ obcopylist = MEM_callocN(totgroup*sizeof(Object), "dupgroup copy list");
+
+ go = part->dup_group->gobject.first;
+ for(a=0; a<totgroup; a++, go=go->next) {
+ oblist[a] = go->ob;
+ obcopylist[a] = *go->ob;
+ }
+ }
+ else {
+ ob = part->dup_ob;
+ obcopy = *ob;
}
if(totchild==0 || part->draw & PART_DRAW_PARENT)
- a=0;
+ a = 0;
else
- a=totpart;
+ a = totpart;
for(pa=psys->particles,counter=0; a<totpart+totchild; a++,pa++,counter++) {
if(a<totpart) {
- if(pa->flag & (PARS_UNEXIST+PARS_NO_DISP)) continue;
-
- pa_num=pa->num;
+ /* handle parent particle */
+ if(pa->flag & (PARS_UNEXIST+PARS_NO_DISP))
+ continue;
- pa_time=pa->time;
-
- size=pa->size;
+ pa_num = pa->num;
+ pa_time = pa->time;
+ size = pa->size;
}
else {
- /* TODO: figure these two out */
- pa_num = a;
- pa_time = psys->particles[psys->child[a - totpart].parent].time;
+ /* handle child particle */
+ cpa = &psys->child[a - totpart];
- size=psys_get_child_size(psys, &psys->child[a - totpart], ctime, 0);
+ pa_num = a;
+ pa_time = psys->particles[cpa->parent].time;
+ size = psys_get_child_size(psys, cpa, ctime, 0);
}
if(part->draw_as==PART_DRAW_GR) {
+ /* for groups, pick the object based on settings */
if(part->draw&PART_DRAW_RAND_GR)
- ob = oblist[BLI_rand() % totgroup];
+ b= BLI_rand() % totgroup;
else if(part->from==PART_FROM_PARTICLE)
- ob = oblist[pa_num % totgroup];
+ b= pa_num % totgroup;
else
- ob = oblist[a % totgroup];
+ b= a % totgroup;
+
+ ob = oblist[b];
+ obmat = oblist[b]->obmat;
+ oldobmat = obcopylist[b].obmat;
+ }
+ else {
+ obmat= ob->obmat;
+ oldobmat= obcopy.obmat;
}
- else
- ob = part->dup_ob;
for(k=0; k<=step_nbr; k++, counter++) {
- if(step_nbr) {
+ if(hair) {
+ /* hair we handle separate and compute transform based on hair keys */
+ if(a < totpart) {
+ cache = psys->pathcache[a];
+ psys_get_dupli_path_transform(par, psys, psmd, pa, 0, cache, pamat, &scale);
+ }
+ else {
+ cache = psys->childcache[a-totpart];
+ psys_get_dupli_path_transform(par, psys, psmd, 0, cpa, cache, pamat, &scale);
+ }
+
+ VECCOPY(pamat[3], cache->co);
+ pamat[3][3]= 1.0f;
+
+ }
+ else if(step_nbr) {
+ /* other keys */
state.time = (float)k / (float)step_nbr;
psys_get_particle_on_path(par, psys, a, &state, 0);
+
+ QuatToMat4(state.rot, pamat);
+ VECCOPY(pamat[3], state.co);
+ pamat[3][3]= 1.0f;
}
else {
+ /* first key */
state.time = -1.0;
if(psys_get_particle_state(par, psys, a, &state, 0) == 0)
continue;
- }
- QuatToMat3(state.rot, parotmat);
+ QuatToMat4(state.rot, pamat);
+ VECCOPY(pamat[3], state.co);
+ pamat[3][3]= 1.0f;
+ }
if(part->draw_as==PART_DRAW_GR && psys->part->draw & PART_DRAW_WHOLE_GR) {
- for(go= part->dup_group->gobject.first; go; go= go->next) {
-
- Mat4CpyMat4(tmat, go->ob->obmat);
- Mat4MulMat43(tmat, go->ob->obmat, parotmat);
- Mat4MulFloat3((float *)tmat, size);
-
- VECADD(tmat[3], go->ob->obmat[3], state.co);
+ for(go= part->dup_group->gobject.first, b=0; go; go= go->next, b++) {
+ Mat4MulMat4(tmat, oblist[b]->obmat, pamat);
+ Mat4MulFloat3((float *)tmat, size*scale);
+ if(par_space_mat)
+ Mat4MulMat4(mat, tmat, par_space_mat);
+ else
+ Mat4CpyMat4(mat, tmat);
- new_dupli_object(lb, go->ob, tmat, par->lay, counter);
+ dob= new_dupli_object(lb, go->ob, mat, par->lay, counter, OB_DUPLIPARTS, animated);
+ Mat4CpyMat4(dob->omat, obcopylist[b].obmat);
+ if(G.rendering)
+ psys_get_dupli_texture(par, part, psmd, pa, cpa, dob->uv, dob->orco);
}
}
else {
/* to give ipos in object correct offset */
where_is_object_time(ob, ctime-pa_time);
- q = vectoquat(xvec, ob->trackflag, ob->upflag);
- QuatToMat3(q, obrotmat);
-
- Mat3MulMat3(mat, parotmat, obrotmat);
- Mat4CpyMat4(tmat, ob->obmat);
- Mat4MulMat43(tmat, ob->obmat, mat);
- Mat4MulFloat3((float *)tmat, size);
+ Mat4CpyMat4(mat, pamat);
- VECCOPY(tmat[3], state.co);
+ Mat4MulMat4(tmat, obmat, mat);
+ Mat4MulFloat3((float *)tmat, size*scale);
+ if(par_space_mat)
+ Mat4MulMat4(mat, tmat, par_space_mat);
+ else
+ Mat4CpyMat4(mat, tmat);
- new_dupli_object(lb, ob, tmat, par->lay, counter);
+ dob= new_dupli_object(lb, ob, mat, par->lay, counter, OB_DUPLIPARTS, animated);
+ Mat4CpyMat4(dob->omat, oldobmat);
+ if(G.rendering)
+ psys_get_dupli_texture(par, part, psmd, pa, cpa, dob->uv, dob->orco);
}
}
}
+
+ /* restore objects since they were changed in where_is_object_time */
+ if(part->draw_as==PART_DRAW_GR) {
+ for(a=0; a<totgroup; a++)
+ *(oblist[a])= obcopylist[a];
+ }
+ else
+ *ob= obcopy;
}
+
+ /* clean up */
if(oblist)
MEM_freeN(oblist);
+ if(obcopylist)
+ MEM_freeN(obcopylist);
if(psys->lattice) {
end_latt_deform();
@@ -717,7 +971,7 @@ static Object *find_family_object(Object **obar, char *family, char ch)
}
-static void font_duplilist(ListBase *lb, Object *par)
+static void font_duplilist(ListBase *lb, Object *par, int level, int animated)
{
Object *ob, *obar[256];
Curve *cu;
@@ -725,6 +979,9 @@ static void font_duplilist(ListBase *lb, Object *par)
float vec[3], obmat[4][4], pmat[4][4], fsize, xof, yof;
int slen, a;
+ /* simple preventing of too deep nested groups */
+ if(level>MAX_DUPLI_RECUR) return;
+
Mat4CpyMat4(pmat, par->obmat);
/* in par the family name is stored, use this to find the other objects */
@@ -755,54 +1012,73 @@ static void font_duplilist(ListBase *lb, Object *par)
Mat4CpyMat4(obmat, par->obmat);
VECCOPY(obmat[3], vec);
- new_dupli_object(lb, ob, obmat, par->lay, a);
+ new_dupli_object(lb, ob, obmat, par->lay, a, OB_DUPLIVERTS, animated);
}
-
}
MEM_freeN(chartransdata);
}
/* ***************************** */
+static void object_duplilist_recursive(ID *id, Object *ob, ListBase *duplilist, float par_space_mat[][4], int level, int animated)
+{
+ if((ob->transflag & OB_DUPLI)==0)
+ return;
+
+ /* Should the dupli's be generated for this object? - Respect restrict flags */
+ if (G.rendering) {
+ if (ob->restrictflag & OB_RESTRICT_RENDER) {
+ return;
+ }
+ } else {
+ if (ob->restrictflag & OB_RESTRICT_VIEW) {
+ return;
+ }
+ }
-/* note; group dupli's already set transform matrix. see note in group_duplilist() */
-ListBase *object_duplilist(Scene *sce, Object *ob)
-{
- ListBase *duplilist= MEM_mallocN(sizeof(ListBase), "duplilist");
- duplilist->first= duplilist->last= NULL;
-
- if(ob->transflag & OB_DUPLI) {
- if(ob->transflag & OB_DUPLIPARTS) {
- ParticleSystem *psys = ob->particlesystem.first;
- for(; psys; psys=psys->next)
- new_particle_duplilist(duplilist, sce, ob, psys);
+ if(ob->transflag & OB_DUPLIPARTS) {
+ ParticleSystem *psys = ob->particlesystem.first;
+ for(; psys; psys=psys->next)
+ new_particle_duplilist(duplilist, id, ob, par_space_mat, psys, level+1, animated);
+ }
+ else if(ob->transflag & OB_DUPLIVERTS) {
+ if(ob->type==OB_MESH) {
+ vertex_duplilist(duplilist, id, ob, par_space_mat, level+1, animated);
}
- else if(ob->transflag & OB_DUPLIVERTS) {
- if(ob->type==OB_MESH) {
- vertex_duplilist(duplilist, sce, ob);
- }
- else if(ob->type==OB_FONT) {
- font_duplilist(duplilist, ob);
+ else if(ob->type==OB_FONT) {
+ if (GS(id->name)==ID_SCE) { /* TODO - support dupligroups */
+ font_duplilist(duplilist, ob, level+1, animated);
}
}
- else if(ob->transflag & OB_DUPLIFACES) {
- if(ob->type==OB_MESH)
- face_duplilist(duplilist, sce, ob);
+ }
+ else if(ob->transflag & OB_DUPLIFACES) {
+ if(ob->type==OB_MESH)
+ face_duplilist(duplilist, id, ob, par_space_mat, level+1, animated);
+ }
+ else if(ob->transflag & OB_DUPLIFRAMES) {
+ if (GS(id->name)==ID_SCE) { /* TODO - support dupligroups */
+ frames_duplilist(duplilist, ob, level+1, animated);
}
- else if(ob->transflag & OB_DUPLIFRAMES)
- frames_duplilist(duplilist, ob);
- else if(ob->transflag & OB_DUPLIGROUP) {
- DupliObject *dob;
-
- group_duplilist(duplilist, ob, 0); /* now recursive */
+ } else if(ob->transflag & OB_DUPLIGROUP) {
+ DupliObject *dob;
+
+ group_duplilist(duplilist, ob, level+1, animated); /* now recursive */
- /* make copy already, because in group dupli's deform displists can be made, requiring parent matrices */
+ if (level==0) {
for(dob= duplilist->first; dob; dob= dob->next)
- Mat4CpyMat4(dob->ob->obmat, dob->mat);
+ if(dob->type == OB_DUPLIGROUP)
+ Mat4CpyMat4(dob->ob->obmat, dob->mat);
}
-
}
-
+}
+
+/* Returns a list of DupliObject
+ * note; group dupli's already set transform matrix. see note in group_duplilist() */
+ListBase *object_duplilist(Scene *sce, Object *ob)
+{
+ ListBase *duplilist= MEM_mallocN(sizeof(ListBase), "duplilist");
+ duplilist->first= duplilist->last= NULL;
+ object_duplilist_recursive((ID *)sce, ob, duplilist, NULL, 0, 0);
return duplilist;
}
diff --git a/source/blender/blenkernel/intern/armature.c b/source/blender/blenkernel/intern/armature.c
index 4d50c268397..8bb694f45e8 100644
--- a/source/blender/blenkernel/intern/armature.c
+++ b/source/blender/blenkernel/intern/armature.c
@@ -30,6 +30,8 @@
#include <math.h>
#include <string.h>
#include <stdio.h>
+#include <float.h>
+
#include "MEM_guardedalloc.h"
//XXX #include "nla.h"
@@ -354,6 +356,117 @@ void bone_flip_name (char *name, int strip_number)
sprintf (name, "%s%s%s%s", prefix, replace, suffix, number);
}
+/* Finds the best possible extension to the name on a particular axis. (For renaming, check for unique names afterwards)
+ * This assumes that bone names are at most 32 chars long!
+ * strip_number: removes number extensions (TODO: not used)
+ * axis: the axis to name on
+ * head/tail: the head/tail co-ordinate of the bone on the specified axis
+ */
+void bone_autoside_name (char *name, int strip_number, short axis, float head, float tail)
+{
+ int len;
+ char basename[32]={""};
+ char extension[5]={""};
+
+ len= strlen(name);
+ if (len == 0) return;
+ strcpy(basename, name);
+
+ /* Figure out extension to append:
+ * - The extension to append is based upon the axis that we are working on.
+ * - If head happens to be on 0, then we must consider the tail position as well to decide
+ * which side the bone is on
+ * -> If tail is 0, then it's bone is considered to be on axis, so no extension should be added
+ * -> Otherwise, extension is added from perspective of object based on which side tail goes to
+ * - If head is non-zero, extension is added from perspective of object based on side head is on
+ */
+ if (axis == 2) {
+ /* z-axis - vertical (top/bottom) */
+ if (IS_EQ(head, 0)) {
+ if (tail < 0)
+ strcpy(extension, "Bot");
+ else if (tail > 0)
+ strcpy(extension, "Top");
+ }
+ else {
+ if (head < 0)
+ strcpy(extension, "Bot");
+ else
+ strcpy(extension, "Top");
+ }
+ }
+ else if (axis == 1) {
+ /* y-axis - depth (front/back) */
+ if (IS_EQ(head, 0)) {
+ if (tail < 0)
+ strcpy(extension, "Fr");
+ else if (tail > 0)
+ strcpy(extension, "Bk");
+ }
+ else {
+ if (head < 0)
+ strcpy(extension, "Fr");
+ else
+ strcpy(extension, "Bk");
+ }
+ }
+ else {
+ /* x-axis - horizontal (left/right) */
+ if (IS_EQ(head, 0)) {
+ if (tail < 0)
+ strcpy(extension, "R");
+ else if (tail > 0)
+ strcpy(extension, "L");
+ }
+ else {
+ if (head < 0)
+ strcpy(extension, "R");
+ else if (head > 0)
+ strcpy(extension, "L");
+ }
+ }
+
+ /* Simple name truncation
+ * - truncate if there is an extension and it wouldn't be able to fit
+ * - otherwise, just append to end
+ */
+ if (extension[0]) {
+ int change = 1;
+
+ while (change) { /* remove extensions */
+ change = 0;
+ if (len > 2 && basename[len-2]=='.') {
+ if (basename[len-1]=='L' || basename[len-1] == 'R' ) { /* L R */
+ basename[len-2] = '\0';
+ len-=2;
+ change= 1;
+ }
+ } else if (len > 3 && basename[len-3]=='.') {
+ if ( (basename[len-2]=='F' && basename[len-1] == 'r') || /* Fr */
+ (basename[len-2]=='B' && basename[len-1] == 'k') /* Bk */
+ ) {
+ basename[len-3] = '\0';
+ len-=3;
+ change= 1;
+ }
+ } else if (len > 4 && basename[len-4]=='.') {
+ if ( (basename[len-3]=='T' && basename[len-2]=='o' && basename[len-1] == 'p') || /* Top */
+ (basename[len-3]=='B' && basename[len-2]=='o' && basename[len-1] == 't') /* Bot */
+ ) {
+ basename[len-4] = '\0';
+ len-=4;
+ change= 1;
+ }
+ }
+ }
+
+ if ((32 - len) < strlen(extension) + 1) { /* add 1 for the '.' */
+ strncpy(name, basename, len-strlen(extension));
+ }
+ }
+
+ sprintf(name, "%s.%s", basename, extension);
+}
/* ************* B-Bone support ******************* */
@@ -1305,18 +1418,27 @@ static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected
bPoseChannel *pchan, *pchanp, pchanw;
bConstraint *con;
- if(frompose==NULL) return;
+ if (frompose==NULL) return;
/* exception, armature local layer should be proxied too */
- if(pose->proxy_layer)
+ if (pose->proxy_layer)
((bArmature *)ob->data)->layer= pose->proxy_layer;
/* clear all transformation values from library */
rest_pose(frompose);
- pchan= pose->chanbase.first;
- for(; pchan; pchan= pchan->next) {
- if(pchan->bone->layer & layer_protected) {
+ /* copy over all of the proxy's bone groups */
+ /* TODO for later - implement 'local' bone groups as for constraints
+ * Note: this isn't trivial, as bones reference groups by index not by pointer,
+ * so syncing things correctly needs careful attention
+ */
+ BLI_freelistN(&pose->agroups);
+ BLI_duplicatelist(&pose->agroups, &frompose->agroups);
+ pose->active_group= frompose->active_group;
+
+ for (pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
+ if (pchan->bone->layer & layer_protected) {
+ ListBase proxylocal_constraints = {NULL, NULL};
pchanp= get_pose_channel(frompose, pchan->name);
/* copy posechannel to temp, but restore important pointers */
@@ -1327,9 +1449,16 @@ static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected
pchanw.child= pchan->child;
pchanw.path= NULL;
- /* constraints, set target ob pointer to own object */
+ /* constraints - proxy constraints are flushed... local ones are added after
+ * 1. extract constraints not from proxy (CONSTRAINT_PROXY_LOCAL) from pchan's constraints
+ * 2. copy proxy-pchan's constraints on-to new
+ * 3. add extracted local constraints back on top
+ */
+ extract_proxylocal_constraints(&proxylocal_constraints, &pchan->constraints);
copy_constraints(&pchanw.constraints, &pchanp->constraints);
+ addlisttolist(&pchanw.constraints, &proxylocal_constraints);
+ /* constraints - set target ob pointer to own object */
for (con= pchanw.constraints.first; con; con= con->next) {
bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
ListBase targets = {NULL, NULL};
@@ -1444,21 +1573,16 @@ static void initialize_posetree(struct Object *ob, bPoseChannel *pchan_tip)
/* find IK constraint, and validate it */
for(con= pchan_tip->constraints.first; con; con= con->next) {
- if(con->type==CONSTRAINT_TYPE_KINEMATIC) break;
+ if(con->type==CONSTRAINT_TYPE_KINEMATIC) {
+ data=(bKinematicConstraint*)con->data;
+ if (data->flag & CONSTRAINT_IK_AUTO) break;
+ if (data->tar==NULL) continue;
+ if (data->tar->type==OB_ARMATURE && data->subtarget[0]==0) continue;
+ if ((con->flag & CONSTRAINT_DISABLE)==0 && (con->enforce!=0.0)) break;
+ }
}
if(con==NULL) return;
- data=(bKinematicConstraint*)con->data;
-
- /* two types of targets */
- if(data->flag & CONSTRAINT_IK_AUTO);
- else {
- if(con->flag & CONSTRAINT_DISABLE) return; /* checked in editconstraint.c */
- if(con->enforce == 0.0f) return;
- if(data->tar==NULL) return;
- if(data->tar->type==OB_ARMATURE && data->subtarget[0]==0) return;
- }
-
/* exclude tip from chain? */
if(!(data->flag & CONSTRAINT_IK_TIP))
pchan_tip= pchan_tip->parent;
@@ -1561,7 +1685,7 @@ static void initialize_posetree(struct Object *ob, bPoseChannel *pchan_tip)
were executed & assigned. Now as last we do an IK pass */
static void execute_posetree(Object *ob, PoseTree *tree)
{
- float R_parmat[3][3];
+ float R_parmat[3][3], identity[3][3];
float iR_parmat[3][3];
float R_bonemat[3][3];
float goalrot[3][3], goalpos[3];
@@ -1570,7 +1694,8 @@ static void execute_posetree(Object *ob, PoseTree *tree)
float irest_basis[3][3], full_basis[3][3];
float end_pose[4][4], world_pose[4][4];
float length, basis[3][3], rest_basis[3][3], start[3], *ikstretch=NULL;
- int a, flag, hasstretch=0;
+ float resultinf=0.0f;
+ int a, flag, hasstretch=0, resultblend=0;
bPoseChannel *pchan;
IK_Segment *seg, *parent, **iktree, *iktarget;
IK_Solver *solver;
@@ -1580,13 +1705,13 @@ static void execute_posetree(Object *ob, PoseTree *tree)
if (tree->totchannel == 0)
return;
-
+
iktree= MEM_mallocN(sizeof(void*)*tree->totchannel, "ik tree");
for(a=0; a<tree->totchannel; a++) {
pchan= tree->pchan[a];
bone= pchan->bone;
-
+
/* set DoF flag */
flag= 0;
if(!(pchan->ikflag & BONE_IK_NO_XDOF) && !(pchan->ikflag & BONE_IK_NO_XDOF_TEMP))
@@ -1595,32 +1720,32 @@ static void execute_posetree(Object *ob, PoseTree *tree)
flag |= IK_YDOF;
if(!(pchan->ikflag & BONE_IK_NO_ZDOF) && !(pchan->ikflag & BONE_IK_NO_ZDOF_TEMP))
flag |= IK_ZDOF;
-
+
if(tree->stretch && (pchan->ikstretch > 0.0)) {
flag |= IK_TRANS_YDOF;
hasstretch = 1;
}
-
+
seg= iktree[a]= IK_CreateSegment(flag);
-
+
/* find parent */
if(a == 0)
parent= NULL;
else
parent= iktree[tree->parent[a]];
-
+
IK_SetParent(seg, parent);
-
+
/* get the matrix that transforms from prevbone into this bone */
Mat3CpyMat4(R_bonemat, pchan->pose_mat);
-
+
/* gather transformations for this IK segment */
-
+
if (pchan->parent)
Mat3CpyMat4(R_parmat, pchan->parent->pose_mat);
else
Mat3One(R_parmat);
-
+
/* bone offset */
if (pchan->parent && (a > 0))
VecSubf(start, pchan->pose_head, pchan->parent->pose_tail);
@@ -1630,40 +1755,40 @@ static void execute_posetree(Object *ob, PoseTree *tree)
/* change length based on bone size */
length= bone->length*VecLength(R_bonemat[1]);
-
+
/* compute rest basis and its inverse */
Mat3CpyMat3(rest_basis, bone->bone_mat);
Mat3CpyMat3(irest_basis, bone->bone_mat);
Mat3Transp(irest_basis);
-
+
/* compute basis with rest_basis removed */
Mat3Inv(iR_parmat, R_parmat);
Mat3MulMat3(full_basis, iR_parmat, R_bonemat);
Mat3MulMat3(basis, irest_basis, full_basis);
-
+
/* basis must be pure rotation */
Mat3Ortho(basis);
-
+
/* transform offset into local bone space */
Mat3Ortho(iR_parmat);
Mat3MulVecfl(iR_parmat, start);
-
+
IK_SetTransform(seg, start, rest_basis, basis, length);
-
+
if (pchan->ikflag & BONE_IK_XLIMIT)
IK_SetLimit(seg, IK_X, pchan->limitmin[0], pchan->limitmax[0]);
if (pchan->ikflag & BONE_IK_YLIMIT)
IK_SetLimit(seg, IK_Y, pchan->limitmin[1], pchan->limitmax[1]);
if (pchan->ikflag & BONE_IK_ZLIMIT)
IK_SetLimit(seg, IK_Z, pchan->limitmin[2], pchan->limitmax[2]);
-
+
IK_SetStiffness(seg, IK_X, pchan->stiffness[0]);
IK_SetStiffness(seg, IK_Y, pchan->stiffness[1]);
IK_SetStiffness(seg, IK_Z, pchan->stiffness[2]);
-
+
if(tree->stretch && (pchan->ikstretch > 0.0)) {
float ikstretch = pchan->ikstretch*pchan->ikstretch;
- IK_SetStiffness(seg, IK_TRANS_Y, MIN2(1.0-ikstretch, 0.999));
+ IK_SetStiffness(seg, IK_TRANS_Y, MIN2(1.0-ikstretch, 0.99));
IK_SetLimit(seg, IK_TRANS_Y, 0.001, 1e10);
}
}
@@ -1689,7 +1814,7 @@ static void execute_posetree(Object *ob, PoseTree *tree)
for (target=tree->targets.first; target; target=target->next) {
float polepos[3];
int poleconstrain= 0;
-
+
data= (bKinematicConstraint*)target->con->data;
/* 1.0=ctime, we pass on object for auto-ik (owner-type here is object, even though
@@ -1706,7 +1831,7 @@ static void execute_posetree(Object *ob, PoseTree *tree)
/* same for pole vector target */
if(data->poletar) {
get_constraint_target_matrix(target->con, 1, CONSTRAINT_OBTYPE_OBJECT, ob, rootmat, 1.0);
-
+
if(data->flag & CONSTRAINT_IK_SETANGLE) {
/* don't solve IK when we are setting the pole angle */
break;
@@ -1716,6 +1841,12 @@ static void execute_posetree(Object *ob, PoseTree *tree)
VECCOPY(polepos, goal[3]);
poleconstrain= 1;
+ /* for pole targets, we blend the result of the ik solver
+ * instead of the target position, otherwise we can't get
+ * a smooth transition */
+ resultblend= 1;
+ resultinf= target->con->enforce;
+
if(data->flag & CONSTRAINT_IK_GETANGLE) {
poleangledata= data;
data->flag &= ~CONSTRAINT_IK_GETANGLE;
@@ -1724,7 +1855,7 @@ static void execute_posetree(Object *ob, PoseTree *tree)
}
/* do we need blending? */
- if (target->con->enforce!=1.0) {
+ if (!resultblend && target->con->enforce!=1.0) {
float q1[4], q2[4], q[4];
float fac= target->con->enforce;
float mfac= 1.0-fac;
@@ -1774,36 +1905,41 @@ static void execute_posetree(Object *ob, PoseTree *tree)
tree->basis_change= MEM_mallocN(sizeof(float[3][3])*tree->totchannel, "ik basis change");
if(hasstretch)
ikstretch= MEM_mallocN(sizeof(float)*tree->totchannel, "ik stretch");
-
+
for(a=0; a<tree->totchannel; a++) {
IK_GetBasisChange(iktree[a], tree->basis_change[a]);
-
+
if(hasstretch) {
/* have to compensate for scaling received from parent */
float parentstretch, stretch;
-
+
pchan= tree->pchan[a];
parentstretch= (tree->parent[a] >= 0)? ikstretch[tree->parent[a]]: 1.0;
-
+
if(tree->stretch && (pchan->ikstretch > 0.0)) {
float trans[3], length;
-
+
IK_GetTranslationChange(iktree[a], trans);
length= pchan->bone->length*VecLength(pchan->pose_mat[1]);
-
+
ikstretch[a]= (length == 0.0)? 1.0: (trans[1]+length)/length;
}
else
ikstretch[a] = 1.0;
-
+
stretch= (parentstretch == 0.0)? 1.0: ikstretch[a]/parentstretch;
-
+
VecMulf(tree->basis_change[a][0], stretch);
VecMulf(tree->basis_change[a][1], stretch);
VecMulf(tree->basis_change[a][2], stretch);
-
}
+ if(resultblend && resultinf!=1.0f) {
+ Mat3One(identity);
+ Mat3BlendMat3(tree->basis_change[a], identity,
+ tree->basis_change[a], resultinf);
+ }
+
IK_FreeSegment(iktree[a]);
}
@@ -2072,8 +2208,10 @@ static void where_is_pose_bone(Object *ob, bPoseChannel *pchan, float ctime)
}
else {
Mat4MulMat4(pchan->pose_mat, pchan->chan_mat, bone->arm_mat);
- /* only rootbones get the cyclic offset */
- VecAddf(pchan->pose_mat[3], pchan->pose_mat[3], ob->pose->cyclic_offset);
+
+ /* only rootbones get the cyclic offset (unless user doesn't want that) */
+ if ((bone->flag & BONE_NO_CYCLICOFFSET) == 0)
+ VecAddf(pchan->pose_mat[3], pchan->pose_mat[3], ob->pose->cyclic_offset);
}
/* do NLA strip modifiers - i.e. curve follow */
diff --git a/source/blender/blenkernel/intern/blender.c b/source/blender/blenkernel/intern/blender.c
index 109fe4b2d74..b63d63c925c 100644
--- a/source/blender/blenkernel/intern/blender.c
+++ b/source/blender/blenkernel/intern/blender.c
@@ -30,11 +30,15 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#ifndef WIN32
- #include <unistd.h> // for read close
- #include <sys/param.h> // for MAXPATHLEN
+#ifndef _WIN32
+ #include <unistd.h> // for read close
+ #include <sys/param.h> // for MAXPATHLEN
#else
- #include <io.h> // for open close read
+ #include <io.h> // for open close read
+ #define open _open
+ #define read _read
+ #define close _close
+ #define write _write
#endif
#include <stdlib.h>
@@ -61,6 +65,7 @@
#include "IMB_imbuf_types.h"
#include "IMB_imbuf.h"
+#include "BKE_action.h"
#include "BKE_blender.h"
#include "BKE_curve.h"
#include "BKE_depsgraph.h"
@@ -282,7 +287,6 @@ static void clean_paths(Main *main)
}
BLI_clean(scene->r.backbuf);
BLI_clean(scene->r.pic);
- BLI_clean(scene->r.ftype);
scene= scene->id.next;
}
@@ -313,6 +317,7 @@ static void setup_app_data(bContext *C, BlendFileData *bfd, char *filename)
extern void lib_link_screen_restore(Main *, Scene *);
SWAP(ListBase, G.main->screen, bfd->main->screen);
+ SWAP(ListBase, G.main->script, bfd->main->script);
/* we re-use current screen */
curscreen= C->screen;
@@ -366,7 +371,8 @@ static void setup_app_data(bContext *C, BlendFileData *bfd, char *filename)
/* special cases, override loaded flags: */
if (G.f & G_DEBUG) bfd->globalf |= G_DEBUG;
else bfd->globalf &= ~G_DEBUG;
- if (!(G.f & G_DOSCRIPTLINKS)) bfd->globalf &= ~G_DOSCRIPTLINKS;
+
+ if ((U.flag & USER_DONT_DOSCRIPTLINKS)) bfd->globalf &= ~G_DOSCRIPTLINKS;
G.f= bfd->globalf;
@@ -377,6 +383,9 @@ static void setup_app_data(bContext *C, BlendFileData *bfd, char *filename)
/* baseflags, groups, make depsgraph, etc */
set_scene_bg(C->scene);
+ /* clear BONE_UNKEYED flags, these are not valid anymore for proxies */
+ framechange_poses_clear_unkeyed();
+
/* last stage of do_versions actually, that sets recalc flags for recalc poses */
for(ob= G.main->object.first; ob; ob= ob->id.next) {
if(ob->type==OB_ARMATURE)
@@ -393,7 +402,7 @@ static void setup_app_data(bContext *C, BlendFileData *bfd, char *filename)
if (G.sce != filename) /* these are the same at times, should never copy to the same location */
strcpy(G.sce, filename);
- strcpy(G.main->name, filename); /* is guaranteed current file */
+ BLI_strncpy(G.main->name, filename, FILE_MAX); /* is guaranteed current file */
MEM_freeN(bfd);
}
@@ -445,8 +454,8 @@ int BKE_read_file_from_memory(bContext *C, char* filebuf, int filelength, void *
BlendFileData *bfd;
bfd= BLO_read_from_memory(filebuf, filelength, &bre);
- if (bfd) {
- setup_app_data(C, bfd, "<memory>");
+ if (bfd) {
+ setup_app_data(C, bfd, "<memory2>");
} else {
// XXX error("Loading failed: %s", BLO_bre_as_string(bre));
}
@@ -462,7 +471,7 @@ int BKE_read_file_from_memfile(bContext *C, MemFile *memfile)
bfd= BLO_read_from_memfile(G.sce, memfile, &bre);
if (bfd) {
- setup_app_data(C, bfd, "<memory>");
+ setup_app_data(C, bfd, "<memory1>");
} else {
// XXX error("Loading failed: %s", BLO_bre_as_string(bre));
}
@@ -481,6 +490,7 @@ typedef struct UndoElem {
char str[FILE_MAXDIR+FILE_MAXFILE];
char name[MAXUNDONAME];
MemFile memfile;
+ uintptr_t undosize;
} UndoElem;
static ListBase undobase={NULL, NULL};
@@ -511,6 +521,7 @@ static int read_undosave(bContext *C, UndoElem *uel)
/* name can be a dynamic string */
void BKE_write_undo(bContext *C, char *name)
{
+ uintptr_t maxmem, totmem, memused;
int nr, success;
UndoElem *uel;
@@ -560,7 +571,7 @@ void BKE_write_undo(bContext *C, char *name)
counter= counter % U.undosteps;
sprintf(numstr, "%d.blend", counter);
- BLI_make_file_string("/", tstr, U.tempdir, numstr);
+ BLI_make_file_string("/", tstr, btempdir, numstr);
success= BLO_write_file(C, tstr, G.fileflags, &err);
@@ -572,12 +583,41 @@ void BKE_write_undo(bContext *C, char *name)
if(curundo->prev) prevfile= &(curundo->prev->memfile);
+ memused= MEM_get_memory_in_use();
success= BLO_write_file_mem(C, prevfile, &curundo->memfile, G.fileflags, &err);
-
+ curundo->undosize= MEM_get_memory_in_use() - memused;
+ }
+
+ if(U.undomemory != 0) {
+ /* limit to maximum memory (afterwards, we can't know in advance) */
+ totmem= 0;
+ maxmem= ((uintptr_t)U.undomemory)*1024*1024;
+
+ /* keep at least two (original + other) */
+ uel= undobase.last;
+ while(uel && uel->prev) {
+ totmem+= uel->undosize;
+ if(totmem>maxmem) break;
+ uel= uel->prev;
+ }
+
+ if(uel) {
+ if(uel->prev && uel->prev->prev)
+ uel= uel->prev;
+
+ while(undobase.first!=uel) {
+ UndoElem *first= undobase.first;
+ BLI_remlink(&undobase, first);
+ /* the merge is because of compression */
+ BLO_merge_memfile(&first->memfile, &first->next->memfile);
+ MEM_freeN(first);
+ }
+ }
}
}
-/* 1= an undo, -1 is a redo. we have to make sure 'curundo' remains at current situation */
+/* 1= an undo, -1 is a redo. we have to make sure 'curundo' remains at current situation
+ * Note, ALWAYS call sound_initialize_sounds after BKE_undo_step() */
void BKE_undo_step(bContext *C, int step)
{
@@ -638,14 +678,14 @@ char *BKE_undo_menu_string(void)
UndoElem *uel;
DynStr *ds= BLI_dynstr_new();
char *menu;
-
+
BLI_dynstr_append(ds, "Global Undo History %t");
for(uel= undobase.first; uel; uel= uel->next) {
BLI_dynstr_append(ds, "|");
BLI_dynstr_append(ds, uel->name);
}
-
+
menu= BLI_dynstr_get_cstring(ds);
BLI_dynstr_free(ds);
@@ -671,11 +711,11 @@ void BKE_undo_save_quit(void)
/* no undo state to save */
if(undobase.first==undobase.last) return;
- BLI_make_file_string("/", str, U.tempdir, "quit.blend");
+ BLI_make_file_string("/", str, btempdir, "quit.blend");
file = open(str,O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
if(file == -1) {
- printf("Unable to save %s\n", str);
+ //XXX error("Unable to save %s, check you have permissions", str);
return;
}
@@ -687,7 +727,7 @@ void BKE_undo_save_quit(void)
close(file);
- if(chunk) printf("Unable to save %s\n", str);
+ if(chunk) ; //XXX error("Unable to save %s, internal error", str);
else printf("Saved session recovery to %s\n", str);
}
diff --git a/source/blender/blenkernel/intern/bmesh_private.h b/source/blender/blenkernel/intern/bmesh_private.h
new file mode 100644
index 00000000000..f34ef0090f3
--- /dev/null
+++ b/source/blender/blenkernel/intern/bmesh_private.h
@@ -0,0 +1,70 @@
+/**
+ * BME_private.h jan 2007
+ *
+ * low level, 'private' function prototypes for bmesh kernel.
+ *
+ * $Id: BKE_bmesh.h,v 1.00 2007/01/17 17:42:01 Briggs Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2004 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Geoffrey Bantle.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef BMESH_PRIVATE
+#define BMESH_PRIVATE
+
+#include "BKE_bmesh.h"
+
+/*ALLOCATION/DEALLOCATION*/
+struct BME_Vert *BME_addvertlist(struct BME_Mesh *bm, struct BME_Vert *example);
+struct BME_Edge *BME_addedgelist(struct BME_Mesh *bm, struct BME_Vert *v1, struct BME_Vert *v2, struct BME_Edge *example);
+struct BME_Poly *BME_addpolylist(struct BME_Mesh *bm, struct BME_Poly *example);
+struct BME_Loop *BME_create_loop(struct BME_Mesh *bm, struct BME_Vert *v, struct BME_Edge *e, struct BME_Poly *f, struct BME_Loop *example);
+
+void BME_free_vert(struct BME_Mesh *bm, struct BME_Vert *v);
+void BME_free_edge(struct BME_Mesh *bm, struct BME_Edge *e);
+void BME_free_poly(struct BME_Mesh *bm, struct BME_Poly *f);
+void BME_free_loop(struct BME_Mesh *bm, struct BME_Loop *l);
+
+/*DOUBLE CIRCULAR LINKED LIST FUNCTIONS*/
+void BME_cycle_append(void *h, void *nt);
+int BME_cycle_remove(void *h, void *remn);
+int BME_cycle_validate(int len, void *h);
+/*DISK CYCLE MANAGMENT*/
+int BME_disk_append_edge(struct BME_Edge *e, struct BME_Vert *v);
+void BME_disk_remove_edge(struct BME_Edge *e, struct BME_Vert *v);
+/*RADIAL CYCLE MANAGMENT*/
+void BME_radial_append(struct BME_Edge *e, struct BME_Loop *l);
+void BME_radial_remove_loop(struct BME_Loop *l, struct BME_Edge *e);
+
+/*MISC FUNCTIONS*/
+int BME_edge_swapverts(struct BME_Edge *e, struct BME_Vert *orig, struct BME_Vert *new); /*relink edge*/
+int BME_disk_hasedge(struct BME_Vert *v, struct BME_Edge *e);
+
+/*Error reporting. Shouldnt be called by tools ever.*/
+void BME_error(void);
+#endif
diff --git a/source/blender/blenkernel/intern/brush.c b/source/blender/blenkernel/intern/brush.c
index f1b12869c0f..1c53af97dbb 100644
--- a/source/blender/blenkernel/intern/brush.c
+++ b/source/blender/blenkernel/intern/brush.c
@@ -70,7 +70,8 @@ Brush *add_brush(char *name)
brush->clone.alpha= 0.5;
/* enable fake user by default */
- brush_toggle_fake_user(brush);
+ brush->id.flag |= LIB_FAKEUSER;
+ brush_toggled_fake_user(brush);
return brush;
}
@@ -92,8 +93,10 @@ Brush *copy_brush(Brush *brush)
}
/* enable fake user by default */
- if (!(brushn->id.flag & LIB_FAKEUSER))
- brush_toggle_fake_user(brushn);
+ if (!(brushn->id.flag & LIB_FAKEUSER)) {
+ brushn->id.flag |= LIB_FAKEUSER;
+ brush_toggled_fake_user(brushn);
+ }
return brushn;
}
@@ -145,8 +148,10 @@ void make_local_brush(Brush *brush)
new_id(0, (ID *)brush, 0);
/* enable fake user by default */
- if (!(brush->id.flag & LIB_FAKEUSER))
- brush_toggle_fake_user(brush);
+ if (!(brush->id.flag & LIB_FAKEUSER)) {
+ brush->id.flag |= LIB_FAKEUSER;
+ brush_toggled_fake_user(brush);
+ }
}
else if(local && lib) {
brushn= copy_brush(brush);
@@ -200,16 +205,14 @@ int brush_delete(Brush **current_brush)
return 0;
}
-void brush_toggle_fake_user(Brush *brush)
+void brush_toggled_fake_user(Brush *brush)
{
ID *id= (ID*)brush;
if(id) {
if(id->flag & LIB_FAKEUSER) {
- id->flag -= LIB_FAKEUSER;
- id->us--;
- } else {
- id->flag |= LIB_FAKEUSER;
id_us_plus(id);
+ } else {
+ id->us--;
}
}
}
@@ -356,7 +359,6 @@ void brush_sample_tex(Brush *brush, float *xy, float *rgba)
rgba[0]= rgba[1]= rgba[2]= rgba[3]= 1.0f;
}
-#define FTOCHAR(val) val<=0.0f?0: (val>=1.0f?255: (char)(255.0f*val))
void brush_imbuf_new(Brush *brush, short flt, short texfall, int size, ImBuf **outbuf)
{
diff --git a/source/blender/blenkernel/intern/bullet.c b/source/blender/blenkernel/intern/bullet.c
new file mode 100644
index 00000000000..b389f8c0536
--- /dev/null
+++ b/source/blender/blenkernel/intern/bullet.c
@@ -0,0 +1,96 @@
+/*
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "MEM_guardedalloc.h"
+
+/* types */
+#include "DNA_object_force.h" /* here is the softbody struct */
+
+#include "BKE_bullet.h"
+
+
+/* ************ Object level, exported functions *************** */
+
+/* allocates and initializes general main data */
+BulletSoftBody *bsbNew(void)
+{
+ BulletSoftBody *bsb;
+
+ bsb= MEM_callocN(sizeof(BulletSoftBody), "bulletsoftbody");
+
+ bsb->flag = OB_BSB_BENDING_CONSTRAINTS | OB_BSB_SHAPE_MATCHING | OB_BSB_AERO_VPOINT;
+ bsb->linStiff = 0.5f;
+ bsb->angStiff = 1.0f;
+ bsb->volume = 1.0f;
+
+
+ bsb->viterations = 0;
+ bsb->piterations = 2;
+ bsb->diterations = 0;
+ bsb->citerations = 4;
+
+ bsb->kSRHR_CL = 0.1f;
+ bsb->kSKHR_CL = 1.f;
+ bsb->kSSHR_CL = 0.5f;
+ bsb->kSR_SPLT_CL = 0.5f;
+
+ bsb->kSK_SPLT_CL = 0.5f;
+ bsb->kSS_SPLT_CL = 0.5f;
+ bsb->kVCF = 1;
+ bsb->kDP = 0;
+
+ bsb->kDG = 0;
+ bsb->kLF = 0;
+ bsb->kPR = 0;
+ bsb->kVC = 0;
+
+ bsb->kDF = 0.2f;
+ bsb->kMT = 0.05;
+ bsb->kCHR = 1.0f;
+ bsb->kKHR = 0.1f;
+
+ bsb->kSHR = 1.0f;
+ bsb->kAHR = 0.7f;
+
+ bsb->collisionflags = 0;
+ //bsb->collisionflags = OB_BSB_COL_CL_RS + OB_BSB_COL_CL_SS;
+ bsb->numclusteriterations = 64;
+
+ return bsb;
+}
+
+/* frees all */
+void bsbFree(BulletSoftBody *bsb)
+{
+ /* no internal data yet */
+ MEM_freeN(bsb);
+}
+
+
diff --git a/source/blender/blenkernel/intern/bvhutils.c b/source/blender/blenkernel/intern/bvhutils.c
new file mode 100644
index 00000000000..ae449843d2a
--- /dev/null
+++ b/source/blender/blenkernel/intern/bvhutils.c
@@ -0,0 +1,577 @@
+/**
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): André Pinto.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#include <stdio.h>
+#include <string.h>
+#include <math.h>
+
+#include "BKE_bvhutils.h"
+
+#include "DNA_object_types.h"
+#include "DNA_modifier_types.h"
+#include "DNA_meshdata_types.h"
+
+#include "BKE_DerivedMesh.h"
+#include "BKE_utildefines.h"
+#include "BKE_deform.h"
+#include "BKE_cdderivedmesh.h"
+#include "BKE_displist.h"
+#include "BKE_global.h"
+
+#include "BLI_arithb.h"
+
+/* Math stuff for ray casting on mesh faces and for nearest surface */
+
+static float ray_tri_intersection(const BVHTreeRay *ray, const float m_dist, const float *v0, const float *v1, const float *v2)
+{
+ float dist;
+
+ if(RayIntersectsTriangle((float*)ray->origin, (float*)ray->direction, (float*)v0, (float*)v1, (float*)v2, &dist, NULL))
+ return dist;
+
+ return FLT_MAX;
+}
+
+static float sphereray_tri_intersection(const BVHTreeRay *ray, float radius, const float m_dist, const float *v0, const float *v1, const float *v2)
+{
+
+ float idist;
+ float p1[3];
+ float plane_normal[3], hit_point[3];
+
+ CalcNormFloat((float*)v0, (float*)v1, (float*)v2, plane_normal);
+
+ VECADDFAC( p1, ray->origin, ray->direction, m_dist);
+ if(SweepingSphereIntersectsTriangleUV((float*)ray->origin, p1, radius, (float*)v0, (float*)v1, (float*)v2, &idist, hit_point))
+ {
+ return idist * m_dist;
+ }
+
+ return FLT_MAX;
+}
+
+
+/*
+ * Function adapted from David Eberly's distance tools (LGPL)
+ * http://www.geometrictools.com/LibFoundation/Distance/Distance.html
+ */
+static float nearest_point_in_tri_surface(const float *v0,const float *v1,const float *v2,const float *p, int *v, int *e, float *nearest )
+{
+ float diff[3];
+ float e0[3];
+ float e1[3];
+ float A00;
+ float A01;
+ float A11;
+ float B0;
+ float B1;
+ float C;
+ float Det;
+ float S;
+ float T;
+ float sqrDist;
+ int lv = -1, le = -1;
+
+ VECSUB(diff, v0, p);
+ VECSUB(e0, v1, v0);
+ VECSUB(e1, v2, v0);
+
+ A00 = INPR ( e0, e0 );
+ A01 = INPR( e0, e1 );
+ A11 = INPR ( e1, e1 );
+ B0 = INPR( diff, e0 );
+ B1 = INPR( diff, e1 );
+ C = INPR( diff, diff );
+ Det = fabs( A00 * A11 - A01 * A01 );
+ S = A01 * B1 - A11 * B0;
+ T = A01 * B0 - A00 * B1;
+
+ if ( S + T <= Det )
+ {
+ if ( S < 0.0f )
+ {
+ if ( T < 0.0f ) // Region 4
+ {
+ if ( B0 < 0.0f )
+ {
+ T = 0.0f;
+ if ( -B0 >= A00 )
+ {
+ S = (float)1.0;
+ sqrDist = A00 + 2.0f * B0 + C;
+ lv = 1;
+ }
+ else
+ {
+ if(fabs(A00) > FLT_EPSILON)
+ S = -B0/A00;
+ else
+ S = 0.0f;
+ sqrDist = B0 * S + C;
+ le = 0;
+ }
+ }
+ else
+ {
+ S = 0.0f;
+ if ( B1 >= 0.0f )
+ {
+ T = 0.0f;
+ sqrDist = C;
+ lv = 0;
+ }
+ else if ( -B1 >= A11 )
+ {
+ T = 1.0f;
+ sqrDist = A11 + 2.0f * B1 + C;
+ lv = 2;
+ }
+ else
+ {
+ if(fabs(A11) > FLT_EPSILON)
+ T = -B1 / A11;
+ else
+ T = 0.0f;
+ sqrDist = B1 * T + C;
+ le = 1;
+ }
+ }
+ }
+ else // Region 3
+ {
+ S = 0.0f;
+ if ( B1 >= 0.0f )
+ {
+ T = 0.0f;
+ sqrDist = C;
+ lv = 0;
+ }
+ else if ( -B1 >= A11 )
+ {
+ T = 1.0f;
+ sqrDist = A11 + 2.0f * B1 + C;
+ lv = 2;
+ }
+ else
+ {
+ if(fabs(A11) > FLT_EPSILON)
+ T = -B1 / A11;
+ else
+ T = 0.0;
+ sqrDist = B1 * T + C;
+ le = 1;
+ }
+ }
+ }
+ else if ( T < 0.0f ) // Region 5
+ {
+ T = 0.0f;
+ if ( B0 >= 0.0f )
+ {
+ S = 0.0f;
+ sqrDist = C;
+ lv = 0;
+ }
+ else if ( -B0 >= A00 )
+ {
+ S = 1.0f;
+ sqrDist = A00 + 2.0f * B0 + C;
+ lv = 1;
+ }
+ else
+ {
+ if(fabs(A00) > FLT_EPSILON)
+ S = -B0 / A00;
+ else
+ S = 0.0f;
+ sqrDist = B0 * S + C;
+ le = 0;
+ }
+ }
+ else // Region 0
+ {
+ // Minimum at interior lv
+ float invDet;
+ if(fabs(Det) > FLT_EPSILON)
+ invDet = 1.0f / Det;
+ else
+ invDet = 0.0f;
+ S *= invDet;
+ T *= invDet;
+ sqrDist = S * ( A00 * S + A01 * T + 2.0f * B0) +
+ T * ( A01 * S + A11 * T + 2.0f * B1 ) + C;
+ }
+ }
+ else
+ {
+ float tmp0, tmp1, numer, denom;
+
+ if ( S < 0.0f ) // Region 2
+ {
+ tmp0 = A01 + B0;
+ tmp1 = A11 + B1;
+ if ( tmp1 > tmp0 )
+ {
+ numer = tmp1 - tmp0;
+ denom = A00 - 2.0f * A01 + A11;
+ if ( numer >= denom )
+ {
+ S = 1.0f;
+ T = 0.0f;
+ sqrDist = A00 + 2.0f * B0 + C;
+ lv = 1;
+ }
+ else
+ {
+ if(fabs(denom) > FLT_EPSILON)
+ S = numer / denom;
+ else
+ S = 0.0f;
+ T = 1.0f - S;
+ sqrDist = S * ( A00 * S + A01 * T + 2.0f * B0 ) +
+ T * ( A01 * S + A11 * T + 2.0f * B1 ) + C;
+ le = 2;
+ }
+ }
+ else
+ {
+ S = 0.0f;
+ if ( tmp1 <= 0.0f )
+ {
+ T = 1.0f;
+ sqrDist = A11 + 2.0f * B1 + C;
+ lv = 2;
+ }
+ else if ( B1 >= 0.0f )
+ {
+ T = 0.0f;
+ sqrDist = C;
+ lv = 0;
+ }
+ else
+ {
+ if(fabs(A11) > FLT_EPSILON)
+ T = -B1 / A11;
+ else
+ T = 0.0f;
+ sqrDist = B1 * T + C;
+ le = 1;
+ }
+ }
+ }
+ else if ( T < 0.0f ) // Region 6
+ {
+ tmp0 = A01 + B1;
+ tmp1 = A00 + B0;
+ if ( tmp1 > tmp0 )
+ {
+ numer = tmp1 - tmp0;
+ denom = A00 - 2.0f * A01 + A11;
+ if ( numer >= denom )
+ {
+ T = 1.0f;
+ S = 0.0f;
+ sqrDist = A11 + 2.0f * B1 + C;
+ lv = 2;
+ }
+ else
+ {
+ if(fabs(denom) > FLT_EPSILON)
+ T = numer / denom;
+ else
+ T = 0.0f;
+ S = 1.0f - T;
+ sqrDist = S * ( A00 * S + A01 * T + 2.0f * B0 ) +
+ T * ( A01 * S + A11 * T + 2.0f * B1 ) + C;
+ le = 2;
+ }
+ }
+ else
+ {
+ T = 0.0f;
+ if ( tmp1 <= 0.0f )
+ {
+ S = 1.0f;
+ sqrDist = A00 + 2.0f * B0 + C;
+ lv = 1;
+ }
+ else if ( B0 >= 0.0f )
+ {
+ S = 0.0f;
+ sqrDist = C;
+ lv = 0;
+ }
+ else
+ {
+ if(fabs(A00) > FLT_EPSILON)
+ S = -B0 / A00;
+ else
+ S = 0.0f;
+ sqrDist = B0 * S + C;
+ le = 0;
+ }
+ }
+ }
+ else // Region 1
+ {
+ numer = A11 + B1 - A01 - B0;
+ if ( numer <= 0.0f )
+ {
+ S = 0.0f;
+ T = 1.0f;
+ sqrDist = A11 + 2.0f * B1 + C;
+ lv = 2;
+ }
+ else
+ {
+ denom = A00 - 2.0f * A01 + A11;
+ if ( numer >= denom )
+ {
+ S = 1.0f;
+ T = 0.0f;
+ sqrDist = A00 + 2.0f * B0 + C;
+ lv = 1;
+ }
+ else
+ {
+ if(fabs(denom) > FLT_EPSILON)
+ S = numer / denom;
+ else
+ S = 0.0f;
+ T = 1.0f - S;
+ sqrDist = S * ( A00 * S + A01 * T + 2.0f * B0 ) +
+ T * ( A01 * S + A11 * T + 2.0f * B1 ) + C;
+ le = 2;
+ }
+ }
+ }
+ }
+
+ // Account for numerical round-off error
+ if ( sqrDist < FLT_EPSILON )
+ sqrDist = 0.0f;
+
+ {
+ float w[3], x[3], y[3], z[3];
+ VECCOPY(w, v0);
+ VECCOPY(x, e0);
+ VecMulf(x, S);
+ VECCOPY(y, e1);
+ VecMulf(y, T);
+ VECADD(z, w, x);
+ VECADD(z, z, y);
+ //VECSUB(d, p, z);
+ VECCOPY(nearest, z);
+ // d = p - ( v0 + S * e0 + T * e1 );
+ }
+ *v = lv;
+ *e = le;
+
+ return sqrDist;
+}
+
+
+/*
+ * BVH from meshs callbacks
+ */
+
+// Callback to bvh tree nearest point. The tree must bust have been built using bvhtree_from_mesh_faces.
+// userdata must be a BVHMeshCallbackUserdata built from the same mesh as the tree.
+static void mesh_faces_nearest_point(void *userdata, int index, const float *co, BVHTreeNearest *nearest)
+{
+ const BVHTreeFromMesh *data = (BVHTreeFromMesh*) userdata;
+ MVert *vert = data->vert;
+ MFace *face = data->face + index;
+
+ float *t0, *t1, *t2, *t3;
+ t0 = vert[ face->v1 ].co;
+ t1 = vert[ face->v2 ].co;
+ t2 = vert[ face->v3 ].co;
+ t3 = face->v4 ? vert[ face->v4].co : NULL;
+
+
+ do
+ {
+ float nearest_tmp[3], dist;
+ int vertex, edge;
+
+ dist = nearest_point_in_tri_surface(t0, t1, t2, co, &vertex, &edge, nearest_tmp);
+ if(dist < nearest->dist)
+ {
+ nearest->index = index;
+ nearest->dist = dist;
+ VECCOPY(nearest->co, nearest_tmp);
+ CalcNormFloat(t0, t1, t2, nearest->no);
+ }
+
+ t1 = t2;
+ t2 = t3;
+ t3 = NULL;
+
+ } while(t2);
+}
+
+// Callback to bvh tree raycast. The tree must bust have been built using bvhtree_from_mesh_faces.
+// userdata must be a BVHMeshCallbackUserdata built from the same mesh as the tree.
+static void mesh_faces_spherecast(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
+{
+ const BVHTreeFromMesh *data = (BVHTreeFromMesh*) userdata;
+ MVert *vert = data->vert;
+ MFace *face = data->face + index;
+
+ float *t0, *t1, *t2, *t3;
+ t0 = vert[ face->v1 ].co;
+ t1 = vert[ face->v2 ].co;
+ t2 = vert[ face->v3 ].co;
+ t3 = face->v4 ? vert[ face->v4].co : NULL;
+
+
+ do
+ {
+ float dist;
+ if(data->sphere_radius == 0.0f)
+ dist = ray_tri_intersection(ray, hit->dist, t0, t1, t2);
+ else
+ dist = sphereray_tri_intersection(ray, data->sphere_radius, hit->dist, t0, t1, t2);
+
+ if(dist >= 0 && dist < hit->dist)
+ {
+ hit->index = index;
+ hit->dist = dist;
+ VECADDFAC(hit->co, ray->origin, ray->direction, dist);
+
+ CalcNormFloat(t0, t1, t2, hit->no);
+ }
+
+ t1 = t2;
+ t2 = t3;
+ t3 = NULL;
+
+ } while(t2);
+}
+
+/*
+ * BVH builders
+ */
+// Builds a bvh tree.. where nodes are the vertexs of the given mesh
+void bvhtree_from_mesh_verts(BVHTreeFromMesh *data, DerivedMesh *mesh, float epsilon, int tree_type, int axis)
+{
+ int i;
+ int numVerts= mesh->getNumVerts(mesh);
+ MVert *vert = mesh->getVertDataArray(mesh, CD_MVERT);
+ BVHTree *tree = NULL;
+
+ memset(data, 0, sizeof(*data));
+
+ if(vert == NULL)
+ {
+ printf("bvhtree cant be build: cant get a vertex array");
+ return;
+ }
+
+ tree = BLI_bvhtree_new(numVerts, epsilon, tree_type, axis);
+ if(tree != NULL)
+ {
+ for(i = 0; i < numVerts; i++)
+ BLI_bvhtree_insert(tree, i, vert[i].co, 1);
+
+ BLI_bvhtree_balance(tree);
+
+ data->tree = tree;
+
+ //a NULL nearest callback works fine
+ //remeber the min distance to point is the same as the min distance to BV of point
+ data->nearest_callback = NULL;
+ data->raycast_callback = NULL;
+
+ data->mesh = mesh;
+ data->vert = mesh->getVertDataArray(mesh, CD_MVERT);
+ data->face = mesh->getFaceDataArray(mesh, CD_MFACE);
+
+ data->sphere_radius = epsilon;
+ }
+}
+
+// Builds a bvh tree.. where nodes are the faces of the given mesh.
+void bvhtree_from_mesh_faces(BVHTreeFromMesh *data, DerivedMesh *mesh, float epsilon, int tree_type, int axis)
+{
+ int i;
+ int numFaces= mesh->getNumFaces(mesh);
+ MVert *vert = mesh->getVertDataArray(mesh, CD_MVERT);
+ MFace *face = mesh->getFaceDataArray(mesh, CD_MFACE);
+ BVHTree *tree = NULL;
+
+ memset(data, 0, sizeof(*data));
+
+ if(vert == NULL && face == NULL)
+ {
+ printf("bvhtree cant be build: cant get a vertex/face array");
+ return;
+ }
+
+ /* Create a bvh-tree of the given target */
+ tree = BLI_bvhtree_new(numFaces, epsilon, tree_type, axis);
+ if(tree != NULL)
+ {
+ for(i = 0; i < numFaces; i++)
+ {
+ float co[4][3];
+ VECCOPY(co[0], vert[ face[i].v1 ].co);
+ VECCOPY(co[1], vert[ face[i].v2 ].co);
+ VECCOPY(co[2], vert[ face[i].v3 ].co);
+ if(face[i].v4)
+ VECCOPY(co[3], vert[ face[i].v4 ].co);
+
+ BLI_bvhtree_insert(tree, i, co[0], face[i].v4 ? 4 : 3);
+ }
+ BLI_bvhtree_balance(tree);
+
+ data->tree = tree;
+ data->nearest_callback = mesh_faces_nearest_point;
+ data->raycast_callback = mesh_faces_spherecast;
+
+ data->mesh = mesh;
+ data->vert = mesh->getVertDataArray(mesh, CD_MVERT);
+ data->face = mesh->getFaceDataArray(mesh, CD_MFACE);
+
+ data->sphere_radius = epsilon;
+ }
+}
+
+// Frees data allocated by a call to bvhtree_from_mesh_*.
+void free_bvhtree_from_mesh(struct BVHTreeFromMesh *data)
+{
+ if(data->tree)
+ {
+ BLI_bvhtree_free(data->tree);
+ memset( data, 0, sizeof(data) );
+ }
+}
+
+
diff --git a/source/blender/blenkernel/intern/cdderivedmesh.c b/source/blender/blenkernel/intern/cdderivedmesh.c
index 6a856307916..2c1b5ced614 100644
--- a/source/blender/blenkernel/intern/cdderivedmesh.c
+++ b/source/blender/blenkernel/intern/cdderivedmesh.c
@@ -52,11 +52,16 @@
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
+#include "DNA_object_fluidsim.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
#include "MEM_guardedalloc.h"
+#include "GPU_draw.h"
+#include "GPU_extensions.h"
+#include "GPU_material.h"
+
#include <string.h>
#include <limits.h>
@@ -116,7 +121,7 @@ static void cdDM_copyEdgeArray(DerivedMesh *dm, MEdge *edge_r)
memcpy(edge_r, cddm->medge, sizeof(*edge_r) * dm->numEdgeData);
}
-void cdDM_copyFaceArray(DerivedMesh *dm, MFace *face_r)
+static void cdDM_copyFaceArray(DerivedMesh *dm, MFace *face_r)
{
CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
memcpy(face_r, cddm->mface, sizeof(*face_r) * dm->numFaceData);
@@ -242,7 +247,7 @@ static void cdDM_drawLooseEdges(DerivedMesh *dm)
glEnd();
}
-static void cdDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int))
+static void cdDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int, void *attribs))
{
CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
MVert *mvert = cddm->mvert;
@@ -270,7 +275,7 @@ static void cdDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int))
|| new_shademodel != shademodel) {
glEnd();
- drawCurrentMat = setMaterial(matnr = new_matnr);
+ drawCurrentMat = setMaterial(matnr = new_matnr, NULL);
glShadeModel(shademodel = new_shademodel);
glBegin(glmode = new_glmode);
@@ -555,6 +560,134 @@ static void cdDM_drawMappedFacesTex(DerivedMesh *dm, int (*setDrawOptions)(void
cdDM_drawFacesTex_common(dm, NULL, setDrawOptions, userData);
}
+static void cdDM_drawMappedFacesGLSL(DerivedMesh *dm, int (*setMaterial)(int, void *attribs), int (*setDrawOptions)(void *userData, int index), void *userData)
+{
+ CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
+ GPUVertexAttribs gattribs;
+ DMVertexAttribs attribs;
+ MVert *mvert = cddm->mvert;
+ MFace *mface = cddm->mface;
+ MTFace *tf = dm->getFaceDataArray(dm, CD_MTFACE);
+ float (*nors)[3] = dm->getFaceDataArray(dm, CD_NORMAL);
+ int a, b, dodraw, smoothnormal, matnr, new_matnr;
+ int transp, new_transp, orig_transp;
+ int orig, *index = dm->getFaceDataArray(dm, CD_ORIGINDEX);
+
+ matnr = -1;
+ smoothnormal = 0;
+ dodraw = 0;
+ transp = GPU_get_material_blend_mode();
+ orig_transp = transp;
+
+ memset(&attribs, 0, sizeof(attribs));
+
+ glShadeModel(GL_SMOOTH);
+ glBegin(GL_QUADS);
+
+ for(a = 0; a < dm->numFaceData; a++, mface++) {
+ new_matnr = mface->mat_nr + 1;
+
+ if(new_matnr != matnr) {
+ glEnd();
+
+ dodraw = setMaterial(matnr = new_matnr, &gattribs);
+ if(dodraw)
+ DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
+
+ glBegin(GL_QUADS);
+ }
+
+ if(!dodraw) {
+ continue;
+ }
+ else if(setDrawOptions) {
+ orig = index[a];
+
+ if(orig == ORIGINDEX_NONE)
+ continue;
+ else if(!setDrawOptions(userData, orig))
+ continue;
+ }
+
+ if(tf) {
+ new_transp = tf[a].transp;
+
+ if(new_transp != transp) {
+ glEnd();
+
+ if(new_transp == GPU_BLEND_SOLID && orig_transp != GPU_BLEND_SOLID)
+ GPU_set_material_blend_mode(orig_transp);
+ else
+ GPU_set_material_blend_mode(new_transp);
+ transp = new_transp;
+
+ glBegin(GL_QUADS);
+ }
+ }
+
+ smoothnormal = (mface->flag & ME_SMOOTH);
+
+ if(!smoothnormal) {
+ if(nors) {
+ glNormal3fv(nors[a]);
+ }
+ else {
+ /* TODO ideally a normal layer should always be available */
+ float nor[3];
+ if(mface->v4) {
+ CalcNormFloat4(mvert[mface->v1].co, mvert[mface->v2].co,
+ mvert[mface->v3].co, mvert[mface->v4].co,
+ nor);
+ } else {
+ CalcNormFloat(mvert[mface->v1].co, mvert[mface->v2].co,
+ mvert[mface->v3].co, nor);
+ }
+ glNormal3fv(nor);
+ }
+ }
+
+#define PASSVERT(index, vert) { \
+ if(attribs.totorco) \
+ glVertexAttrib3fvARB(attribs.orco.glIndex, attribs.orco.array[index]); \
+ for(b = 0; b < attribs.tottface; b++) { \
+ MTFace *tf = &attribs.tface[b].array[a]; \
+ glVertexAttrib2fvARB(attribs.tface[b].glIndex, tf->uv[vert]); \
+ } \
+ for(b = 0; b < attribs.totmcol; b++) { \
+ MCol *cp = &attribs.mcol[b].array[a*4 + vert]; \
+ GLubyte col[4]; \
+ col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a; \
+ glVertexAttrib4ubvARB(attribs.mcol[b].glIndex, col); \
+ } \
+ if(attribs.tottang) { \
+ float *tang = attribs.tang.array[a*4 + vert]; \
+ glVertexAttrib3fvARB(attribs.tang.glIndex, tang); \
+ } \
+ if(smoothnormal) \
+ glNormal3sv(mvert[index].no); \
+ glVertex3fv(mvert[index].co); \
+}
+
+ PASSVERT(mface->v1, 0);
+ PASSVERT(mface->v2, 1);
+ PASSVERT(mface->v3, 2);
+ if(mface->v4)
+ PASSVERT(mface->v4, 3)
+ else
+ PASSVERT(mface->v3, 2)
+
+#undef PASSVERT
+ }
+ glEnd();
+
+ glShadeModel(GL_FLAT);
+}
+
+static void cdDM_drawFacesGLSL(DerivedMesh *dm, int (*setMaterial)(int, void *attribs))
+{
+ dm->drawMappedFacesGLSL(dm, setMaterial, NULL, NULL);
+}
+
static void cdDM_drawMappedEdges(DerivedMesh *dm, int (*setDrawOptions)(void *userData, int index), void *userData)
{
CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
@@ -712,8 +845,10 @@ static CDDerivedMesh *cdDM_create(const char *desc)
dm->drawFacesSolid = cdDM_drawFacesSolid;
dm->drawFacesColored = cdDM_drawFacesColored;
dm->drawFacesTex = cdDM_drawFacesTex;
+ dm->drawFacesGLSL = cdDM_drawFacesGLSL;
dm->drawMappedFaces = cdDM_drawMappedFaces;
dm->drawMappedFacesTex = cdDM_drawMappedFacesTex;
+ dm->drawMappedFacesGLSL = cdDM_drawMappedFacesGLSL;
dm->foreachMappedVert = cdDM_foreachMappedVert;
dm->foreachMappedEdge = cdDM_foreachMappedEdge;
@@ -731,6 +866,10 @@ DerivedMesh *CDDM_new(int numVerts, int numEdges, int numFaces)
DM_init(dm, numVerts, numEdges, numFaces);
+ CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, numVerts);
+ CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
+ CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, numFaces);
+
CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL, numVerts);
CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numFaces);
@@ -746,18 +885,26 @@ DerivedMesh *CDDM_from_mesh(Mesh *mesh, Object *ob)
{
CDDerivedMesh *cddm = cdDM_create("CDDM_from_mesh dm");
DerivedMesh *dm = &cddm->dm;
- int i, *index;
+ int i, *index, alloctype;
- /* this does a referenced copy, the only new layers being ORIGINDEX */
+ /* this does a referenced copy, the only new layers being ORIGINDEX,
+ * with an exception for fluidsim */
DM_init(dm, mesh->totvert, mesh->totedge, mesh->totface);
+
+ CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, mesh->totvert);
+ CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, mesh->totedge);
+ CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, mesh->totface);
+
dm->deformedOnly = 1;
- CustomData_merge(&mesh->vdata, &dm->vertData, CD_MASK_MESH, CD_REFERENCE,
+ alloctype= CD_REFERENCE;
+
+ CustomData_merge(&mesh->vdata, &dm->vertData, CD_MASK_MESH, alloctype,
mesh->totvert);
- CustomData_merge(&mesh->edata, &dm->edgeData, CD_MASK_MESH, CD_REFERENCE,
+ CustomData_merge(&mesh->edata, &dm->edgeData, CD_MASK_MESH, alloctype,
mesh->totedge);
- CustomData_merge(&mesh->fdata, &dm->faceData, CD_MASK_MESH, CD_REFERENCE,
+ CustomData_merge(&mesh->fdata, &dm->faceData, CD_MASK_MESH, alloctype,
mesh->totface);
cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
@@ -833,6 +980,7 @@ DerivedMesh *CDDM_from_editmesh(EditMesh *em, Mesh *me)
mv->no[0] = eve->no[0] * 32767.0;
mv->no[1] = eve->no[1] * 32767.0;
mv->no[2] = eve->no[2] * 32767.0;
+ mv->bweight = (unsigned char) (eve->bweight * 255.0f);
mv->mat_nr = 0;
mv->flag = 0;
@@ -850,6 +998,7 @@ DerivedMesh *CDDM_from_editmesh(EditMesh *em, Mesh *me)
med->v1 = eed->v1->tmp.l;
med->v2 = eed->v2->tmp.l;
med->crease = (unsigned char) (eed->crease * 255.0f);
+ med->bweight = (unsigned char) (eed->bweight * 255.0f);
med->flag = ME_EDGEDRAW|ME_EDGERENDER;
if(eed->seam) med->flag |= ME_SEAM;
diff --git a/source/blender/blenkernel/intern/cloth.c b/source/blender/blenkernel/intern/cloth.c
new file mode 100644
index 00000000000..dbc94571cad
--- /dev/null
+++ b/source/blender/blenkernel/intern/cloth.c
@@ -0,0 +1,1290 @@
+/* cloth.c
+*
+*
+* ***** BEGIN GPL LICENSE BLOCK *****
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 2
+* of the License, or (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software Foundation,
+* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*
+* The Original Code is Copyright (C) Blender Foundation
+* All rights reserved.
+*
+* Contributor(s): Daniel Genrich
+*
+* ***** END GPL LICENSE BLOCK *****
+*/
+
+#include "MEM_guardedalloc.h"
+
+#include "BKE_cloth.h"
+
+#include "DNA_cloth_types.h"
+#include "DNA_mesh_types.h"
+#include "DNA_object_force.h"
+#include "DNA_scene_types.h"
+
+#include "BKE_deform.h"
+#include "BKE_DerivedMesh.h"
+#include "BKE_cdderivedmesh.h"
+#include "BKE_effect.h"
+#include "BKE_global.h"
+#include "BKE_object.h"
+#include "BKE_modifier.h"
+#include "BKE_utildefines.h"
+
+#include "BKE_pointcache.h"
+
+#include "BLI_kdopbvh.h"
+
+#ifdef _WIN32
+void tstart ( void )
+{}
+void tend ( void )
+{
+}
+double tval()
+{
+ return 0;
+}
+#else
+#include <sys/time.h>
+ static struct timeval _tstart, _tend;
+ static struct timezone tz;
+ void tstart ( void )
+{
+ gettimeofday ( &_tstart, &tz );
+}
+void tend ( void )
+{
+ gettimeofday ( &_tend,&tz );
+}
+double tval()
+{
+ double t1, t2;
+ t1 = ( double ) _tstart.tv_sec + ( double ) _tstart.tv_usec/ ( 1000*1000 );
+ t2 = ( double ) _tend.tv_sec + ( double ) _tend.tv_usec/ ( 1000*1000 );
+ return t2-t1;
+}
+#endif
+
+/* Our available solvers. */
+// 255 is the magic reserved number, so NEVER try to put 255 solvers in here!
+// 254 = MAX!
+static CM_SOLVER_DEF solvers [] =
+{
+ { "Implicit", CM_IMPLICIT, implicit_init, implicit_solver, implicit_free },
+ // { "Implicit C++", CM_IMPLICITCPP, implicitcpp_init, implicitcpp_solver, implicitcpp_free },
+};
+
+/* ********** cloth engine ******* */
+/* Prototypes for internal functions.
+*/
+static void cloth_to_object (Object *ob, ClothModifierData *clmd, DerivedMesh *dm);
+static void cloth_from_mesh ( Object *ob, ClothModifierData *clmd, DerivedMesh *dm );
+static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *dm, float framenr, int first);
+int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm );
+static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm );
+
+
+/******************************************************************************
+*
+* External interface called by modifier.c clothModifier functions.
+*
+******************************************************************************/
+/**
+ * cloth_init - creates a new cloth simulation.
+ *
+ * 1. create object
+ * 2. fill object with standard values or with the GUI settings if given
+ */
+void cloth_init ( ClothModifierData *clmd )
+{
+ /* Initialize our new data structure to reasonable values. */
+ clmd->sim_parms->gravity [0] = 0.0;
+ clmd->sim_parms->gravity [1] = 0.0;
+ clmd->sim_parms->gravity [2] = -9.81;
+ clmd->sim_parms->structural = 15.0;
+ clmd->sim_parms->shear = 15.0;
+ clmd->sim_parms->bending = 0.5;
+ clmd->sim_parms->Cdis = 5.0;
+ clmd->sim_parms->Cvi = 1.0;
+ clmd->sim_parms->mass = 0.3f;
+ clmd->sim_parms->stepsPerFrame = 5;
+ clmd->sim_parms->flags = 0;
+ clmd->sim_parms->solver_type = 0;
+ clmd->sim_parms->preroll = 0;
+ clmd->sim_parms->maxspringlen = 10;
+ clmd->sim_parms->vgroup_mass = 0;
+ clmd->sim_parms->avg_spring_len = 0.0;
+ clmd->sim_parms->presets = 2; /* cotton as start setting */
+ clmd->sim_parms->timescale = 1.0f; /* speed factor, describes how fast cloth moves */
+
+ clmd->coll_parms->self_friction = 5.0;
+ clmd->coll_parms->friction = 5.0;
+ clmd->coll_parms->loop_count = 2;
+ clmd->coll_parms->epsilon = 0.015f;
+ clmd->coll_parms->flags = CLOTH_COLLSETTINGS_FLAG_ENABLED;
+ clmd->coll_parms->collision_list = NULL;
+ clmd->coll_parms->self_loop_count = 1.0;
+ clmd->coll_parms->selfepsilon = 0.75;
+
+ /* These defaults are copied from softbody.c's
+ * softbody_calc_forces() function.
+ */
+ clmd->sim_parms->eff_force_scale = 1000.0;
+ clmd->sim_parms->eff_wind_scale = 250.0;
+
+ // also from softbodies
+ clmd->sim_parms->maxgoal = 1.0f;
+ clmd->sim_parms->mingoal = 0.0f;
+ clmd->sim_parms->defgoal = 0.0f;
+ clmd->sim_parms->goalspring = 1.0f;
+ clmd->sim_parms->goalfrict = 0.0f;
+}
+
+BVHTree *bvhselftree_build_from_cloth (ClothModifierData *clmd, float epsilon)
+{
+ unsigned int i;
+ BVHTree *bvhtree;
+ Cloth *cloth = clmd->clothObject;
+ ClothVertex *verts;
+ MFace *mfaces;
+ float co[12];
+
+ if(!clmd)
+ return NULL;
+
+ cloth = clmd->clothObject;
+
+ if(!cloth)
+ return NULL;
+
+ verts = cloth->verts;
+ mfaces = cloth->mfaces;
+
+ // in the moment, return zero if no faces there
+ if(!cloth->numverts)
+ return NULL;
+
+ // create quadtree with k=26
+ bvhtree = BLI_bvhtree_new(cloth->numverts, epsilon, 4, 6);
+
+ // fill tree
+ for(i = 0; i < cloth->numverts; i++, verts++)
+ {
+ VECCOPY(&co[0*3], verts->xold);
+
+ BLI_bvhtree_insert(bvhtree, i, co, 1);
+ }
+
+ // balance tree
+ BLI_bvhtree_balance(bvhtree);
+
+ return bvhtree;
+}
+
+BVHTree *bvhtree_build_from_cloth (ClothModifierData *clmd, float epsilon)
+{
+ unsigned int i;
+ BVHTree *bvhtree;
+ Cloth *cloth = clmd->clothObject;
+ ClothVertex *verts;
+ MFace *mfaces;
+ float co[12];
+
+ if(!clmd)
+ return NULL;
+
+ cloth = clmd->clothObject;
+
+ if(!cloth)
+ return NULL;
+
+ verts = cloth->verts;
+ mfaces = cloth->mfaces;
+
+ // in the moment, return zero if no faces there
+ if(!cloth->numfaces)
+ return NULL;
+
+ // create quadtree with k=26
+ bvhtree = BLI_bvhtree_new(cloth->numfaces, epsilon, 4, 26);
+
+ // fill tree
+ for(i = 0; i < cloth->numfaces; i++, mfaces++)
+ {
+ VECCOPY(&co[0*3], verts[mfaces->v1].xold);
+ VECCOPY(&co[1*3], verts[mfaces->v2].xold);
+ VECCOPY(&co[2*3], verts[mfaces->v3].xold);
+
+ if(mfaces->v4)
+ VECCOPY(&co[3*3], verts[mfaces->v4].xold);
+
+ BLI_bvhtree_insert(bvhtree, i, co, (mfaces->v4 ? 4 : 3));
+ }
+
+ // balance tree
+ BLI_bvhtree_balance(bvhtree);
+
+ return bvhtree;
+}
+
+void bvhtree_update_from_cloth(ClothModifierData *clmd, int moving)
+{
+ unsigned int i = 0;
+ Cloth *cloth = clmd->clothObject;
+ BVHTree *bvhtree = cloth->bvhtree;
+ ClothVertex *verts = cloth->verts;
+ MFace *mfaces;
+ float co[12], co_moving[12];
+ int ret = 0;
+
+ if(!bvhtree)
+ return;
+
+ mfaces = cloth->mfaces;
+
+ // update vertex position in bvh tree
+ if(verts && mfaces)
+ {
+ for(i = 0; i < cloth->numfaces; i++, mfaces++)
+ {
+ VECCOPY(&co[0*3], verts[mfaces->v1].txold);
+ VECCOPY(&co[1*3], verts[mfaces->v2].txold);
+ VECCOPY(&co[2*3], verts[mfaces->v3].txold);
+
+ if(mfaces->v4)
+ VECCOPY(&co[3*3], verts[mfaces->v4].txold);
+
+ // copy new locations into array
+ if(moving)
+ {
+ // update moving positions
+ VECCOPY(&co_moving[0*3], verts[mfaces->v1].tx);
+ VECCOPY(&co_moving[1*3], verts[mfaces->v2].tx);
+ VECCOPY(&co_moving[2*3], verts[mfaces->v3].tx);
+
+ if(mfaces->v4)
+ VECCOPY(&co_moving[3*3], verts[mfaces->v4].tx);
+
+ ret = BLI_bvhtree_update_node(bvhtree, i, co, co_moving, (mfaces->v4 ? 4 : 3));
+ }
+ else
+ {
+ ret = BLI_bvhtree_update_node(bvhtree, i, co, NULL, (mfaces->v4 ? 4 : 3));
+ }
+
+ // check if tree is already full
+ if(!ret)
+ break;
+ }
+
+ BLI_bvhtree_update_tree(bvhtree);
+ }
+}
+
+void bvhselftree_update_from_cloth(ClothModifierData *clmd, int moving)
+{
+ unsigned int i = 0;
+ Cloth *cloth = clmd->clothObject;
+ BVHTree *bvhtree = cloth->bvhselftree;
+ ClothVertex *verts = cloth->verts;
+ MFace *mfaces;
+ float co[12], co_moving[12];
+ int ret = 0;
+
+ if(!bvhtree)
+ return;
+
+ mfaces = cloth->mfaces;
+
+ // update vertex position in bvh tree
+ if(verts && mfaces)
+ {
+ for(i = 0; i < cloth->numverts; i++, verts++)
+ {
+ VECCOPY(&co[0*3], verts->txold);
+
+ // copy new locations into array
+ if(moving)
+ {
+ // update moving positions
+ VECCOPY(&co_moving[0*3], verts->tx);
+
+ ret = BLI_bvhtree_update_node(bvhtree, i, co, co_moving, 1);
+ }
+ else
+ {
+ ret = BLI_bvhtree_update_node(bvhtree, i, co, NULL, 1);
+ }
+
+ // check if tree is already full
+ if(!ret)
+ break;
+ }
+
+ BLI_bvhtree_update_tree(bvhtree);
+ }
+}
+
+int modifiers_indexInObject(Object *ob, ModifierData *md_seek);
+
+int cloth_read_cache(Object *ob, ClothModifierData *clmd, float framenr)
+{
+ PTCacheID pid;
+ PTCacheFile *pf;
+ Cloth *cloth = clmd->clothObject;
+ unsigned int a, ret = 1;
+
+ if(!cloth)
+ return 0;
+
+ BKE_ptcache_id_from_cloth(&pid, ob, clmd);
+ pf = BKE_ptcache_file_open(&pid, PTCACHE_FILE_READ, framenr);
+ if(pf) {
+ for(a = 0; a < cloth->numverts; a++) {
+ if(!BKE_ptcache_file_read_floats(pf, cloth->verts[a].x, 3)) {
+ ret = 0;
+ break;
+ }
+ if(!BKE_ptcache_file_read_floats(pf, cloth->verts[a].xconst, 3)) {
+ ret = 0;
+ break;
+ }
+ if(!BKE_ptcache_file_read_floats(pf, cloth->verts[a].v, 3)) {
+ ret = 0;
+ break;
+ }
+ }
+
+ BKE_ptcache_file_close(pf);
+ }
+ else
+ ret = 0;
+
+ return ret;
+}
+
+void cloth_clear_cache(Object *ob, ClothModifierData *clmd, float framenr)
+{
+ PTCacheID pid;
+
+ BKE_ptcache_id_from_cloth(&pid, ob, clmd);
+
+ // don't do anything as long as we're in editmode!
+ if(pid.cache->flag & PTCACHE_BAKE_EDIT_ACTIVE)
+ return;
+
+ BKE_ptcache_id_clear(&pid, PTCACHE_CLEAR_AFTER, framenr);
+}
+
+void cloth_write_cache(Object *ob, ClothModifierData *clmd, float framenr)
+{
+ Cloth *cloth = clmd->clothObject;
+ PTCacheID pid;
+ PTCacheFile *pf;
+ unsigned int a;
+
+ if(!cloth)
+ return;
+
+ BKE_ptcache_id_from_cloth(&pid, ob, clmd);
+ pf = BKE_ptcache_file_open(&pid, PTCACHE_FILE_WRITE, framenr);
+ if(!pf)
+ return;
+
+ for(a = 0; a < cloth->numverts; a++) {
+ BKE_ptcache_file_write_floats(pf, cloth->verts[a].x, 3);
+ BKE_ptcache_file_write_floats(pf, cloth->verts[a].xconst, 3);
+ BKE_ptcache_file_write_floats(pf, cloth->verts[a].v, 3);
+ }
+
+ BKE_ptcache_file_close(pf);
+}
+
+static int do_init_cloth(Object *ob, ClothModifierData *clmd, DerivedMesh *result, int framenr)
+{
+ PointCache *cache;
+
+ cache= clmd->point_cache;
+
+ /* initialize simulation data if it didn't exist already */
+ if(clmd->clothObject == NULL) {
+ if(!cloth_from_object(ob, clmd, result, framenr, 1)) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ return 0;
+ }
+
+ if(clmd->clothObject == NULL) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ return 0;
+ }
+
+ implicit_set_positions(clmd);
+ }
+
+ return 1;
+}
+
+static int do_step_cloth(Object *ob, ClothModifierData *clmd, DerivedMesh *result, int framenr)
+{
+ ClothVertex *verts = NULL;
+ Cloth *cloth;
+ ListBase *effectors = NULL;
+ MVert *mvert;
+ int i, ret = 0;
+
+ /* simulate 1 frame forward */
+ cloth = clmd->clothObject;
+ verts = cloth->verts;
+ mvert = result->getVertArray(result);
+
+ /* force any pinned verts to their constrained location. */
+ for(i = 0; i < clmd->clothObject->numverts; i++, verts++) {
+ /* save the previous position. */
+ VECCOPY(verts->xold, verts->xconst);
+ VECCOPY(verts->txold, verts->x);
+
+ /* Get the current position. */
+ VECCOPY(verts->xconst, mvert[i].co);
+ Mat4MulVecfl(ob->obmat, verts->xconst);
+ }
+
+ tstart();
+
+ /* call the solver. */
+ if(solvers [clmd->sim_parms->solver_type].solver)
+ ret = solvers[clmd->sim_parms->solver_type].solver(ob, framenr, clmd, effectors);
+
+ tend();
+
+ // printf ( "%f\n", ( float ) tval() );
+
+ return ret;
+}
+
+/************************************************
+ * clothModifier_do - main simulation function
+************************************************/
+DerivedMesh *clothModifier_do(ClothModifierData *clmd, Object *ob, DerivedMesh *dm, int useRenderParams, int isFinalCalc)
+{
+ DerivedMesh *result;
+ PointCache *cache;
+ PTCacheID pid;
+ float timescale;
+ int framedelta, framenr, startframe, endframe;
+
+ framenr= (int)G.scene->r.cfra;
+ cache= clmd->point_cache;
+ result = CDDM_copy(dm);
+
+ BKE_ptcache_id_from_cloth(&pid, ob, clmd);
+ BKE_ptcache_id_time(&pid, framenr, &startframe, &endframe, &timescale);
+ clmd->sim_parms->timescale= timescale;
+
+ if(!result) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ return dm;
+ }
+
+ /* verify we still have the same number of vertices, if not do nothing.
+ * note that this should only happen if the number of vertices changes
+ * during an animation due to a preceding modifier, this should not
+ * happen because of object changes! */
+ if(clmd->clothObject) {
+ if(result->getNumVerts(result) != clmd->clothObject->numverts) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ return result;
+ }
+ }
+
+ // unused in the moment, calculated seperately in implicit.c
+ clmd->sim_parms->dt = clmd->sim_parms->timescale / clmd->sim_parms->stepsPerFrame;
+
+ /* handle continuous simulation with the play button */
+ if(BKE_ptcache_get_continue_physics()) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+
+ /* do simulation */
+ if(!do_init_cloth(ob, clmd, result, framenr))
+ return result;
+
+ do_step_cloth(ob, clmd, result, framenr);
+ cloth_to_object(ob, clmd, result);
+
+ return result;
+ }
+
+ /* simulation is only active during a specific period */
+ if(framenr < startframe) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ return result;
+ }
+ else if(framenr > endframe) {
+ framenr= endframe;
+ }
+
+ if(cache->flag & PTCACHE_SIMULATION_VALID)
+ framedelta= framenr - cache->simframe;
+ else
+ framedelta= -1;
+
+ /* initialize simulation data if it didn't exist already */
+ if(!do_init_cloth(ob, clmd, result, framenr))
+ return result;
+
+ /* try to read from cache */
+ if(cloth_read_cache(ob, clmd, framenr)) {
+ cache->flag |= PTCACHE_SIMULATION_VALID;
+ cache->simframe= framenr;
+
+ implicit_set_positions(clmd);
+ cloth_to_object (ob, clmd, result);
+
+ return result;
+ }
+ else if(ob->id.lib || (cache->flag & PTCACHE_BAKED)) {
+ /* if baked and nothing in cache, do nothing */
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ return result;
+ }
+
+ if(framenr == startframe) {
+ cache->flag |= PTCACHE_SIMULATION_VALID;
+ cache->simframe= framenr;
+
+ /* don't write cache on first frame, but on second frame write
+ * cache for frame 1 and 2 */
+ }
+ else if(framedelta == 1) {
+ /* if on second frame, write cache for first frame */
+ if(framenr == startframe+1)
+ cloth_write_cache(ob, clmd, startframe);
+
+ /* do simulation */
+ cache->flag |= PTCACHE_SIMULATION_VALID;
+ cache->simframe= framenr;
+
+ if(!do_step_cloth(ob, clmd, result, framenr)) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ }
+ else
+ cloth_write_cache(ob, clmd, framenr);
+
+ cloth_to_object (ob, clmd, result);
+ }
+ else {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ }
+
+ return result;
+}
+
+/* frees all */
+void cloth_free_modifier ( Object *ob, ClothModifierData *clmd )
+{
+ Cloth *cloth = NULL;
+
+ if ( !clmd )
+ return;
+
+ cloth = clmd->clothObject;
+
+
+ if ( cloth )
+ {
+ // If our solver provides a free function, call it
+ if ( solvers [clmd->sim_parms->solver_type].free )
+ {
+ solvers [clmd->sim_parms->solver_type].free ( clmd );
+ }
+
+ // Free the verts.
+ if ( cloth->verts != NULL )
+ MEM_freeN ( cloth->verts );
+
+ cloth->verts = NULL;
+ cloth->numverts = 0;
+
+ // Free the springs.
+ if ( cloth->springs != NULL )
+ {
+ LinkNode *search = cloth->springs;
+ while(search)
+ {
+ ClothSpring *spring = search->link;
+
+ MEM_freeN ( spring );
+ search = search->next;
+ }
+ BLI_linklist_free(cloth->springs, NULL);
+
+ cloth->springs = NULL;
+ }
+
+ cloth->springs = NULL;
+ cloth->numsprings = 0;
+
+ // free BVH collision tree
+ if ( cloth->bvhtree )
+ BLI_bvhtree_free ( cloth->bvhtree );
+
+ if ( cloth->bvhselftree )
+ BLI_bvhtree_free ( cloth->bvhselftree );
+
+ // we save our faces for collision objects
+ if ( cloth->mfaces )
+ MEM_freeN ( cloth->mfaces );
+
+ if(cloth->edgehash)
+ BLI_edgehash_free ( cloth->edgehash, NULL );
+
+
+ /*
+ if(clmd->clothObject->facemarks)
+ MEM_freeN(clmd->clothObject->facemarks);
+ */
+ MEM_freeN ( cloth );
+ clmd->clothObject = NULL;
+ }
+}
+
+/* frees all */
+void cloth_free_modifier_extern ( ClothModifierData *clmd )
+{
+ Cloth *cloth = NULL;
+ if(G.rt > 0)
+ printf("cloth_free_modifier_extern\n");
+
+ if ( !clmd )
+ return;
+
+ cloth = clmd->clothObject;
+
+ if ( cloth )
+ {
+ if(G.rt > 0)
+ printf("cloth_free_modifier_extern in\n");
+
+ // If our solver provides a free function, call it
+ if ( solvers [clmd->sim_parms->solver_type].free )
+ {
+ solvers [clmd->sim_parms->solver_type].free ( clmd );
+ }
+
+ // Free the verts.
+ if ( cloth->verts != NULL )
+ MEM_freeN ( cloth->verts );
+
+ cloth->verts = NULL;
+ cloth->numverts = 0;
+
+ // Free the springs.
+ if ( cloth->springs != NULL )
+ {
+ LinkNode *search = cloth->springs;
+ while(search)
+ {
+ ClothSpring *spring = search->link;
+
+ MEM_freeN ( spring );
+ search = search->next;
+ }
+ BLI_linklist_free(cloth->springs, NULL);
+
+ cloth->springs = NULL;
+ }
+
+ cloth->springs = NULL;
+ cloth->numsprings = 0;
+
+ // free BVH collision tree
+ if ( cloth->bvhtree )
+ BLI_bvhtree_free ( cloth->bvhtree );
+
+ if ( cloth->bvhselftree )
+ BLI_bvhtree_free ( cloth->bvhselftree );
+
+ // we save our faces for collision objects
+ if ( cloth->mfaces )
+ MEM_freeN ( cloth->mfaces );
+
+ if(cloth->edgehash)
+ BLI_edgehash_free ( cloth->edgehash, NULL );
+
+
+ /*
+ if(clmd->clothObject->facemarks)
+ MEM_freeN(clmd->clothObject->facemarks);
+ */
+ MEM_freeN ( cloth );
+ clmd->clothObject = NULL;
+ }
+}
+
+/******************************************************************************
+*
+* Internal functions.
+*
+******************************************************************************/
+
+/**
+ * cloth_to_object - copies the deformed vertices to the object.
+ *
+ **/
+static void cloth_to_object (Object *ob, ClothModifierData *clmd, DerivedMesh *dm)
+{
+ unsigned int i = 0;
+ MVert *mvert = NULL;
+ unsigned int numverts;
+ Cloth *cloth = clmd->clothObject;
+
+ if (clmd->clothObject) {
+ /* inverse matrix is not uptodate... */
+ Mat4Invert (ob->imat, ob->obmat);
+
+ mvert = CDDM_get_verts(dm);
+ numverts = dm->getNumVerts(dm);
+
+ for (i = 0; i < numverts; i++)
+ {
+ VECCOPY (mvert[i].co, cloth->verts[i].x);
+ Mat4MulVecfl (ob->imat, mvert[i].co); /* cloth is in global coords */
+ }
+ }
+}
+
+
+/**
+ * cloth_apply_vgroup - applies a vertex group as specified by type
+ *
+ **/
+/* can be optimized to do all groups in one loop */
+static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm )
+{
+ int i = 0;
+ int j = 0;
+ MDeformVert *dvert = NULL;
+ Cloth *clothObj = NULL;
+ int numverts = dm->getNumVerts ( dm );
+ float goalfac = 0;
+ ClothVertex *verts = NULL;
+
+ clothObj = clmd->clothObject;
+
+ if ( !dm )
+ return;
+
+ numverts = dm->getNumVerts ( dm );
+
+ verts = clothObj->verts;
+
+ if (((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SCALING ) ||
+ (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )) &&
+ ((clmd->sim_parms->vgroup_mass>0) ||
+ (clmd->sim_parms->vgroup_struct>0)||
+ (clmd->sim_parms->vgroup_bend>0)))
+ {
+ for ( i = 0; i < numverts; i++, verts++ )
+ {
+ dvert = dm->getVertData ( dm, i, CD_MDEFORMVERT );
+ if ( dvert )
+ {
+ for ( j = 0; j < dvert->totweight; j++ )
+ {
+ if (( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_mass-1)) && (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL ))
+ {
+ verts->goal = dvert->dw [j].weight;
+ goalfac= 1.0f;
+
+ /*
+ // Kicking goal factor to simplify things...who uses that anyway?
+ // ABS ( clmd->sim_parms->maxgoal - clmd->sim_parms->mingoal );
+ */
+
+ verts->goal = ( float ) pow ( verts->goal , 4.0f );
+ if ( verts->goal >=SOFTGOALSNAP )
+ {
+ verts->flags |= CLOTH_VERT_FLAG_PINNED;
+ }
+ }
+
+ if (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SCALING )
+ {
+ if( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_struct-1))
+ {
+ verts->struct_stiff = dvert->dw [j].weight;
+ verts->shear_stiff = dvert->dw [j].weight;
+ }
+
+ if( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_bend-1))
+ {
+ verts->bend_stiff = dvert->dw [j].weight;
+ }
+ }
+ /*
+ // for later
+ if( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_weight-1))
+ {
+ verts->mass = dvert->dw [j].weight;
+ }
+ */
+ }
+ }
+ }
+ }
+}
+
+static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *dm, float framenr, int first)
+{
+ int i = 0;
+ MVert *mvert = NULL;
+ ClothVertex *verts = NULL;
+ float tnull[3] = {0,0,0};
+ Cloth *cloth = NULL;
+ float maxdist = 0;
+
+ // If we have a clothObject, free it.
+ if ( clmd->clothObject != NULL )
+ {
+ cloth_free_modifier ( ob, clmd );
+ if(G.rt > 0)
+ printf("cloth_free_modifier cloth_from_object\n");
+ }
+
+ // Allocate a new cloth object.
+ clmd->clothObject = MEM_callocN ( sizeof ( Cloth ), "cloth" );
+ if ( clmd->clothObject )
+ {
+ clmd->clothObject->old_solver_type = 255;
+ // clmd->clothObject->old_collision_type = 255;
+ cloth = clmd->clothObject;
+ clmd->clothObject->edgehash = NULL;
+ }
+ else if ( !clmd->clothObject )
+ {
+ modifier_setError ( & ( clmd->modifier ), "Out of memory on allocating clmd->clothObject." );
+ return 0;
+ }
+
+ // mesh input objects need DerivedMesh
+ if ( !dm )
+ return 0;
+
+ cloth_from_mesh ( ob, clmd, dm );
+
+ // create springs
+ clmd->clothObject->springs = NULL;
+ clmd->clothObject->numsprings = -1;
+
+ mvert = dm->getVertArray ( dm );
+ verts = clmd->clothObject->verts;
+
+ // set initial values
+ for ( i = 0; i < dm->getNumVerts(dm); i++, verts++ )
+ {
+ if(first)
+ {
+ VECCOPY ( verts->x, mvert[i].co );
+ Mat4MulVecfl ( ob->obmat, verts->x );
+ }
+
+ /* no GUI interface yet */
+ verts->mass = clmd->sim_parms->mass;
+ verts->impulse_count = 0;
+
+ if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )
+ verts->goal= clmd->sim_parms->defgoal;
+ else
+ verts->goal= 0.0f;
+
+ verts->flags = 0;
+ VECCOPY ( verts->xold, verts->x );
+ VECCOPY ( verts->xconst, verts->x );
+ VECCOPY ( verts->txold, verts->x );
+ VECCOPY ( verts->tx, verts->x );
+ VecMulf ( verts->v, 0.0f );
+
+ verts->impulse_count = 0;
+ VECCOPY ( verts->impulse, tnull );
+ }
+
+ // apply / set vertex groups
+ // has to be happen before springs are build!
+ cloth_apply_vgroup (clmd, dm);
+
+ if ( !cloth_build_springs ( clmd, dm ) )
+ {
+ cloth_free_modifier ( ob, clmd );
+ modifier_setError ( & ( clmd->modifier ), "Can't build springs." );
+ printf("cloth_free_modifier cloth_build_springs\n");
+ return 0;
+ }
+
+ for ( i = 0; i < dm->getNumVerts(dm); i++)
+ {
+ if((!(cloth->verts[i].flags & CLOTH_VERT_FLAG_PINNED)) && (cloth->verts[i].goal > ALMOST_ZERO))
+ {
+ cloth_add_spring (clmd, i, i, 0.0, CLOTH_SPRING_TYPE_GOAL);
+ }
+ }
+
+ // init our solver
+ if ( solvers [clmd->sim_parms->solver_type].init ) {
+ solvers [clmd->sim_parms->solver_type].init ( ob, clmd );
+ }
+
+ if(!first)
+ implicit_set_positions(clmd);
+
+ clmd->clothObject->bvhtree = bvhtree_build_from_cloth ( clmd, clmd->coll_parms->epsilon );
+
+ for(i = 0; i < dm->getNumVerts(dm); i++)
+ {
+ maxdist = MAX2(maxdist, clmd->coll_parms->selfepsilon* ( cloth->verts[i].avg_spring_len*2.0));
+ }
+
+ clmd->clothObject->bvhselftree = bvhselftree_build_from_cloth ( clmd, maxdist );
+
+ return 1;
+}
+
+static void cloth_from_mesh ( Object *ob, ClothModifierData *clmd, DerivedMesh *dm )
+{
+ unsigned int numverts = dm->getNumVerts ( dm );
+ unsigned int numfaces = dm->getNumFaces ( dm );
+ MFace *mface = CDDM_get_faces(dm);
+ unsigned int i = 0;
+
+ /* Allocate our vertices. */
+ clmd->clothObject->numverts = numverts;
+ clmd->clothObject->verts = MEM_callocN ( sizeof ( ClothVertex ) * clmd->clothObject->numverts, "clothVertex" );
+ if ( clmd->clothObject->verts == NULL )
+ {
+ cloth_free_modifier ( ob, clmd );
+ modifier_setError ( & ( clmd->modifier ), "Out of memory on allocating clmd->clothObject->verts." );
+ printf("cloth_free_modifier clmd->clothObject->verts\n");
+ return;
+ }
+
+ // save face information
+ clmd->clothObject->numfaces = numfaces;
+ clmd->clothObject->mfaces = MEM_callocN ( sizeof ( MFace ) * clmd->clothObject->numfaces, "clothMFaces" );
+ if ( clmd->clothObject->mfaces == NULL )
+ {
+ cloth_free_modifier ( ob, clmd );
+ modifier_setError ( & ( clmd->modifier ), "Out of memory on allocating clmd->clothObject->mfaces." );
+ printf("cloth_free_modifier clmd->clothObject->mfaces\n");
+ return;
+ }
+ for ( i = 0; i < numfaces; i++ )
+ memcpy ( &clmd->clothObject->mfaces[i], &mface[i], sizeof ( MFace ) );
+
+ /* Free the springs since they can't be correct if the vertices
+ * changed.
+ */
+ if ( clmd->clothObject->springs != NULL )
+ MEM_freeN ( clmd->clothObject->springs );
+
+}
+
+/***************************************************************************************
+* SPRING NETWORK BUILDING IMPLEMENTATION BEGIN
+***************************************************************************************/
+
+// be carefull: implicit solver has to be resettet when using this one!
+// --> only for implicit handling of this spring!
+int cloth_add_spring ( ClothModifierData *clmd, unsigned int indexA, unsigned int indexB, float restlength, int spring_type)
+{
+ Cloth *cloth = clmd->clothObject;
+ ClothSpring *spring = NULL;
+
+ if(cloth)
+ {
+ // TODO: look if this spring is already there
+
+ spring = ( ClothSpring * ) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
+
+ if(!spring)
+ return 0;
+
+ spring->ij = indexA;
+ spring->kl = indexB;
+ spring->restlen = restlength;
+ spring->type = spring_type;
+ spring->flags = 0;
+ spring->stiffness = 0;
+
+ cloth->numsprings++;
+
+ BLI_linklist_prepend ( &cloth->springs, spring );
+
+ return 1;
+ }
+ return 0;
+}
+
+void cloth_free_errorsprings(Cloth *cloth, EdgeHash *edgehash, LinkNode **edgelist)
+{
+ unsigned int i = 0;
+
+ if ( cloth->springs != NULL )
+ {
+ LinkNode *search = cloth->springs;
+ while(search)
+ {
+ ClothSpring *spring = search->link;
+
+ MEM_freeN ( spring );
+ search = search->next;
+ }
+ BLI_linklist_free(cloth->springs, NULL);
+
+ cloth->springs = NULL;
+ }
+
+ if(edgelist)
+ {
+ for ( i = 0; i < cloth->numverts; i++ )
+ {
+ BLI_linklist_free ( edgelist[i],NULL );
+ }
+
+ MEM_freeN ( edgelist );
+ }
+
+ if(cloth->edgehash)
+ BLI_edgehash_free ( cloth->edgehash, NULL );
+}
+
+int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm )
+{
+ Cloth *cloth = clmd->clothObject;
+ ClothSpring *spring = NULL, *tspring = NULL, *tspring2 = NULL;
+ unsigned int struct_springs = 0, shear_springs=0, bend_springs = 0;
+ int i = 0;
+ int numverts = dm->getNumVerts ( dm );
+ int numedges = dm->getNumEdges ( dm );
+ int numfaces = dm->getNumFaces ( dm );
+ MEdge *medge = CDDM_get_edges ( dm );
+ MFace *mface = CDDM_get_faces ( dm );
+ int index2 = 0; // our second vertex index
+ LinkNode **edgelist = NULL;
+ EdgeHash *edgehash = NULL;
+ LinkNode *search = NULL, *search2 = NULL;
+ float temp[3];
+
+ // error handling
+ if ( numedges==0 )
+ return 0;
+
+ cloth->springs = NULL;
+
+ edgelist = MEM_callocN ( sizeof ( LinkNode * ) * numverts, "cloth_edgelist_alloc" );
+
+ if(!edgelist)
+ return 0;
+
+ for ( i = 0; i < numverts; i++ )
+ {
+ edgelist[i] = NULL;
+ }
+
+ if ( cloth->springs )
+ MEM_freeN ( cloth->springs );
+
+ // create spring network hash
+ edgehash = BLI_edgehash_new();
+
+ // structural springs
+ for ( i = 0; i < numedges; i++ )
+ {
+ spring = ( ClothSpring * ) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
+
+ if ( spring )
+ {
+ spring->ij = MIN2(medge[i].v1, medge[i].v2);
+ spring->kl = MAX2(medge[i].v2, medge[i].v1);
+ VECSUB ( temp, cloth->verts[spring->kl].x, cloth->verts[spring->ij].x );
+ spring->restlen = sqrt ( INPR ( temp, temp ) );
+ clmd->sim_parms->avg_spring_len += spring->restlen;
+ cloth->verts[spring->ij].avg_spring_len += spring->restlen;
+ cloth->verts[spring->kl].avg_spring_len += spring->restlen;
+ cloth->verts[spring->ij].spring_count++;
+ cloth->verts[spring->kl].spring_count++;
+ spring->type = CLOTH_SPRING_TYPE_STRUCTURAL;
+ spring->flags = 0;
+ spring->stiffness = (cloth->verts[spring->kl].struct_stiff + cloth->verts[spring->ij].struct_stiff) / 2.0;
+ struct_springs++;
+
+ BLI_linklist_prepend ( &cloth->springs, spring );
+ }
+ else
+ {
+ cloth_free_errorsprings(cloth, edgehash, edgelist);
+ return 0;
+ }
+ }
+
+ if(struct_springs > 0)
+ clmd->sim_parms->avg_spring_len /= struct_springs;
+
+ for(i = 0; i < numverts; i++)
+ {
+ cloth->verts[i].avg_spring_len = cloth->verts[i].avg_spring_len * 0.49 / ((float)cloth->verts[i].spring_count);
+ }
+
+ // shear springs
+ for ( i = 0; i < numfaces; i++ )
+ {
+ // triangle faces already have shear springs due to structural geometry
+ if ( !mface[i].v4 )
+ continue;
+
+ spring = ( ClothSpring *) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
+
+ if(!spring)
+ {
+ cloth_free_errorsprings(cloth, edgehash, edgelist);
+ return 0;
+ }
+
+ spring->ij = MIN2(mface[i].v1, mface[i].v3);
+ spring->kl = MAX2(mface[i].v3, mface[i].v1);
+ VECSUB ( temp, cloth->verts[spring->kl].x, cloth->verts[spring->ij].x );
+ spring->restlen = sqrt ( INPR ( temp, temp ) );
+ spring->type = CLOTH_SPRING_TYPE_SHEAR;
+ spring->stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0;
+
+ BLI_linklist_append ( &edgelist[spring->ij], spring );
+ BLI_linklist_append ( &edgelist[spring->kl], spring );
+ shear_springs++;
+
+ BLI_linklist_prepend ( &cloth->springs, spring );
+
+
+ // if ( mface[i].v4 ) --> Quad face
+ spring = ( ClothSpring * ) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
+
+ if(!spring)
+ {
+ cloth_free_errorsprings(cloth, edgehash, edgelist);
+ return 0;
+ }
+
+ spring->ij = MIN2(mface[i].v2, mface[i].v4);
+ spring->kl = MAX2(mface[i].v4, mface[i].v2);
+ VECSUB ( temp, cloth->verts[spring->kl].x, cloth->verts[spring->ij].x );
+ spring->restlen = sqrt ( INPR ( temp, temp ) );
+ spring->type = CLOTH_SPRING_TYPE_SHEAR;
+ spring->stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0;
+
+ BLI_linklist_append ( &edgelist[spring->ij], spring );
+ BLI_linklist_append ( &edgelist[spring->kl], spring );
+ shear_springs++;
+
+ BLI_linklist_prepend ( &cloth->springs, spring );
+ }
+
+ // bending springs
+ search2 = cloth->springs;
+ for ( i = struct_springs; i < struct_springs+shear_springs; i++ )
+ {
+ if ( !search2 )
+ break;
+
+ tspring2 = search2->link;
+ search = edgelist[tspring2->kl];
+ while ( search )
+ {
+ tspring = search->link;
+ index2 = ( ( tspring->ij==tspring2->kl ) ? ( tspring->kl ) : ( tspring->ij ) );
+
+ // check for existing spring
+ // check also if startpoint is equal to endpoint
+ if ( !BLI_edgehash_haskey ( edgehash, MIN2(tspring2->ij, index2), MAX2(tspring2->ij, index2) )
+ && ( index2!=tspring2->ij ) )
+ {
+ spring = ( ClothSpring * ) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
+
+ if(!spring)
+ {
+ cloth_free_errorsprings(cloth, edgehash, edgelist);
+ return 0;
+ }
+
+ spring->ij = MIN2(tspring2->ij, index2);
+ spring->kl = MAX2(tspring2->ij, index2);
+ VECSUB ( temp, cloth->verts[spring->kl].x, cloth->verts[spring->ij].x );
+ spring->restlen = sqrt ( INPR ( temp, temp ) );
+ spring->type = CLOTH_SPRING_TYPE_BENDING;
+ spring->stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0;
+ BLI_edgehash_insert ( edgehash, spring->ij, spring->kl, NULL );
+ bend_springs++;
+
+ BLI_linklist_prepend ( &cloth->springs, spring );
+ }
+ search = search->next;
+ }
+ search2 = search2->next;
+ }
+
+ /* insert other near springs in edgehash AFTER bending springs are calculated (for selfcolls) */
+ for ( i = 0; i < numedges; i++ ) // struct springs
+ BLI_edgehash_insert ( edgehash, MIN2(medge[i].v1, medge[i].v2), MAX2(medge[i].v2, medge[i].v1), NULL );
+
+ for ( i = 0; i < numfaces; i++ ) // edge springs
+ {
+ if(mface[i].v4)
+ {
+ BLI_edgehash_insert ( edgehash, MIN2(mface[i].v1, mface[i].v3), MAX2(mface[i].v3, mface[i].v1), NULL );
+
+ BLI_edgehash_insert ( edgehash, MIN2(mface[i].v2, mface[i].v4), MAX2(mface[i].v2, mface[i].v4), NULL );
+ }
+ }
+
+
+ cloth->numsprings = struct_springs + shear_springs + bend_springs;
+
+ if ( edgelist )
+ {
+ for ( i = 0; i < numverts; i++ )
+ {
+ BLI_linklist_free ( edgelist[i],NULL );
+ }
+
+ MEM_freeN ( edgelist );
+ }
+
+ cloth->edgehash = edgehash;
+
+ if(G.rt>0)
+ printf("avg_len: %f\n",clmd->sim_parms->avg_spring_len);
+
+ return 1;
+
+} /* cloth_build_springs */
+/***************************************************************************************
+* SPRING NETWORK BUILDING IMPLEMENTATION END
+***************************************************************************************/
+
diff --git a/source/blender/blenkernel/intern/collision.c b/source/blender/blenkernel/intern/collision.c
new file mode 100644
index 00000000000..9db3dda94eb
--- /dev/null
+++ b/source/blender/blenkernel/intern/collision.c
@@ -0,0 +1,1677 @@
+/* collision.c
+*
+*
+* ***** BEGIN GPL LICENSE BLOCK *****
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 2
+* of the License, or (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software Foundation,
+* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*
+* The Original Code is Copyright (C) Blender Foundation
+* All rights reserved.
+*
+* The Original Code is: all of this file.
+*
+* Contributor(s): none yet.
+*
+* ***** END GPL LICENSE BLOCK *****
+*/
+
+#include "MEM_guardedalloc.h"
+
+#include "BKE_cloth.h"
+
+#include "DNA_cloth_types.h"
+#include "DNA_group_types.h"
+#include "DNA_mesh_types.h"
+#include "DNA_object_types.h"
+#include "DNA_object_force.h"
+#include "DNA_scene_types.h"
+
+#include "BKE_DerivedMesh.h"
+#include "BKE_global.h"
+#include "BKE_mesh.h"
+#include "BKE_object.h"
+#include "BKE_modifier.h"
+#include "BKE_utildefines.h"
+#include "BKE_DerivedMesh.h"
+
+#include "Bullet-C-Api.h"
+
+#include "BLI_kdopbvh.h"
+#include "BKE_collision.h"
+
+
+/***********************************
+Collision modifier code start
+***********************************/
+
+/* step is limited from 0 (frame start position) to 1 (frame end position) */
+void collision_move_object ( CollisionModifierData *collmd, float step, float prevstep )
+{
+ float tv[3] = {0,0,0};
+ unsigned int i = 0;
+
+ for ( i = 0; i < collmd->numverts; i++ )
+ {
+ VECSUB ( tv, collmd->xnew[i].co, collmd->x[i].co );
+ VECADDS ( collmd->current_x[i].co, collmd->x[i].co, tv, prevstep );
+ VECADDS ( collmd->current_xnew[i].co, collmd->x[i].co, tv, step );
+ VECSUB ( collmd->current_v[i].co, collmd->current_xnew[i].co, collmd->current_x[i].co );
+ }
+ bvhtree_update_from_mvert ( collmd->bvhtree, collmd->mfaces, collmd->numfaces, collmd->current_x, collmd->current_xnew, collmd->numverts, 1 );
+}
+
+BVHTree *bvhtree_build_from_mvert ( MFace *mfaces, unsigned int numfaces, MVert *x, unsigned int numverts, float epsilon )
+{
+ BVHTree *tree;
+ float co[12];
+ int i;
+ MFace *tface = mfaces;
+
+ tree = BLI_bvhtree_new ( numfaces*2, epsilon, 4, 26 );
+
+ // fill tree
+ for ( i = 0; i < numfaces; i++, tface++ )
+ {
+ VECCOPY ( &co[0*3], x[tface->v1].co );
+ VECCOPY ( &co[1*3], x[tface->v2].co );
+ VECCOPY ( &co[2*3], x[tface->v3].co );
+ if ( tface->v4 )
+ VECCOPY ( &co[3*3], x[tface->v4].co );
+
+ BLI_bvhtree_insert ( tree, i, co, ( mfaces->v4 ? 4 : 3 ) );
+ }
+
+ // balance tree
+ BLI_bvhtree_balance ( tree );
+
+ return tree;
+}
+
+void bvhtree_update_from_mvert ( BVHTree * bvhtree, MFace *faces, int numfaces, MVert *x, MVert *xnew, int numverts, int moving )
+{
+ int i;
+ MFace *mfaces = faces;
+ float co[12], co_moving[12];
+ int ret = 0;
+
+ if ( !bvhtree )
+ return;
+
+ if ( x )
+ {
+ for ( i = 0; i < numfaces; i++, mfaces++ )
+ {
+ VECCOPY ( &co[0*3], x[mfaces->v1].co );
+ VECCOPY ( &co[1*3], x[mfaces->v2].co );
+ VECCOPY ( &co[2*3], x[mfaces->v3].co );
+ if ( mfaces->v4 )
+ VECCOPY ( &co[3*3], x[mfaces->v4].co );
+
+ // copy new locations into array
+ if ( moving && xnew )
+ {
+ // update moving positions
+ VECCOPY ( &co_moving[0*3], xnew[mfaces->v1].co );
+ VECCOPY ( &co_moving[1*3], xnew[mfaces->v2].co );
+ VECCOPY ( &co_moving[2*3], xnew[mfaces->v3].co );
+ if ( mfaces->v4 )
+ VECCOPY ( &co_moving[3*3], xnew[mfaces->v4].co );
+
+ ret = BLI_bvhtree_update_node ( bvhtree, i, co, co_moving, ( mfaces->v4 ? 4 : 3 ) );
+ }
+ else
+ {
+ ret = BLI_bvhtree_update_node ( bvhtree, i, co, NULL, ( mfaces->v4 ? 4 : 3 ) );
+ }
+
+ // check if tree is already full
+ if ( !ret )
+ break;
+ }
+
+ BLI_bvhtree_update_tree ( bvhtree );
+ }
+}
+
+/***********************************
+Collision modifier code end
+***********************************/
+
+/**
+* gsl_poly_solve_cubic -
+*
+* copied from SOLVE_CUBIC.C --> GSL
+*/
+
+#define mySWAP(a,b) do { double tmp = b ; b = a ; a = tmp ; } while(0)
+
+int
+gsl_poly_solve_cubic (double a, double b, double c,
+ double *x0, double *x1, double *x2)
+{
+ double q = (a * a - 3 * b);
+ double r = (2 * a * a * a - 9 * a * b + 27 * c);
+
+ double Q = q / 9;
+ double R = r / 54;
+
+ double Q3 = Q * Q * Q;
+ double R2 = R * R;
+
+ double CR2 = 729 * r * r;
+ double CQ3 = 2916 * q * q * q;
+
+ if (R == 0 && Q == 0)
+ {
+ *x0 = - a / 3 ;
+ *x1 = - a / 3 ;
+ *x2 = - a / 3 ;
+ return 3 ;
+ }
+ else if (CR2 == CQ3)
+ {
+ /* this test is actually R2 == Q3, written in a form suitable
+ for exact computation with integers */
+
+ /* Due to finite precision some double roots may be missed, and
+ considered to be a pair of complex roots z = x +/- epsilon i
+ close to the real axis. */
+
+ double sqrtQ = sqrt (Q);
+
+ if (R > 0)
+ {
+ *x0 = -2 * sqrtQ - a / 3;
+ *x1 = sqrtQ - a / 3;
+ *x2 = sqrtQ - a / 3;
+ }
+ else
+ {
+ *x0 = - sqrtQ - a / 3;
+ *x1 = - sqrtQ - a / 3;
+ *x2 = 2 * sqrtQ - a / 3;
+ }
+ return 3 ;
+ }
+ else if (CR2 < CQ3) /* equivalent to R2 < Q3 */
+ {
+ double sqrtQ = sqrt (Q);
+ double sqrtQ3 = sqrtQ * sqrtQ * sqrtQ;
+ double theta = acos (R / sqrtQ3);
+ double norm = -2 * sqrtQ;
+ *x0 = norm * cos (theta / 3) - a / 3;
+ *x1 = norm * cos ((theta + 2.0 * M_PI) / 3) - a / 3;
+ *x2 = norm * cos ((theta - 2.0 * M_PI) / 3) - a / 3;
+
+ /* Sort *x0, *x1, *x2 into increasing order */
+
+ if (*x0 > *x1)
+ mySWAP(*x0, *x1) ;
+
+ if (*x1 > *x2)
+ {
+ mySWAP(*x1, *x2) ;
+
+ if (*x0 > *x1)
+ mySWAP(*x0, *x1) ;
+ }
+
+ return 3;
+ }
+ else
+ {
+ double sgnR = (R >= 0 ? 1 : -1);
+ double A = -sgnR * pow (fabs (R) + sqrt (R2 - Q3), 1.0/3.0);
+ double B = Q / A ;
+ *x0 = A + B - a / 3;
+ return 1;
+ }
+}
+
+
+
+/**
+* gsl_poly_solve_quadratic
+*
+* copied from GSL
+*/
+int
+gsl_poly_solve_quadratic (double a, double b, double c,
+ double *x0, double *x1)
+{
+ double disc = b * b - 4 * a * c;
+
+ if (a == 0) /* Handle linear case */
+ {
+ if (b == 0)
+ {
+ return 0;
+ }
+ else
+ {
+ *x0 = -c / b;
+ return 1;
+ };
+ }
+
+ if (disc > 0)
+ {
+ if (b == 0)
+ {
+ double r = fabs (0.5 * sqrt (disc) / a);
+ *x0 = -r;
+ *x1 = r;
+ }
+ else
+ {
+ double sgnb = (b > 0 ? 1 : -1);
+ double temp = -0.5 * (b + sgnb * sqrt (disc));
+ double r1 = temp / a ;
+ double r2 = c / temp ;
+
+ if (r1 < r2)
+ {
+ *x0 = r1 ;
+ *x1 = r2 ;
+ }
+ else
+ {
+ *x0 = r2 ;
+ *x1 = r1 ;
+ }
+ }
+ return 2;
+ }
+ else if (disc == 0)
+ {
+ *x0 = -0.5 * b / a ;
+ *x1 = -0.5 * b / a ;
+ return 2 ;
+ }
+ else
+ {
+ return 0;
+ }
+}
+
+
+
+
+/*
+* See Bridson et al. "Robust Treatment of Collision, Contact and Friction for Cloth Animation"
+* page 4, left column
+*/
+int cloth_get_collision_time ( double a[3], double b[3], double c[3], double d[3], double e[3], double f[3], double solution[3] )
+{
+ int num_sols = 0;
+
+ // x^0 - checked
+ double g = a[0] * c[1] * e[2] - a[0] * c[2] * e[1] +
+ a[1] * c[2] * e[0] - a[1] * c[0] * e[2] +
+ a[2] * c[0] * e[1] - a[2] * c[1] * e[0];
+
+ // x^1
+ double h = -b[2] * c[1] * e[0] + b[1] * c[2] * e[0] - a[2] * d[1] * e[0] +
+ a[1] * d[2] * e[0] + b[2] * c[0] * e[1] - b[0] * c[2] * e[1] +
+ a[2] * d[0] * e[1] - a[0] * d[2] * e[1] - b[1] * c[0] * e[2] +
+ b[0] * c[1] * e[2] - a[1] * d[0] * e[2] + a[0] * d[1] * e[2] -
+ a[2] * c[1] * f[0] + a[1] * c[2] * f[0] + a[2] * c[0] * f[1] -
+ a[0] * c[2] * f[1] - a[1] * c[0] * f[2] + a[0] * c[1] * f[2];
+
+ // x^2
+ double i = -b[2] * d[1] * e[0] + b[1] * d[2] * e[0] +
+ b[2] * d[0] * e[1] - b[0] * d[2] * e[1] -
+ b[1] * d[0] * e[2] + b[0] * d[1] * e[2] -
+ b[2] * c[1] * f[0] + b[1] * c[2] * f[0] -
+ a[2] * d[1] * f[0] + a[1] * d[2] * f[0] +
+ b[2] * c[0] * f[1] - b[0] * c[2] * f[1] +
+ a[2] * d[0] * f[1] - a[0] * d[2] * f[1] -
+ b[1] * c[0] * f[2] + b[0] * c[1] * f[2] -
+ a[1] * d[0] * f[2] + a[0] * d[1] * f[2];
+
+ // x^3 - checked
+ double j = -b[2] * d[1] * f[0] + b[1] * d[2] * f[0] +
+ b[2] * d[0] * f[1] - b[0] * d[2] * f[1] -
+ b[1] * d[0] * f[2] + b[0] * d[1] * f[2];
+
+ /*
+ printf("r1: %lf\n", a[0] * c[1] * e[2] - a[0] * c[2] * e[1]);
+ printf("r2: %lf\n", a[1] * c[2] * e[0] - a[1] * c[0] * e[2]);
+ printf("r3: %lf\n", a[2] * c[0] * e[1] - a[2] * c[1] * e[0]);
+
+ printf("x1 x: %f, y: %f, z: %f\n", a[0], a[1], a[2]);
+ printf("x2 x: %f, y: %f, z: %f\n", c[0], c[1], c[2]);
+ printf("x3 x: %f, y: %f, z: %f\n", e[0], e[1], e[2]);
+
+ printf("v1 x: %f, y: %f, z: %f\n", b[0], b[1], b[2]);
+ printf("v2 x: %f, y: %f, z: %f\n", d[0], d[1], d[2]);
+ printf("v3 x: %f, y: %f, z: %f\n", f[0], f[1], f[2]);
+
+ printf("t^3: %lf, t^2: %lf, t^1: %lf, t^0: %lf\n", j, i, h, g);
+
+*/
+ // Solve cubic equation to determine times t1, t2, t3, when the collision will occur.
+ if ( ABS ( j ) > DBL_EPSILON )
+ {
+ i /= j;
+ h /= j;
+ g /= j;
+ num_sols = gsl_poly_solve_cubic ( i, h, g, &solution[0], &solution[1], &solution[2] );
+ }
+ else
+ {
+ num_sols = gsl_poly_solve_quadratic ( i, h, g, &solution[0], &solution[1] );
+ solution[2] = -1.0;
+ }
+
+ // printf("num_sols: %d, sol1: %lf, sol2: %lf, sol3: %lf\n", num_sols, solution[0], solution[1], solution[2]);
+
+ // Discard negative solutions
+ if ( ( num_sols >= 1 ) && ( solution[0] < DBL_EPSILON ) )
+ {
+ --num_sols;
+ solution[0] = solution[num_sols];
+ }
+ if ( ( num_sols >= 2 ) && ( solution[1] < DBL_EPSILON ) )
+ {
+ --num_sols;
+ solution[1] = solution[num_sols];
+ }
+ if ( ( num_sols == 3 ) && ( solution[2] < DBL_EPSILON ) )
+ {
+ --num_sols;
+ }
+
+ // Sort
+ if ( num_sols == 2 )
+ {
+ if ( solution[0] > solution[1] )
+ {
+ double tmp = solution[0];
+ solution[0] = solution[1];
+ solution[1] = tmp;
+ }
+ }
+ else if ( num_sols == 3 )
+ {
+
+ // Bubblesort
+ if ( solution[0] > solution[1] )
+ {
+ double tmp = solution[0]; solution[0] = solution[1]; solution[1] = tmp;
+ }
+ if ( solution[1] > solution[2] )
+ {
+ double tmp = solution[1]; solution[1] = solution[2]; solution[2] = tmp;
+ }
+ if ( solution[0] > solution[1] )
+ {
+ double tmp = solution[0]; solution[0] = solution[1]; solution[1] = tmp;
+ }
+ }
+
+ return num_sols;
+}
+
+
+// w3 is not perfect
+void collision_compute_barycentric ( float pv[3], float p1[3], float p2[3], float p3[3], float *w1, float *w2, float *w3 )
+{
+ double tempV1[3], tempV2[3], tempV4[3];
+ double a,b,c,d,e,f;
+
+ VECSUB ( tempV1, p1, p3 );
+ VECSUB ( tempV2, p2, p3 );
+ VECSUB ( tempV4, pv, p3 );
+
+ a = INPR ( tempV1, tempV1 );
+ b = INPR ( tempV1, tempV2 );
+ c = INPR ( tempV2, tempV2 );
+ e = INPR ( tempV1, tempV4 );
+ f = INPR ( tempV2, tempV4 );
+
+ d = ( a * c - b * b );
+
+ if ( ABS ( d ) < ALMOST_ZERO )
+ {
+ *w1 = *w2 = *w3 = 1.0 / 3.0;
+ return;
+ }
+
+ w1[0] = ( float ) ( ( e * c - b * f ) / d );
+
+ if ( w1[0] < 0 )
+ w1[0] = 0;
+
+ w2[0] = ( float ) ( ( f - b * ( double ) w1[0] ) / c );
+
+ if ( w2[0] < 0 )
+ w2[0] = 0;
+
+ w3[0] = 1.0f - w1[0] - w2[0];
+}
+
+DO_INLINE void collision_interpolateOnTriangle ( float to[3], float v1[3], float v2[3], float v3[3], double w1, double w2, double w3 )
+{
+ to[0] = to[1] = to[2] = 0;
+ VECADDMUL ( to, v1, w1 );
+ VECADDMUL ( to, v2, w2 );
+ VECADDMUL ( to, v3, w3 );
+}
+
+
+int cloth_collision_response_static ( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair, CollPair *collision_end )
+{
+ int result = 0;
+ Cloth *cloth1;
+ float w1, w2, w3, u1, u2, u3;
+ float v1[3], v2[3], relativeVelocity[3];
+ float magrelVel;
+ float epsilon2 = BLI_bvhtree_getepsilon ( collmd->bvhtree );
+
+ cloth1 = clmd->clothObject;
+
+ for ( ; collpair != collision_end; collpair++ )
+ {
+ // only handle static collisions here
+ if ( collpair->flag & COLLISION_IN_FUTURE )
+ continue;
+
+ // compute barycentric coordinates for both collision points
+ collision_compute_barycentric ( collpair->pa,
+ cloth1->verts[collpair->ap1].txold,
+ cloth1->verts[collpair->ap2].txold,
+ cloth1->verts[collpair->ap3].txold,
+ &w1, &w2, &w3 );
+
+ // was: txold
+ collision_compute_barycentric ( collpair->pb,
+ collmd->current_x[collpair->bp1].co,
+ collmd->current_x[collpair->bp2].co,
+ collmd->current_x[collpair->bp3].co,
+ &u1, &u2, &u3 );
+
+ // Calculate relative "velocity".
+ collision_interpolateOnTriangle ( v1, cloth1->verts[collpair->ap1].tv, cloth1->verts[collpair->ap2].tv, cloth1->verts[collpair->ap3].tv, w1, w2, w3 );
+
+ collision_interpolateOnTriangle ( v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3 );
+
+ VECSUB ( relativeVelocity, v2, v1 );
+
+ // Calculate the normal component of the relative velocity (actually only the magnitude - the direction is stored in 'normal').
+ magrelVel = INPR ( relativeVelocity, collpair->normal );
+
+ // printf("magrelVel: %f\n", magrelVel);
+
+ // Calculate masses of points.
+ // TODO
+
+ // If v_n_mag < 0 the edges are approaching each other.
+ if ( magrelVel > ALMOST_ZERO )
+ {
+ // Calculate Impulse magnitude to stop all motion in normal direction.
+ float magtangent = 0, repulse = 0, d = 0;
+ double impulse = 0.0;
+ float vrel_t_pre[3];
+ float temp[3];
+
+ // calculate tangential velocity
+ VECCOPY ( temp, collpair->normal );
+ VecMulf ( temp, magrelVel );
+ VECSUB ( vrel_t_pre, relativeVelocity, temp );
+
+ // Decrease in magnitude of relative tangential velocity due to coulomb friction
+ // in original formula "magrelVel" should be the "change of relative velocity in normal direction"
+ magtangent = MIN2 ( clmd->coll_parms->friction * 0.01 * magrelVel,sqrt ( INPR ( vrel_t_pre,vrel_t_pre ) ) );
+
+ // Apply friction impulse.
+ if ( magtangent > ALMOST_ZERO )
+ {
+ Normalize ( vrel_t_pre );
+
+ impulse = magtangent / ( 1.0 + w1*w1 + w2*w2 + w3*w3 ); // 2.0 *
+ VECADDMUL ( cloth1->verts[collpair->ap1].impulse, vrel_t_pre, w1 * impulse );
+ VECADDMUL ( cloth1->verts[collpair->ap2].impulse, vrel_t_pre, w2 * impulse );
+ VECADDMUL ( cloth1->verts[collpair->ap3].impulse, vrel_t_pre, w3 * impulse );
+ }
+
+ // Apply velocity stopping impulse
+ // I_c = m * v_N / 2.0
+ // no 2.0 * magrelVel normally, but looks nicer DG
+ impulse = magrelVel / ( 1.0 + w1*w1 + w2*w2 + w3*w3 );
+
+ VECADDMUL ( cloth1->verts[collpair->ap1].impulse, collpair->normal, w1 * impulse );
+ cloth1->verts[collpair->ap1].impulse_count++;
+
+ VECADDMUL ( cloth1->verts[collpair->ap2].impulse, collpair->normal, w2 * impulse );
+ cloth1->verts[collpair->ap2].impulse_count++;
+
+ VECADDMUL ( cloth1->verts[collpair->ap3].impulse, collpair->normal, w3 * impulse );
+ cloth1->verts[collpair->ap3].impulse_count++;
+
+ // Apply repulse impulse if distance too short
+ // I_r = -min(dt*kd, m(0,1d/dt - v_n))
+ d = clmd->coll_parms->epsilon*8.0/9.0 + epsilon2*8.0/9.0 - collpair->distance;
+ if ( ( magrelVel < 0.1*d*clmd->sim_parms->stepsPerFrame ) && ( d > ALMOST_ZERO ) )
+ {
+ repulse = MIN2 ( d*1.0/clmd->sim_parms->stepsPerFrame, 0.1*d*clmd->sim_parms->stepsPerFrame - magrelVel );
+
+ // stay on the safe side and clamp repulse
+ if ( impulse > ALMOST_ZERO )
+ repulse = MIN2 ( repulse, 5.0*impulse );
+ repulse = MAX2 ( impulse, repulse );
+
+ impulse = repulse / ( 1.0 + w1*w1 + w2*w2 + w3*w3 ); // original 2.0 / 0.25
+ VECADDMUL ( cloth1->verts[collpair->ap1].impulse, collpair->normal, impulse );
+ VECADDMUL ( cloth1->verts[collpair->ap2].impulse, collpair->normal, impulse );
+ VECADDMUL ( cloth1->verts[collpair->ap3].impulse, collpair->normal, impulse );
+ }
+
+ result = 1;
+ }
+ }
+ return result;
+}
+
+//Determines collisions on overlap, collisions are writen to collpair[i] and collision+number_collision_found is returned
+CollPair* cloth_collision ( ModifierData *md1, ModifierData *md2, BVHTreeOverlap *overlap, CollPair *collpair )
+{
+ ClothModifierData *clmd = ( ClothModifierData * ) md1;
+ CollisionModifierData *collmd = ( CollisionModifierData * ) md2;
+ MFace *face1=NULL, *face2 = NULL;
+ ClothVertex *verts1 = clmd->clothObject->verts;
+ double distance = 0;
+ float epsilon1 = clmd->coll_parms->epsilon;
+ float epsilon2 = BLI_bvhtree_getepsilon ( collmd->bvhtree );
+ int i;
+
+ face1 = & ( clmd->clothObject->mfaces[overlap->indexA] );
+ face2 = & ( collmd->mfaces[overlap->indexB] );
+
+ // check all 4 possible collisions
+ for ( i = 0; i < 4; i++ )
+ {
+ if ( i == 0 )
+ {
+ // fill faceA
+ collpair->ap1 = face1->v1;
+ collpair->ap2 = face1->v2;
+ collpair->ap3 = face1->v3;
+
+ // fill faceB
+ collpair->bp1 = face2->v1;
+ collpair->bp2 = face2->v2;
+ collpair->bp3 = face2->v3;
+ }
+ else if ( i == 1 )
+ {
+ if ( face1->v4 )
+ {
+ // fill faceA
+ collpair->ap1 = face1->v1;
+ collpair->ap2 = face1->v4;
+ collpair->ap3 = face1->v3;
+
+ // fill faceB
+ collpair->bp1 = face2->v1;
+ collpair->bp2 = face2->v2;
+ collpair->bp3 = face2->v3;
+ }
+ else
+ i++;
+ }
+ if ( i == 2 )
+ {
+ if ( face2->v4 )
+ {
+ // fill faceA
+ collpair->ap1 = face1->v1;
+ collpair->ap2 = face1->v2;
+ collpair->ap3 = face1->v3;
+
+ // fill faceB
+ collpair->bp1 = face2->v1;
+ collpair->bp2 = face2->v4;
+ collpair->bp3 = face2->v3;
+ }
+ else
+ break;
+ }
+ else if ( i == 3 )
+ {
+ if ( face1->v4 && face2->v4 )
+ {
+ // fill faceA
+ collpair->ap1 = face1->v1;
+ collpair->ap2 = face1->v4;
+ collpair->ap3 = face1->v3;
+
+ // fill faceB
+ collpair->bp1 = face2->v1;
+ collpair->bp2 = face2->v4;
+ collpair->bp3 = face2->v3;
+ }
+ else
+ break;
+ }
+
+#ifdef WITH_BULLET
+ // calc distance + normal
+ distance = plNearestPoints (
+ verts1[collpair->ap1].txold, verts1[collpair->ap2].txold, verts1[collpair->ap3].txold, collmd->current_x[collpair->bp1].co, collmd->current_x[collpair->bp2].co, collmd->current_x[collpair->bp3].co, collpair->pa,collpair->pb,collpair->vector );
+#else
+ // just be sure that we don't add anything
+ distance = 2.0 * ( epsilon1 + epsilon2 + ALMOST_ZERO );
+#endif
+
+ if ( distance <= ( epsilon1 + epsilon2 + ALMOST_ZERO ) )
+ {
+ VECCOPY ( collpair->normal, collpair->vector );
+ Normalize ( collpair->normal );
+
+ collpair->distance = distance;
+ collpair->flag = 0;
+ collpair++;
+ }/*
+ else
+ {
+ float w1, w2, w3, u1, u2, u3;
+ float v1[3], v2[3], relativeVelocity[3];
+
+ // calc relative velocity
+
+ // compute barycentric coordinates for both collision points
+ collision_compute_barycentric ( collpair->pa,
+ verts1[collpair->ap1].txold,
+ verts1[collpair->ap2].txold,
+ verts1[collpair->ap3].txold,
+ &w1, &w2, &w3 );
+
+ // was: txold
+ collision_compute_barycentric ( collpair->pb,
+ collmd->current_x[collpair->bp1].co,
+ collmd->current_x[collpair->bp2].co,
+ collmd->current_x[collpair->bp3].co,
+ &u1, &u2, &u3 );
+
+ // Calculate relative "velocity".
+ collision_interpolateOnTriangle ( v1, verts1[collpair->ap1].tv, verts1[collpair->ap2].tv, verts1[collpair->ap3].tv, w1, w2, w3 );
+
+ collision_interpolateOnTriangle ( v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3 );
+
+ VECSUB ( relativeVelocity, v2, v1 );
+
+ if(sqrt(INPR(relativeVelocity, relativeVelocity)) >= distance)
+ {
+ // check for collision in the future
+ collpair->flag |= COLLISION_IN_FUTURE;
+ collpair++;
+ }
+ }*/
+ }
+ return collpair;
+}
+
+int cloth_collision_response_moving( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair, CollPair *collision_end )
+{
+ int result = 0;
+ Cloth *cloth1;
+ float w1, w2, w3, u1, u2, u3;
+ float v1[3], v2[3], relativeVelocity[3];
+ float magrelVel;
+
+ cloth1 = clmd->clothObject;
+
+ for ( ; collpair != collision_end; collpair++ )
+ {
+ // compute barycentric coordinates for both collision points
+ collision_compute_barycentric ( collpair->pa,
+ cloth1->verts[collpair->ap1].txold,
+ cloth1->verts[collpair->ap2].txold,
+ cloth1->verts[collpair->ap3].txold,
+ &w1, &w2, &w3 );
+
+ // was: txold
+ collision_compute_barycentric ( collpair->pb,
+ collmd->current_x[collpair->bp1].co,
+ collmd->current_x[collpair->bp2].co,
+ collmd->current_x[collpair->bp3].co,
+ &u1, &u2, &u3 );
+
+ // Calculate relative "velocity".
+ collision_interpolateOnTriangle ( v1, cloth1->verts[collpair->ap1].tv, cloth1->verts[collpair->ap2].tv, cloth1->verts[collpair->ap3].tv, w1, w2, w3 );
+
+ collision_interpolateOnTriangle ( v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3 );
+
+ VECSUB ( relativeVelocity, v2, v1 );
+
+ // Calculate the normal component of the relative velocity (actually only the magnitude - the direction is stored in 'normal').
+ magrelVel = INPR ( relativeVelocity, collpair->normal );
+
+ // printf("magrelVel: %f\n", magrelVel);
+
+ // Calculate masses of points.
+ // TODO
+
+ // If v_n_mag < 0 the edges are approaching each other.
+ if ( magrelVel > ALMOST_ZERO )
+ {
+ // Calculate Impulse magnitude to stop all motion in normal direction.
+ float magtangent = 0;
+ double impulse = 0.0;
+ float vrel_t_pre[3];
+ float temp[3];
+
+ // calculate tangential velocity
+ VECCOPY ( temp, collpair->normal );
+ VecMulf ( temp, magrelVel );
+ VECSUB ( vrel_t_pre, relativeVelocity, temp );
+
+ // Decrease in magnitude of relative tangential velocity due to coulomb friction
+ // in original formula "magrelVel" should be the "change of relative velocity in normal direction"
+ magtangent = MIN2 ( clmd->coll_parms->friction * 0.01 * magrelVel,sqrt ( INPR ( vrel_t_pre,vrel_t_pre ) ) );
+
+ // Apply friction impulse.
+ if ( magtangent > ALMOST_ZERO )
+ {
+ Normalize ( vrel_t_pre );
+
+ impulse = 2.0 * magtangent / ( 1.0 + w1*w1 + w2*w2 + w3*w3 );
+ VECADDMUL ( cloth1->verts[collpair->ap1].impulse, vrel_t_pre, w1 * impulse );
+ VECADDMUL ( cloth1->verts[collpair->ap2].impulse, vrel_t_pre, w2 * impulse );
+ VECADDMUL ( cloth1->verts[collpair->ap3].impulse, vrel_t_pre, w3 * impulse );
+ }
+
+ // Apply velocity stopping impulse
+ // I_c = m * v_N / 2.0
+ // no 2.0 * magrelVel normally, but looks nicer DG
+ impulse = magrelVel / ( 1.0 + w1*w1 + w2*w2 + w3*w3 );
+
+ VECADDMUL ( cloth1->verts[collpair->ap1].impulse, collpair->normal, w1 * impulse );
+ cloth1->verts[collpair->ap1].impulse_count++;
+
+ VECADDMUL ( cloth1->verts[collpair->ap2].impulse, collpair->normal, w2 * impulse );
+ cloth1->verts[collpair->ap2].impulse_count++;
+
+ VECADDMUL ( cloth1->verts[collpair->ap3].impulse, collpair->normal, w3 * impulse );
+ cloth1->verts[collpair->ap3].impulse_count++;
+
+ // Apply repulse impulse if distance too short
+ // I_r = -min(dt*kd, m(0,1d/dt - v_n))
+ /*
+ d = clmd->coll_parms->epsilon*8.0/9.0 + epsilon2*8.0/9.0 - collpair->distance;
+ if ( ( magrelVel < 0.1*d*clmd->sim_parms->stepsPerFrame ) && ( d > ALMOST_ZERO ) )
+ {
+ repulse = MIN2 ( d*1.0/clmd->sim_parms->stepsPerFrame, 0.1*d*clmd->sim_parms->stepsPerFrame - magrelVel );
+
+ // stay on the safe side and clamp repulse
+ if ( impulse > ALMOST_ZERO )
+ repulse = MIN2 ( repulse, 5.0*impulse );
+ repulse = MAX2 ( impulse, repulse );
+
+ impulse = repulse / ( 1.0 + w1*w1 + w2*w2 + w3*w3 ); // original 2.0 / 0.25
+ VECADDMUL ( cloth1->verts[collpair->ap1].impulse, collpair->normal, impulse );
+ VECADDMUL ( cloth1->verts[collpair->ap2].impulse, collpair->normal, impulse );
+ VECADDMUL ( cloth1->verts[collpair->ap3].impulse, collpair->normal, impulse );
+ }
+ */
+ result = 1;
+ }
+ }
+ return result;
+}
+
+static float projectPointOntoLine(float *p, float *a, float *b)
+{
+ float ba[3], pa[3];
+ VECSUB(ba, b, a);
+ VECSUB(pa, p, a);
+ return INPR(pa, ba) / INPR(ba, ba);
+}
+
+static void calculateEENormal(float *np1, float *np2, float *np3, float *np4,float *out_normal)
+{
+ float line1[3], line2[3];
+ float length;
+
+ VECSUB(line1, np2, np1);
+ VECSUB(line2, np3, np1);
+
+ // printf("l1: %f, l1: %f, l2: %f, l2: %f\n", line1[0], line1[1], line2[0], line2[1]);
+
+ Crossf(out_normal, line1, line2);
+
+
+
+ length = Normalize(out_normal);
+ if (length <= FLT_EPSILON)
+ { // lines are collinear
+ VECSUB(out_normal, np2, np1);
+ Normalize(out_normal);
+ }
+}
+
+static void findClosestPointsEE(float *x1, float *x2, float *x3, float *x4, float *w1, float *w2)
+{
+ float temp[3], temp2[3];
+
+ double a, b, c, e, f;
+
+ VECSUB(temp, x2, x1);
+ a = INPR(temp, temp);
+
+ VECSUB(temp2, x4, x3);
+ b = -INPR(temp, temp2);
+
+ c = INPR(temp2, temp2);
+
+ VECSUB(temp2, x3, x1);
+ e = INPR(temp, temp2);
+
+ VECSUB(temp, x4, x3);
+ f = -INPR(temp, temp2);
+
+ *w1 = (e * c - b * f) / (a * c - b * b);
+ *w2 = (f - b * *w1) / c;
+
+}
+
+// calculates the distance of 2 edges
+float edgedge_distance(float np11[3], float np12[3], float np21[3], float np22[3], float *out_a1, float *out_a2, float *out_normal)
+{
+ float line1[3], line2[3], cross[3];
+ float length;
+ float temp[3], temp2[3];
+ float dist_a1, dist_a2;
+
+ VECSUB(line1, np12, np11);
+ VECSUB(line2, np22, np21);
+
+ Crossf(cross, line1, line2);
+ length = INPR(cross, cross);
+
+ if (length < FLT_EPSILON)
+ {
+ *out_a2 = projectPointOntoLine(np11, np21, np22);
+ if ((*out_a2 >= -FLT_EPSILON) && (*out_a2 <= 1.0 + FLT_EPSILON))
+ {
+ *out_a1 = 0;
+ calculateEENormal(np11, np12, np21, np22, out_normal);
+ VECSUB(temp, np22, np21);
+ VecMulf(temp, *out_a2);
+ VECADD(temp2, temp, np21);
+ VECADD(temp2, temp2, np11);
+ return INPR(temp2, temp2);
+ }
+
+ CLAMP(*out_a2, 0.0, 1.0);
+ if (*out_a2 > .5)
+ { // == 1.0
+ *out_a1 = projectPointOntoLine(np22, np11, np12);
+ if ((*out_a1 >= -FLT_EPSILON) && (*out_a1 <= 1.0 + FLT_EPSILON))
+ {
+ calculateEENormal(np11, np12, np21, np22, out_normal);
+
+ // return (np22 - (np11 + (np12 - np11) * out_a1)).lengthSquared();
+ VECSUB(temp, np12, np11);
+ VecMulf(temp, *out_a1);
+ VECADD(temp2, temp, np11);
+ VECSUB(temp2, np22, temp2);
+ return INPR(temp2, temp2);
+ }
+ }
+ else
+ { // == 0.0
+ *out_a1 = projectPointOntoLine(np21, np11, np12);
+ if ((*out_a1 >= -FLT_EPSILON) && (*out_a1 <= 1.0 + FLT_EPSILON))
+ {
+ calculateEENormal(np11, np11, np21, np22, out_normal);
+
+ // return (np21 - (np11 + (np12 - np11) * out_a1)).lengthSquared();
+ VECSUB(temp, np12, np11);
+ VecMulf(temp, *out_a1);
+ VECADD(temp2, temp, np11);
+ VECSUB(temp2, np21, temp2);
+ return INPR(temp2, temp2);
+ }
+ }
+
+ CLAMP(*out_a1, 0.0, 1.0);
+ calculateEENormal(np11, np12, np21, np22, out_normal);
+ if(*out_a1 > .5)
+ {
+ if(*out_a2 > .5)
+ {
+ VECSUB(temp, np12, np22);
+ }
+ else
+ {
+ VECSUB(temp, np12, np21);
+ }
+ }
+ else
+ {
+ if(*out_a2 > .5)
+ {
+ VECSUB(temp, np11, np22);
+ }
+ else
+ {
+ VECSUB(temp, np11, np21);
+ }
+ }
+
+ return INPR(temp, temp);
+ }
+ else
+ {
+
+ // If the lines aren't parallel (but coplanar) they have to intersect
+
+ findClosestPointsEE(np11, np12, np21, np22, out_a1, out_a2);
+
+ // If both points are on the finite edges, we're done.
+ if (*out_a1 >= 0.0 && *out_a1 <= 1.0 && *out_a2 >= 0.0 && *out_a2 <= 1.0)
+ {
+ float p1[3], p2[3];
+
+ // p1= np11 + (np12 - np11) * out_a1;
+ VECSUB(temp, np12, np11);
+ VecMulf(temp, *out_a1);
+ VECADD(p1, np11, temp);
+
+ // p2 = np21 + (np22 - np21) * out_a2;
+ VECSUB(temp, np22, np21);
+ VecMulf(temp, *out_a2);
+ VECADD(p2, np21, temp);
+
+ calculateEENormal(np11, np12, np21, np22, out_normal);
+ VECSUB(temp, p1, p2);
+ return INPR(temp, temp);
+ }
+
+
+ /*
+ * Clamp both points to the finite edges.
+ * The one that moves most during clamping is one part of the solution.
+ */
+ dist_a1 = *out_a1;
+ CLAMP(dist_a1, 0.0, 1.0);
+ dist_a2 = *out_a2;
+ CLAMP(dist_a2, 0.0, 1.0);
+
+ // Now project the "most clamped" point on the other line.
+ if (dist_a1 > dist_a2)
+ {
+ /* keep out_a1 */
+ float p1[3];
+
+ // p1 = np11 + (np12 - np11) * out_a1;
+ VECSUB(temp, np12, np11);
+ VecMulf(temp, *out_a1);
+ VECADD(p1, np11, temp);
+
+ *out_a2 = projectPointOntoLine(p1, np21, np22);
+ CLAMP(*out_a2, 0.0, 1.0);
+
+ calculateEENormal(np11, np12, np21, np22, out_normal);
+
+ // return (p1 - (np21 + (np22 - np21) * out_a2)).lengthSquared();
+ VECSUB(temp, np22, np21);
+ VecMulf(temp, *out_a2);
+ VECADD(temp, temp, np21);
+ VECSUB(temp, p1, temp);
+ return INPR(temp, temp);
+ }
+ else
+ {
+ /* keep out_a2 */
+ float p2[3];
+
+ // p2 = np21 + (np22 - np21) * out_a2;
+ VECSUB(temp, np22, np21);
+ VecMulf(temp, *out_a2);
+ VECADD(p2, np21, temp);
+
+ *out_a1 = projectPointOntoLine(p2, np11, np12);
+ CLAMP(*out_a1, 0.0, 1.0);
+
+ calculateEENormal(np11, np12, np21, np22, out_normal);
+
+ // return ((np11 + (np12 - np11) * out_a1) - p2).lengthSquared();
+ VECSUB(temp, np12, np11);
+ VecMulf(temp, *out_a1);
+ VECADD(temp, temp, np11);
+ VECSUB(temp, temp, p2);
+ return INPR(temp, temp);
+ }
+ }
+
+ printf("Error in edgedge_distance: end of function\n");
+ return 0;
+}
+
+int cloth_collision_moving_edges ( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair )
+{
+ EdgeCollPair edgecollpair;
+ Cloth *cloth1=NULL;
+ ClothVertex *verts1=NULL;
+ unsigned int i = 0, k = 0;
+ int numsolutions = 0;
+ double x1[3], v1[3], x2[3], v2[3], x3[3], v3[3];
+ double solution[3], solution2[3];
+ MVert *verts2 = collmd->current_x; // old x
+ MVert *velocity2 = collmd->current_v; // velocity
+ float distance = 0;
+ float triA[3][3], triB[3][3];
+ int result = 0;
+
+ cloth1 = clmd->clothObject;
+ verts1 = cloth1->verts;
+
+ for(i = 0; i < 9; i++)
+ {
+ // 9 edge - edge possibilities
+
+ if(i == 0) // cloth edge: 1-2; coll edge: 1-2
+ {
+ edgecollpair.p11 = collpair->ap1;
+ edgecollpair.p12 = collpair->ap2;
+
+ edgecollpair.p21 = collpair->bp1;
+ edgecollpair.p22 = collpair->bp2;
+ }
+ else if(i == 1) // cloth edge: 1-2; coll edge: 2-3
+ {
+ edgecollpair.p11 = collpair->ap1;
+ edgecollpair.p12 = collpair->ap2;
+
+ edgecollpair.p21 = collpair->bp2;
+ edgecollpair.p22 = collpair->bp3;
+ }
+ else if(i == 2) // cloth edge: 1-2; coll edge: 1-3
+ {
+ edgecollpair.p11 = collpair->ap1;
+ edgecollpair.p12 = collpair->ap2;
+
+ edgecollpair.p21 = collpair->bp1;
+ edgecollpair.p22 = collpair->bp3;
+ }
+ else if(i == 3) // cloth edge: 2-3; coll edge: 1-2
+ {
+ edgecollpair.p11 = collpair->ap2;
+ edgecollpair.p12 = collpair->ap3;
+
+ edgecollpair.p21 = collpair->bp1;
+ edgecollpair.p22 = collpair->bp2;
+ }
+ else if(i == 4) // cloth edge: 2-3; coll edge: 2-3
+ {
+ edgecollpair.p11 = collpair->ap2;
+ edgecollpair.p12 = collpair->ap3;
+
+ edgecollpair.p21 = collpair->bp2;
+ edgecollpair.p22 = collpair->bp3;
+ }
+ else if(i == 5) // cloth edge: 2-3; coll edge: 1-3
+ {
+ edgecollpair.p11 = collpair->ap2;
+ edgecollpair.p12 = collpair->ap3;
+
+ edgecollpair.p21 = collpair->bp1;
+ edgecollpair.p22 = collpair->bp3;
+ }
+ else if(i ==6) // cloth edge: 1-3; coll edge: 1-2
+ {
+ edgecollpair.p11 = collpair->ap1;
+ edgecollpair.p12 = collpair->ap3;
+
+ edgecollpair.p21 = collpair->bp1;
+ edgecollpair.p22 = collpair->bp2;
+ }
+ else if(i ==7) // cloth edge: 1-3; coll edge: 2-3
+ {
+ edgecollpair.p11 = collpair->ap1;
+ edgecollpair.p12 = collpair->ap3;
+
+ edgecollpair.p21 = collpair->bp2;
+ edgecollpair.p22 = collpair->bp3;
+ }
+ else if(i == 8) // cloth edge: 1-3; coll edge: 1-3
+ {
+ edgecollpair.p11 = collpair->ap1;
+ edgecollpair.p12 = collpair->ap3;
+
+ edgecollpair.p21 = collpair->bp1;
+ edgecollpair.p22 = collpair->bp3;
+ }
+ /*
+ if((edgecollpair.p11 == 3) && (edgecollpair.p12 == 16))
+ printf("Ahier!\n");
+ if((edgecollpair.p11 == 16) && (edgecollpair.p12 == 3))
+ printf("Ahier!\n");
+ */
+
+ // if ( !cloth_are_edges_adjacent ( clmd, collmd, &edgecollpair ) )
+ {
+ // always put coll points in p21/p22
+ VECSUB ( x1, verts1[edgecollpair.p12].txold, verts1[edgecollpair.p11].txold );
+ VECSUB ( v1, verts1[edgecollpair.p12].tv, verts1[edgecollpair.p11].tv );
+
+ VECSUB ( x2, verts2[edgecollpair.p21].co, verts1[edgecollpair.p11].txold );
+ VECSUB ( v2, velocity2[edgecollpair.p21].co, verts1[edgecollpair.p11].tv );
+
+ VECSUB ( x3, verts2[edgecollpair.p22].co, verts1[edgecollpair.p11].txold );
+ VECSUB ( v3, velocity2[edgecollpair.p22].co, verts1[edgecollpair.p11].tv );
+
+ numsolutions = cloth_get_collision_time ( x1, v1, x2, v2, x3, v3, solution );
+
+ if((edgecollpair.p11 == 3 && edgecollpair.p12==16)|| (edgecollpair.p11==16 && edgecollpair.p12==3))
+ {
+ if(edgecollpair.p21==6 || edgecollpair.p22 == 6)
+ {
+ printf("dist: %f, sol[k]: %lf, sol2[k]: %lf\n", distance, solution[k], solution2[k]);
+ printf("a1: %f, a2: %f, b1: %f, b2: %f\n", x1[0], x2[0], x3[0], v1[0]);
+ printf("b21: %d, b22: %d\n", edgecollpair.p21, edgecollpair.p22);
+ }
+ }
+
+ for ( k = 0; k < numsolutions; k++ )
+ {
+ // printf("sol %d: %lf\n", k, solution[k]);
+ if ( ( solution[k] >= ALMOST_ZERO ) && ( solution[k] <= 1.0 ) && ( solution[k] > ALMOST_ZERO))
+ {
+ float a,b;
+ float out_normal[3];
+ float distance;
+ float impulse = 0;
+ float I_mag;
+
+ // move verts
+ VECADDS(triA[0], verts1[edgecollpair.p11].txold, verts1[edgecollpair.p11].tv, solution[k]);
+ VECADDS(triA[1], verts1[edgecollpair.p12].txold, verts1[edgecollpair.p12].tv, solution[k]);
+
+ VECADDS(triB[0], collmd->current_x[edgecollpair.p21].co, collmd->current_v[edgecollpair.p21].co, solution[k]);
+ VECADDS(triB[1], collmd->current_x[edgecollpair.p22].co, collmd->current_v[edgecollpair.p22].co, solution[k]);
+
+ // TODO: check for collisions
+ distance = edgedge_distance(triA[0], triA[1], triB[0], triB[1], &a, &b, out_normal);
+
+ if ((distance <= clmd->coll_parms->epsilon + BLI_bvhtree_getepsilon ( collmd->bvhtree ) + ALMOST_ZERO) && (INPR(out_normal, out_normal) > 0))
+ {
+ float vrel_1_to_2[3], temp[3], temp2[3], out_normalVelocity;
+ float desiredVn;
+
+ VECCOPY(vrel_1_to_2, verts1[edgecollpair.p11].tv);
+ VecMulf(vrel_1_to_2, 1.0 - a);
+ VECCOPY(temp, verts1[edgecollpair.p12].tv);
+ VecMulf(temp, a);
+
+ VECADD(vrel_1_to_2, vrel_1_to_2, temp);
+
+ VECCOPY(temp, verts1[edgecollpair.p21].tv);
+ VecMulf(temp, 1.0 - b);
+ VECCOPY(temp2, verts1[edgecollpair.p22].tv);
+ VecMulf(temp2, b);
+ VECADD(temp, temp, temp2);
+
+ VECSUB(vrel_1_to_2, vrel_1_to_2, temp);
+
+ out_normalVelocity = INPR(vrel_1_to_2, out_normal);
+/*
+ // this correction results in wrong normals sometimes?
+ if(out_normalVelocity < 0.0)
+ {
+ out_normalVelocity*= -1.0;
+ VecMulf(out_normal, -1.0);
+ }
+*/
+ /* Inelastic repulsion impulse. */
+
+ // Calculate which normal velocity we need.
+ desiredVn = (out_normalVelocity * (float)solution[k] - (.1 * (clmd->coll_parms->epsilon + BLI_bvhtree_getepsilon ( collmd->bvhtree )) - sqrt(distance)) - ALMOST_ZERO);
+
+ // Now calculate what impulse we need to reach that velocity.
+ I_mag = (out_normalVelocity - desiredVn) / 2.0; // / (1/m1 + 1/m2);
+
+ // Finally apply that impulse.
+ impulse = (2.0 * -I_mag) / (a*a + (1.0-a)*(1.0-a) + b*b + (1.0-b)*(1.0-b));
+
+ VECADDMUL ( verts1[edgecollpair.p11].impulse, out_normal, (1.0-a) * impulse );
+ verts1[edgecollpair.p11].impulse_count++;
+
+ VECADDMUL ( verts1[edgecollpair.p12].impulse, out_normal, a * impulse );
+ verts1[edgecollpair.p12].impulse_count++;
+
+ // return true;
+ result = 1;
+ break;
+ }
+ else
+ {
+ // missing from collision.hpp
+ }
+ // mintime = MIN2(mintime, (float)solution[k]);
+
+ break;
+ }
+ }
+ }
+ }
+ return result;
+}
+
+int cloth_collision_moving ( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair, CollPair *collision_end )
+{
+ Cloth *cloth1;
+ cloth1 = clmd->clothObject;
+
+ for ( ; collpair != collision_end; collpair++ )
+ {
+ // only handle moving collisions here
+ if (!( collpair->flag & COLLISION_IN_FUTURE ))
+ continue;
+
+ cloth_collision_moving_edges ( clmd, collmd, collpair);
+ // cloth_collision_moving_tris ( clmd, collmd, collpair);
+ }
+
+ return 1;
+}
+
+
+// return all collision objects in scene
+// collision object will exclude self
+CollisionModifierData **get_collisionobjects(Object *self, int *numcollobj)
+{
+ Base *base=NULL;
+ CollisionModifierData **objs = NULL;
+ Object *coll_ob = NULL;
+ CollisionModifierData *collmd = NULL;
+ int numobj = 0, maxobj = 100;
+
+ objs = MEM_callocN(sizeof(CollisionModifierData *)*maxobj, "CollisionObjectsArray");
+ // check all collision objects
+ for ( base = G.scene->base.first; base; base = base->next )
+ {
+ /*Only proceed for mesh object in same layer */
+ if(!(base->object->type==OB_MESH && (base->lay & self->lay)))
+ continue;
+
+ coll_ob = base->object;
+
+ if(coll_ob == self)
+ continue;
+
+ if(coll_ob->pd && coll_ob->pd->deflect)
+ {
+ collmd = ( CollisionModifierData * ) modifiers_findByType ( coll_ob, eModifierType_Collision );
+ }
+ else
+ collmd = NULL;
+
+ if ( collmd )
+ {
+ if(numobj >= maxobj)
+ {
+ // realloc
+ int oldmax = maxobj;
+ CollisionModifierData **tmp;
+ maxobj *= 2;
+ tmp = MEM_callocN(sizeof(CollisionModifierData *)*maxobj, "CollisionObjectsArray");
+ memcpy(tmp, objs, sizeof(CollisionModifierData *)*oldmax);
+ MEM_freeN(objs);
+ objs = tmp;
+
+ }
+
+ objs[numobj] = collmd;
+ numobj++;
+ }
+ else
+ {
+ if ( coll_ob->dup_group )
+ {
+ GroupObject *go;
+ Group *group = coll_ob->dup_group;
+
+ for ( go= group->gobject.first; go; go= go->next )
+ {
+ coll_ob = go->ob;
+ collmd = NULL;
+
+ if(coll_ob == self)
+ continue;
+
+ if(coll_ob->pd && coll_ob->pd->deflect)
+ {
+ collmd = ( CollisionModifierData * ) modifiers_findByType ( coll_ob, eModifierType_Collision );
+ }
+ else
+ collmd = NULL;
+
+ if ( !collmd )
+ continue;
+
+ if( !collmd->bvhtree)
+ continue;
+
+ if(numobj >= maxobj)
+ {
+ // realloc
+ int oldmax = maxobj;
+ CollisionModifierData **tmp;
+ maxobj *= 2;
+ tmp = MEM_callocN(sizeof(CollisionModifierData *)*maxobj, "CollisionObjectsArray");
+ memcpy(tmp, objs, sizeof(CollisionModifierData *)*oldmax);
+ MEM_freeN(objs);
+ objs = tmp;
+ }
+
+ objs[numobj] = collmd;
+ numobj++;
+ }
+ }
+ }
+ }
+ *numcollobj = numobj;
+ return objs;
+}
+
+void cloth_bvh_objcollisions_nearcheck ( ClothModifierData * clmd, CollisionModifierData *collmd, CollPair **collisions, CollPair **collisions_index, int numresult, BVHTreeOverlap *overlap)
+{
+ int i;
+
+ *collisions = ( CollPair* ) MEM_mallocN ( sizeof ( CollPair ) * numresult * 4, "collision array" ); //*4 since cloth_collision_static can return more than 1 collision
+ *collisions_index = *collisions;
+
+ for ( i = 0; i < numresult; i++ )
+ {
+ *collisions_index = cloth_collision ( ( ModifierData * ) clmd, ( ModifierData * ) collmd, overlap+i, *collisions_index );
+ }
+}
+
+int cloth_bvh_objcollisions_resolve ( ClothModifierData * clmd, CollisionModifierData *collmd, CollPair *collisions, CollPair *collisions_index)
+{
+ Cloth *cloth = clmd->clothObject;
+ int i=0, j = 0, numfaces = 0, numverts = 0;
+ ClothVertex *verts = NULL;
+ int ret = 0;
+ int result = 0;
+ float tnull[3] = {0,0,0};
+
+ numfaces = clmd->clothObject->numfaces;
+ numverts = clmd->clothObject->numverts;
+
+ verts = cloth->verts;
+
+ // process all collisions (calculate impulses, TODO: also repulses if distance too short)
+ result = 1;
+ for ( j = 0; j < 5; j++ ) // 5 is just a value that ensures convergence
+ {
+ result = 0;
+
+ if ( collmd->bvhtree )
+ {
+ result += cloth_collision_response_static ( clmd, collmd, collisions, collisions_index );
+
+ // apply impulses in parallel
+ if ( result )
+ {
+ for ( i = 0; i < numverts; i++ )
+ {
+ // calculate "velocities" (just xnew = xold + v; no dt in v)
+ if ( verts[i].impulse_count )
+ {
+ VECADDMUL ( verts[i].tv, verts[i].impulse, 1.0f / verts[i].impulse_count );
+ VECCOPY ( verts[i].impulse, tnull );
+ verts[i].impulse_count = 0;
+
+ ret++;
+ }
+ }
+ }
+ }
+ }
+ return ret;
+}
+
+// cloth - object collisions
+int cloth_bvh_objcollision ( Object *ob, ClothModifierData * clmd, float step, float dt )
+{
+ Cloth *cloth=NULL;
+ BVHTree *cloth_bvh=NULL;
+ int i=0, numfaces = 0, numverts = 0, k, l, j;
+ int rounds = 0; // result counts applied collisions; ic is for debug output;
+ ClothVertex *verts = NULL;
+ int ret = 0, ret2 = 0;
+ CollisionModifierData **collobjs = NULL;
+ int numcollobj = 0;
+
+ if ( ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_COLLOBJ ) || ! ( ( ( Cloth * ) clmd->clothObject )->bvhtree ) )
+ {
+ return 0;
+ }
+
+ cloth = clmd->clothObject;
+ verts = cloth->verts;
+ cloth_bvh = ( BVHTree * ) cloth->bvhtree;
+ numfaces = clmd->clothObject->numfaces;
+ numverts = clmd->clothObject->numverts;
+
+ ////////////////////////////////////////////////////////////
+ // static collisions
+ ////////////////////////////////////////////////////////////
+
+ // update cloth bvh
+ bvhtree_update_from_cloth ( clmd, 1 ); // 0 means STATIC, 1 means MOVING (see later in this function)
+ bvhselftree_update_from_cloth ( clmd, 0 ); // 0 means STATIC, 1 means MOVING (see later in this function)
+
+ collobjs = get_collisionobjects(ob, &numcollobj);
+
+ if(!collobjs)
+ return 0;
+
+ do
+ {
+ CollPair **collisions, **collisions_index;
+
+ ret2 = 0;
+
+ collisions = MEM_callocN(sizeof(CollPair *) *numcollobj , "CollPair");
+ collisions_index = MEM_callocN(sizeof(CollPair *) *numcollobj , "CollPair");
+
+ // check all collision objects
+ for(i = 0; i < numcollobj; i++)
+ {
+ CollisionModifierData *collmd = collobjs[i];
+ BVHTreeOverlap *overlap = NULL;
+ int result = 0;
+
+ if(!collmd->bvhtree)
+ continue;
+
+ /* move object to position (step) in time */
+ collision_move_object ( collmd, step + dt, step );
+
+ /* search for overlapping collision pairs */
+ overlap = BLI_bvhtree_overlap ( cloth_bvh, collmd->bvhtree, &result );
+
+ // go to next object if no overlap is there
+ if(!result || !overlap)
+ {
+ if ( overlap )
+ MEM_freeN ( overlap );
+ continue;
+ }
+
+ /* check if collisions really happen (costly near check) */
+ cloth_bvh_objcollisions_nearcheck ( clmd, collmd, &collisions[i], &collisions_index[i], result, overlap);
+
+ // resolve nearby collisions
+ ret += cloth_bvh_objcollisions_resolve ( clmd, collmd, collisions[i], collisions_index[i]);
+ ret2 += ret;
+
+ if ( overlap )
+ MEM_freeN ( overlap );
+ }
+ rounds++;
+
+ for(i = 0; i < numcollobj; i++)
+ {
+ if ( collisions[i] ) MEM_freeN ( collisions[i] );
+ }
+
+ MEM_freeN(collisions);
+ MEM_freeN(collisions_index);
+
+ ////////////////////////////////////////////////////////////
+ // update positions
+ // this is needed for bvh_calc_DOP_hull_moving() [kdop.c]
+ ////////////////////////////////////////////////////////////
+
+ // verts come from clmd
+ for ( i = 0; i < numverts; i++ )
+ {
+ if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )
+ {
+ if ( verts [i].flags & CLOTH_VERT_FLAG_PINNED )
+ {
+ continue;
+ }
+ }
+
+ VECADD ( verts[i].tx, verts[i].txold, verts[i].tv );
+ }
+ ////////////////////////////////////////////////////////////
+
+
+ ////////////////////////////////////////////////////////////
+ // Test on *simple* selfcollisions
+ ////////////////////////////////////////////////////////////
+ if ( clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF )
+ {
+ for(l = 0; l < clmd->coll_parms->self_loop_count; l++)
+ {
+ // TODO: add coll quality rounds again
+ BVHTreeOverlap *overlap = NULL;
+ int result = 0;
+
+ // collisions = 1;
+ verts = cloth->verts; // needed for openMP
+
+ numfaces = clmd->clothObject->numfaces;
+ numverts = clmd->clothObject->numverts;
+
+ verts = cloth->verts;
+
+ if ( cloth->bvhselftree )
+ {
+ // search for overlapping collision pairs
+ overlap = BLI_bvhtree_overlap ( cloth->bvhselftree, cloth->bvhselftree, &result );
+
+ // #pragma omp parallel for private(k, i, j) schedule(static)
+ for ( k = 0; k < result; k++ )
+ {
+ float temp[3];
+ float length = 0;
+ float mindistance;
+
+ i = overlap[k].indexA;
+ j = overlap[k].indexB;
+
+ mindistance = clmd->coll_parms->selfepsilon* ( cloth->verts[i].avg_spring_len + cloth->verts[j].avg_spring_len );
+
+ if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )
+ {
+ if ( ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED )
+ && ( cloth->verts [j].flags & CLOTH_VERT_FLAG_PINNED ) )
+ {
+ continue;
+ }
+ }
+
+ VECSUB ( temp, verts[i].tx, verts[j].tx );
+
+ if ( ( ABS ( temp[0] ) > mindistance ) || ( ABS ( temp[1] ) > mindistance ) || ( ABS ( temp[2] ) > mindistance ) ) continue;
+
+ // check for adjacent points (i must be smaller j)
+ if ( BLI_edgehash_haskey ( cloth->edgehash, MIN2(i, j), MAX2(i, j) ) )
+ {
+ continue;
+ }
+
+ length = Normalize ( temp );
+
+ if ( length < mindistance )
+ {
+ float correction = mindistance - length;
+
+ if ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED )
+ {
+ VecMulf ( temp, -correction );
+ VECADD ( verts[j].tx, verts[j].tx, temp );
+ }
+ else if ( cloth->verts [j].flags & CLOTH_VERT_FLAG_PINNED )
+ {
+ VecMulf ( temp, correction );
+ VECADD ( verts[i].tx, verts[i].tx, temp );
+ }
+ else
+ {
+ VecMulf ( temp, -correction*0.5 );
+ VECADD ( verts[j].tx, verts[j].tx, temp );
+
+ VECSUB ( verts[i].tx, verts[i].tx, temp );
+ }
+ ret = 1;
+ ret2 += ret;
+ }
+ else
+ {
+ // check for approximated time collisions
+ }
+ }
+
+ if ( overlap )
+ MEM_freeN ( overlap );
+
+ }
+ }
+ ////////////////////////////////////////////////////////////
+
+ ////////////////////////////////////////////////////////////
+ // SELFCOLLISIONS: update velocities
+ ////////////////////////////////////////////////////////////
+ if ( ret2 )
+ {
+ for ( i = 0; i < cloth->numverts; i++ )
+ {
+ if ( ! ( verts [i].flags & CLOTH_VERT_FLAG_PINNED ) )
+ {
+ VECSUB ( verts[i].tv, verts[i].tx, verts[i].txold );
+ }
+ }
+ }
+ ////////////////////////////////////////////////////////////
+ }
+ }
+ while ( ret2 && ( clmd->coll_parms->loop_count>rounds ) );
+
+ if(collobjs)
+ MEM_freeN(collobjs);
+
+ return MIN2 ( ret, 1 );
+}
diff --git a/source/blender/blenkernel/intern/colortools.c b/source/blender/blenkernel/intern/colortools.c
index 83b014cdd63..1bc34aea9a1 100644
--- a/source/blender/blenkernel/intern/colortools.c
+++ b/source/blender/blenkernel/intern/colortools.c
@@ -167,18 +167,30 @@ void curvemap_remove(CurveMap *cuma, int flag)
void curvemap_insert(CurveMap *cuma, float x, float y)
{
CurveMapPoint *cmp= MEM_callocN((cuma->totpoint+1)*sizeof(CurveMapPoint), "curve points");
- int a;
-
- memcpy(cmp, cuma->curve, (cuma->totpoint)*sizeof(CurveMapPoint));
+ int a, b, foundloc= 0;
+
+ /* insert fragments of the old one and the new point to the new curve */
+ cuma->totpoint++;
+ for(a=0, b=0; a<cuma->totpoint; a++) {
+ if((x < cuma->curve[a].x) && !foundloc) {
+ cmp[a].x= x;
+ cmp[a].y= y;
+ cmp[a].flag= CUMA_SELECT;
+ foundloc= 1;
+ }
+ else {
+ cmp[a].x= cuma->curve[b].x;
+ cmp[a].y= cuma->curve[b].y;
+ cmp[a].flag= cuma->curve[b].flag;
+ cmp[a].flag &= ~CUMA_SELECT; /* make sure old points don't remain selected */
+ cmp[a].shorty= cuma->curve[b].shorty;
+ b++;
+ }
+ }
+
+ /* free old curve and replace it with new one */
MEM_freeN(cuma->curve);
cuma->curve= cmp;
-
- cuma->curve[cuma->totpoint].x= x;
- cuma->curve[cuma->totpoint].y= y;
- cuma->curve[cuma->totpoint].flag = CUMA_SELECT;
- for(a=0; a<cuma->totpoint; a++, cmp++)
- cmp->flag= 0;
- cuma->totpoint++;
}
void curvemap_reset(CurveMap *cuma, rctf *clipr)
@@ -580,7 +592,8 @@ float curvemap_evaluateF(CurveMap *cuma, float value)
fi= (value-cuma->mintable)*cuma->range;
i= (int)fi;
- if(fi<0.0f || fi>cuma->range)
+ /* fi is table float index and should check against table range i.e. [0.0 CM_TABLE] */
+ if(fi<0.0f || fi>CM_TABLE)
return curvemap_calc_extend(cuma, value, &cuma->table[0].x, &cuma->table[CM_TABLE].x);
else {
if(i<0) return cuma->table[0].y;
@@ -637,7 +650,6 @@ void curvemapping_evaluate_premulRGBF(CurveMapping *cumap, float *vecout, const
vecout[2]= curvemap_evaluateF(cumap->cm+2, fac);
}
-#define FTOCHAR(val) val<=0.0f?0: (val>=1.0f?255: (char)(255.0f*val))
void curvemapping_do_ibuf(CurveMapping *cumap, ImBuf *ibuf)
{
@@ -717,3 +729,24 @@ void curvemapping_initialize(CurveMapping *cumap)
curvemap_make_table(cumap->cm+a, &cumap->clipr);
}
}
+
+void curvemapping_table_RGBA(CurveMapping *cumap, float **array, int *size)
+{
+ int a;
+
+ *size = CM_TABLE+1;
+ *array = MEM_callocN(sizeof(float)*(*size)*4, "CurveMapping");
+ curvemapping_initialize(cumap);
+
+ for(a=0; a<*size; a++) {
+ if(cumap->cm[0].table)
+ (*array)[a*4+0]= cumap->cm[0].table[a].y;
+ if(cumap->cm[1].table)
+ (*array)[a*4+1]= cumap->cm[1].table[a].y;
+ if(cumap->cm[2].table)
+ (*array)[a*4+2]= cumap->cm[2].table[a].y;
+ if(cumap->cm[3].table)
+ (*array)[a*4+3]= cumap->cm[3].table[a].y;
+ }
+}
+
diff --git a/source/blender/blenkernel/intern/constraint.c b/source/blender/blenkernel/intern/constraint.c
index 3ed4d134145..b8bfb002075 100644
--- a/source/blender/blenkernel/intern/constraint.c
+++ b/source/blender/blenkernel/intern/constraint.c
@@ -28,8 +28,10 @@
*/
#include <stdio.h>
+#include <stddef.h>
#include <string.h>
#include <math.h>
+#include <float.h>
#include "MEM_guardedalloc.h"
//XXX #include "nla.h"
@@ -63,8 +65,9 @@
#include "BKE_library.h"
#include "BKE_idprop.h"
-
+#ifndef DISABLE_PYTHON
#include "BPY_extern.h"
+#endif
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -78,10 +81,10 @@
/* ******************* Constraint Channels ********************** */
/* Constraint Channels exist in one of two places:
* - Under Action Channels in an Action (act->chanbase->achan->constraintChannels)
- * - Under Object without object-level action yet (ob->constraintChannels)
+ * - Under Object without Object-level Action yet (ob->constraintChannels)
*
- * The main purpose that constraint channels serve is to act as a link
- * between an IPO-block which
+ * The main purpose that Constraint Channels serve is to act as a link
+ * between an IPO-block (which provides values to interpolate between for some settings)
*/
/* ------------ Data Management ----------- */
@@ -137,7 +140,7 @@ bConstraintChannel *get_constraint_channel (ListBase *list, const char name[])
{
bConstraintChannel *chan;
- if(list) {
+ if (list) {
for (chan = list->first; chan; chan=chan->next) {
if (!strcmp(name, chan->name)) {
return chan;
@@ -177,11 +180,11 @@ void do_constraint_channels (ListBase *conbase, ListBase *chanbase, float ctime,
for (con=conbase->first; con; con=con->next) {
Ipo *ipo= NULL;
- if(con->flag & CONSTRAINT_OWN_IPO)
+ if (con->flag & CONSTRAINT_OWN_IPO)
ipo= con->ipo;
else {
bConstraintChannel *chan = get_constraint_channel(chanbase, con->name);
- if(chan) ipo= chan->ipo;
+ if (chan) ipo= chan->ipo;
}
if (ipo) {
@@ -200,7 +203,24 @@ void do_constraint_channels (ListBase *conbase, ListBase *chanbase, float ctime,
break;
case CO_HEADTAIL:
{
- con->headtail = icu->curval;
+ /* we need to check types of constraints that can get this here, as user
+ * may have created an IPO-curve for this from IPO-editor but for a constraint
+ * that cannot support this
+ */
+ switch (con->type) {
+ /* supported constraints go here... */
+ case CONSTRAINT_TYPE_LOCLIKE:
+ case CONSTRAINT_TYPE_TRACKTO:
+ case CONSTRAINT_TYPE_MINMAX:
+ case CONSTRAINT_TYPE_STRETCHTO:
+ case CONSTRAINT_TYPE_DISTLIMIT:
+ con->headtail = icu->curval;
+ break;
+
+ default:
+ /* not supported */
+ break;
+ }
}
break;
}
@@ -221,55 +241,7 @@ void do_constraint_channels (ListBase *conbase, ListBase *chanbase, float ctime,
/* Find the first available, non-duplicate name for a given constraint */
void unique_constraint_name (bConstraint *con, ListBase *list)
{
- bConstraint *curcon;
- char tempname[64];
- int number = 1, exists = 0;
- char *dot;
-
- /* See if we are given an empty string */
- if (con->name[0] == '\0') {
- /* give it default name first */
- strcpy(con->name, "Const");
- }
-
- /* See if we even need to do this */
- if (list == NULL)
- return;
-
- for (curcon = list->first; curcon; curcon=curcon->next) {
- if (curcon != con) {
- if (!strcmp(curcon->name, con->name)) {
- exists = 1;
- break;
- }
- }
- }
-
- if (exists == 0)
- return;
-
- /* Strip off the suffix */
- dot = strchr(con->name, '.');
- if (dot)
- *dot=0;
-
- for (number = 1; number <= 999; number++) {
- sprintf(tempname, "%s.%03d", con->name, number);
-
- exists = 0;
- for (curcon=list->first; curcon; curcon=curcon->next) {
- if (con != curcon) {
- if (strcmp(curcon->name, tempname)==0) {
- exists = 1;
- break;
- }
- }
- }
- if (exists == 0) {
- strcpy(con->name, tempname);
- return;
- }
- }
+ BLI_uniquename(list, con, "Const", offsetof(bConstraint, name), 32);
}
/* ----------------- Evaluation Loop Preparation --------------- */
@@ -337,7 +309,7 @@ void constraints_clear_evalob (bConstraintOb *cob)
/* calculate delta of constraints evaluation */
Mat4Invert(imat, cob->startmat);
- Mat4MulMat4(delta, cob->matrix, imat);
+ Mat4MulMat4(delta, imat, cob->matrix);
/* copy matrices back to source */
switch (cob->type) {
@@ -395,19 +367,12 @@ void constraint_mat_convertspace (Object *ob, bPoseChannel *pchan, float mat[][4
case CONSTRAINT_SPACE_WORLD: /* ---------- FROM WORLDSPACE ---------- */
{
/* world to pose */
- if (to==CONSTRAINT_SPACE_POSE || to==CONSTRAINT_SPACE_LOCAL || to==CONSTRAINT_SPACE_PARLOCAL) {
- Mat4Invert(imat, ob->obmat);
- Mat4CpyMat4(tempmat, mat);
- Mat4MulMat4(mat, tempmat, imat);
- }
+ Mat4Invert(imat, ob->obmat);
+ Mat4CpyMat4(tempmat, mat);
+ Mat4MulMat4(mat, tempmat, imat);
- /* pose to local */
- if (to == CONSTRAINT_SPACE_LOCAL) {
- /* call self with slightly different values */
- constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to);
- }
- /* pose to local + parent */
- else if (to == CONSTRAINT_SPACE_PARLOCAL) {
+ /* use pose-space as stepping stone for other spaces... */
+ if (ELEM(to, CONSTRAINT_SPACE_LOCAL, CONSTRAINT_SPACE_PARLOCAL)) {
/* call self with slightly different values */
constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to);
}
@@ -473,69 +438,66 @@ void constraint_mat_convertspace (Object *ob, bPoseChannel *pchan, float mat[][4
break;
case CONSTRAINT_SPACE_LOCAL: /* ------------ FROM LOCALSPACE --------- */
{
- /* local to pose */
- if (to==CONSTRAINT_SPACE_POSE || to==CONSTRAINT_SPACE_WORLD) {
- /* do inverse procedure that was done for pose to local */
- if (pchan->bone) {
- /* we need the posespace_matrix = local_matrix + (parent_posespace_matrix + restpos) */
- if (pchan->parent) {
- float offs_bone[4][4];
-
- /* construct offs_bone the same way it is done in armature.c */
- Mat4CpyMat3(offs_bone, pchan->bone->bone_mat);
- VECCOPY(offs_bone[3], pchan->bone->head);
- offs_bone[3][1]+= pchan->bone->parent->length;
+ /* local to pose - do inverse procedure that was done for pose to local */
+ if (pchan->bone) {
+ /* we need the posespace_matrix = local_matrix + (parent_posespace_matrix + restpos) */
+ if (pchan->parent) {
+ float offs_bone[4][4];
+
+ /* construct offs_bone the same way it is done in armature.c */
+ Mat4CpyMat3(offs_bone, pchan->bone->bone_mat);
+ VECCOPY(offs_bone[3], pchan->bone->head);
+ offs_bone[3][1]+= pchan->bone->parent->length;
+
+ if (pchan->bone->flag & BONE_HINGE) {
+ /* pose_mat = par_pose-space_location * chan_mat */
+ float tmat[4][4];
- if (pchan->bone->flag & BONE_HINGE) {
- /* pose_mat = par_pose-space_location * chan_mat */
- float tmat[4][4];
-
- /* the rotation of the parent restposition */
- Mat4CpyMat4(tmat, pchan->bone->parent->arm_mat);
-
- /* the location of actual parent transform */
- VECCOPY(tmat[3], offs_bone[3]);
- offs_bone[3][0]= offs_bone[3][1]= offs_bone[3][2]= 0.0f;
- Mat4MulVecfl(pchan->parent->pose_mat, tmat[3]);
-
- Mat4MulMat4(diff_mat, offs_bone, tmat);
- Mat4CpyMat4(tempmat, mat);
- Mat4MulMat4(mat, tempmat, diff_mat);
- }
- else {
- /* pose_mat = par_pose_mat * bone_mat * chan_mat */
- Mat4MulMat4(diff_mat, offs_bone, pchan->parent->pose_mat);
- Mat4CpyMat4(tempmat, mat);
- Mat4MulMat4(mat, tempmat, diff_mat);
- }
+ /* the rotation of the parent restposition */
+ Mat4CpyMat4(tmat, pchan->bone->parent->arm_mat);
+
+ /* the location of actual parent transform */
+ VECCOPY(tmat[3], offs_bone[3]);
+ offs_bone[3][0]= offs_bone[3][1]= offs_bone[3][2]= 0.0f;
+ Mat4MulVecfl(pchan->parent->pose_mat, tmat[3]);
+
+ Mat4MulMat4(diff_mat, offs_bone, tmat);
+ Mat4CpyMat4(tempmat, mat);
+ Mat4MulMat4(mat, tempmat, diff_mat);
}
else {
- Mat4CpyMat4(diff_mat, pchan->bone->arm_mat);
-
+ /* pose_mat = par_pose_mat * bone_mat * chan_mat */
+ Mat4MulMat4(diff_mat, offs_bone, pchan->parent->pose_mat);
Mat4CpyMat4(tempmat, mat);
Mat4MulMat4(mat, tempmat, diff_mat);
}
}
+ else {
+ Mat4CpyMat4(diff_mat, pchan->bone->arm_mat);
+
+ Mat4CpyMat4(tempmat, mat);
+ Mat4MulMat4(mat, tempmat, diff_mat);
+ }
}
- /* local to world */
- if (to == CONSTRAINT_SPACE_WORLD) {
+
+ /* use pose-space as stepping stone for other spaces */
+ if (ELEM(to, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_PARLOCAL)) {
/* call self with slightly different values */
constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to);
- }
+ }
}
break;
case CONSTRAINT_SPACE_PARLOCAL: /* -------------- FROM LOCAL WITH PARENT ---------- */
{
- /* local to pose */
- if (to==CONSTRAINT_SPACE_POSE || to==CONSTRAINT_SPACE_WORLD) {
- if (pchan->bone) {
- Mat4CpyMat4(diff_mat, pchan->bone->arm_mat);
- Mat4CpyMat4(tempmat, mat);
- Mat4MulMat4(mat, diff_mat, tempmat);
- }
+ /* local + parent to pose */
+ if (pchan->bone) {
+ Mat4CpyMat4(diff_mat, pchan->bone->arm_mat);
+ Mat4CpyMat4(tempmat, mat);
+ Mat4MulMat4(mat, diff_mat, tempmat);
}
- /* local to world */
- if (to == CONSTRAINT_SPACE_WORLD) {
+
+ /* use pose-space as stepping stone for other spaces */
+ if (ELEM(to, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_LOCAL)) {
/* call self with slightly different values */
constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to);
}
@@ -586,8 +548,8 @@ static void contarget_get_mesh_mat (Object *ob, char *substring, float mat[][4])
if (dgroup < 0) return;
/* get DerivedMesh */
- if (G.obedit && G.editMesh) {
- /* we are in editmode, so get a special derived mesh */
+ if ((G.obedit == ob) && (G.editMesh)) {
+ /* target is in editmode, so get a special derived mesh */
dm = CDDM_from_editmesh(G.editMesh, ob->data);
}
else {
@@ -880,7 +842,7 @@ static void default_get_tarmat (bConstraint *con, bConstraintOb *cob, bConstrain
if (nocopy == 0) { \
datatar= ct->tar; \
strcpy(datasubtarget, ct->subtarget); \
- con->tarspace= ct->space; \
+ con->tarspace= (char)ct->space; \
} \
\
BLI_freelinkN(list, ct); \
@@ -900,7 +862,7 @@ static void default_get_tarmat (bConstraint *con, bConstraintOb *cob, bConstrain
bConstraintTarget *ctn = ct->next; \
if (nocopy == 0) { \
datatar= ct->tar; \
- con->tarspace= ct->space; \
+ con->tarspace= (char)ct->space; \
} \
\
BLI_freelinkN(list, ct); \
@@ -920,7 +882,7 @@ static void childof_new_data (void *cdata)
Mat4One(data->invmat);
}
-static void childof_get_tars (bConstraint *con, ListBase *list)
+static int childof_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bChildOfConstraint *data= con->data;
@@ -928,7 +890,11 @@ static void childof_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void childof_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -1018,7 +984,7 @@ static void trackto_new_data (void *cdata)
data->reserved2 = UP_Z;
}
-static void trackto_get_tars (bConstraint *con, ListBase *list)
+static int trackto_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bTrackToConstraint *data= con->data;
@@ -1026,7 +992,11 @@ static void trackto_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void trackto_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -1124,9 +1094,9 @@ static void vectomat (float *vec, float *target_up, short axis, short upflag, sh
/* identity matrix - don't do anything if the two axes are the same */
else {
m[0][0]= m[1][1]= m[2][2]= 1.0;
- m[0][1]= m[0][2]= m[0][3]= 0.0;
- m[1][0]= m[1][2]= m[1][3]= 0.0;
- m[2][0]= m[2][1]= m[2][3]= 0.0;
+ m[0][1]= m[0][2]= 0.0;
+ m[1][0]= m[1][2]= 0.0;
+ m[2][0]= m[2][1]= 0.0;
}
}
@@ -1195,16 +1165,20 @@ static void kinematic_new_data (void *cdata)
data->flag= CONSTRAINT_IK_TIP|CONSTRAINT_IK_STRETCH|CONSTRAINT_IK_POS;
}
-static void kinematic_get_tars (bConstraint *con, ListBase *list)
+static int kinematic_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bKinematicConstraint *data= con->data;
bConstraintTarget *ct;
- /* standard target-getting macro for single-target constraints */
+ /* standard target-getting macro for single-target constraints is used twice here */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
SINGLETARGET_GET_TARS(con, data->poletar, data->polesubtarget, ct, list)
+
+ return 2;
}
+
+ return 0;
}
static void kinematic_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -1273,7 +1247,7 @@ static void followpath_new_data (void *cdata)
data->followflag = 0;
}
-static void followpath_get_tars (bConstraint *con, ListBase *list)
+static int followpath_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bFollowPathConstraint *data= con->data;
@@ -1281,7 +1255,11 @@ static void followpath_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints without subtargets */
SINGLETARGETNS_GET_TARS(con, data->tar, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void followpath_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -1301,7 +1279,7 @@ static void followpath_get_tarmat (bConstraint *con, bConstraintOb *cob, bConstr
if (VALID_CONS_TARGET(ct)) {
Curve *cu= ct->tar->data;
- float q[4], vec[4], dir[3], *quat, x1;
+ float q[4], vec[4], dir[3], quat[4], x1;
float totmat[4][4];
float curvetime;
@@ -1326,7 +1304,7 @@ static void followpath_get_tarmat (bConstraint *con, bConstraintOb *cob, bConstr
if ( where_on_path(ct->tar, curvetime, vec, dir) ) {
if (data->followflag) {
- quat= vectoquat(dir, (short) data->trackflag, (short) data->upflag);
+ vectoquat(dir, (short) data->trackflag, (short) data->upflag, quat);
Normalize(dir);
q[0]= (float)cos(0.5*vec[3]);
@@ -1456,9 +1434,9 @@ static void rotlimit_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *t
Mat4ToEul(cob->matrix, eul);
/* eulers: radians to degrees! */
- eul[0] = (eul[0] / M_PI * 180);
- eul[1] = (eul[1] / M_PI * 180);
- eul[2] = (eul[2] / M_PI * 180);
+ eul[0] = (float)(eul[0] / M_PI * 180);
+ eul[1] = (float)(eul[1] / M_PI * 180);
+ eul[2] = (float)(eul[2] / M_PI * 180);
/* limiting of euler values... */
if (data->flag & LIMIT_XROT) {
@@ -1484,9 +1462,9 @@ static void rotlimit_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *t
}
/* eulers: degrees to radians ! */
- eul[0] = (eul[0] / 180 * M_PI);
- eul[1] = (eul[1] / 180 * M_PI);
- eul[2] = (eul[2] / 180 * M_PI);
+ eul[0] = (float)(eul[0] / 180 * M_PI);
+ eul[1] = (float)(eul[1] / 180 * M_PI);
+ eul[2] = (float)(eul[2] / 180 * M_PI);
LocEulSizeToMat4(cob->matrix, loc, eul, size);
}
@@ -1574,7 +1552,7 @@ static void loclike_new_data (void *cdata)
data->flag = LOCLIKE_X|LOCLIKE_Y|LOCLIKE_Z;
}
-static void loclike_get_tars (bConstraint *con, ListBase *list)
+static int loclike_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bLocateLikeConstraint *data= con->data;
@@ -1582,7 +1560,11 @@ static void loclike_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void loclike_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -1652,7 +1634,7 @@ static void rotlike_new_data (void *cdata)
data->flag = ROTLIKE_X|ROTLIKE_Y|ROTLIKE_Z;
}
-static void rotlike_get_tars (bConstraint *con, ListBase *list)
+static int rotlike_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bRotateLikeConstraint *data= con->data;
@@ -1660,7 +1642,11 @@ static void rotlike_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void rotlike_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -1749,7 +1735,7 @@ static void sizelike_new_data (void *cdata)
data->flag = SIZELIKE_X|SIZELIKE_Y|SIZELIKE_Z;
}
-static void sizelike_get_tars (bConstraint *con, ListBase *list)
+static int sizelike_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bSizeLikeConstraint *data= con->data;
@@ -1757,7 +1743,11 @@ static void sizelike_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void sizelike_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -1824,6 +1814,7 @@ static bConstraintTypeInfo CTI_SIZELIKE = {
sizelike_evaluate /* evaluate */
};
+
/* ----------- Python Constraint -------------- */
static void pycon_free (bConstraint *con)
@@ -1863,14 +1854,18 @@ static void pycon_new_data (void *cdata)
data->prop->type = IDP_GROUP;
}
-static void pycon_get_tars (bConstraint *con, ListBase *list)
+static int pycon_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bPythonConstraint *data= con->data;
list->first = data->targets.first;
list->last = data->targets.last;
+
+ return data->tarnum;
}
+
+ return 0;
}
/* Whether this approach is maintained remains to be seen (aligorith) */
@@ -1892,7 +1887,12 @@ static void pycon_get_tarmat (bConstraint *con, bConstraintOb *cob, bConstraintT
* this matrix if it needs to do so
*/
constraint_target_to_mat4(ct->tar, ct->subtarget, ct->matrix, CONSTRAINT_SPACE_WORLD, ct->space, con->headtail);
- BPY_pyconstraint_target(data, ct);
+
+ /* only execute target calculation if allowed */
+#ifndef DISABLE_PYTHON
+ if (G.f & G_DOSCRIPTLINKS)
+ BPY_pyconstraint_target(data, ct);
+#endif
}
else if (ct)
Mat4One(ct->matrix);
@@ -1900,8 +1900,14 @@ static void pycon_get_tarmat (bConstraint *con, bConstraintOb *cob, bConstraintT
static void pycon_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
{
+#ifdef DISABLE_PYTHON
+ return;
+#else
bPythonConstraint *data= con->data;
+ /* only evaluate in python if we're allowed to do so */
+ if ((G.f & G_DOSCRIPTLINKS)==0) return;
+
/* currently removed, until I this can be re-implemented for multiple targets */
#if 0
/* Firstly, run the 'driver' function which has direct access to the objects involved
@@ -1913,6 +1919,7 @@ static void pycon_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targ
/* Now, run the actual 'constraint' function, which should only access the matrices */
BPY_pyconstraint_eval(data, cob, targets);
+#endif /* DISABLE_PYTHON */
}
static bConstraintTypeInfo CTI_PYTHON = {
@@ -1946,7 +1953,7 @@ static void actcon_new_data (void *cdata)
data->type = 20;
}
-static void actcon_get_tars (bConstraint *con, ListBase *list)
+static int actcon_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bActionConstraint *data= con->data;
@@ -1954,7 +1961,11 @@ static void actcon_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void actcon_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -2031,8 +2042,7 @@ static void actcon_get_tarmat (bConstraint *con, bConstraintOb *cob, bConstraint
Mat4CpyMat4(ct->matrix, tchan->chan_mat);
/* Clean up */
- free_pose_channels(pose);
- MEM_freeN(pose);
+ free_pose(pose);
}
else if (cob->type == CONSTRAINT_OBTYPE_OBJECT) {
/* evaluate using workob */
@@ -2086,7 +2096,7 @@ static void locktrack_new_data (void *cdata)
data->lockflag = LOCK_Z;
}
-static void locktrack_get_tars (bConstraint *con, ListBase *list)
+static int locktrack_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bLockTrackConstraint *data= con->data;
@@ -2094,7 +2104,11 @@ static void locktrack_get_tars (bConstraint *con, ListBase *list)
/* the following macro is used for all standard single-target constraints */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void locktrack_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -2425,6 +2439,122 @@ static bConstraintTypeInfo CTI_LOCKTRACK = {
locktrack_evaluate /* evaluate */
};
+/* ---------- Limit Distance Constraint ----------- */
+
+static void distlimit_new_data (void *cdata)
+{
+ bDistLimitConstraint *data= (bDistLimitConstraint *)cdata;
+
+ data->dist= 0.0;
+}
+
+static int distlimit_get_tars (bConstraint *con, ListBase *list)
+{
+ if (con && list) {
+ bDistLimitConstraint *data= con->data;
+ bConstraintTarget *ct;
+
+ /* standard target-getting macro for single-target constraints */
+ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
+ }
+
+ return 0;
+}
+
+static void distlimit_flush_tars (bConstraint *con, ListBase *list, short nocopy)
+{
+ if (con && list) {
+ bDistLimitConstraint *data= con->data;
+ bConstraintTarget *ct= list->first;
+
+ /* the following macro is used for all standard single-target constraints */
+ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
+ }
+}
+
+static void distlimit_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
+{
+ bDistLimitConstraint *data= con->data;
+ bConstraintTarget *ct= targets->first;
+
+ /* only evaluate if there is a target */
+ if (VALID_CONS_TARGET(ct)) {
+ float dvec[3], dist=0.0f, sfac=1.0f;
+ short clamp_surf= 0;
+
+ /* calculate our current distance from the target */
+ dist= VecLenf(cob->matrix[3], ct->matrix[3]);
+
+ /* set distance (flag is only set when user demands it) */
+ if (data->dist == 0)
+ data->dist= dist;
+
+ /* check if we're which way to clamp from, and calculate interpolation factor (if needed) */
+ if (data->mode == LIMITDIST_OUTSIDE) {
+ /* if inside, then move to surface */
+ if (dist <= data->dist) {
+ clamp_surf= 1;
+ sfac= data->dist / dist;
+ }
+ /* if soft-distance is enabled, start fading once owner is dist+softdist from the target */
+ else if (data->flag & LIMITDIST_USESOFT) {
+ if (dist <= (data->dist + data->soft)) {
+
+ }
+ }
+ }
+ else if (data->mode == LIMITDIST_INSIDE) {
+ /* if outside, then move to surface */
+ if (dist >= data->dist) {
+ clamp_surf= 1;
+ sfac= data->dist / dist;
+ }
+ /* if soft-distance is enabled, start fading once owner is dist-soft from the target */
+ else if (data->flag & LIMITDIST_USESOFT) {
+ // FIXME: there's a problem with "jumping" when this kicks in
+ if (dist >= (data->dist - data->soft)) {
+ sfac = (float)( data->soft*(1.0 - exp(-(dist - data->dist)/data->soft)) + data->dist );
+ sfac /= dist;
+
+ clamp_surf= 1;
+ }
+ }
+ }
+ else {
+ if (IS_EQ(dist, data->dist)==0) {
+ clamp_surf= 1;
+ sfac= data->dist / dist;
+ }
+ }
+
+ /* clamp to 'surface' (i.e. move owner so that dist == data->dist) */
+ if (clamp_surf) {
+ /* simply interpolate along line formed by target -> owner */
+ VecLerpf(dvec, ct->matrix[3], cob->matrix[3], sfac);
+
+ /* copy new vector onto owner */
+ VECCOPY(cob->matrix[3], dvec);
+ }
+ }
+}
+
+static bConstraintTypeInfo CTI_DISTLIMIT = {
+ CONSTRAINT_TYPE_DISTLIMIT, /* type */
+ sizeof(bDistLimitConstraint), /* size */
+ "Limit Distance", /* name */
+ "bDistLimitConstraint", /* struct name */
+ NULL, /* free data */
+ NULL, /* relink data */
+ NULL, /* copy data */
+ distlimit_new_data, /* new data */
+ distlimit_get_tars, /* get constraint targets */
+ distlimit_flush_tars, /* flush constraint targets */
+ default_get_tarmat, /* get a target matrix */
+ distlimit_evaluate /* evaluate */
+};
+
/* ---------- Stretch To ------------ */
static void stretchto_new_data (void *cdata)
@@ -2437,7 +2567,7 @@ static void stretchto_new_data (void *cdata)
data->bulge = 1.0;
}
-static void stretchto_get_tars (bConstraint *con, ListBase *list)
+static int stretchto_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bStretchToConstraint *data= con->data;
@@ -2445,7 +2575,11 @@ static void stretchto_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void stretchto_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -2613,7 +2747,7 @@ static void minmax_new_data (void *cdata)
data->flag = 0;
}
-static void minmax_get_tars (bConstraint *con, ListBase *list)
+static int minmax_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bMinMaxConstraint *data= con->data;
@@ -2621,7 +2755,11 @@ static void minmax_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void minmax_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -2743,7 +2881,7 @@ static void rbj_new_data (void *cdata)
data->type=1;
}
-static void rbj_get_tars (bConstraint *con, ListBase *list)
+static int rbj_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bRigidBodyJointConstraint *data= con->data;
@@ -2751,7 +2889,11 @@ static void rbj_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints without subtargets */
SINGLETARGETNS_GET_TARS(con, data->tar, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void rbj_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -2782,7 +2924,7 @@ static bConstraintTypeInfo CTI_RIGIDBODYJOINT = {
/* -------- Clamp To ---------- */
-static void clampto_get_tars (bConstraint *con, ListBase *list)
+static int clampto_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bClampToConstraint *data= con->data;
@@ -2790,7 +2932,11 @@ static void clampto_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints without subtargets */
SINGLETARGETNS_GET_TARS(con, data->tar, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void clampto_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -2955,7 +3101,7 @@ static void transform_new_data (void *cdata)
data->map[2]= 2;
}
-static void transform_get_tars (bConstraint *con, ListBase *list)
+static int transform_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bTransformConstraint *data= con->data;
@@ -2963,7 +3109,11 @@ static void transform_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void transform_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -2990,11 +3140,13 @@ static void transform_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *
/* obtain target effect */
switch (data->from) {
- case 2: /* scale */
+ case 2: /* scale */
Mat4ToSize(ct->matrix, dvec);
break;
- case 1: /* rotation */
+ case 1: /* rotation (convert to degrees first) */
Mat4ToEul(ct->matrix, dvec);
+ for (i=0; i<3; i++)
+ dvec[i] = (float)(dvec[i] / M_PI * 180);
break;
default: /* location */
VecCopyf(dvec, ct->matrix[3]);
@@ -3004,7 +3156,7 @@ static void transform_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *
/* extract components of owner's matrix */
VECCOPY(loc, cob->matrix[3]);
Mat4ToEul(cob->matrix, eul);
- Mat4ToSize(cob->matrix, size);
+ Mat4ToSize(cob->matrix, size);
/* determine where in range current transforms lie */
if (data->expo) {
@@ -3026,17 +3178,6 @@ static void transform_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *
}
}
- /* convert radian<->degree */
- if (data->from==1 && data->to==0) {
- /* from radians to degrees */
- for (i=0; i<3; i++)
- sval[i] = sval[i] / M_PI * 180;
- }
- else if (data->from==0 && data->to==1) {
- /* from degrees to radians */
- for (i=0; i<3; i++)
- sval[i] = sval[i] / 180 * M_PI;
- }
/* apply transforms */
switch (data->to) {
@@ -3048,11 +3189,14 @@ static void transform_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *
for (i=0; i<3; i++) {
float tmin, tmax;
- /* convert destination min/max ranges from degrees to radians */
- tmin= data->to_min[i] / M_PI * 180;
- tmax= data->to_max[i] / M_PI * 180;
+ tmin= data->to_min[i];
+ tmax= data->to_max[i];
+ /* all values here should be in degrees */
eul[i]= tmin + (sval[data->map[i]] * (tmax - tmin));
+
+ /* now convert final value back to radians */
+ eul[i] = (float)(eul[i] / 180 * M_PI);
}
break;
default: /* location */
@@ -3110,12 +3254,12 @@ static void constraints_init_typeinfo () {
constraintsTypeInfo[11]= &CTI_PYTHON; /* Python/Script Constraint */
constraintsTypeInfo[12]= &CTI_ACTION; /* Action Constraint */
constraintsTypeInfo[13]= &CTI_LOCKTRACK; /* Locked-Track Constraint */
- constraintsTypeInfo[14]= NULL; /* 'Distance Limit' Constraint */
+ constraintsTypeInfo[14]= &CTI_DISTLIMIT; /* Limit Distance Constraint */
constraintsTypeInfo[15]= &CTI_STRETCHTO; /* StretchTo Constaint */
constraintsTypeInfo[16]= &CTI_MINMAX; /* Floor Constraint */
constraintsTypeInfo[17]= &CTI_RIGIDBODYJOINT; /* RigidBody Constraint */
constraintsTypeInfo[18]= &CTI_CLAMPTO; /* ClampTo Constraint */
- constraintsTypeInfo[19]= &CTI_TRANSFORM; /* Transformation Constraint */
+ constraintsTypeInfo[19]= &CTI_TRANSFORM; /* Transformation Constraint */
}
/* This function should be used for getting the appropriate type-info when only
@@ -3241,6 +3385,46 @@ void copy_constraints (ListBase *dst, ListBase *src)
}
}
+/* -------- Constraints and Proxies ------- */
+
+/* Rescue all constraints tagged as being CONSTRAINT_PROXY_LOCAL (i.e. added to bone that's proxy-synced in this file) */
+void extract_proxylocal_constraints (ListBase *dst, ListBase *src)
+{
+ bConstraint *con, *next;
+
+ /* for each tagged constraint, remove from src and move to dst */
+ for (con= src->first; con; con= next) {
+ next= con->next;
+
+ /* check if tagged */
+ if (con->flag & CONSTRAINT_PROXY_LOCAL) {
+ BLI_remlink(src, con);
+ BLI_addtail(dst, con);
+ }
+ }
+}
+
+/* Returns if the owner of the constraint is proxy-protected */
+short proxylocked_constraints_owner (Object *ob, bPoseChannel *pchan)
+{
+ /* Currently, constraints can only be on object or bone level */
+ if (ob && ob->proxy) {
+ if (ob->pose && pchan) {
+ bArmature *arm= ob->data;
+
+ /* On bone-level, check if bone is on proxy-protected layer */
+ if ((pchan->bone) && (pchan->bone->layer & arm->layer_protected))
+ return 1;
+ }
+ else {
+ /* FIXME: constraints on object-level are not handled well yet */
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
/* -------- Target-Matrix Stuff ------- */
/* This function is a relic from the prior implementations of the constraints system, when all
diff --git a/source/blender/blenkernel/intern/curve.c b/source/blender/blenkernel/intern/curve.c
index 90e65b629b4..1a671dfe771 100644
--- a/source/blender/blenkernel/intern/curve.c
+++ b/source/blender/blenkernel/intern/curve.c
@@ -247,7 +247,7 @@ void tex_space_curve(Curve *cu)
{
DispList *dl;
BoundBox *bb;
- float *data, min[3], max[3], loc[3], size[3];
+ float *fp, min[3], max[3], loc[3], size[3];
int tot, doit= 0;
if(cu->bb==NULL) cu->bb= MEM_callocN(sizeof(BoundBox), "boundbox");
@@ -262,10 +262,10 @@ void tex_space_curve(Curve *cu)
else tot= dl->nr*dl->parts;
if(tot) doit= 1;
- data= dl->verts;
+ fp= dl->verts;
while(tot--) {
- DO_MINMAX(data, min, max);
- data+= 3;
+ DO_MINMAX(fp, min, max);
+ fp += 3;
}
dl= dl->next;
}
@@ -348,9 +348,9 @@ void freeNurb(Nurb *nu)
if(nu->bp) MEM_freeN(nu->bp);
nu->bp= 0;
if(nu->knotsu) MEM_freeN(nu->knotsu);
- nu->knotsu= 0;
+ nu->knotsu= NULL;
if(nu->knotsv) MEM_freeN(nu->knotsv);
- nu->knotsv= 0;
+ nu->knotsv= NULL;
/* if(nu->trim.first) freeNurblist(&(nu->trim)); */
MEM_freeN(nu);
@@ -393,7 +393,7 @@ Nurb *duplicateNurb(Nurb *nu)
(BPoint*)MEM_mallocN((len)* sizeof(BPoint),"duplicateNurb3");
memcpy(newnu->bp, nu->bp, len*sizeof(BPoint));
- newnu->knotsu=newnu->knotsv= 0;
+ newnu->knotsu= newnu->knotsv= NULL;
if(nu->knotsu) {
len= KNOTSU(nu);
@@ -506,6 +506,7 @@ static void calcknots(float *knots, short aantal, short order, short type)
}
}
else if(type==2) {
+ /* Warning, the order MUST be 2 or 4, if this is not enforced, the displist will be corrupt */
if(order==4) {
k= 0.34;
for(a=0;a<t;a++) {
@@ -520,6 +521,9 @@ static void calcknots(float *knots, short aantal, short order, short type)
knots[a]= (float)floor(k);
}
}
+ else {
+ printf("bez nurb curve order is not 3 or 4, should never happen\n");
+ }
}
}
@@ -529,7 +533,8 @@ static void makecyclicknots(float *knots, short pnts, short order)
int a, b, order2, c;
if(knots==0) return;
- order2=order-1;
+
+ order2=order-1;
/* do first long rows (order -1), remove identical knots at endpoints */
if(order>2) {
@@ -549,26 +554,35 @@ static void makecyclicknots(float *knots, short pnts, short order)
}
-void makeknots(Nurb *nu, short uv, short type) /* 0: uniform, 1: endpoints, 2: bezier */
+/* type - 0: uniform, 1: endpoints, 2: bezier, note, cyclic nurbs are always uniform */
+void makeknots(Nurb *nu, short uv, short type)
{
if( (nu->type & 7)==CU_NURBS ) {
- if(uv & 1) {
+ if(uv == 1) {
if(nu->knotsu) MEM_freeN(nu->knotsu);
- if(nu->pntsu>1) {
+ if(check_valid_nurb_u(nu)) {
nu->knotsu= MEM_callocN(4+sizeof(float)*KNOTSU(nu), "makeknots");
- calcknots(nu->knotsu, nu->pntsu, nu->orderu, type);
- if(nu->flagu & 1) makecyclicknots(nu->knotsu, nu->pntsu, nu->orderu);
+ if(nu->flagu & CU_CYCLIC) {
+ calcknots(nu->knotsu, nu->pntsu, nu->orderu, 0); /* cyclic should be uniform */
+ makecyclicknots(nu->knotsu, nu->pntsu, nu->orderu);
+ } else {
+ calcknots(nu->knotsu, nu->pntsu, nu->orderu, type);
+ }
}
- else nu->knotsu= 0;
- }
- if(uv & 2) {
+ else nu->knotsu= NULL;
+
+ } else if(uv == 2) {
if(nu->knotsv) MEM_freeN(nu->knotsv);
- if(nu->pntsv>1) {
+ if(check_valid_nurb_v(nu)) {
nu->knotsv= MEM_callocN(4+sizeof(float)*KNOTSV(nu), "makeknots");
- calcknots(nu->knotsv, nu->pntsv, nu->orderv, type);
- if(nu->flagv & 1) makecyclicknots(nu->knotsv, nu->pntsv, nu->orderv);
+ if(nu->flagv & CU_CYCLIC) {
+ calcknots(nu->knotsv, nu->pntsv, nu->orderv, 0); /* cyclic should be uniform */
+ makecyclicknots(nu->knotsv, nu->pntsv, nu->orderv);
+ } else {
+ calcknots(nu->knotsv, nu->pntsv, nu->orderv, type);
+ }
}
- else nu->knotsv= 0;
+ else nu->knotsv= NULL;
}
}
}
@@ -636,31 +650,31 @@ static void basisNurb(float t, short order, short pnts, float *knots, float *bas
}
-void makeNurbfaces(Nurb *nu, float *data, int rowstride)
-/* data has to be 3*4*resolu*resolv in size, and zero-ed */
+void makeNurbfaces(Nurb *nu, float *coord_array, int rowstride)
+/* coord_array has to be 3*4*resolu*resolv in size, and zero-ed */
{
BPoint *bp;
float *basisu, *basis, *basisv, *sum, *fp, *in;
float u, v, ustart, uend, ustep, vstart, vend, vstep, sumdiv;
int i, j, iofs, jofs, cycl, len, resolu, resolv;
int istart, iend, jsta, jen, *jstart, *jend, ratcomp;
-
- if(nu->knotsu==0 || nu->knotsv==0) return;
+
+ int totu = nu->pntsu*nu->resolu, totv = nu->pntsv*nu->resolv;
+
+ if(nu->knotsu==NULL || nu->knotsv==NULL) return;
if(nu->orderu>nu->pntsu) return;
if(nu->orderv>nu->pntsv) return;
- if(data==0) return;
-
+ if(coord_array==NULL) return;
+
/* allocate and initialize */
- len= nu->pntsu*nu->pntsv;
+ len = totu * totv;
if(len==0) return;
sum= (float *)MEM_callocN(sizeof(float)*len, "makeNurbfaces1");
-
- resolu= nu->resolu;
- resolv= nu->resolv;
- len= resolu*resolv;
+
+ len= totu*totv;
if(len==0) {
MEM_freeN(sum);
return;
@@ -676,46 +690,50 @@ void makeNurbfaces(Nurb *nu, float *data, int rowstride)
}
bp++;
}
-
+
fp= nu->knotsu;
ustart= fp[nu->orderu-1];
- if(nu->flagu & 1) uend= fp[nu->pntsu+nu->orderu-1];
+ if(nu->flagu & CU_CYCLIC) uend= fp[nu->pntsu+nu->orderu-1];
else uend= fp[nu->pntsu];
- ustep= (uend-ustart)/(resolu-1+(nu->flagu & 1));
+ ustep= (uend-ustart)/((nu->flagu & CU_CYCLIC) ? totu : totu - 1);
+
basisu= (float *)MEM_mallocN(sizeof(float)*KNOTSU(nu), "makeNurbfaces3");
fp= nu->knotsv;
vstart= fp[nu->orderv-1];
- if(nu->flagv & 1) vend= fp[nu->pntsv+nu->orderv-1];
+ if(nu->flagv & CU_CYCLIC) vend= fp[nu->pntsv+nu->orderv-1];
else vend= fp[nu->pntsv];
- vstep= (vend-vstart)/(resolv-1+(nu->flagv & 1));
+ vstep= (vend-vstart)/((nu->flagv & CU_CYCLIC) ? totv : totv - 1);
+
len= KNOTSV(nu);
- basisv= (float *)MEM_mallocN(sizeof(float)*len*resolv, "makeNurbfaces3");
- jstart= (int *)MEM_mallocN(sizeof(float)*resolv, "makeNurbfaces4");
- jend= (int *)MEM_mallocN(sizeof(float)*resolv, "makeNurbfaces5");
+ basisv= (float *)MEM_mallocN(sizeof(float)*len*totv, "makeNurbfaces3");
+ jstart= (int *)MEM_mallocN(sizeof(float)*totv, "makeNurbfaces4");
+ jend= (int *)MEM_mallocN(sizeof(float)*totv, "makeNurbfaces5");
/* precalculation of basisv and jstart,jend */
- if(nu->flagv & 1) cycl= nu->orderv-1;
+ if(nu->flagv & CU_CYCLIC) cycl= nu->orderv-1;
else cycl= 0;
v= vstart;
basis= basisv;
+ resolv= totv;
while(resolv--) {
basisNurb(v, nu->orderv, (short)(nu->pntsv+cycl), nu->knotsv, basis, jstart+resolv, jend+resolv);
basis+= KNOTSV(nu);
v+= vstep;
}
- if(nu->flagu & 1) cycl= nu->orderu-1;
+ if(nu->flagu & CU_CYCLIC) cycl= nu->orderu-1;
else cycl= 0;
- in= data;
+ in= coord_array;
u= ustart;
+ resolu= totu;
while(resolu--) {
basisNurb(u, nu->orderu, (short)(nu->pntsu+cycl), nu->knotsu, basisu, &istart, &iend);
basis= basisv;
- resolv= nu->resolv;
+ resolv= totv;
while(resolv--) {
jsta= jstart[resolv];
@@ -784,7 +802,7 @@ void makeNurbfaces(Nurb *nu, float *data, int rowstride)
basis+= KNOTSV(nu);
}
u+= ustep;
- if (rowstride!=0) in = (float*) (((unsigned char*) in) + (rowstride - 3*nu->resolv*sizeof(*in)));
+ if (rowstride!=0) in = (float*) (((unsigned char*) in) + (rowstride - 3*totv*sizeof(*in)));
}
/* free */
@@ -795,24 +813,28 @@ void makeNurbfaces(Nurb *nu, float *data, int rowstride)
MEM_freeN(jend);
}
-void makeNurbcurve(Nurb *nu, float *data, int resolu, int dim)
-/* data has to be dim*4*pntsu*resolu in size and zero-ed */
+void makeNurbcurve(Nurb *nu, float *coord_array, float *tilt_array, float *radius_array, int resolu)
+/* coord_array has to be 3*4*pntsu*resolu in size and zero-ed
+ * tilt_array and radius_array will be written to if valid */
{
BPoint *bp;
float u, ustart, uend, ustep, sumdiv;
- float *basisu, *sum, *fp, *in;
+ float *basisu, *sum, *fp;
+ float *coord_fp= coord_array, *tilt_fp= tilt_array, *radius_fp= radius_array;
int i, len, istart, iend, cycl;
- if(nu->knotsu==0) return;
+ if(nu->knotsu==NULL) return;
if(nu->orderu>nu->pntsu) return;
- if(data==0) return;
+ if(coord_array==0) return;
/* allocate and initialize */
len= nu->pntsu;
if(len==0) return;
sum= (float *)MEM_callocN(sizeof(float)*len, "makeNurbcurve1");
-
- resolu*= nu->pntsu;
+
+ resolu= (resolu*SEGMENTSU(nu));
+ if((nu->flagu & CU_CYCLIC)==0) resolu++;
+
if(resolu==0) {
MEM_freeN(sum);
return;
@@ -820,15 +842,15 @@ void makeNurbcurve(Nurb *nu, float *data, int resolu, int dim)
fp= nu->knotsu;
ustart= fp[nu->orderu-1];
- if(nu->flagu & 1) uend= fp[nu->pntsu+nu->orderu-1];
+ if(nu->flagu & CU_CYCLIC) uend= fp[nu->pntsu+nu->orderu-1];
else uend= fp[nu->pntsu];
- ustep= (uend-ustart)/(resolu-1+(nu->flagu & 1));
+ ustep= (uend-ustart)/(resolu - ((nu->flagu & CU_CYCLIC) ? 0 : 1));
+
basisu= (float *)MEM_mallocN(sizeof(float)*KNOTSU(nu), "makeNurbcurve3");
- if(nu->flagu & 1) cycl= nu->orderu-1;
+ if(nu->flagu & CU_CYCLIC) cycl= nu->orderu-1;
else cycl= 0;
- in= data;
u= ustart;
while(resolu--) {
@@ -863,17 +885,24 @@ void makeNurbcurve(Nurb *nu, float *data, int resolu, int dim)
if(*fp!=0.0) {
- in[0]+= (*fp) * bp->vec[0];
- in[1]+= (*fp) * bp->vec[1];
- if(dim>=3) {
- in[2]+= (*fp) * bp->vec[2];
- if(dim==4) in[3]+= (*fp) * bp->alfa;
- }
+ coord_fp[0]+= (*fp) * bp->vec[0];
+ coord_fp[1]+= (*fp) * bp->vec[1];
+ coord_fp[2]+= (*fp) * bp->vec[2];
+
+ if (tilt_fp)
+ (*tilt_fp) += (*fp) * bp->alfa;
+
+ if (radius_fp)
+ (*radius_fp) += (*fp) * bp->radius;
+
}
}
- in+= dim;
-
+ coord_fp+= 3;
+
+ if (tilt_fp) tilt_fp++;
+ if (radius_fp) radius_fp++;
+
u+= ustep;
}
@@ -918,7 +947,7 @@ float *make_orco_surf(Object *ob)
Nurb *nu;
int a, b, tot=0;
int sizeu, sizev;
- float *data, *orco;
+ float *fp, *coord_array;
/* first calculate the size of the datablock */
nu= cu->nurb.first;
@@ -932,8 +961,8 @@ float *make_orco_surf(Object *ob)
See also convertblender.c: init_render_surf()
*/
- sizeu = nu->resolu;
- sizev = nu->resolv;
+ sizeu = nu->pntsu*nu->resolu;
+ sizev = nu->pntsv*nu->resolv;
if (nu->flagu & CU_CYCLIC) sizeu++;
if (nu->flagv & CU_CYCLIC) sizev++;
if(nu->pntsv>1) tot+= sizeu * sizev;
@@ -941,13 +970,13 @@ float *make_orco_surf(Object *ob)
nu= nu->next;
}
/* makeNurbfaces wants zeros */
- data= orco= MEM_callocN(3*sizeof(float)*tot, "make_orco");
+ fp= coord_array= MEM_callocN(3*sizeof(float)*tot, "make_orco");
nu= cu->nurb.first;
while(nu) {
if(nu->pntsv>1) {
- sizeu = nu->resolu;
- sizev = nu->resolv;
+ sizeu = nu->pntsu*nu->resolu;
+ sizev = nu->pntsv*nu->resolv;
if (nu->flagu & CU_CYCLIC) sizeu++;
if (nu->flagv & CU_CYCLIC) sizev++;
@@ -955,20 +984,20 @@ float *make_orco_surf(Object *ob)
for(b=0; b< sizeu; b++) {
for(a=0; a< sizev; a++) {
- if(sizev <2) data[0]= 0.0f;
- else data[0]= -1.0f + 2.0f*((float)a)/(sizev - 1);
+ if(sizev <2) fp[0]= 0.0f;
+ else fp[0]= -1.0f + 2.0f*((float)a)/(sizev - 1);
- if(sizeu <2) data[1]= 0.0f;
- else data[1]= -1.0f + 2.0f*((float)b)/(sizeu - 1);
+ if(sizeu <2) fp[1]= 0.0f;
+ else fp[1]= -1.0f + 2.0f*((float)b)/(sizeu - 1);
- data[2]= 0.0;
+ fp[2]= 0.0;
- data+= 3;
+ fp+= 3;
}
}
}
else {
- float *_tdata= MEM_callocN(nu->resolu*nu->resolv*3*sizeof(float), "temp data");
+ float *_tdata= MEM_callocN((nu->pntsu*nu->resolu) * (nu->pntsv*nu->resolv) *3*sizeof(float), "temp data");
float *tdata= _tdata;
makeNurbfaces(nu, tdata, 0);
@@ -983,12 +1012,12 @@ float *make_orco_surf(Object *ob)
if (a==sizev-1 && (nu->flagv & CU_CYCLIC))
use_a= 0;
- tdata = _tdata + 3 * (use_b * nu->resolv + use_a);
+ tdata = _tdata + 3 * (use_b * (nu->pntsv*nu->resolv) + use_a);
- data[0]= (tdata[0]-cu->loc[0])/cu->size[0];
- data[1]= (tdata[1]-cu->loc[1])/cu->size[1];
- data[2]= (tdata[2]-cu->loc[2])/cu->size[2];
- data+= 3;
+ fp[0]= (tdata[0]-cu->loc[0])/cu->size[0];
+ fp[1]= (tdata[1]-cu->loc[1])/cu->size[1];
+ fp[2]= (tdata[2]-cu->loc[2])/cu->size[2];
+ fp+= 3;
}
}
@@ -998,7 +1027,7 @@ float *make_orco_surf(Object *ob)
nu= nu->next;
}
- return orco;
+ return coord_array;
}
@@ -1010,7 +1039,7 @@ float *make_orco_curve(Object *ob)
Curve *cu = ob->data;
DispList *dl;
int u, v, numVerts;
- float *fp, *orco;
+ float *fp, *coord_array;
int remakeDisp = 0;
if (!(cu->flag&CU_UV_ORCO) && cu->key && cu->key->refkey) {
@@ -1038,7 +1067,7 @@ float *make_orco_curve(Object *ob)
}
}
- fp= orco= MEM_mallocN(3*sizeof(float)*numVerts, "cu_orco");
+ fp= coord_array= MEM_mallocN(3*sizeof(float)*numVerts, "cu_orco");
for (dl=cu->disp.first; dl; dl=dl->next) {
if (dl->type==DL_INDEX3) {
for (u=0; u<dl->nr; u++, fp+=3) {
@@ -1071,9 +1100,12 @@ float *make_orco_curve(Object *ob)
fp[1]= 2.0f*v/(dl->nr-1) - 1.0f;
fp[2]= 0.0;
} else {
+ float *vert;
int realv= v % dl->nr;
-
- VECCOPY(fp, &dl->verts[(dl->nr*u + realv)*3]);
+ int realu= u % dl->parts;
+
+ vert= dl->verts + 3*(dl->nr*realu + realv);
+ VECCOPY(fp, vert);
fp[0]= (fp[0]-cu->loc[0])/cu->size[0];
fp[1]= (fp[1]-cu->loc[1])/cu->size[1];
@@ -1088,7 +1120,7 @@ float *make_orco_curve(Object *ob)
makeDispListCurveTypes(ob, 0);
}
- return orco;
+ return coord_array;
}
@@ -1415,7 +1447,7 @@ static void calc_bevel_sin_cos(float x1, float y1, float x2, float y2, float *si
}
-static void alfa_bezpart(BezTriple *prevbezt, BezTriple *bezt, Nurb *nu, float *data_a, int resolu)
+static void alfa_bezpart(BezTriple *prevbezt, BezTriple *bezt, Nurb *nu, float *tilt_array, float *radius_array, int resolu)
{
BezTriple *pprev, *next, *last;
float fac, dfac, t[4];
@@ -1425,14 +1457,14 @@ static void alfa_bezpart(BezTriple *prevbezt, BezTriple *bezt, Nurb *nu, float *
/* returns a point */
if(prevbezt==nu->bezt) {
- if(nu->flagu & 1) pprev= last;
+ if(nu->flagu & CU_CYCLIC) pprev= last;
else pprev= prevbezt;
}
else pprev= prevbezt-1;
/* next point */
if(bezt==last) {
- if(nu->flagu & 1) next= nu->bezt;
+ if(nu->flagu & CU_CYCLIC) next= nu->bezt;
else next= bezt;
}
else next= bezt+1;
@@ -1441,10 +1473,30 @@ static void alfa_bezpart(BezTriple *prevbezt, BezTriple *bezt, Nurb *nu, float *
dfac= 1.0f/(float)resolu;
for(a=0; a<resolu; a++, fac+= dfac) {
+ if (tilt_array) {
+ if (nu->tilt_interp==3) { /* May as well support for tilt also 2.47 ease interp */
+ tilt_array[a] = prevbezt->alfa + (bezt->alfa - prevbezt->alfa)*(3.0f*fac*fac - 2.0f*fac*fac*fac);
+ } else {
+ set_four_ipo(fac, t, nu->tilt_interp);
+ tilt_array[a]= t[0]*pprev->alfa + t[1]*prevbezt->alfa + t[2]*bezt->alfa + t[3]*next->alfa;
+ }
+ }
- set_four_ipo(fac, t, nu->tilt_interp);
-
- data_a[a]= t[0]*pprev->alfa + t[1]*prevbezt->alfa + t[2]*bezt->alfa + t[3]*next->alfa;
+ if (radius_array) {
+ if (nu->radius_interp==3) {
+ /* Support 2.47 ease interp
+ * Note! - this only takes the 2 points into account,
+ * giving much more localized results to changes in radius, sometimes you want that */
+ radius_array[a] = prevbezt->radius + (bezt->radius - prevbezt->radius)*(3.0f*fac*fac - 2.0f*fac*fac*fac);
+ } else {
+
+ /* reuse interpolation from tilt if we can */
+ if (tilt_array==NULL || nu->tilt_interp != nu->radius_interp) {
+ set_four_ipo(fac, t, nu->radius_interp);
+ }
+ radius_array[a]= t[0]*pprev->radius + t[1]*prevbezt->radius + t[2]*bezt->radius + t[3]*next->radius;
+ }
+ }
}
}
@@ -1462,13 +1514,19 @@ void makeBevelList(Object *ob)
BPoint *bp;
BevList *bl, *blnew, *blnext;
BevPoint *bevp, *bevp2, *bevp1 = NULL, *bevp0;
- float *data, *data_a, *v1, *v2, min, inp, x1, x2, y1, y2, vec[3];
+ float min, inp, x1, x2, y1, y2, vec[3];
+ float *coord_array, *tilt_array=NULL, *radius_array=NULL, *coord_fp, *tilt_fp=NULL, *radius_fp=NULL;
+ float *v1, *v2;
struct bevelsort *sortdata, *sd, *sd1;
- int a, b, len, nr, poly, resolu;
-
+ int a, b, nr, poly, resolu, len=0;
+ int do_tilt, do_radius;
+
/* this function needs an object, because of tflag and upflag */
cu= ob->data;
+ /* do we need to calculate the radius for each point? */
+ /* do_radius = (cu->bevobj || cu->taperobj || (cu->flag & CU_FRONT) || (cu->flag & CU_BACK)) ? 0 : 1; */
+
/* STEP 1: MAKE POLYS */
BLI_freelistN(&(cu->bev));
@@ -1476,8 +1534,15 @@ void makeBevelList(Object *ob)
else nu= cu->nurb.first;
while(nu) {
- if(nu->pntsu<=1) {
- bl= MEM_callocN(sizeof(BevList)+1*sizeof(BevPoint), "makeBevelList");
+
+ /* check if we will calculate tilt data */
+ do_tilt = ((nu->type & CU_2D) && (cu->flag & CU_3D)==0) ? 0 : 1;
+ do_radius = (do_tilt || cu->bevobj) ? 1 : 0; /* normal display uses the radius, better just to calculate them */
+
+ /* check we are a single point? also check we are not a surface and that the orderu is sane,
+ * enforced in the UI but can go wrong possibly */
+ if(!check_valid_nurb_u(nu)) {
+ bl= MEM_callocN(sizeof(BevList)+1*sizeof(BevPoint), "makeBevelList1");
BLI_addtail(&(cu->bev), bl);
bl->nr= 0;
} else {
@@ -1487,11 +1552,11 @@ void makeBevelList(Object *ob)
resolu= nu->resolu;
if((nu->type & 7)==CU_POLY) {
-
- bl= MEM_callocN(sizeof(BevList)+len*sizeof(BevPoint), "makeBevelList");
+ len= nu->pntsu;
+ bl= MEM_callocN(sizeof(BevList)+len*sizeof(BevPoint), "makeBevelList2");
BLI_addtail(&(cu->bev), bl);
- if(nu->flagu & 1) bl->poly= 0;
+ if(nu->flagu & CU_CYCLIC) bl->poly= 0;
else bl->poly= -1;
bl->nr= len;
bl->flag= 0;
@@ -1503,24 +1568,25 @@ void makeBevelList(Object *ob)
bevp->y= bp->vec[1];
bevp->z= bp->vec[2];
bevp->alfa= bp->alfa;
- bevp->f1= 1;
+ bevp->radius= bp->radius;
+ bevp->f1= SELECT;
bevp++;
bp++;
}
}
else if((nu->type & 7)==CU_BEZIER) {
- len= resolu*(nu->pntsu+ (nu->flagu & 1) -1)+1; /* in case last point is not cyclic */
- bl= MEM_callocN(sizeof(BevList)+len*sizeof(BevPoint), "makeBevelList");
+ len= resolu*(nu->pntsu+ (nu->flagu & CU_CYCLIC) -1)+1; /* in case last point is not cyclic */
+ bl= MEM_callocN(sizeof(BevList)+len*sizeof(BevPoint), "makeBevelBPoints");
BLI_addtail(&(cu->bev), bl);
- if(nu->flagu & 1) bl->poly= 0;
+ if(nu->flagu & CU_CYCLIC) bl->poly= 0;
else bl->poly= -1;
bevp= (BevPoint *)(bl+1);
a= nu->pntsu-1;
bezt= nu->bezt;
- if(nu->flagu & 1) {
+ if(nu->flagu & CU_CYCLIC) {
a++;
prevbezt= nu->bezt+(nu->pntsu-1);
}
@@ -1529,8 +1595,13 @@ void makeBevelList(Object *ob)
bezt++;
}
- data= MEM_mallocN(3*sizeof(float)*(resolu+1), "makeBevelList2");
- data_a= MEM_callocN(sizeof(float)*(resolu+1), "data_a");
+ coord_array= coord_fp= MEM_mallocN(3*sizeof(float)*(resolu+1), "makeBevelCoords");
+
+ if(do_tilt)
+ tilt_array= tilt_fp= MEM_callocN(sizeof(float)*(resolu+1), "makeBevelTilt");
+
+ if (do_radius)
+ radius_array= radius_fp= MEM_callocN(sizeof(float)*(resolu+1), "nakeBevelRadius");
while(a--) {
if(prevbezt->h2==HD_VECT && bezt->h1==HD_VECT) {
@@ -1539,6 +1610,7 @@ void makeBevelList(Object *ob)
bevp->y= prevbezt->vec[1][1];
bevp->z= prevbezt->vec[1][2];
bevp->alfa= prevbezt->alfa;
+ bevp->radius= prevbezt->radius;
bevp->f1= SELECT;
bevp->f2= 0;
bevp++;
@@ -1550,38 +1622,44 @@ void makeBevelList(Object *ob)
v2= bezt->vec[0];
/* always do all three, to prevent data hanging around */
- forward_diff_bezier(v1[0], v1[3], v2[0], v2[3], data, resolu, 3);
- forward_diff_bezier(v1[1], v1[4], v2[1], v2[4], data+1, resolu, 3);
- forward_diff_bezier(v1[2], v1[5], v2[2], v2[5], data+2, resolu, 3);
-
- if((nu->type & CU_2D)==0) {
- if(cu->flag & CU_3D) {
- alfa_bezpart(prevbezt, bezt, nu, data_a, resolu);
- }
- }
+ forward_diff_bezier(v1[0], v1[3], v2[0], v2[3], coord_array, resolu, 3);
+ forward_diff_bezier(v1[1], v1[4], v2[1], v2[4], coord_array+1, resolu, 3);
+ forward_diff_bezier(v1[2], v1[5], v2[2], v2[5], coord_array+2, resolu, 3);
+ if (do_tilt || do_radius)
+ alfa_bezpart(prevbezt, bezt, nu, tilt_array, radius_array, resolu);
/* indicate with handlecodes double points */
if(prevbezt->h1==prevbezt->h2) {
- if(prevbezt->h1==0 || prevbezt->h1==HD_VECT) bevp->f1= 1;
+ if(prevbezt->h1==0 || prevbezt->h1==HD_VECT) bevp->f1= SELECT;
}
else {
- if(prevbezt->h1==0 || prevbezt->h1==HD_VECT) bevp->f1= 1;
- else if(prevbezt->h2==0 || prevbezt->h2==HD_VECT) bevp->f1= 1;
+ if(prevbezt->h1==0 || prevbezt->h1==HD_VECT) bevp->f1= SELECT;
+ else if(prevbezt->h2==0 || prevbezt->h2==HD_VECT) bevp->f1= SELECT;
}
- v1= data;
- v2= data_a;
nr= resolu;
+ coord_fp = coord_array;
+ tilt_fp = tilt_array;
+ radius_fp = radius_array;
+
while(nr--) {
- bevp->x= v1[0];
- bevp->y= v1[1];
- bevp->z= v1[2];
- bevp->alfa= v2[0];
+ bevp->x= coord_fp[0];
+ bevp->y= coord_fp[1];
+ bevp->z= coord_fp[2];
+ coord_fp+=3;
+
+ if (do_tilt) {
+ bevp->alfa= *tilt_fp;
+ tilt_fp++;
+ }
+
+ if (do_radius) {
+ bevp->radius= *radius_fp;
+ radius_fp++;
+ }
bevp++;
- v1+=3;
- v2++;
}
bl->nr+= resolu;
@@ -1590,44 +1668,67 @@ void makeBevelList(Object *ob)
bezt++;
}
- MEM_freeN(data);
- MEM_freeN(data_a);
+ MEM_freeN(coord_array);
+ if (do_tilt) MEM_freeN(tilt_array);
+ if (do_radius) MEM_freeN(radius_array);
+ coord_array = tilt_array = radius_array = NULL;
- if((nu->flagu & 1)==0) { /* not cyclic: endpoint */
+ if((nu->flagu & CU_CYCLIC)==0) { /* not cyclic: endpoint */
bevp->x= prevbezt->vec[1][0];
bevp->y= prevbezt->vec[1][1];
bevp->z= prevbezt->vec[1][2];
bevp->alfa= prevbezt->alfa;
+ bevp->radius= prevbezt->radius;
bl->nr++;
}
-
}
else if((nu->type & 7)==CU_NURBS) {
if(nu->pntsv==1) {
- len= resolu*nu->pntsu;
- bl= MEM_mallocN(sizeof(BevList)+len*sizeof(BevPoint), "makeBevelList3");
+ len= (resolu*SEGMENTSU(nu));
+ if((nu->flagu & CU_CYCLIC)==0) len++;
+
+ bl= MEM_callocN(sizeof(BevList)+len*sizeof(BevPoint), "makeBevelList3");
BLI_addtail(&(cu->bev), bl);
bl->nr= len;
bl->flag= 0;
- if(nu->flagu & 1) bl->poly= 0;
+ if(nu->flagu & CU_CYCLIC) bl->poly= 0;
else bl->poly= -1;
bevp= (BevPoint *)(bl+1);
- data= MEM_callocN(4*sizeof(float)*len, "makeBevelList4"); /* has to be zero-ed */
- makeNurbcurve(nu, data, resolu, 4);
+ coord_array= coord_fp= MEM_callocN(3*sizeof(float)*len, "makeBevelCoords"); /* has to be zero-ed */
+
+ if(do_tilt)
+ tilt_array= tilt_fp= MEM_callocN(sizeof(float)*len, "makeBevelTilt");
+
+ if (do_radius)
+ radius_array= radius_fp= MEM_callocN(sizeof(float)*len, "nakeBevelRadius");
+
+ makeNurbcurve(nu, coord_array, tilt_array, radius_array, resolu);
- v1= data;
while(len--) {
- bevp->x= v1[0];
- bevp->y= v1[1];
- bevp->z= v1[2];
- bevp->alfa= v1[3];
+ bevp->x= coord_fp[0];
+ bevp->y= coord_fp[1];
+ bevp->z= coord_fp[2];
+ coord_fp+=3;
+
+ if (do_tilt) {
+ bevp->alfa= *tilt_fp;
+ tilt_fp++;
+ }
+
+ if (do_radius) {
+ bevp->radius= *radius_fp;
+ radius_fp++;
+ }
+
bevp->f1= bevp->f2= 0;
bevp++;
- v1+=4;
}
- MEM_freeN(data);
+ MEM_freeN(coord_array);
+ if (do_tilt) MEM_freeN(tilt_array);
+ if (do_radius) MEM_freeN(radius_array);
+ coord_array = tilt_array = radius_array = NULL;
}
}
}
@@ -1662,7 +1763,7 @@ void makeBevelList(Object *ob)
blnext= bl->next;
if(bl->nr && bl->flag) {
nr= bl->nr- bl->flag+1; /* +1 because vectorbezier sets flag too */
- blnew= MEM_mallocN(sizeof(BevList)+nr*sizeof(BevPoint), "makeBevelList");
+ blnew= MEM_mallocN(sizeof(BevList)+nr*sizeof(BevPoint), "makeBevelList4");
memcpy(blnew, bl, sizeof(BevList));
blnew->nr= 0;
BLI_remlink(&(cu->bev), bl);
@@ -1785,13 +1886,13 @@ void makeBevelList(Object *ob)
bevp2->cosa= bevp1->cosa;
if(cu->flag & CU_3D) { /* 3D */
- float *quat, q[4];
+ float quat[4], q[4];
vec[0]= bevp1->x - bevp2->x;
vec[1]= bevp1->y - bevp2->y;
vec[2]= bevp1->z - bevp2->z;
- quat= vectoquat(vec, 5, 1);
+ vectoquat(vec, 5, 1, quat);
Normalize(vec);
q[0]= (float)cos(0.5*bevp1->alfa);
@@ -1817,7 +1918,7 @@ void makeBevelList(Object *ob)
while(nr--) {
if(cu->flag & CU_3D) { /* 3D */
- float *quat, q[4];
+ float quat[4], q[4];
vec[0]= bevp2->x - bevp0->x;
vec[1]= bevp2->y - bevp0->y;
@@ -1825,7 +1926,7 @@ void makeBevelList(Object *ob)
Normalize(vec);
- quat= vectoquat(vec, 5, 1);
+ vectoquat(vec, 5, 1, quat);
q[0]= (float)cos(0.5*bevp1->alfa);
x1= (float)sin(0.5*bevp1->alfa);
@@ -1870,134 +1971,6 @@ void makeBevelList(Object *ob)
}
}
-/* calculates a bevel width (radius) for a particular subdivided curve part,
- * based on the radius value of the surrounding CVs */
-float calc_curve_subdiv_radius(Curve *cu, Nurb *nu, int cursubdiv)
-{
- BezTriple *bezt, *beztfirst, *beztlast, *beztnext, *beztprev;
- BPoint *bp, *bpfirst, *bplast;
- int resolu;
- float prevrad=0.0, nextrad=0.0, rad=0.0, ratio=0.0;
- int vectseg=0, subdivs=0;
-
- if((nu==NULL) || (nu->pntsu<=1)) return 1.0;
- bezt= nu->bezt;
- bp = nu->bp;
-
- if(G.rendering && cu->resolu_ren!=0) resolu= cu->resolu_ren;
- else resolu= nu->resolu;
-
- if(((nu->type & 7)==CU_BEZIER) && (bezt != NULL)) {
- beztfirst = nu->bezt;
- beztlast = nu->bezt + (nu->pntsu - 1);
-
- /* loop through the CVs to end up with a pointer to the CV before the subdiv in question, and a ratio
- * of how far that subdiv is between this CV and the next */
- while(bezt<=beztlast) {
- beztnext = bezt+1;
- beztprev = bezt-1;
- vectseg=0;
-
- if (subdivs==cursubdiv) {
- ratio= 0.0;
- break;
- }
-
- /* check to see if we're looking at a vector segment (no subdivisions) */
- if (nu->flagu & CU_CYCLIC) {
- if (bezt == beztfirst) {
- if ((beztlast->h2==HD_VECT) && (bezt->h1==HD_VECT)) vectseg = 1;
- } else {
- if ((beztprev->h2==HD_VECT) && (bezt->h1==HD_VECT)) vectseg = 1;
- }
- } else if ((bezt->h2==HD_VECT) && (beztnext->h1==HD_VECT)) vectseg = 1;
-
-
- if (vectseg==0) {
- /* if it's NOT a vector segment, check to see if the subdiv falls within the segment */
- subdivs += resolu;
-
- if (cursubdiv < subdivs) {
- ratio = 1.0 - ((subdivs - cursubdiv)/(float)resolu);
- break;
- }
- } else {
- /* must be a vector segment.. loop again! */
- subdivs += 1;
- }
-
- bezt++;
- }
-
- /* Now we have a nice bezt pointer to the CV that we want. But cyclic messes it up, so must correct for that..
- * (cyclic goes last-> first -> first+1 -> first+2 -> ...) */
- if (nu->flagu & CU_CYCLIC) {
- if (bezt == beztfirst) bezt = beztlast;
- else bezt--;
- }
-
- /* find the radii at the bounding CVs and interpolate between them based on ratio */
- rad = prevrad = bezt->radius;
-
- if ((bezt == beztlast) && (nu->flagu & CU_CYCLIC)) { /* loop around */
- bezt= beztfirst;
- } else if (bezt != beztlast) {
- bezt++;
- }
- nextrad = bezt->radius;
-
- }
- else if( ( ((nu->type & 7)==CU_NURBS) || ((nu->type & 7)==CU_POLY)) && (bp != NULL)) {
- /* follows similar algo as for bezt above */
- bpfirst = nu->bp;
- bplast = nu->bp + (nu->pntsu - 1);
-
- if ((nu->type & 7)==CU_POLY) resolu=1;
-
- while(bp<=bplast) {
- if (subdivs==cursubdiv) {
- ratio= 0.0;
- break;
- }
-
- subdivs += resolu;
-
- if (cursubdiv < subdivs) {
- ratio = 1.0 - ((subdivs - cursubdiv)/(float)resolu);
- break;
- }
-
- bp++;
- }
-
- if ( ((nu->type & 7)==CU_NURBS) && (nu->flagu & CU_CYCLIC)) {
- if (bp == bplast) bp = bpfirst;
- else bp++;
- }
-
- rad = prevrad = bp->radius;
-
- if ((bp == bplast) && (nu->flagu & CU_CYCLIC)) { /* loop around */
- bp= bpfirst;
- } else if (bp != bplast) {
- bp++;
- }
- nextrad = bp->radius;
-
- }
-
-
- if (nextrad != prevrad) {
- /* smooth interpolation */
- rad = prevrad + (nextrad-prevrad)*(3.0f*ratio*ratio - 2.0f*ratio*ratio*ratio);
- }
-
- if (rad > 0.0)
- return rad;
- else
- return 1.0;
-}
-
/* ****************** HANDLES ************** */
/*
@@ -2204,7 +2177,7 @@ void calchandlesNurb(Nurb *nu) /* first, if needed, set handle flags */
a= nu->pntsu;
bezt= nu->bezt;
- if(nu->flagu & 1) prev= bezt+(a-1);
+ if(nu->flagu & CU_CYCLIC) prev= bezt+(a-1);
else prev= 0;
next= bezt+1;
@@ -2212,7 +2185,7 @@ void calchandlesNurb(Nurb *nu) /* first, if needed, set handle flags */
calchandleNurb(bezt, prev, next, 0);
prev= bezt;
if(a==1) {
- if(nu->flagu & 1) next= nu->bezt;
+ if(nu->flagu & CU_CYCLIC) next= nu->bezt;
else next= 0;
}
else next++;
@@ -2366,9 +2339,9 @@ void sethandlesNurb(short code)
bezt= nu->bezt;
a= nu->pntsu;
while(a--) {
- if(bezt->f1 || bezt->f3) {
- if(bezt->f1) bezt->h1= code;
- if(bezt->f3) bezt->h2= code;
+ if((bezt->f1 & SELECT) || (bezt->f3 & SELECT)) {
+ if(bezt->f1 & SELECT) bezt->h1= code;
+ if(bezt->f3 & SELECT) bezt->h2= code;
if(bezt->h1!=bezt->h2) {
if ELEM(bezt->h1, HD_ALIGN, HD_AUTO) bezt->h1= HD_FREE;
if ELEM(bezt->h2, HD_ALIGN, HD_AUTO) bezt->h2= HD_FREE;
@@ -2396,8 +2369,8 @@ void sethandlesNurb(short code)
bezt= nu->bezt;
a= nu->pntsu;
while(a--) {
- if(bezt->f1 && bezt->h1) ok= 1;
- if(bezt->f3 && bezt->h2) ok= 1;
+ if((bezt->f1 & SELECT) && bezt->h1) ok= 1;
+ if((bezt->f3 & SELECT) && bezt->h2) ok= 1;
if(ok) break;
bezt++;
}
@@ -2413,8 +2386,8 @@ void sethandlesNurb(short code)
bezt= nu->bezt;
a= nu->pntsu;
while(a--) {
- if(bezt->f1) bezt->h1= ok;
- if(bezt->f3 ) bezt->h2= ok;
+ if(bezt->f1 & SELECT) bezt->h1= ok;
+ if(bezt->f3 & SELECT) bezt->h2= ok;
bezt++;
}
@@ -2603,3 +2576,63 @@ void curve_applyVertexCos(Curve *cu, ListBase *lb, float (*vertexCos)[3])
}
}
}
+
+int check_valid_nurb_u( struct Nurb *nu )
+{
+ if (nu==NULL) return 0;
+ if (nu->pntsu <= 1) return 0;
+ if ((nu->type & 7)!=CU_NURBS) return 1; /* not a nurb, lets assume its valid */
+
+ if (nu->pntsu < nu->orderu) return 0;
+ if (((nu->flag & CU_CYCLIC)==0) && ((nu->flagu>>1) & 2)) { /* Bezier U Endpoints */
+ if (nu->orderu==4) {
+ if (nu->pntsu < 5) return 0; /* bezier with 4 orderu needs 5 points */
+ } else if (nu->orderu != 3) return 0; /* order must be 3 or 4 */
+ }
+ return 1;
+}
+int check_valid_nurb_v( struct Nurb *nu)
+{
+ if (nu==NULL) return 0;
+ if (nu->pntsv <= 1) return 0;
+ if ((nu->type & 7)!=CU_NURBS) return 1; /* not a nurb, lets assume its valid */
+
+ if (nu->pntsv < nu->orderv) return 0;
+ if (((nu->flag & CU_CYCLIC)==0) && ((nu->flagv>>1) & 2)) { /* Bezier V Endpoints */
+ if (nu->orderv==4) {
+ if (nu->pntsv < 5) return 0; /* bezier with 4 orderu needs 5 points */
+ } else if (nu->orderv != 3) return 0; /* order must be 3 or 4 */
+ }
+ return 1;
+}
+
+int clamp_nurb_order_u( struct Nurb *nu )
+{
+ int change = 0;
+ if(nu->pntsu<nu->orderu) {
+ nu->orderu= nu->pntsu;
+ change= 1;
+ }
+ if(((nu->flag & CU_CYCLIC)==0) && (nu->flagu>>1)&2) {
+ CLAMP(nu->orderu, 3,4);
+ change= 1;
+ }
+ return change;
+}
+
+int clamp_nurb_order_v( struct Nurb *nu)
+{
+ int change = 0;
+ if(nu->pntsv<nu->orderv) {
+ nu->orderv= nu->pntsv;
+ change= 1;
+ }
+ if(((nu->flag & CU_CYCLIC)==0) && (nu->flagv>>1)&2) {
+ CLAMP(nu->orderv, 3,4);
+ change= 1;
+ }
+ return change;
+}
+
+
+
diff --git a/source/blender/blenkernel/intern/customdata.c b/source/blender/blenkernel/intern/customdata.c
index d8ce311b5ca..e93266c85f3 100644
--- a/source/blender/blenkernel/intern/customdata.c
+++ b/source/blender/blenkernel/intern/customdata.c
@@ -36,6 +36,7 @@
#include "BLI_blenlib.h"
#include "BLI_linklist.h"
+#include "BLI_mempool.h"
#include "DNA_customdata_types.h"
#include "DNA_listBase.h"
@@ -97,11 +98,16 @@ static void layerCopy_mdeformvert(const void *source, void *dest,
for(i = 0; i < count; ++i) {
MDeformVert *dvert = (MDeformVert *)((char *)dest + i * size);
- MDeformWeight *dw = MEM_callocN(dvert->totweight * sizeof(*dw),
- "layerCopy_mdeformvert dw");
- memcpy(dw, dvert->dw, dvert->totweight * sizeof(*dw));
- dvert->dw = dw;
+ if(dvert->totweight) {
+ MDeformWeight *dw = MEM_callocN(dvert->totweight * sizeof(*dw),
+ "layerCopy_mdeformvert dw");
+
+ memcpy(dw, dvert->dw, dvert->totweight * sizeof(*dw));
+ dvert->dw = dw;
+ }
+ else
+ dvert->dw = NULL;
}
}
@@ -259,14 +265,34 @@ static void layerSwap_tface(void *data, int *corner_indices)
{
MTFace *tf = data;
float uv[4][2];
+ static const short pin_flags[4] =
+ { TF_PIN1, TF_PIN2, TF_PIN3, TF_PIN4 };
+ static const char sel_flags[4] =
+ { TF_SEL1, TF_SEL2, TF_SEL3, TF_SEL4 };
+ short unwrap = tf->unwrap & ~(TF_PIN1 | TF_PIN2 | TF_PIN3 | TF_PIN4);
+ char flag = tf->flag & ~(TF_SEL1 | TF_SEL2 | TF_SEL3 | TF_SEL4);
int j;
for(j = 0; j < 4; ++j) {
- uv[j][0] = tf->uv[corner_indices[j]][0];
- uv[j][1] = tf->uv[corner_indices[j]][1];
+ int source_index = corner_indices[j];
+
+ uv[j][0] = tf->uv[source_index][0];
+ uv[j][1] = tf->uv[source_index][1];
+
+ // swap pinning flags around
+ if(tf->unwrap & pin_flags[source_index]) {
+ unwrap |= pin_flags[j];
+ }
+
+ // swap selection flags around
+ if(tf->flag & sel_flags[source_index]) {
+ flag |= sel_flags[j];
+ }
}
memcpy(tf->uv, uv, sizeof(tf->uv));
+ tf->unwrap = unwrap;
+ tf->flag = flag;
}
static void layerDefault_tface(void *data, int count)
@@ -354,8 +380,80 @@ static void layerDefault_origspace_face(void *data, int count)
}
/* --------- */
+static void layerDefault_mloopcol(void *data, int count)
+{
+ static MLoopCol default_mloopcol = {255,255,255,255};
+ MLoopCol *mlcol = (MLoopCol*)data;
+ int i;
+ for(i = 0; i < count; i++)
+ mlcol[i] = default_mloopcol;
+
+}
+
+static void layerInterp_mloopcol(void **sources, float *weights,
+ float *sub_weights, int count, void *dest)
+{
+ MLoopCol *mc = dest;
+ int i;
+ float *sub_weight;
+ struct {
+ float a;
+ float r;
+ float g;
+ float b;
+ } col;
+ col.a = col.r = col.g = col.b = 0;
+ sub_weight = sub_weights;
+ for(i = 0; i < count; ++i){
+ float weight = weights ? weights[i] : 1;
+ MLoopCol *src = sources[i];
+ if(sub_weights){
+ col.a += src->a * (*sub_weight) * weight;
+ col.r += src->r * (*sub_weight) * weight;
+ col.g += src->g * (*sub_weight) * weight;
+ col.b += src->b * (*sub_weight) * weight;
+ sub_weight++;
+ } else {
+ col.a += src->a * weight;
+ col.r += src->r * weight;
+ col.g += src->g * weight;
+ col.b += src->b * weight;
+ }
+ }
+ mc->a = (int)col.a;
+ mc->r = (int)col.r;
+ mc->g = (int)col.g;
+ mc->b = (int)col.b;
+}
+static void layerInterp_mloopuv(void **sources, float *weights,
+ float *sub_weights, int count, void *dest)
+{
+ MLoopUV *mluv = dest;
+ int i;
+ float *sub_weight;
+ struct {
+ float u;
+ float v;
+ }uv;
+ uv.u = uv.v = 0.0;
+ sub_weight = sub_weights;
+ for(i = 0; i < count; ++i){
+ float weight = weights ? weights[i] : 1;
+ MLoopUV *src = sources[i];
+ if(sub_weights){
+ uv.u += src->uv[0] * (*sub_weight) * weight;
+ uv.v += src->uv[1] * (*sub_weight) * weight;
+ sub_weight++;
+ } else {
+ uv.u += src->uv[0] * weight;
+ uv.v += src->uv[1] * weight;
+ }
+ }
+ mluv->uv[0] = uv.u;
+ mluv->uv[1] = uv.v;
+}
static void layerInterp_mcol(void **sources, float *weights,
float *sub_weights, int count, void *dest)
@@ -427,6 +525,8 @@ static void layerDefault_mcol(void *data, int count)
mcol[i] = default_mcol;
}
+
+
const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = {
{sizeof(MVert), "MVert", 1, NULL, NULL, NULL, NULL, NULL, NULL},
{sizeof(MSticky), "MSticky", 1, NULL, NULL, NULL, layerInterp_msticky, NULL,
@@ -449,13 +549,17 @@ const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = {
{sizeof(MStringProperty), "MStringProperty",1,"String",NULL,NULL,NULL,NULL},
{sizeof(OrigSpaceFace), "OrigSpaceFace", 1, "UVTex", layerCopy_origspace_face, NULL,
layerInterp_origspace_face, layerSwap_origspace_face, layerDefault_origspace_face},
- {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL}
+ {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
+ {sizeof(MTexPoly), "MTexPoly", 1, "Face Texture", NULL, NULL, NULL, NULL, NULL},
+ {sizeof(MLoopUV), "MLoopUV", 1, "UV coord", NULL, NULL, layerInterp_mloopuv, NULL, NULL},
+ {sizeof(MLoopCol), "MLoopCol", 1, "Col", NULL, NULL, layerInterp_mloopcol, NULL, layerDefault_mloopcol},
+ {sizeof(float)*3*4, "", 0, NULL, NULL, NULL, NULL, NULL, NULL}
};
const char *LAYERTYPENAMES[CD_NUMTYPES] = {
"CDMVert", "CDMSticky", "CDMDeformVert", "CDMEdge", "CDMFace", "CDMTFace",
"CDMCol", "CDOrigIndex", "CDNormal", "CDFlags","CDMFloatProperty",
- "CDMIntProperty","CDMStringProperty", "CDOrigSpace", "CDOrco"};
+ "CDMIntProperty","CDMStringProperty", "CDOrigSpace", "CDOrco", "CDMTexPoly", "CDMLoopUV", "CDMloopCol", "CDTangent"};
const CustomDataMask CD_MASK_BAREMESH =
CD_MASK_MVERT | CD_MASK_MEDGE | CD_MASK_MFACE;
@@ -469,7 +573,13 @@ const CustomDataMask CD_MASK_EDITMESH =
const CustomDataMask CD_MASK_DERIVEDMESH =
CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE |
CD_MASK_MCOL | CD_MASK_ORIGINDEX | CD_MASK_PROP_FLT | CD_MASK_PROP_INT |
- CD_MASK_PROP_STR | CD_MASK_ORIGSPACE | CD_MASK_ORCO;
+ CD_MASK_PROP_STR | CD_MASK_ORIGSPACE | CD_MASK_ORCO | CD_MASK_TANGENT;
+const CustomDataMask CD_MASK_BMESH =
+ CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR;
+const CustomDataMask CD_MASK_FACECORNERS =
+ CD_MASK_MTFACE | CD_MASK_MCOL | CD_MASK_MTEXPOLY | CD_MASK_MLOOPUV |
+ CD_MASK_MLOOPCOL;
+
static const LayerTypeInfo *layerType_getInfo(int type)
{
@@ -816,12 +926,9 @@ void *CustomData_add_layer_named(CustomData *data, int type, int alloctype,
int CustomData_free_layer(CustomData *data, int type, int totelem, int index)
{
int i;
- CustomDataLayer *layer;
if (index < 0) return 0;
- layer = &data->layers[index];
-
customData_free_layer__internal(&data->layers[index], totelem);
for (i=index+1; i < data->totlayer; ++i)
@@ -1236,7 +1343,8 @@ void CustomData_em_copy_data(const CustomData *source, CustomData *dest,
if(dest_i >= dest->totlayer) return;
/* if we found a matching layer, copy the data */
- if(dest->layers[dest_i].type == source->layers[src_i].type) {
+ if(dest->layers[dest_i].type == source->layers[src_i].type &&
+ strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
char *src_data = (char*)src_block + source->layers[src_i].offset;
char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
@@ -1272,7 +1380,7 @@ void *CustomData_em_get_n(const CustomData *data, void *block, int type, int n)
int layer_index;
/* get the layer index of the first layer of type */
- layer_index = CustomData_get_active_layer_index(data, type);
+ layer_index = CustomData_get_layer_index(data, type);
if(layer_index < 0) return NULL;
return (char *)block + data->layers[layer_index+n].offset;
@@ -1443,6 +1551,302 @@ void CustomData_from_em_block(const CustomData *source, CustomData *dest,
}
+/*Bmesh functions*/
+/*needed to convert to/from different face reps*/
+void CustomData_to_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata)
+{
+ int i;
+ for(i=0; i < fdata->totlayer; i++){
+ if(fdata->layers[i].type == CD_MTFACE){
+ CustomData_add_layer(pdata, CD_MTEXPOLY, CD_CALLOC, &(fdata->layers[i].name), 0);
+ CustomData_add_layer(ldata, CD_MLOOPUV, CD_CALLOC, &(fdata->layers[i].name), 0);
+ }
+ else if(fdata->layers[i].type == CD_MCOL)
+ CustomData_add_layer(ldata, CD_MLOOPCOL, CD_CALLOC, &(fdata->layers[i].name), 0);
+ }
+}
+void CustomData_from_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata, int total){
+ int i;
+ for(i=0; i < pdata->totlayer; i++){
+ if(pdata->layers[i].type == CD_MTEXPOLY)
+ CustomData_add_layer(fdata, CD_MTFACE, CD_CALLOC, &(pdata->layers[i].name), total);
+ }
+ for(i=0; i < ldata->totlayer; i++){
+ if(ldata->layers[i].type == CD_MLOOPCOL)
+ CustomData_add_layer(fdata, CD_MCOL, CD_CALLOC, &(ldata->layers[i].name), total);
+ }
+}
+
+
+void CustomData_bmesh_init_pool(CustomData *data, int allocsize){
+ if(data->totlayer)data->pool = BLI_mempool_create(data->totsize, allocsize, allocsize);
+}
+
+void CustomData_bmesh_free_block(CustomData *data, void **block)
+{
+ const LayerTypeInfo *typeInfo;
+ int i;
+
+ if(!*block) return;
+ for(i = 0; i < data->totlayer; ++i) {
+ if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
+ typeInfo = layerType_getInfo(data->layers[i].type);
+
+ if(typeInfo->free) {
+ int offset = data->layers[i].offset;
+ typeInfo->free((char*)*block + offset, 1, typeInfo->size);
+ }
+ }
+ }
+
+ BLI_mempool_free(data->pool, *block);
+ *block = NULL;
+}
+
+static void CustomData_bmesh_alloc_block(CustomData *data, void **block)
+{
+
+ if (*block)
+ CustomData_bmesh_free_block(data, block);
+
+ if (data->totsize > 0)
+ *block = BLI_mempool_calloc(data->pool);
+ else
+ *block = NULL;
+}
+
+void CustomData_bmesh_copy_data(const CustomData *source, CustomData *dest,
+ void *src_block, void **dest_block)
+{
+ const LayerTypeInfo *typeInfo;
+ int dest_i, src_i;
+
+ if (!*dest_block)
+ CustomData_bmesh_alloc_block(dest, dest_block);
+
+ /* copies a layer at a time */
+ dest_i = 0;
+ for(src_i = 0; src_i < source->totlayer; ++src_i) {
+
+ /* find the first dest layer with type >= the source type
+ * (this should work because layers are ordered by type)
+ */
+ while(dest_i < dest->totlayer
+ && dest->layers[dest_i].type < source->layers[src_i].type)
+ ++dest_i;
+
+ /* if there are no more dest layers, we're done */
+ if(dest_i >= dest->totlayer) return;
+
+ /* if we found a matching layer, copy the data */
+ if(dest->layers[dest_i].type == source->layers[src_i].type &&
+ strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
+ char *src_data = (char*)src_block + source->layers[src_i].offset;
+ char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
+
+ typeInfo = layerType_getInfo(source->layers[src_i].type);
+
+ if(typeInfo->copy)
+ typeInfo->copy(src_data, dest_data, 1);
+ else
+ memcpy(dest_data, src_data, typeInfo->size);
+
+ /* if there are multiple source & dest layers of the same type,
+ * we don't want to copy all source layers to the same dest, so
+ * increment dest_i
+ */
+ ++dest_i;
+ }
+ }
+}
+
+/*Bmesh Custom Data Functions. Should replace editmesh ones with these as well, due to more effecient memory alloc*/
+void *CustomData_bmesh_get(const CustomData *data, void *block, int type)
+{
+ int layer_index;
+
+ /* get the layer index of the first layer of type */
+ layer_index = CustomData_get_active_layer_index(data, type);
+ if(layer_index < 0) return NULL;
+
+ return (char *)block + data->layers[layer_index].offset;
+}
+
+void *CustomData_bmesh_get_n(const CustomData *data, void *block, int type, int n)
+{
+ int layer_index;
+
+ /* get the layer index of the first layer of type */
+ layer_index = CustomData_get_layer_index(data, type);
+ if(layer_index < 0) return NULL;
+
+ return (char *)block + data->layers[layer_index+n].offset;
+}
+
+void CustomData_bmesh_set(const CustomData *data, void *block, int type, void *source)
+{
+ void *dest = CustomData_bmesh_get(data, block, type);
+ const LayerTypeInfo *typeInfo = layerType_getInfo(type);
+
+ if(!dest) return;
+
+ if(typeInfo->copy)
+ typeInfo->copy(source, dest, 1);
+ else
+ memcpy(dest, source, typeInfo->size);
+}
+
+void CustomData_bmesh_set_n(CustomData *data, void *block, int type, int n, void *source)
+{
+ void *dest = CustomData_bmesh_get_n(data, block, type, n);
+ const LayerTypeInfo *typeInfo = layerType_getInfo(type);
+
+ if(!dest) return;
+
+ if(typeInfo->copy)
+ typeInfo->copy(source, dest, 1);
+ else
+ memcpy(dest, source, typeInfo->size);
+}
+
+void CustomData_bmesh_interp(CustomData *data, void **src_blocks, float *weights,
+ float *sub_weights, int count, void *dest_block)
+{
+ int i, j;
+ void *source_buf[SOURCE_BUF_SIZE];
+ void **sources = source_buf;
+
+ /* slow fallback in case we're interpolating a ridiculous number of
+ * elements
+ */
+ if(count > SOURCE_BUF_SIZE)
+ sources = MEM_callocN(sizeof(*sources) * count,
+ "CustomData_interp sources");
+
+ /* interpolates a layer at a time */
+ for(i = 0; i < data->totlayer; ++i) {
+ CustomDataLayer *layer = &data->layers[i];
+ const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
+ if(typeInfo->interp) {
+ for(j = 0; j < count; ++j)
+ sources[j] = (char *)src_blocks[j] + layer->offset;
+
+ typeInfo->interp(sources, weights, sub_weights, count,
+ (char *)dest_block + layer->offset);
+ }
+ }
+
+ if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
+}
+
+void CustomData_bmesh_set_default(CustomData *data, void **block)
+{
+ const LayerTypeInfo *typeInfo;
+ int i;
+
+ if (!*block)
+ CustomData_bmesh_alloc_block(data, block);
+
+ for(i = 0; i < data->totlayer; ++i) {
+ int offset = data->layers[i].offset;
+
+ typeInfo = layerType_getInfo(data->layers[i].type);
+
+ if(typeInfo->set_default)
+ typeInfo->set_default((char*)*block + offset, 1);
+ }
+}
+
+void CustomData_to_bmesh_block(const CustomData *source, CustomData *dest,
+ int src_index, void **dest_block)
+{
+ const LayerTypeInfo *typeInfo;
+ int dest_i, src_i, src_offset;
+
+ if (!*dest_block)
+ CustomData_bmesh_alloc_block(dest, dest_block);
+
+ /* copies a layer at a time */
+ dest_i = 0;
+ for(src_i = 0; src_i < source->totlayer; ++src_i) {
+
+ /* find the first dest layer with type >= the source type
+ * (this should work because layers are ordered by type)
+ */
+ while(dest_i < dest->totlayer
+ && dest->layers[dest_i].type < source->layers[src_i].type)
+ ++dest_i;
+
+ /* if there are no more dest layers, we're done */
+ if(dest_i >= dest->totlayer) return;
+
+ /* if we found a matching layer, copy the data */
+ if(dest->layers[dest_i].type == source->layers[src_i].type) {
+ int offset = dest->layers[dest_i].offset;
+ char *src_data = source->layers[src_i].data;
+ char *dest_data = (char*)*dest_block + offset;
+
+ typeInfo = layerType_getInfo(dest->layers[dest_i].type);
+ src_offset = src_index * typeInfo->size;
+
+ if(typeInfo->copy)
+ typeInfo->copy(src_data + src_offset, dest_data, 1);
+ else
+ memcpy(dest_data, src_data + src_offset, typeInfo->size);
+
+ /* if there are multiple source & dest layers of the same type,
+ * we don't want to copy all source layers to the same dest, so
+ * increment dest_i
+ */
+ ++dest_i;
+ }
+ }
+}
+
+void CustomData_from_bmesh_block(const CustomData *source, CustomData *dest,
+ void *src_block, int dest_index)
+{
+ const LayerTypeInfo *typeInfo;
+ int dest_i, src_i, dest_offset;
+
+ /* copies a layer at a time */
+ dest_i = 0;
+ for(src_i = 0; src_i < source->totlayer; ++src_i) {
+
+ /* find the first dest layer with type >= the source type
+ * (this should work because layers are ordered by type)
+ */
+ while(dest_i < dest->totlayer
+ && dest->layers[dest_i].type < source->layers[src_i].type)
+ ++dest_i;
+
+ /* if there are no more dest layers, we're done */
+ if(dest_i >= dest->totlayer) return;
+
+ /* if we found a matching layer, copy the data */
+ if(dest->layers[dest_i].type == source->layers[src_i].type) {
+ int offset = source->layers[src_i].offset;
+ char *src_data = (char*)src_block + offset;
+ char *dest_data = dest->layers[dest_i].data;
+
+ typeInfo = layerType_getInfo(dest->layers[dest_i].type);
+ dest_offset = dest_index * typeInfo->size;
+
+ if(typeInfo->copy)
+ typeInfo->copy(src_data, dest_data + dest_offset, 1);
+ else
+ memcpy(dest_data + dest_offset, src_data, typeInfo->size);
+
+ /* if there are multiple source & dest layers of the same type,
+ * we don't want to copy all source layers to the same dest, so
+ * increment dest_i
+ */
+ ++dest_i;
+ }
+ }
+
+}
+
void CustomData_file_write_info(int type, char **structname, int *structnum)
{
const LayerTypeInfo *typeInfo = layerType_getInfo(type);
diff --git a/source/blender/blenkernel/intern/deform.c b/source/blender/blenkernel/intern/deform.c
index ab53571b62d..47736865273 100644
--- a/source/blender/blenkernel/intern/deform.c
+++ b/source/blender/blenkernel/intern/deform.c
@@ -220,3 +220,28 @@ void unique_vertexgroup_name (bDeformGroup *dg, Object *ob)
}
}
}
+
+float deformvert_get_weight(const struct MDeformVert *dvert, int group_num)
+{
+ if(dvert)
+ {
+ const MDeformWeight *dw = dvert->dw;
+ int i;
+
+ for(i=dvert->totweight; i>0; i--, dw++)
+ if(dw->def_nr == group_num)
+ return dw->weight;
+ }
+
+ /* Not found */
+ return 0.0;
+}
+
+float vertexgroup_get_vertex_weight(const struct MDeformVert *dvert, int index, int group_num)
+{
+ if(group_num == -1 || dvert == NULL)
+ return 1.0;
+
+ return deformvert_get_weight(dvert+index, group_num);
+}
+
diff --git a/source/blender/blenkernel/intern/depsgraph.c b/source/blender/blenkernel/intern/depsgraph.c
index 0ce318eb57f..f5deda9c3c9 100644
--- a/source/blender/blenkernel/intern/depsgraph.c
+++ b/source/blender/blenkernel/intern/depsgraph.c
@@ -46,6 +46,7 @@
#include "DNA_effect_types.h"
#include "DNA_group_types.h"
#include "DNA_lattice_types.h"
+#include "DNA_lamp_types.h"
#include "DNA_key_types.h"
#include "DNA_mesh_types.h"
#include "DNA_modifier_types.h"
@@ -71,12 +72,15 @@
#include "BKE_modifier.h"
#include "BKE_object.h"
#include "BKE_particle.h"
+#include "BKE_pointcache.h"
#include "BKE_utildefines.h"
#include "BKE_scene.h"
#include "MEM_guardedalloc.h"
+#ifndef DISABLE_PYTHON
#include "BPY_extern.h"
+#endif
#include "depsgraph_private.h"
@@ -310,6 +314,7 @@ static void dag_add_driver_relation(Ipo *ipo, DagForest *dag, DagNode *node, int
if ((icu->driver->flag & IPO_DRIVER_FLAG_INVALID) || (icu->driver->name[0] == '\0'))
continue; /* empty or invalid expression */
+#ifndef DISABLE_PYTHON
else {
/* now we need refs to all objects mentioned in this
* pydriver expression, to call 'dag_add_relation'
@@ -322,22 +327,41 @@ static void dag_add_driver_relation(Ipo *ipo, DagForest *dag, DagNode *node, int
ob = *oba;
node1 = dag_get_node(dag, ob);
if (ob->type == OB_ARMATURE)
- dag_add_relation(dag, node1, node, isdata?DAG_RL_DATA_DATA:DAG_RL_DATA_OB);
+ dag_add_relation(dag, node1, node, isdata?DAG_RL_DATA_DATA:DAG_RL_DATA_OB, "Python Ipo Driver");
else
- dag_add_relation(dag, node1, node, isdata?DAG_RL_OB_DATA:DAG_RL_OB_OB);
+ dag_add_relation(dag, node1, node, isdata?DAG_RL_OB_DATA:DAG_RL_OB_OB, "Python Ipo Driver");
oba++;
}
MEM_freeN(obarray);
}
}
+#endif /* DISABLE_PYTHON */
}
else if (icu->driver->ob) {
node1 = dag_get_node(dag, icu->driver->ob);
if(icu->driver->blocktype==ID_AR)
- dag_add_relation(dag, node1, node, isdata?DAG_RL_DATA_DATA:DAG_RL_DATA_OB);
+ dag_add_relation(dag, node1, node, isdata?DAG_RL_DATA_DATA:DAG_RL_DATA_OB, "Ipo Driver");
else
- dag_add_relation(dag, node1, node, isdata?DAG_RL_OB_DATA:DAG_RL_OB_OB);
+ dag_add_relation(dag, node1, node, isdata?DAG_RL_OB_DATA:DAG_RL_OB_OB, "Ipo Driver");
+ }
+ }
+ }
+}
+
+static void dag_add_collision_field_relation(DagForest *dag, Object *ob, DagNode *node)
+{
+ Base *base;
+ DagNode *node2;
+
+ // would be nice to have a list of colliders here
+ // so for now walk all objects in scene check 'same layer rule'
+ for(base = G.scene->base.first; base; base= base->next) {
+ if((base->lay & ob->lay) && base->object->pd) {
+ Object *ob1= base->object;
+ if((ob1->pd->deflect || ob1->pd->forcefield) && (ob1 != ob)) {
+ node2 = dag_get_node(dag, ob1);
+ dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Field Collision");
}
}
}
@@ -358,7 +382,7 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Object *ob, int
if ((ob->data) && (mask&DAG_RL_DATA)) {
node2 = dag_get_node(dag,ob->data);
- dag_add_relation(dag,node,node2,DAG_RL_DATA);
+ dag_add_relation(dag,node,node2,DAG_RL_DATA, "Object-Data Relation");
node2->first_ancestor = ob;
node2->ancestor_count += 1;
}
@@ -383,11 +407,11 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Object *ob, int
node3 = dag_get_node(dag, ct->tar);
if (ct->subtarget[0])
- dag_add_relation(dag,node3,node, DAG_RL_OB_DATA|DAG_RL_DATA_DATA);
+ dag_add_relation(dag,node3,node, DAG_RL_OB_DATA|DAG_RL_DATA_DATA, cti->name);
else if(ELEM(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO))
- dag_add_relation(dag,node3,node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
+ dag_add_relation(dag,node3,node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA, cti->name);
else
- dag_add_relation(dag,node3,node, DAG_RL_OB_DATA);
+ dag_add_relation(dag,node3,node, DAG_RL_OB_DATA, cti->name);
}
}
@@ -435,7 +459,7 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Object *ob, int
for(amod= strip->modifiers.first; amod; amod= amod->next) {
if(amod->ob) {
node2 = dag_get_node(dag, amod->ob);
- dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
+ dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "NLA Strip Modifier");
}
}
}
@@ -455,46 +479,55 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Object *ob, int
switch(ob->partype) {
case PARSKEL:
- dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_OB);
+ dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_OB, "Parent");
break;
case PARVERT1: case PARVERT3: case PARBONE:
- dag_add_relation(dag,node2,node,DAG_RL_DATA_OB|DAG_RL_OB_OB);
+ dag_add_relation(dag,node2,node,DAG_RL_DATA_OB|DAG_RL_OB_OB, "Vertex Parent");
break;
default:
if(ob->parent->type==OB_LATTICE)
- dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_OB);
+ dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_OB, "Lattice Parent");
else if(ob->parent->type==OB_CURVE) {
Curve *cu= ob->parent->data;
if(cu->flag & CU_PATH)
- dag_add_relation(dag,node2,node,DAG_RL_DATA_OB|DAG_RL_OB_OB);
+ dag_add_relation(dag,node2,node,DAG_RL_DATA_OB|DAG_RL_OB_OB, "Curve Parent");
else
- dag_add_relation(dag,node2,node,DAG_RL_OB_OB);
+ dag_add_relation(dag,node2,node,DAG_RL_OB_OB, "Curve Parent");
}
- else
- dag_add_relation(dag,node2,node,DAG_RL_OB_OB);
+ else
+ dag_add_relation(dag,node2,node,DAG_RL_OB_OB, "Parent");
}
/* exception case: parent is duplivert */
if(ob->type==OB_MBALL && (ob->parent->transflag & OB_DUPLIVERTS)) {
- dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_OB);
+ dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_OB, "Duplivert");
}
addtoroot = 0;
}
if (ob->track) {
node2 = dag_get_node(dag,ob->track);
- dag_add_relation(dag,node2,node,DAG_RL_OB_OB);
+ dag_add_relation(dag,node2,node,DAG_RL_OB_OB, "Track To");
addtoroot = 0;
}
if (ob->proxy) {
node2 = dag_get_node(dag, ob->proxy);
- dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA|DAG_RL_OB_OB);
+ dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA|DAG_RL_OB_OB, "Proxy");
/* inverted relation, so addtoroot shouldn't be set to zero */
}
if (ob->type==OB_CAMERA) {
Camera *cam = (Camera *)ob->data;
+ if (cam->ipo) {
+ dag_add_driver_relation(cam->ipo, dag, node, 1);
+ }
if (cam->dof_ob) {
node2 = dag_get_node(dag, cam->dof_ob);
- dag_add_relation(dag,node2,node,DAG_RL_OB_OB);
+ dag_add_relation(dag,node2,node,DAG_RL_OB_OB, "Camera DoF");
+ }
+ }
+ if (ob->type==OB_LAMP) {
+ Lamp *la = (Lamp *)ob->data;
+ if (la->ipo) {
+ dag_add_driver_relation(la->ipo, dag, node, 1);
}
}
if (ob->transflag & OB_DUPLI) {
@@ -504,46 +537,33 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Object *ob, int
if(go->ob) {
node2 = dag_get_node(dag, go->ob);
/* node2 changes node1, this keeps animations updated in groups?? not logical? */
- dag_add_relation(dag, node2, node, DAG_RL_OB_OB);
+ dag_add_relation(dag, node2, node, DAG_RL_OB_OB, "Dupligroup");
}
}
}
}
/* softbody collision */
- if((ob->type==OB_MESH) || (ob->type==OB_CURVE) || (ob->type==OB_LATTICE)) {
- Base *base;
- if(modifiers_isSoftbodyEnabled(ob)){
- // would be nice to have a list of colliders here
- // so for now walk all objects in scene check 'same layer rule'
- for(base = G.scene->base.first; base; base= base->next) {
- if( (base->lay & ob->lay) && base->object->pd) {
- Object *ob1= base->object;
- if((ob1->pd->deflect) && (ob1 != ob)) {
- node2 = dag_get_node(dag, ob1);
- dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
- }
- }
- }
- }
- }
+ if((ob->type==OB_MESH) || (ob->type==OB_CURVE) || (ob->type==OB_LATTICE))
+ if(modifiers_isSoftbodyEnabled(ob) || modifiers_isClothEnabled(ob))
+ dag_add_collision_field_relation(dag, ob, node);
if (ob->type==OB_MBALL) {
Object *mom= find_basis_mball(ob);
if(mom!=ob) {
node2 = dag_get_node(dag, mom);
- dag_add_relation(dag,node,node2,DAG_RL_DATA_DATA|DAG_RL_OB_DATA); // mom depends on children!
+ dag_add_relation(dag,node,node2,DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Metaball"); // mom depends on children!
}
}
else if (ob->type==OB_CURVE) {
Curve *cu= ob->data;
if(cu->bevobj) {
node2 = dag_get_node(dag, cu->bevobj);
- dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
+ dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Curve Bevel");
}
if(cu->taperobj) {
node2 = dag_get_node(dag, cu->taperobj);
- dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
+ dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Curve Taper");
}
if(cu->ipo)
dag_add_driver_relation(cu->ipo, dag, node, 1);
@@ -553,52 +573,41 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Object *ob, int
Curve *cu= ob->data;
if(cu->textoncurve) {
node2 = dag_get_node(dag, cu->textoncurve);
- dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
- }
- }
- else if(ob->type==OB_MESH) {
- PartEff *paf= give_parteff(ob);
- if(paf) {
- ListBase *listb;
- pEffectorCache *ec;
-
- /* ob location depends on itself */
- if((paf->flag & PAF_STATIC)==0)
- dag_add_relation(dag, node, node, DAG_RL_OB_DATA);
-
- listb= pdInitEffectors(ob, paf->group); /* note, makes copy... */
- if(listb) {
- for(ec= listb->first; ec; ec= ec->next) {
- Object *ob1= ec->ob;
- PartDeflect *pd= ob1->pd;
-
- if(pd->forcefield) {
- node2 = dag_get_node(dag, ob1);
- if(pd->forcefield==PFIELD_GUIDE)
- dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
- else
- dag_add_relation(dag, node2, node, DAG_RL_OB_DATA);
- }
- }
-
- pdEndEffectors(listb); /* restores copy... */
- }
+ dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Texture On Curve");
}
}
-
+
psys= ob->particlesystem.first;
if(psys) {
ParticleEffectorCache *nec;
+ GroupObject *go;
for(; psys; psys=psys->next) {
ParticleSettings *part= psys->part;
-
- dag_add_relation(dag, node, node, DAG_RL_OB_DATA);
+
+ dag_add_relation(dag, node, node, DAG_RL_OB_DATA, "Particle-Object Relation");
+
+ if(psys->flag & PSYS_DISABLED || psys->flag & PSYS_DELETE)
+ continue;
if(part->phystype==PART_PHYS_KEYED && psys->keyed_ob &&
BLI_findlink(&psys->keyed_ob->particlesystem,psys->keyed_psys-1)) {
node2 = dag_get_node(dag, psys->keyed_ob);
- dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA);
+ dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA, "Particle Keyed Physics");
+ }
+
+ if(part->draw_as == PART_DRAW_OB && part->dup_ob) {
+ node2 = dag_get_node(dag, part->dup_ob);
+ dag_add_relation(dag, node, node2, DAG_RL_OB_OB, "Particle Object Visualisation");
+ if(part->dup_ob->type == OB_MBALL)
+ dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA, "Particle Object Visualisation");
+ }
+
+ if(part->draw_as == PART_DRAW_GR && part->dup_group) {
+ for(go=part->dup_group->gobject.first; go; go=go->next) {
+ node2 = dag_get_node(dag, go->ob);
+ dag_add_relation(dag, node, node2, DAG_RL_OB_OB, "Particle Group Visualisation");
+ }
}
if(psys->effectors.first)
@@ -612,22 +621,22 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Object *ob, int
if(nec->type & PSYS_EC_EFFECTOR) {
node2 = dag_get_node(dag, ob1);
if(ob1->pd->forcefield==PFIELD_GUIDE)
- dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
+ dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Particle Field");
else
- dag_add_relation(dag, node2, node, DAG_RL_OB_DATA);
+ dag_add_relation(dag, node2, node, DAG_RL_OB_DATA, "Particle Field");
}
else if(nec->type & PSYS_EC_DEFLECT) {
node2 = dag_get_node(dag, ob1);
- dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
+ dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Particle Collision");
}
else if(nec->type & PSYS_EC_PARTICLE) {
node2 = dag_get_node(dag, ob1);
- dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA);
+ dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA, "Particle Field");
}
if(nec->type & PSYS_EC_REACTOR) {
node2 = dag_get_node(dag, ob1);
- dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA);
+ dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA, "Particle Reactor");
}
}
}
@@ -652,12 +661,12 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Object *ob, int
node2 = dag_get_node(dag, obt);
if (ELEM(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO))
- dag_add_relation(dag, node2, node, DAG_RL_DATA_OB|DAG_RL_OB_OB);
+ dag_add_relation(dag, node2, node, DAG_RL_DATA_OB|DAG_RL_OB_OB, cti->name);
else {
if (ELEM3(obt->type, OB_ARMATURE, OB_MESH, OB_LATTICE) && (ct->subtarget[0]))
- dag_add_relation(dag, node2, node, DAG_RL_DATA_OB|DAG_RL_OB_OB);
+ dag_add_relation(dag, node2, node, DAG_RL_DATA_OB|DAG_RL_OB_OB, cti->name);
else
- dag_add_relation(dag, node2, node, DAG_RL_OB_OB);
+ dag_add_relation(dag, node2, node, DAG_RL_OB_OB, cti->name);
}
addtoroot = 0;
}
@@ -668,7 +677,7 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Object *ob, int
}
if (addtoroot == 1 )
- dag_add_relation(dag,scenenode,node,DAG_RL_SCENE);
+ dag_add_relation(dag,scenenode,node,DAG_RL_SCENE, "Scene Relation");
}
struct DagForest *build_dag(struct Scene *sce, short mask)
@@ -859,12 +868,12 @@ DagNode * dag_get_sub_node (DagForest *forest,void * fob)
return node;
}
-void dag_add_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel)
+static void dag_add_parent_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel, char *name)
{
- DagAdjList *itA = fob1->child;
+ DagAdjList *itA = fob2->parent;
while (itA) { /* search if relation exist already */
- if (itA->node == fob2) {
+ if (itA->node == fob1) {
itA->type |= rel;
itA->count += 1;
return;
@@ -873,19 +882,23 @@ void dag_add_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel
}
/* create new relation and insert at head. MALLOC alert! */
itA = MEM_mallocN(sizeof(DagAdjList),"DAG adj list");
- itA->node = fob2;
+ itA->node = fob1;
itA->type = rel;
itA->count = 1;
- itA->next = fob1->child;
- fob1->child = itA;
+ itA->next = fob2->parent;
+ itA->name = name;
+ fob2->parent = itA;
}
-static void dag_add_parent_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel)
+void dag_add_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel, char *name)
{
- DagAdjList *itA = fob2->parent;
+ DagAdjList *itA = fob1->child;
+ /* parent relation is for cycle checking */
+ dag_add_parent_relation(forest, fob1, fob2, rel, name);
+
while (itA) { /* search if relation exist already */
- if (itA->node == fob1) {
+ if (itA->node == fob2) {
itA->type |= rel;
itA->count += 1;
return;
@@ -894,13 +907,127 @@ static void dag_add_parent_relation(DagForest *forest, DagNode *fob1, DagNode *f
}
/* create new relation and insert at head. MALLOC alert! */
itA = MEM_mallocN(sizeof(DagAdjList),"DAG adj list");
- itA->node = fob1;
+ itA->node = fob2;
itA->type = rel;
itA->count = 1;
- itA->next = fob2->parent;
- fob2->parent = itA;
+ itA->next = fob1->child;
+ itA->name = name;
+ fob1->child = itA;
}
+static char *dag_node_name(DagNode *node)
+{
+ if(node->ob == NULL)
+ return "null";
+ else if(ugly_hack_sorry)
+ return ((ID*)(node->ob))->name+2;
+ else
+ return ((bPoseChannel*)(node->ob))->name;
+}
+
+#if 0
+static void dag_node_print_dependencies(DagNode *node)
+{
+ DagAdjList *itA;
+
+ printf("%s depends on:\n", dag_node_name(node));
+
+ for(itA= node->parent; itA; itA= itA->next)
+ printf(" %s through %s\n", dag_node_name(itA->node), itA->name);
+ printf("\n");
+}
+#endif
+
+static int dag_node_print_dependency_recurs(DagNode *node, DagNode *endnode)
+{
+ DagAdjList *itA;
+
+ if(node->color == DAG_BLACK)
+ return 0;
+
+ node->color= DAG_BLACK;
+
+ if(node == endnode)
+ return 1;
+
+ for(itA= node->parent; itA; itA= itA->next) {
+ if(dag_node_print_dependency_recurs(itA->node, endnode)) {
+ printf(" %s depends on %s through %s.\n", dag_node_name(node), dag_node_name(itA->node), itA->name);
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+static void dag_node_print_dependency_cycle(DagForest *dag, DagNode *startnode, DagNode *endnode, char *name)
+{
+ DagNode *node;
+
+ for(node = dag->DagNode.first; node; node= node->next)
+ node->color= DAG_WHITE;
+
+ printf(" %s depends on %s through %s.\n", dag_node_name(endnode), dag_node_name(startnode), name);
+ dag_node_print_dependency_recurs(startnode, endnode);
+ printf("\n");
+}
+
+static int dag_node_recurs_level(DagNode *node, int level)
+{
+ DagAdjList *itA;
+ int newlevel;
+
+ node->color= DAG_BLACK; /* done */
+ newlevel= ++level;
+
+ for(itA= node->parent; itA; itA= itA->next) {
+ if(itA->node->color==DAG_WHITE) {
+ itA->node->ancestor_count= dag_node_recurs_level(itA->node, level);
+ newlevel= MAX2(newlevel, level+itA->node->ancestor_count);
+ }
+ else
+ newlevel= MAX2(newlevel, level+itA->node->ancestor_count);
+ }
+
+ return newlevel;
+}
+
+static void dag_check_cycle(DagForest *dag)
+{
+ DagNode *node;
+ DagAdjList *itA;
+
+ /* tag nodes unchecked */
+ for(node = dag->DagNode.first; node; node= node->next)
+ node->color= DAG_WHITE;
+
+ for(node = dag->DagNode.first; node; node= node->next) {
+ if(node->color==DAG_WHITE) {
+ node->ancestor_count= dag_node_recurs_level(node, 0);
+ }
+ }
+
+ /* check relations, and print errors */
+ for(node = dag->DagNode.first; node; node= node->next) {
+ for(itA= node->parent; itA; itA= itA->next) {
+ if(itA->node->ancestor_count > node->ancestor_count) {
+ if(node->ob && itA->node->ob) {
+ printf("Dependency cycle detected:\n");
+ dag_node_print_dependency_cycle(dag, itA->node, node, itA->name);
+ }
+ }
+ }
+ }
+
+ /* parent relations are only needed for cycle checking, so free now */
+ for(node = dag->DagNode.first; node; node= node->next) {
+ while (node->parent) {
+ itA = node->parent->next;
+ MEM_freeN(node->parent);
+ node->parent = itA;
+ }
+ }
+}
/*
* MainDAG is the DAG of all objects in current scene
@@ -1539,6 +1666,8 @@ void DAG_scene_sort(struct Scene *sce)
build_dag(sce, DAG_RL_ALL_BUT_DATA);
+ dag_check_cycle(sce->theDag);
+
nqueue = queue_create(DAGQUEUEALLOC);
for(node = sce->theDag->DagNode.first; node; node= node->next) {
@@ -1630,11 +1759,12 @@ static void flush_update_node(DagNode *node, unsigned int layer, int curtime)
ob= node->ob;
if(ob && (ob->recalc & OB_RECALC)) {
all_layer= ob->lay;
+
/* got an object node that changes, now check relations */
for(itA = node->child; itA; itA= itA->next) {
all_layer |= itA->lay;
/* the relationship is visible */
- if(itA->lay & layer) {
+ if((itA->lay & layer) || (itA->node->ob == G.obedit)) {
if(itA->node->type==ID_OB) {
obc= itA->node->ob;
oldflag= obc->recalc;
@@ -1665,7 +1795,7 @@ static void flush_update_node(DagNode *node, unsigned int layer, int curtime)
}
}
/* even nicer, we can clear recalc flags... */
- if((all_layer & layer)==0) {
+ if((all_layer & layer)==0 && (ob != G.obedit)) {
/* but existing displaylists or derivedmesh should be freed */
if(ob->recalc & OB_RECALC_DATA)
object_free_display(ob);
@@ -1679,7 +1809,7 @@ static void flush_update_node(DagNode *node, unsigned int layer, int curtime)
/* could merge this in with loop above...? (ton) */
for(itA = node->child; itA; itA= itA->next) {
/* the relationship is visible */
- if(itA->lay & layer) {
+ if((itA->lay & layer) || (itA->node->ob == G.obedit)) {
if(itA->node->type==ID_OB) {
obc= itA->node->ob;
/* child moves */
@@ -1703,18 +1833,24 @@ static void flush_update_node(DagNode *node, unsigned int layer, int curtime)
}
/* node was checked to have lasttime != curtime , and is of type ID_OB */
-static unsigned int flush_layer_node(DagNode *node, int curtime)
+static unsigned int flush_layer_node(Scene *sce, DagNode *node, int curtime)
{
+ Base *base;
DagAdjList *itA;
node->lasttime= curtime;
- node->lay= ((Object *)node->ob)->lay;
+ node->lay= 0;
+ for(base= sce->base.first; base; base= base->next) {
+ if(node->ob == base->object) {
+ node->lay= ((Object *)node->ob)->lay;
+ break;
+ }
+ }
for(itA = node->child; itA; itA= itA->next) {
if(itA->node->type==ID_OB) {
if(itA->node->lasttime!=curtime) {
- itA->lay= flush_layer_node(itA->node, curtime); // lay is only set once for each relation
- //printf("layer %d for relation %s to %s\n", itA->lay, ((Object *)node->ob)->id.name, ((Object *)itA->node->ob)->id.name);
+ itA->lay= flush_layer_node(sce, itA->node, curtime); // lay is only set once for each relation
}
else itA->lay= itA->node->lay;
@@ -1725,11 +1861,38 @@ static unsigned int flush_layer_node(DagNode *node, int curtime)
return node->lay;
}
+/* node was checked to have lasttime != curtime , and is of type ID_OB */
+static void flush_pointcache_reset(DagNode *node, int curtime, int reset)
+{
+ DagAdjList *itA;
+ Object *ob;
+
+ node->lasttime= curtime;
+
+ for(itA = node->child; itA; itA= itA->next) {
+ if(itA->node->type==ID_OB) {
+ if(itA->node->lasttime!=curtime) {
+ ob= (Object*)(node->ob);
+
+ if(reset || (ob->recalc & OB_RECALC)) {
+ if(BKE_ptcache_object_reset(ob, PTCACHE_RESET_DEPSGRAPH))
+ ob->recalc |= OB_RECALC_DATA;
+
+ flush_pointcache_reset(itA->node, curtime, 1);
+ }
+ else
+ flush_pointcache_reset(itA->node, curtime, 0);
+ }
+ }
+ }
+}
+
/* flushes all recalc flags in objects down the dependency tree */
-void DAG_scene_flush_update(Scene *sce, unsigned int lay)
+void DAG_scene_flush_update(Scene *sce, unsigned int lay, int time)
{
DagNode *firstnode;
DagAdjList *itA;
+ Object *ob;
int lasttime;
if(sce->theDag==NULL) {
@@ -1738,21 +1901,43 @@ void DAG_scene_flush_update(Scene *sce, unsigned int lay)
}
firstnode= sce->theDag->DagNode.first; // always scene node
+
+ for(itA = firstnode->child; itA; itA= itA->next)
+ itA->lay= 0;
/* first we flush the layer flags */
sce->theDag->time++; // so we know which nodes were accessed
lasttime= sce->theDag->time;
- for(itA = firstnode->child; itA; itA= itA->next) {
+
+ for(itA = firstnode->child; itA; itA= itA->next)
if(itA->node->lasttime!=lasttime && itA->node->type==ID_OB)
- flush_layer_node(itA->node, lasttime);
- }
+ flush_layer_node(sce, itA->node, lasttime);
/* then we use the relationships + layer info to flush update events */
sce->theDag->time++; // so we know which nodes were accessed
lasttime= sce->theDag->time;
- for(itA = firstnode->child; itA; itA= itA->next) {
- if(itA->node->lasttime!=lasttime && itA->node->type==ID_OB)
+ for(itA = firstnode->child; itA; itA= itA->next)
+ if(itA->node->lasttime!=lasttime && itA->node->type==ID_OB)
flush_update_node(itA->node, lay, lasttime);
+
+ /* if update is not due to time change, do pointcache clears */
+ if(!time) {
+ sce->theDag->time++; // so we know which nodes were accessed
+ lasttime= sce->theDag->time;
+ for(itA = firstnode->child; itA; itA= itA->next) {
+ if(itA->node->lasttime!=lasttime && itA->node->type==ID_OB) {
+ ob= (Object*)(itA->node->ob);
+
+ if(ob->recalc & OB_RECALC) {
+ if(BKE_ptcache_object_reset(ob, PTCACHE_RESET_DEPSGRAPH))
+ ob->recalc |= OB_RECALC_DATA;
+
+ flush_pointcache_reset(itA->node, lasttime, 1);
+ }
+ else
+ flush_pointcache_reset(itA->node, lasttime, 0);
+ }
+ }
}
}
@@ -1807,8 +1992,10 @@ static void dag_object_time_update_flags(Object *ob)
}
}
}
- else if(ob->scriptlink.totscript) ob->recalc |= OB_RECALC_OB;
- else if(ob->parent) {
+
+ if(ob->scriptlink.totscript) ob->recalc |= OB_RECALC_OB;
+
+ if(ob->parent) {
/* motion path or bone child */
if(ob->parent->type==OB_CURVE || ob->parent->type==OB_ARMATURE) ob->recalc |= OB_RECALC_OB;
}
@@ -1829,9 +2016,11 @@ static void dag_object_time_update_flags(Object *ob)
}
}
}
- else if(modifiers_isSoftbodyEnabled(ob)) ob->recalc |= OB_RECALC_DATA;
- else if(object_modifiers_use_time(ob)) ob->recalc |= OB_RECALC_DATA;
- else {
+
+ if(object_modifiers_use_time(ob)) ob->recalc |= OB_RECALC_DATA;
+ if((ob->pose) && (ob->pose->flag & POSE_CONSTRAINTS_TIMEDEPEND)) ob->recalc |= OB_RECALC_DATA;
+
+ {
Mesh *me;
Curve *cu;
Lattice *lt;
@@ -1845,21 +2034,6 @@ static void dag_object_time_update_flags(Object *ob)
ob->shapeflag &= ~OB_SHAPE_TEMPLOCK;
}
}
- else if(ob->effect.first) {
- Effect *eff= ob->effect.first;
- PartEff *paf= give_parteff(ob);
-
- if(eff->type==EFF_WAVE)
- ob->recalc |= OB_RECALC_DATA;
- else if(paf && paf->keys==NULL)
- ob->recalc |= OB_RECALC_DATA;
- }
- if((ob->fluidsimFlag & OB_FLUIDSIM_ENABLE) && (ob->fluidsimSettings)) {
- // fluidsimSettings might not be initialized during load...
- if(ob->fluidsimSettings->type & (OB_FLUIDSIM_DOMAIN|OB_FLUIDSIM_PARTICLE)) {
- ob->recalc |= OB_RECALC_DATA; // NT FSPARTICLE
- }
- }
if(ob->particlesystem.first)
ob->recalc |= OB_RECALC_DATA;
break;
@@ -1937,7 +2111,7 @@ void DAG_scene_update_flags(Scene *scene, unsigned int lay)
}
for(sce= scene; sce; sce= sce->set)
- DAG_scene_flush_update(sce, lay);
+ DAG_scene_flush_update(sce, lay, 1);
/* test: set time flag, to disable baked systems to update */
for(SETLOOPER(scene, base)) {
@@ -1987,7 +2161,9 @@ void DAG_object_flush_update(Scene *sce, Object *ob, short flag)
{
if(ob==NULL || sce->theDag==NULL) return;
+
ob->recalc |= flag;
+ BKE_ptcache_object_reset(ob, PTCACHE_RESET_DEPSGRAPH);
/* all users of this ob->data should be checked */
/* BUT! displists for curves are still only on cu */
@@ -2000,8 +2176,9 @@ void DAG_object_flush_update(Scene *sce, Object *ob, short flag)
else {
Object *obt;
for (obt=G.main->object.first; obt; obt= obt->id.next) {
- if (obt->data==ob->data) {
+ if (obt != ob && obt->data==ob->data) {
obt->recalc |= OB_RECALC_DATA;
+ BKE_ptcache_object_reset(obt, PTCACHE_RESET_DEPSGRAPH);
}
}
}
@@ -2010,9 +2187,9 @@ void DAG_object_flush_update(Scene *sce, Object *ob, short flag)
}
if(G.curscreen)
- DAG_scene_flush_update(sce, dag_screen_view3d_layers());
+ DAG_scene_flush_update(sce, dag_screen_view3d_layers(), 0);
else
- DAG_scene_flush_update(sce, sce->lay);
+ DAG_scene_flush_update(sce, sce->lay, 0);
}
/* recursively descends tree, each node only checked once */
@@ -2060,8 +2237,8 @@ void DAG_object_update_flags(Scene *sce, Object *ob, unsigned int lay)
/* object not in scene? then handle group exception. needs to be dagged once too */
if(node==NULL) {
- Group *group= find_group(ob);
- if(group) {
+ Group *group= NULL;
+ while( (group = find_group(ob, group)) ) {
GroupObject *go;
/* primitive; tag all... this call helps building groups for particles */
for(go= group->gobject.first; go; go= go->next)
@@ -2094,51 +2271,6 @@ void DAG_object_update_flags(Scene *sce, Object *ob, unsigned int lay)
/* ******************* DAG FOR ARMATURE POSE ***************** */
-static int node_recurs_level(DagNode *node, int level)
-{
- DagAdjList *itA;
-
- node->color= DAG_BLACK; /* done */
- level++;
-
- for(itA= node->parent; itA; itA= itA->next) {
- if(itA->node->color==DAG_WHITE)
- itA->node->ancestor_count= node_recurs_level(itA->node, level);
- }
-
- return level;
-}
-
-static void pose_check_cycle(DagForest *dag)
-{
- DagNode *node;
- DagAdjList *itA;
-
- /* tag nodes unchecked */
- for(node = dag->DagNode.first; node; node= node->next)
- node->color= DAG_WHITE;
-
- for(node = dag->DagNode.first; node; node= node->next) {
- if(node->color==DAG_WHITE) {
- node->ancestor_count= node_recurs_level(node, 0);
- }
- }
-
- /* check relations, and print errors */
- for(node = dag->DagNode.first; node; node= node->next) {
- for(itA= node->parent; itA; itA= itA->next) {
- if(itA->node->ancestor_count > node->ancestor_count) {
- bPoseChannel *pchan= (bPoseChannel *)node->ob;
- bPoseChannel *parchan= (bPoseChannel *)itA->node->ob;
-
- if(pchan && parchan)
- if(pchan->parent!=parchan)
- printf("Cycle in %s to %s\n", pchan->name, parchan->name);
- }
- }
- }
-}
-
/* we assume its an armature with pose */
void DAG_pose_sort(Object *ob)
{
@@ -2167,8 +2299,7 @@ void DAG_pose_sort(Object *ob)
if(pchan->parent) {
node2 = dag_get_node(dag, pchan->parent);
- dag_add_relation(dag, node2, node, 0);
- dag_add_parent_relation(dag, node2, node, 0);
+ dag_add_relation(dag, node2, node, 0, "Parent Relation");
addtoroot = 0;
}
for (con = pchan->constraints.first; con; con=con->next) {
@@ -2179,12 +2310,14 @@ void DAG_pose_sort(Object *ob)
if(con->ipo) {
IpoCurve *icu;
for(icu= con->ipo->curve.first; icu; icu= icu->next) {
- if(icu->driver && icu->driver->ob==ob) {
+ /* icu->driver->ob should actually point to ob->proxy if it
+ * is a proxy, but since it wasn't set correct it older
+ * files comparing with ob->proxy makes it work for those */
+ if(icu->driver && (icu->driver->ob==ob || icu->driver->ob==ob->proxy)) {
bPoseChannel *target= get_pose_channel(ob->pose, icu->driver->name);
if(target) {
node2 = dag_get_node(dag, target);
- dag_add_relation(dag, node2, node, 0);
- dag_add_parent_relation(dag, node2, node, 0);
+ dag_add_relation(dag, node2, node, 0, "Ipo Driver");
/* uncommented this line, results in dependencies
* not being added properly for this constraint,
@@ -2203,9 +2336,8 @@ void DAG_pose_sort(Object *ob)
bPoseChannel *target= get_pose_channel(ob->pose, ct->subtarget);
if (target) {
node2= dag_get_node(dag, target);
- dag_add_relation(dag, node2, node, 0);
- dag_add_parent_relation(dag, node2, node, 0);
-
+ dag_add_relation(dag, node2, node, 0, "IK Constraint");
+
if (con->type==CONSTRAINT_TYPE_KINEMATIC) {
bKinematicConstraint *data = (bKinematicConstraint *)con->data;
bPoseChannel *parchan;
@@ -2220,8 +2352,7 @@ void DAG_pose_sort(Object *ob)
/* Walk to the chain's root */
while (parchan) {
node3= dag_get_node(dag, parchan);
- dag_add_relation(dag, node2, node3, 0);
- dag_add_parent_relation(dag, node2, node3, 0);
+ dag_add_relation(dag, node2, node3, 0, "IK Constraint");
segcount++;
if (segcount==data->rootbone || segcount>255) break; // 255 is weak
@@ -2237,12 +2368,11 @@ void DAG_pose_sort(Object *ob)
}
}
if (addtoroot == 1 ) {
- dag_add_relation(dag, rootnode, node, 0);
- dag_add_parent_relation(dag, rootnode, node, 0);
+ dag_add_relation(dag, rootnode, node, 0, "Root Bone Relation");
}
}
- pose_check_cycle(dag);
+ dag_check_cycle(dag);
/* now we try to sort... */
tempbase.first= tempbase.last= NULL;
diff --git a/source/blender/blenkernel/intern/displist.c b/source/blender/blenkernel/intern/displist.c
index 6071ce1c871..44aa439ee3e 100644
--- a/source/blender/blenkernel/intern/displist.c
+++ b/source/blender/blenkernel/intern/displist.c
@@ -87,6 +87,8 @@
#include "RE_pipeline.h"
#include "RE_shader_ext.h"
+#include "BLO_sys_types.h" // for intptr_t support
+
static void boundbox_displist(Object *ob);
@@ -203,8 +205,9 @@ void addnormalsDispList(Object *ob, ListBase *lb)
ndata= dl->nors;
for(a=0; a<dl->parts; a++) {
-
- DL_SURFINDEX(dl->flag & DL_CYCL_U, dl->flag & DL_CYCL_V, dl->nr, dl->parts);
+
+ if (surfindex_displist(dl, a, &b, &p1, &p2, &p3, &p4)==0)
+ break;
v1= vdata+ 3*p1;
n1= ndata+ 3*p1;
@@ -268,6 +271,33 @@ void count_displist(ListBase *lb, int *totvert, int *totface)
}
}
+int surfindex_displist(DispList *dl, int a, int *b, int *p1, int *p2, int *p3, int *p4)
+{
+ if((dl->flag & DL_CYCL_V)==0 && a==(dl->parts)-1) {
+ return 0;
+ }
+
+ if(dl->flag & DL_CYCL_U) {
+ (*p1)= dl->nr*a;
+ (*p2)= (*p1)+ dl->nr-1;
+ (*p3)= (*p1)+ dl->nr;
+ (*p4)= (*p2)+ dl->nr;
+ (*b)= 0;
+ } else {
+ (*p2)= dl->nr*a;
+ (*p1)= (*p2)+1;
+ (*p4)= (*p2)+ dl->nr;
+ (*p3)= (*p1)+ dl->nr;
+ (*b)= 1;
+ }
+
+ if( (dl->flag & DL_CYCL_V) && a==dl->parts-1) { \
+ (*p3)-= dl->nr*dl->parts; \
+ (*p4)-= dl->nr*dl->parts; \
+ }
+
+ return 1;
+}
/* ***************************** shade displist. note colors now are in rgb(a) order ******************** */
@@ -758,7 +788,10 @@ void reshadeall_displist(void)
for(base= G.scene->base.first; base; base= base->next) {
ob= base->object;
- freedisplist(&ob->disp);
+
+ if(ELEM5(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL))
+ freedisplist(&ob->disp);
+
if(base->lay & G.scene->lay) {
/* Metaballs have standard displist at the Object */
if(ob->type==OB_MBALL) shadeDispList(base);
@@ -786,7 +819,7 @@ static void curve_to_displist(Curve *cu, ListBase *nubase, ListBase *dispbase)
else
resolu= nu->resolu;
- if(nu->pntsu<2);
+ if(!check_valid_nurb_u(nu));
else if((nu->type & 7)==CU_BEZIER) {
/* count */
@@ -819,7 +852,7 @@ static void curve_to_displist(Curve *cu, ListBase *nubase, ListBase *dispbase)
data= dl->verts;
- if(nu->flagu & 1) {
+ if(nu->flagu & CU_CYCLIC) {
dl->type= DL_POLY;
a= nu->pntsu;
}
@@ -856,19 +889,22 @@ static void curve_to_displist(Curve *cu, ListBase *nubase, ListBase *dispbase)
}
}
else if((nu->type & 7)==CU_NURBS) {
- len= nu->pntsu*resolu;
+ len= (resolu*SEGMENTSU(nu));
+ if((nu->flagu & CU_CYCLIC)==0) len++;
+
dl= MEM_callocN(sizeof(DispList), "makeDispListsurf");
dl->verts= MEM_callocN(len*3*sizeof(float), "dlverts");
BLI_addtail(dispbase, dl);
dl->parts= 1;
+
dl->nr= len;
dl->col= nu->mat_nr;
dl->charidx = nu->charidx;
data= dl->verts;
- if(nu->flagu & 1) dl->type= DL_POLY;
+ if(nu->flagu & CU_CYCLIC) dl->type= DL_POLY;
else dl->type= DL_SEGM;
- makeNurbcurve(nu, data, resolu, 3);
+ makeNurbcurve(nu, data, NULL, NULL, resolu);
}
else if((nu->type & 7)==CU_POLY) {
len= nu->pntsu;
@@ -881,7 +917,7 @@ static void curve_to_displist(Curve *cu, ListBase *nubase, ListBase *dispbase)
dl->charidx = nu->charidx;
data= dl->verts;
- if(nu->flagu & 1) dl->type= DL_POLY;
+ if(nu->flagu & CU_CYCLIC) dl->type= DL_POLY;
else dl->type= DL_SEGM;
a= len;
@@ -989,9 +1025,9 @@ void filldisplist(ListBase *dispbase, ListBase *to)
efa= fillfacebase.first;
index= dlnew->index;
while(efa) {
- index[0]= (long)efa->v1->tmp.l;
- index[1]= (long)efa->v2->tmp.l;
- index[2]= (long)efa->v3->tmp.l;
+ index[0]= (intptr_t)efa->v1->tmp.l;
+ index[1]= (intptr_t)efa->v2->tmp.l;
+ index[2]= (intptr_t)efa->v3->tmp.l;
index+= 3;
efa= efa->next;
@@ -1174,7 +1210,7 @@ static ModifierData *curve_get_tesselate_point(Object *ob, int forRender, int ed
if ((md->mode & required_mode) != required_mode) continue;
if (mti->isDisabled && mti->isDisabled(md)) continue;
- if (md->type==eModifierType_Hook || md->type==eModifierType_Softbody) {
+ if (ELEM3(md->type, eModifierType_Hook, eModifierType_Softbody, eModifierType_MeshDeform)) {
preTesselatePoint = md;
}
}
@@ -1231,7 +1267,7 @@ void curve_calc_modifiers_pre(Object *ob, ListBase *nurb, int forRender, float (
*numVerts_r = numVerts;
}
-void curve_calc_modifiers_post(Object *ob, ListBase *nurb, ListBase *dispbase, int forRender, float (*originalVerts)[3], float (*deformedVerts)[3])
+static void curve_calc_modifiers_post(Object *ob, ListBase *nurb, ListBase *dispbase, int forRender, float (*originalVerts)[3], float (*deformedVerts)[3])
{
int editmode = (!forRender && ob==G.obedit);
ModifierData *md = modifiers_getVirtualModifierList(ob);
@@ -1250,13 +1286,40 @@ void curve_calc_modifiers_post(Object *ob, ListBase *nurb, ListBase *dispbase, i
for (; md; md=md->next) {
ModifierTypeInfo *mti = modifierType_getInfo(md->type);
-
+
if ((md->mode & required_mode) != required_mode) continue;
if (mti->isDisabled && mti->isDisabled(md)) continue;
if (mti->type!=eModifierTypeType_OnlyDeform && mti->type!=eModifierTypeType_DeformOrConstruct) continue;
- for (dl=dispbase->first; dl; dl=dl->next) {
- mti->deformVerts(md, ob, NULL, (float(*)[3]) dl->verts, (dl->type==DL_INDEX3)?dl->nr:dl->parts*dl->nr);
+ /* need to put all verts in 1 block for curve deform */
+ if(md->type==eModifierType_Curve) {
+ float *allverts, *fp;
+ int totvert= 0;
+
+ for (dl=dispbase->first; dl; dl=dl->next)
+ totvert+= (dl->type==DL_INDEX3)?dl->nr:dl->parts*dl->nr;
+
+ fp= allverts= MEM_mallocN(totvert*sizeof(float)*3, "temp vert");
+ for (dl=dispbase->first; dl; dl=dl->next) {
+ int offs= 3 * ((dl->type==DL_INDEX3)?dl->nr:dl->parts*dl->nr);
+ memcpy(fp, dl->verts, sizeof(float) * offs);
+ fp+= offs;
+ }
+
+ mti->deformVerts(md, ob, NULL, (float(*)[3]) allverts, totvert);
+
+ fp= allverts;
+ for (dl=dispbase->first; dl; dl=dl->next) {
+ int offs= 3 * ((dl->type==DL_INDEX3)?dl->nr:dl->parts*dl->nr);
+ memcpy(dl->verts, fp, sizeof(float) * offs);
+ fp+= offs;
+ }
+ MEM_freeN(allverts);
+ }
+ else {
+ for (dl=dispbase->first; dl; dl=dl->next) {
+ mti->deformVerts(md, ob, NULL, (float(*)[3]) dl->verts, (dl->type==DL_INDEX3)?dl->nr:dl->parts*dl->nr);
+ }
}
}
@@ -1278,7 +1341,8 @@ static void displist_surf_indices(DispList *dl)
for(a=0; a<dl->parts; a++) {
- DL_SURFINDEX(dl->flag & DL_CYCL_U, dl->flag & DL_CYCL_V, dl->nr, dl->parts);
+ if (surfindex_displist(dl, a, &b, &p1, &p2, &p3, &p4)==0)
+ break;
for(; b<dl->nr; b++, index+=4) {
index[0]= p1;
@@ -1333,13 +1397,13 @@ void makeDispListSurf(Object *ob, ListBase *dispbase, int forRender)
dl->rt= nu->flag;
data= dl->verts;
- if(nu->flagu & 1) dl->type= DL_POLY;
+ if(nu->flagu & CU_CYCLIC) dl->type= DL_POLY;
else dl->type= DL_SEGM;
- makeNurbcurve(nu, data, nu->resolu, 3);
+ makeNurbcurve(nu, data, NULL, NULL, nu->resolu);
}
else {
- len= nu->resolu*nu->resolv;
+ len= (nu->pntsu*nu->resolu) * (nu->pntsv*nu->resolv);
dl= MEM_callocN(sizeof(DispList), "makeDispListsurf");
dl->verts= MEM_callocN(len*3*sizeof(float), "dlverts");
@@ -1351,9 +1415,9 @@ void makeDispListSurf(Object *ob, ListBase *dispbase, int forRender)
data= dl->verts;
dl->type= DL_SURF;
-
- dl->parts= nu->resolu; /* in reverse, because makeNurbfaces works that way */
- dl->nr= nu->resolv;
+
+ dl->parts= (nu->pntsu*nu->resolu); /* in reverse, because makeNurbfaces works that way */
+ dl->nr= (nu->pntsv*nu->resolv);
if(nu->flagv & CU_CYCLIC) dl->flag|= DL_CYCL_U; /* reverse too! */
if(nu->flagu & CU_CYCLIC) dl->flag|= DL_CYCL_V;
@@ -1483,7 +1547,7 @@ void makeDispListCurveTypes(Object *ob, int forOrco)
float fac=1.0;
if (cu->taperobj==NULL) {
if ( (cu->bevobj!=NULL) || !((cu->flag & CU_FRONT) || (cu->flag & CU_BACK)) )
- fac = calc_curve_subdiv_radius(cu, nu, a);
+ fac = bevp->radius;
} else {
fac = calc_taper(cu->taperobj, a, bl->nr);
}
diff --git a/source/blender/blenkernel/intern/effect.c b/source/blender/blenkernel/intern/effect.c
index 881e67eef8a..66e8a039dda 100644
--- a/source/blender/blenkernel/intern/effect.c
+++ b/source/blender/blenkernel/intern/effect.c
@@ -58,6 +58,7 @@
#include "BKE_anim.h" /* needed for where_on_path */
#include "BKE_armature.h"
#include "BKE_blender.h"
+#include "BKE_collision.h"
#include "BKE_constraint.h"
#include "BKE_deform.h"
#include "BKE_depsgraph.h"
@@ -98,43 +99,19 @@ typedef struct VeNoCo {
float co[3], no[3];
} VeNoCo;
-Effect *add_effect(int type)
+/* ***************** PARTICLES ***************** */
+
+/* deprecated, only keep this for readfile.c */
+PartEff *give_parteff(Object *ob)
{
- Effect *eff=0;
PartEff *paf;
- int a;
- switch(type) {
- case EFF_PARTICLE:
- paf= MEM_callocN(sizeof(PartEff), "neweff");
- eff= (Effect *)paf;
-
- paf->sta= 1.0;
- paf->end= 100.0;
- paf->lifetime= 50.0;
- for(a=0; a<PAF_MAXMULT; a++) {
- paf->life[a]= 50.0;
- paf->child[a]= 4;
- paf->mat[a]= 1;
- }
-
- paf->totpart= 1000;
- paf->totkey= 8;
- paf->staticstep= 5;
- paf->defvec[2]= 1.0f;
- paf->nabla= 0.05f;
- paf->disp = 100;
- paf->speedtex = 8;
- paf->omat = 1;
- paf->flag= PAF_FACE;
-
- break;
+ paf= ob->effect.first;
+ while(paf) {
+ if(paf->type==EFF_PARTICLE) return paf;
+ paf= paf->next;
}
-
- eff->type= eff->buttype= type;
- eff->flag |= SELECT;
-
- return eff;
+ return 0;
}
void free_effect(Effect *eff)
@@ -161,172 +138,6 @@ void free_effects(ListBase *lb)
}
}
-Effect *copy_effect(Effect *eff)
-{
- Effect *effn;
-
- effn= MEM_dupallocN(eff);
- if(effn->type==EFF_PARTICLE) ((PartEff *)effn)->keys= 0;
-
- return effn;
-}
-
-void copy_act_effect(Object *ob)
-{
- /* return a copy of the active effect */
- Effect *effn, *eff;
-
- eff= ob->effect.first;
- while(eff) {
- if(eff->flag & SELECT) {
-
- effn= copy_effect(eff);
- BLI_addtail(&ob->effect, effn);
-
- eff->flag &= ~SELECT;
- return;
-
- }
- eff= eff->next;
- }
-
- /* when it comes here: add new effect */
- eff= add_effect(EFF_PARTICLE);
- BLI_addtail(&ob->effect, eff);
-
-}
-
-void copy_effects(ListBase *lbn, ListBase *lb)
-{
- Effect *eff, *effn;
-
- lbn->first= lbn->last= 0;
-
- eff= lb->first;
- while(eff) {
- effn= copy_effect(eff);
- BLI_addtail(lbn, effn);
-
- eff= eff->next;
- }
-
-}
-
-void deselectall_eff(Object *ob)
-{
- Effect *eff= ob->effect.first;
-
- while(eff) {
- eff->flag &= ~SELECT;
- eff= eff->next;
- }
-}
-
-/* ***************** PARTICLES ***************** */
-
-static Particle *new_particle(PartEff *paf)
-{
- static Particle *pa;
- static int cur;
-
- /* we agree: when paf->keys==0: alloc */
- if(paf->keys==NULL) {
- pa= paf->keys= MEM_callocN( paf->totkey*paf->totpart*sizeof(Particle), "particlekeys" );
- cur= 0;
- }
- else {
- if(cur && cur<paf->totpart) pa+=paf->totkey;
- cur++;
- }
- return pa;
-}
-
-PartEff *give_parteff(Object *ob)
-{
- PartEff *paf;
-
- paf= ob->effect.first;
- while(paf) {
- if(paf->type==EFF_PARTICLE) return paf;
- paf= paf->next;
- }
- return 0;
-}
-
-void where_is_particle(PartEff *paf, Particle *pa, float ctime, float *vec)
-{
- Particle *p[4];
- float dt, t[4];
- int a;
-
- if(paf->totkey==1 || ctime < pa->time) {
- VECCOPY(vec, pa->co);
- return;
- }
-
- /* first find the first particlekey */
- a= (int)((paf->totkey-1)*(ctime-pa->time)/pa->lifetime);
- if(a>=paf->totkey) a= paf->totkey-1;
- else if(a<0) a= 0;
-
- pa+= a;
-
- if(a>0) p[0]= pa-1; else p[0]= pa;
- p[1]= pa;
-
- if(a+1<paf->totkey) p[2]= pa+1; else p[2]= pa;
- if(a+2<paf->totkey) p[3]= pa+2; else p[3]= p[2];
-
- if(p[1]==p[2] || p[2]->time == p[1]->time) dt= 0.0;
- else dt= (ctime-p[1]->time)/(p[2]->time - p[1]->time);
-
- if(paf->flag & PAF_BSPLINE) set_four_ipo(dt, t, KEY_BSPLINE);
- else set_four_ipo(dt, t, KEY_CARDINAL);
-
- vec[0]= t[0]*p[0]->co[0] + t[1]*p[1]->co[0] + t[2]*p[2]->co[0] + t[3]*p[3]->co[0];
- vec[1]= t[0]*p[0]->co[1] + t[1]*p[1]->co[1] + t[2]*p[2]->co[1] + t[3]*p[3]->co[1];
- vec[2]= t[0]*p[0]->co[2] + t[1]*p[1]->co[2] + t[2]*p[2]->co[2] + t[3]*p[3]->co[2];
-
-}
-
-static void particle_tex(MTex *mtex, PartEff *paf, float *co, float *no)
-{
- float tin, tr, tg, tb, ta;
- float old;
-
- externtex(mtex, co, &tin, &tr, &tg, &tb, &ta);
-
- if(paf->texmap==PAF_TEXINT) {
- tin*= paf->texfac;
- no[0]+= tin*paf->defvec[0];
- no[1]+= tin*paf->defvec[1];
- no[2]+= tin*paf->defvec[2];
- }
- else if(paf->texmap==PAF_TEXRGB) {
- no[0]+= (tr-0.5f)*paf->texfac;
- no[1]+= (tg-0.5f)*paf->texfac;
- no[2]+= (tb-0.5f)*paf->texfac;
- }
- else { /* PAF_TEXGRAD */
-
- old= tin;
- co[0]+= paf->nabla;
- externtex(mtex, co, &tin, &tr, &tg, &tb, &ta);
- no[0]+= (old-tin)*paf->texfac;
-
- co[0]-= paf->nabla;
- co[1]+= paf->nabla;
- externtex(mtex, co, &tin, &tr, &tg, &tb, &ta);
- no[1]+= (old-tin)*paf->texfac;
-
- co[1]-= paf->nabla;
- co[2]+= paf->nabla;
- externtex(mtex, co, &tin, &tr, &tg, &tb, &ta);
- no[2]+= (old-tin)*paf->texfac;
-
- }
-}
-
/* -------------------------- Effectors ------------------ */
static void add_to_effectorcache(ListBase *lb, Object *ob, Object *obsrc)
@@ -349,6 +160,13 @@ static void add_to_effectorcache(ListBase *lb, Object *ob, Object *obsrc)
}
}
else if(pd->forcefield) {
+
+ if(pd->forcefield == PFIELD_WIND)
+ {
+ pd->rng = rng_new(1);
+ rng_srandom(pd->rng, (unsigned int)(ceil(PIL_check_seconds_timer()))); // use better seed
+ }
+
ec= MEM_callocN(sizeof(pEffectorCache), "effector cache");
ec->ob= ob;
BLI_addtail(lb, ec);
@@ -397,1713 +215,354 @@ void pdEndEffectors(ListBase *lb)
pEffectorCache *ec;
/* restore full copy */
for(ec= lb->first; ec; ec= ec->next)
+ {
+ if(ec->ob->pd && (ec->ob->pd->forcefield == PFIELD_WIND))
+ rng_free(ec->ob->pd->rng);
+
*(ec->ob)= ec->obcopy;
+ }
BLI_freelistN(lb);
}
}
-/* local for this c file, only for guides now */
-static void precalc_effectors(Object *ob, PartEff *paf, Particle *pa, ListBase *lb)
-{
- pEffectorCache *ec;
-
- for(ec= lb->first; ec; ec= ec->next) {
- PartDeflect *pd= ec->ob->pd;
-
- ec->oldspeed[0]= ec->oldspeed[1]= ec->oldspeed[2]= 0.0f;
-
- if(pd->forcefield==PFIELD_GUIDE && ec->ob->type==OB_CURVE) {
- float vec[4], dir[3];
-
- if(!(paf->flag & PAF_STATIC))
- where_is_object_time(ec->ob, pa->time);
-
- /* scale corrects speed vector to curve size */
- if(paf->totkey>1) ec->scale= (paf->totkey-1)/pa->lifetime;
- else ec->scale= 1.0f;
-
- /* time_scale is for random life */
- if(pa->lifetime>paf->lifetime)
- ec->time_scale= paf->lifetime/pa->lifetime;
- else
- ec->time_scale= pa->lifetime/paf->lifetime;
-
- /* distance of first path point to particle origin */
- where_on_path(ec->ob, 0.0f, vec, dir);
- VECCOPY(ec->oldloc, vec); /* store local coord for differences */
- Mat4MulVecfl(ec->ob->obmat, vec);
-
- /* for static we need to move to global space */
- if(paf->flag & PAF_STATIC) {
- VECCOPY(dir, pa->co);
- Mat4MulVecfl(ob->obmat, dir);
- ec->guide_dist= VecLenf(vec, dir);
- }
- else
- ec->guide_dist= VecLenf(vec, pa->co);
- }
- }
-}
+/************************************************/
+/* Effectors */
+/************************************************/
-/* -------- pdDoEffectors() --------
- generic force/speed system, now used for particles and softbodies
- lb = listbase with objects that take part in effecting
- opco = global coord, as input
- force = force accumulator
- speed = actual current speed which can be altered
- cur_time = "external" time in frames, is constant for static particles
- loc_time = "local" time in frames, range <0-1> for the lifetime of particle
- par_layer = layer the caller is in
- flags = only used for softbody wind now
- guide = old speed of particle
+// triangle - ray callback function
+static void eff_tri_ray_hit(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
+{
+ // whenever we hit a bounding box, we don't check further
+ hit->dist = -1;
+ hit->index = 1;
+}
-*/
-void pdDoEffectors(ListBase *lb, float *opco, float *force, float *speed, float cur_time, float loc_time, unsigned int flags)
+// get visibility of a wind ray
+static float eff_calc_visibility(Object *ob, float *co, float *dir)
{
-/*
- Modifies the force on a particle according to its
- relation with the effector object
- Different kind of effectors include:
- Forcefields: Gravity-like attractor
- (force power is related to the inverse of distance to the power of a falloff value)
- Vortex fields: swirling effectors
- (particles rotate around Z-axis of the object. otherwise, same relation as)
- (Forcefields, but this is not done through a force/acceleration)
- Guide: particles on a path
- (particles are guided along a curve bezier or old nurbs)
- (is independent of other effectors)
-*/
- Object *ob;
- pEffectorCache *ec;
- PartDeflect *pd;
- float vect_to_vert[3];
- float f_force, force_vec[3];
- float *obloc;
- float distance, force_val, ffall_val;
- float guidecollect[3], guidedist= 0.0f;
- int cur_frame;
+ CollisionModifierData **collobjs = NULL;
+ int numcollobj = 0, i;
+ float norm[3], len = 0.0;
+ float visibility = 1.0;
- guidecollect[0]= guidecollect[1]= guidecollect[2]=0.0f;
-
- /* Cycle through collected objects, get total of (1/(gravity_strength * dist^gravity_power)) */
- /* Check for min distance here? (yes would be cool to add that, ton) */
+ collobjs = get_collisionobjects(ob, &numcollobj);
- for(ec = lb->first; ec; ec= ec->next) {
- /* object effectors were fully checked to be OK to evaluate! */
- ob= ec->ob;
- pd= ob->pd;
-
- /* Get IPO force strength and fall off values here */
- if (has_ipo_code(ob->ipo, OB_PD_FSTR))
- force_val = IPO_GetFloatValue(ob->ipo, OB_PD_FSTR, cur_time);
- else
- force_val = pd->f_strength;
+ if(!collobjs)
+ return 0;
+
+ VECCOPY(norm, dir);
+ VecMulf(norm, -1.0);
+ len = Normalize(norm);
+
+ // check all collision objects
+ for(i = 0; i < numcollobj; i++)
+ {
+ CollisionModifierData *collmd = collobjs[i];
- if (has_ipo_code(ob->ipo, OB_PD_FFALL))
- ffall_val = IPO_GetFloatValue(ob->ipo, OB_PD_FFALL, cur_time);
- else
- ffall_val = pd->f_power;
+ if(collmd->bvhtree)
+ {
+ BVHTreeRayHit hit;
- /* Need to set r.cfra for paths (investigate, ton) (uses ob->ctime now, ton) */
- if(ob->ctime!=cur_time) {
- cur_frame = G.scene->r.cfra;
- G.scene->r.cfra = (int)cur_time;
- where_is_object_time(ob, cur_time);
- G.scene->r.cfra = cur_frame;
- }
-
- /* use center of object for distance calculus */
- obloc= ob->obmat[3];
- VECSUB(vect_to_vert, obloc, opco);
- distance = VecLength(vect_to_vert);
+ hit.index = -1;
+ hit.dist = len + FLT_EPSILON;
- if((pd->flag & PFIELD_USEMAX) && distance>pd->maxdist && pd->forcefield != PFIELD_GUIDE)
- ; /* don't do anything */
- else if(pd->forcefield == PFIELD_WIND) {
- VECCOPY(force_vec, ob->obmat[2]);
-
- /* wind works harder perpendicular to normal, would be nice for softbody later (ton) */
-
- /* Limit minimum distance to vertex so that */
- /* the force is not too big */
- if (distance < 0.001) distance = 0.001f;
- f_force = (force_val)*(1/(1000 * (float)pow((double)distance, (double)ffall_val)));
- /* this option for softbody only */
- if(flags && PE_WIND_AS_SPEED){
- speed[0] -= (force_vec[0] * f_force );
- speed[1] -= (force_vec[1] * f_force );
- speed[2] -= (force_vec[2] * f_force );
- }
- else{
- force[0] += force_vec[0]*f_force;
- force[1] += force_vec[1]*f_force;
- force[2] += force_vec[2]*f_force;
- }
- }
- else if(pd->forcefield == PFIELD_FORCE) {
-
- /* only use center of object */
- obloc= ob->obmat[3];
-
- /* Now calculate the gravitational force */
- VECSUB(vect_to_vert, obloc, opco);
- distance = VecLength(vect_to_vert);
-
- /* Limit minimum distance to vertex so that */
- /* the force is not too big */
- if (distance < 0.001) distance = 0.001f;
- f_force = (force_val)*(1.0/(1000.0 * (float)pow((double)distance, (double)ffall_val)));
- force[0] += (vect_to_vert[0] * f_force );
- force[1] += (vect_to_vert[1] * f_force );
- force[2] += (vect_to_vert[2] * f_force );
- }
- else if(pd->forcefield == PFIELD_VORTEX) {
- float vortexvec[3];
-
- /* only use center of object */
- obloc= ob->obmat[3];
-
- /* Now calculate the vortex force */
- VECSUB(vect_to_vert, obloc, opco);
- distance = VecLength(vect_to_vert);
-
- Crossf(force_vec, ob->obmat[2], vect_to_vert);
- Normalize(force_vec);
-
- /* Limit minimum distance to vertex so that */
- /* the force is not too big */
- if (distance < 0.001) distance = 0.001f;
- f_force = (force_val)*(1.0/(100.0 * (float)pow((double)distance, (double)ffall_val)));
- vortexvec[0]= -(force_vec[0] * f_force );
- vortexvec[1]= -(force_vec[1] * f_force );
- vortexvec[2]= -(force_vec[2] * f_force );
-
- /* this option for softbody only */
- if(flags &&PE_WIND_AS_SPEED) {
- speed[0]+= vortexvec[0];
- speed[1]+= vortexvec[1];
- speed[2]+= vortexvec[2];
- }
- else {
- /* since vortex alters the speed, we have to correct for the previous vortex result */
- speed[0]+= vortexvec[0] - ec->oldspeed[0];
- speed[1]+= vortexvec[1] - ec->oldspeed[1];
- speed[2]+= vortexvec[2] - ec->oldspeed[2];
+ // check if the way is blocked
+ if(BLI_bvhtree_ray_cast(collmd->bvhtree, co, norm, 0.0f, &hit, eff_tri_ray_hit, NULL)>=0)
+ {
+ // visibility is only between 0 and 1, calculated from 1-absorption
+ visibility *= MAX2(0.0, MIN2(1.0, (1.0-((float)collmd->absorption)*0.01)));
- VECCOPY(ec->oldspeed, vortexvec);
+ if(visibility <= 0.0f)
+ break;
}
}
- else if(pd->forcefield == PFIELD_GUIDE) {
- float guidevec[4], guidedir[3];
- float mindist= force_val; /* force_val is actually mindist in the UI */
-
- distance= ec->guide_dist;
-
- /* WARNING: bails out with continue here */
- if((pd->flag & PFIELD_USEMAX) && distance>pd->maxdist) continue;
-
- /* calculate contribution factor for this guide */
- if(distance<=mindist) f_force= 1.0f;
- else if(pd->flag & PFIELD_USEMAX) {
- if(distance>pd->maxdist || mindist>=pd->maxdist) f_force= 0.0f;
- else {
- f_force= 1.0f - (distance-mindist)/(pd->maxdist - mindist);
- if(ffall_val!=0.0f)
- f_force = (float)pow(f_force, ffall_val+1.0);
- }
- }
- else {
- f_force= 1.0f/(1.0f + distance-mindist);
- if(ffall_val!=0.0f)
- f_force = (float)pow(f_force, ffall_val+1.0);
- }
-
- /* now derive path point from loc_time */
- if(pd->flag & PFIELD_GUIDE_PATH_ADD)
- where_on_path(ob, f_force*loc_time*ec->time_scale, guidevec, guidedir);
- else
- where_on_path(ob, loc_time*ec->time_scale, guidevec, guidedir);
-
- VECSUB(guidedir, guidevec, ec->oldloc);
- VECCOPY(ec->oldloc, guidevec);
-
- Mat4Mul3Vecfl(ob->obmat, guidedir);
- VecMulf(guidedir, ec->scale); /* correction for lifetime and speed */
-
- /* we subtract the speed we gave it previous step */
- VECCOPY(guidevec, guidedir);
- VECSUB(guidedir, guidedir, ec->oldspeed);
- VECCOPY(ec->oldspeed, guidevec);
-
- /* if it fully contributes, we stop */
- if(f_force==1.0) {
- VECCOPY(guidecollect, guidedir);
- guidedist= 1.0f;
- break;
- }
- else if(guidedist<1.0f) {
- VecMulf(guidedir, f_force);
- VECADD(guidecollect, guidecollect, guidedir);
- guidedist += f_force;
- }
- }
- }
-
- /* all guides are accumulated here */
- if(guidedist!=0.0f) {
- if(guidedist!=1.0f) VecMulf(guidecollect, 1.0f/guidedist);
- VECADD(speed, speed, guidecollect);
}
-}
-
-static void cache_object_vertices(Object *ob)
-{
- Mesh *me;
- MVert *mvert;
- float *fp;
- int a;
- me= ob->data;
- if(me->totvert==0) return;
-
- fp= ob->sumohandle= MEM_mallocN(3*sizeof(float)*me->totvert, "cache particles");
- mvert= me->mvert;
- a= me->totvert;
- while(a--) {
- VECCOPY(fp, mvert->co);
- Mat4MulVecfl(ob->obmat, fp);
- mvert++;
- fp+= 3;
- }
+ MEM_freeN(collobjs);
+
+ return visibility;
}
-static int pdDoDeflection(RNG *rng, float opco[3], float npco[3], float opno[3],
- float npno[3], float life, float force[3], int def_depth,
- float cur_time, unsigned int par_layer, int *last_object,
- int *last_face, int *same_face)
+// noise function for wind e.g.
+static float wind_func(struct RNG *rng, float strength)
{
- /* Particle deflection code */
- /* The code is in two sections: the first part checks whether a particle has */
- /* intersected a face of a deflector mesh, given its old and new co-ords, opco and npco */
- /* and which face it hit first */
- /* The second part calculates the new co-ordinates given that collision and updates */
- /* the new co-ordinates accordingly */
- Base *base;
- Object *ob, *deflection_object = NULL;
- Mesh *def_mesh;
- MFace *mface, *deflection_face = NULL;
- float *v1, *v2, *v3, *v4, *vcache=NULL;
- float nv1[3], nv2[3], nv3[3], nv4[3], edge1[3], edge2[3];
- float dv1[3] = {0}, dv2[3] = {0}, dv3[3] = {0};
- float vect_to_int[3], refl_vel[3];
- float d_intersect_co[3], d_intersect_vect[3], d_nvect[3], d_i_co_above[3];
- float forcec[3];
- float k_point3, dist_to_plane;
- float first_dist, ref_plane_mag;
- float dk_plane=0, dk_point1=0;
- float icalctop, icalcbot, n_mag;
- float mag_iv, x_m,y_m,z_m;
- float damping, perm_thresh;
- float perm_val, rdamp_val;
- int a, deflected=0, deflected_now=0;
- float t,t2, min_t;
- float mat[3][3], obloc[3] = {0};
- int cur_frame;
- float time_before, time_after;
- float force_mag_norm;
- int d_object=0, d_face=0, ds_object=0, ds_face=0;
-
- first_dist = 200000;
- min_t = 200000;
-
- /* The first part of the code, finding the first intersected face*/
- base= G.scene->base.first;
- while (base) {
- /*Only proceed for mesh object in same layer */
- if(base->object->type==OB_MESH && (base->lay & par_layer)) {
- ob= base->object;
- /* only with deflecting set */
- if(ob->pd && ob->pd->deflect) {
- def_mesh= ob->data;
-
- d_object = d_object + 1;
-
- d_face = d_face + 1;
- mface= def_mesh->mface;
- a = def_mesh->totface;
-
-
- if(ob->parent==NULL && ob->ipo==NULL) { // static
- if(ob->sumohandle==NULL) cache_object_vertices(ob);
- vcache= ob->sumohandle;
- }
- else {
- /*Find out where the object is at this time*/
- cur_frame = G.scene->r.cfra;
- G.scene->r.cfra = (int)cur_time;
- where_is_object_time(ob, cur_time);
- G.scene->r.cfra = cur_frame;
-
- /*Pass the values from ob->obmat to mat*/
- /*and the location values to obloc */
- Mat3CpyMat4(mat,ob->obmat);
- obloc[0] = ob->obmat[3][0];
- obloc[1] = ob->obmat[3][1];
- obloc[2] = ob->obmat[3][2];
- vcache= NULL;
-
- }
-
- while (a--) {
-
- if(vcache) {
- v1= vcache+ 3*(mface->v1);
- VECCOPY(nv1, v1);
- v1= vcache+ 3*(mface->v2);
- VECCOPY(nv2, v1);
- v1= vcache+ 3*(mface->v3);
- VECCOPY(nv3, v1);
- v1= vcache+ 3*(mface->v4);
- VECCOPY(nv4, v1);
- }
- else {
- /* Calculate the global co-ordinates of the vertices*/
- v1= (def_mesh->mvert+(mface->v1))->co;
- v2= (def_mesh->mvert+(mface->v2))->co;
- v3= (def_mesh->mvert+(mface->v3))->co;
- v4= (def_mesh->mvert+(mface->v4))->co;
+ int random = (rng_getInt(rng)+1) % 65535; // max 2357
+ float force = rng_getFloat(rng) + 1.0f;
+ float ret;
+ float sign = 0;
- VECCOPY(nv1, v1);
- VECCOPY(nv2, v2);
- VECCOPY(nv3, v3);
- VECCOPY(nv4, v4);
+ sign = (random > 32000.0) ? 1.0: -1.0; // dividing by 2 is not giving equal sign distribution
- /*Apply the objects deformation matrix*/
- Mat3MulVecfl(mat, nv1);
- Mat3MulVecfl(mat, nv2);
- Mat3MulVecfl(mat, nv3);
- Mat3MulVecfl(mat, nv4);
+ ret = sign*((float)random / force)*strength/65535.0f;
- VECADD(nv1, nv1, obloc);
- VECADD(nv2, nv2, obloc);
- VECADD(nv3, nv3, obloc);
- VECADD(nv4, nv4, obloc);
- }
-
- deflected_now = 0;
-
-
-
-// t= 0.5; // this is labda of line, can use it optimize quad intersection
-// sorry but no .. see below (BM)
- if( LineIntersectsTriangle(opco, npco, nv1, nv2, nv3, &t, NULL) ) {
- if (t < min_t) {
- deflected = 1;
- deflected_now = 1;
- }
- }
-// else if (mface->v4 && (t>=0.0 && t<=1.0)) {
-// no, you can't skip testing the other triangle
-// it might give a smaller t on (close to) the edge .. this is numerics not esoteric maths :)
-// note: the 2 triangles don't need to share a plane ! (BM)
- if (mface->v4) {
- if( LineIntersectsTriangle(opco, npco, nv1, nv3, nv4, &t2, NULL) ) {
- if (t2 < min_t) {
- deflected = 1;
- deflected_now = 2;
- }
- }
- }
-
- if ((deflected_now > 0) && ((t < min_t) ||(t2 < min_t))) {
- min_t = t;
- ds_object = d_object;
- ds_face = d_face;
- deflection_object = ob;
- deflection_face = mface;
- if (deflected_now==1) {
- min_t = t;
- VECCOPY(dv1, nv1);
- VECCOPY(dv2, nv2);
- VECCOPY(dv3, nv3);
- }
- else {
- min_t = t2;
- VECCOPY(dv1, nv1);
- VECCOPY(dv2, nv3);
- VECCOPY(dv3, nv4);
- }
- }
- mface++;
- }
- }
- }
- base = base->next;
- }
-
-
- /* Here's the point to do the permeability calculation */
- /* Set deflected to 0 if a random number is below the value */
- /* Get the permeability IPO here*/
- if (deflected) {
-
- if (has_ipo_code(deflection_object->ipo, OB_PD_PERM))
- perm_val = IPO_GetFloatValue(deflection_object->ipo, OB_PD_PERM, cur_time);
- else
- perm_val = deflection_object->pd->pdef_perm;
-
- perm_thresh = rng_getFloat(rng) - perm_val;
- if (perm_thresh < 0 ) {
- deflected = 0;
- }
- }
-
- /* Now for the second part of the deflection code - work out the new speed */
- /* and position of the particle if a collision occurred */
- if (deflected) {
- VECSUB(edge1, dv1, dv2);
- VECSUB(edge2, dv3, dv2);
- Crossf(d_nvect, edge2, edge1);
- n_mag = Normalize(d_nvect);
- dk_plane = INPR(d_nvect, nv1);
- dk_point1 = INPR(d_nvect,opco);
-
- VECSUB(d_intersect_vect, npco, opco);
-
- d_intersect_co[0] = opco[0] + (min_t * (npco[0] - opco[0]));
- d_intersect_co[1] = opco[1] + (min_t * (npco[1] - opco[1]));
- d_intersect_co[2] = opco[2] + (min_t * (npco[2] - opco[2]));
-
- d_i_co_above[0] = (d_intersect_co[0] + (0.001f * d_nvect[0]));
- d_i_co_above[1] = (d_intersect_co[1] + (0.001f * d_nvect[1]));
- d_i_co_above[2] = (d_intersect_co[2] + (0.001f * d_nvect[2]));
- mag_iv = Normalize(d_intersect_vect);
- VECCOPY(npco, d_intersect_co);
-
- VECSUB(vect_to_int, opco, d_intersect_co);
- first_dist = Normalize(vect_to_int);
-
- /* Work out the lengths of time before and after collision*/
- time_before = (life*(first_dist / (mag_iv)));
- time_after = (life*((mag_iv - first_dist) / (mag_iv)));
-
- /* We have to recalculate what the speed would have been at the */
- /* point of collision, not the key frame time */
- npno[0]= opno[0] + time_before*force[0];
- npno[1]= opno[1] + time_before*force[1];
- npno[2]= opno[2] + time_before*force[2];
-
-
- /* Reflect the speed vector in the face */
- x_m = (2 * npno[0] * d_nvect[0]);
- y_m = (2 * npno[1] * d_nvect[1]);
- z_m = (2 * npno[2] * d_nvect[2]);
- refl_vel[0] = npno[0] - (d_nvect[0] * (x_m + y_m + z_m));
- refl_vel[1] = npno[1] - (d_nvect[1] * (x_m + y_m + z_m));
- refl_vel[2] = npno[2] - (d_nvect[2] * (x_m + y_m + z_m));
-
- /*A random variation in the damping factor........ */
- /*Get the IPO values for damping here*/
-
- if (has_ipo_code(deflection_object->ipo, OB_PD_SDAMP))
- damping = IPO_GetFloatValue(deflection_object->ipo, OB_PD_SDAMP, cur_time);
- else
- damping = deflection_object->pd->pdef_damp;
-
- if (has_ipo_code(deflection_object->ipo, OB_PD_RDAMP))
- rdamp_val = IPO_GetFloatValue(deflection_object->ipo, OB_PD_RDAMP, cur_time);
- else
- rdamp_val = deflection_object->pd->pdef_rdamp;
-
- damping = damping + ((1.0f - damping) * rng_getFloat(rng) *rdamp_val);
- damping = damping * damping;
- ref_plane_mag = INPR(refl_vel,d_nvect);
-
- if (damping > 0.999) damping = 0.999f;
-
- /* Now add in the damping force - only damp in the direction of */
- /* the faces normal vector */
- npno[0] = (refl_vel[0] - (d_nvect[0] * ref_plane_mag * damping));
- npno[1] = (refl_vel[1] - (d_nvect[1] * ref_plane_mag * damping));
- npno[2] = (refl_vel[2] - (d_nvect[2] * ref_plane_mag * damping));
-
- /* Now reset opno */
- VECCOPY(opno,npno);
- VECCOPY(forcec, force);
-
- /* If the particle has bounced more than four times on the same */
- /* face within this cycle (depth > 4, same face > 4 ) */
- /* Then set the force to be only that component of the force */
- /* in the same direction as the face normal */
- /* i.e. subtract the component of the force in the direction */
- /* of the face normal from the actual force */
- if ((ds_object == *last_object) && (ds_face == *last_face)) {
- /* Increment same_face */
- *same_face = *same_face + 1;
- if ((*same_face > 3) && (def_depth > 3)) {
- force_mag_norm = INPR(forcec, d_nvect);
- forcec[0] = forcec[0] - (d_nvect[0] * force_mag_norm);
- forcec[1] = forcec[1] - (d_nvect[1] * force_mag_norm);
- forcec[2] = forcec[2] - (d_nvect[2] * force_mag_norm);
- }
- }
- else *same_face = 1;
-
- *last_object = ds_object;
- *last_face = ds_face;
-
- /* We have the particles speed at the point of collision */
- /* Now we want the particles speed at the current key frame */
-
- npno[0]= npno[0] + time_after*forcec[0];
- npno[1]= npno[1] + time_after*forcec[1];
- npno[2]= npno[2] + time_after*forcec[2];
-
- /* Now we have to recalculate pa->co for the remainder*/
- /* of the time since the intersect*/
- npco[0]= npco[0] + time_after*npno[0];
- npco[1]= npco[1] + time_after*npno[1];
- npco[2]= npco[2] + time_after*npno[2];
-
- /* And set the old co-ordinates back to the point just above the intersection */
- VECCOPY(opco, d_i_co_above);
-
- /* Finally update the time */
- life = time_after;
- cur_time += time_before;
-
- /* The particle may have fallen through the face again by now!!*/
- /* So check if the particle has changed sides of the plane compared*/
- /* the co-ordinates at the last keyframe*/
- /* But only do this as a last resort, if we've got to the end of the */
- /* number of collisions allowed */
- if (def_depth==9) {
- k_point3 = INPR(d_nvect,npco);
- if (((dk_plane > k_point3) && (dk_plane < dk_point1))||((dk_plane < k_point3) && (dk_plane > dk_point1))) {
-
- /* Yup, the pesky particle may have fallen through a hole!!! */
- /* So we'll cheat a bit and move the particle along the normal vector */
- /* until it's just the other side of the plane */
- icalctop = (dk_plane - d_nvect[0]*npco[0] - d_nvect[1]*npco[1] - d_nvect[2]*npco[2]);
- icalcbot = (d_nvect[0]*d_nvect[0] + d_nvect[1]*d_nvect[1] + d_nvect[2]*d_nvect[2]);
- dist_to_plane = icalctop / icalcbot;
-
- /* Now just increase the distance a little to place */
- /* the point the other side of the plane */
- dist_to_plane *= 1.1f;
- npco[0]= npco[0] + (dist_to_plane * d_nvect[0]);
- npco[1]= npco[1] + (dist_to_plane * d_nvect[1]);
- npco[2]= npco[2] + (dist_to_plane * d_nvect[2]);
-
- }
- }
- }
- return deflected;
+ return ret;
}
-/*
- rng= random number generator
- ob = object that spawns the particles
- depth = for fireworks
- nr = index nr of current particle
- paf = the particle system
- part = current particle
- force = force vector
- deform = flag to indicate lattice deform
- */
-static void make_particle_keys(RNG *rng, Object *ob, int depth, int nr, PartEff *paf, Particle *part, float *force, int deform, MTex *mtex, ListBase *effectorbase)
+
+static float falloff_func(float fac, int usemin, float mindist, int usemax, float maxdist, float power)
{
- Particle *pa, *opa = NULL;
- float damp, deltalife, life;
- float cur_time, maxspeed= paf->maxlen/(float)paf->totkey;
- float opco[3], opno[3], npco[3], npno[3], new_force[3], new_speed[3];
- int b, rt1, rt2, deflected, deflection, finish_defs, def_count;
- int last_ob, last_fc, same_fc;
-
- damp= 1.0f-paf->damp;
- pa= part;
-
- /* start speed: random */
- if(paf->randfac!=0.0) {
- pa->no[0]+= paf->randfac*(rng_getFloat(rng) - 0.5f);
- pa->no[1]+= paf->randfac*(rng_getFloat(rng) - 0.5f);
- pa->no[2]+= paf->randfac*(rng_getFloat(rng) - 0.5f);
- }
+ if(!usemin)
+ mindist= 0.0f;
- /* start speed: texture */
- if(mtex && paf->texfac!=0.0) {
- particle_tex(mtex, paf, pa->co, pa->no);
+ if(fac < mindist) {
+ return 1.0f;
}
+ else if(usemax) {
+ if(fac>maxdist || (maxdist-mindist)<=0.0f)
+ return 0.0f;
- /* effectors here? */
- if(effectorbase)
- precalc_effectors(ob, paf, pa, effectorbase);
-
- if(paf->totkey>1) deltalife= pa->lifetime/(paf->totkey-1);
- else deltalife= pa->lifetime;
-
- /* longer lifetime results in longer distance covered */
- VecMulf(pa->no, deltalife);
-
- opa= pa;
- pa++;
-
- for(b=1; b<paf->totkey; b++) {
-
- /* new time */
- pa->time= opa->time+deltalife;
- cur_time = pa->time;
-
- /* set initial variables */
- VECCOPY(opco, opa->co);
- VECCOPY(new_force, force);
- VECCOPY(new_speed, opa->no);
- VecMulf(new_speed, 1.0f/deltalife);
- //new_speed[0] = new_speed[1] = new_speed[2] = 0.0f;
-
- /* handle differences between static (local coords, fixed frame) and dynamic */
- if(effectorbase) {
- float loc_time= ((float)b)/(float)(paf->totkey-1);
-
- if(paf->flag & PAF_STATIC) {
- float opco1[3], new_force1[3];
-
- /* move co and force to global coords */
- VECCOPY(opco1, opco);
- Mat4MulVecfl(ob->obmat, opco1);
- VECCOPY(new_force1, new_force);
- Mat4Mul3Vecfl(ob->obmat, new_force1);
- Mat4Mul3Vecfl(ob->obmat, new_speed);
-
- cur_time = G.scene->r.cfra;
-
- /* force fields */
- pdDoEffectors(effectorbase, opco1, new_force1, new_speed, cur_time, loc_time, 0);
-
- /* move co, force and newspeed back to local */
- VECCOPY(opco, opco1);
- Mat4MulVecfl(ob->imat, opco);
- VECCOPY(new_force, new_force1);
- Mat4Mul3Vecfl(ob->imat, new_force);
- Mat4Mul3Vecfl(ob->imat, new_speed);
- }
- else {
- /* force fields */
- pdDoEffectors(effectorbase, opco, new_force, new_speed, cur_time, loc_time, 0);
- }
- }
-
- /* new speed */
- pa->no[0]= deltalife * (new_speed[0] + new_force[0]);
- pa->no[1]= deltalife * (new_speed[1] + new_force[1]);
- pa->no[2]= deltalife * (new_speed[2] + new_force[2]);
-
- /* speed limitor */
- if((paf->flag & PAF_STATIC) && maxspeed!=0.0f) {
- float len= VecLength(pa->no);
- if(len > maxspeed)
- VecMulf(pa->no, maxspeed/len);
- }
-
- /* new location */
- pa->co[0]= opa->co[0] + pa->no[0];
- pa->co[1]= opa->co[1] + pa->no[1];
- pa->co[2]= opa->co[2] + pa->no[2];
-
- /* Particle deflection code */
- if((paf->flag & PAF_STATIC)==0) {
- deflection = 0;
- finish_defs = 1;
- def_count = 0;
-
- VECCOPY(opno, opa->no);
- VECCOPY(npco, pa->co);
- VECCOPY(npno, pa->no);
-
- life = deltalife;
- cur_time -= deltalife;
-
- last_ob = -1;
- last_fc = -1;
- same_fc = 0;
-
- /* First call the particle deflection check for the particle moving */
- /* between the old co-ordinates and the new co-ordinates */
- /* If a deflection occurs, call the code again, this time between the */
- /* intersection point and the updated new co-ordinates */
- /* Bail out if we've done the calculation 10 times - this seems ok */
- /* for most scenes I've tested */
- while (finish_defs) {
- deflected = pdDoDeflection(rng, opco, npco, opno, npno, life, new_force,
- def_count, cur_time, ob->lay,
- &last_ob, &last_fc, &same_fc);
- if (deflected) {
- def_count = def_count + 1;
- deflection = 1;
- if (def_count==10) finish_defs = 0;
- }
- else {
- finish_defs = 0;
- }
- }
-
- /* Only update the particle positions and speed if we had a deflection */
- if (deflection) {
- pa->co[0] = npco[0];
- pa->co[1] = npco[1];
- pa->co[2] = npco[2];
- pa->no[0] = npno[0];
- pa->no[1] = npno[1];
- pa->no[2] = npno[2];
- }
- }
-
- /* speed: texture */
- if(mtex && paf->texfac!=0.0) {
- particle_tex(mtex, paf, pa->co, pa->no);
- }
- if(damp!=1.0) {
- pa->no[0]*= damp;
- pa->no[1]*= damp;
- pa->no[2]*= damp;
- }
-
- opa= pa;
- pa++;
- /* opa is used later on too! */
+ fac= (fac-mindist)/(maxdist-mindist);
+ return 1.0f - (float)pow((double)fac, (double)power);
}
+ else
+ return pow((double)1.0f+fac-mindist, (double)-power);
+}
- if(deform) {
- /* deform all keys */
- pa= part;
- b= paf->totkey;
- while(b--) {
- calc_latt_deform(pa->co, 1.0f);
- pa++;
- }
- }
-
- /* the big multiplication */
- if(depth<PAF_MAXMULT && paf->mult[depth]!=0.0) {
-
- /* new 'child' emerges from an average 'mult' part from
- the particles */
- damp = (float)nr;
- rt1= (int)(damp*paf->mult[depth]);
- rt2= (int)((damp+1.0)*paf->mult[depth]);
- if(rt1!=rt2) {
-
- for(b=0; b<paf->child[depth]; b++) {
- pa= new_particle(paf);
- *pa= *opa;
- pa->lifetime= paf->life[depth];
- if(paf->randlife!=0.0) {
- pa->lifetime*= 1.0f + paf->randlife*(rng_getFloat(rng) - 0.5f);
- }
- pa->mat_nr= paf->mat[depth];
+static float falloff_func_dist(PartDeflect *pd, float fac)
+{
+ return falloff_func(fac, pd->flag&PFIELD_USEMIN, pd->mindist, pd->flag&PFIELD_USEMAX, pd->maxdist, pd->f_power);
+}
- make_particle_keys(rng, ob, depth+1, b, paf, pa, force, deform, mtex, effectorbase);
- }
- }
- }
+static float falloff_func_rad(PartDeflect *pd, float fac)
+{
+ return falloff_func(fac, pd->flag&PFIELD_USEMINR, pd->minrad, pd->flag&PFIELD_USEMAXR, pd->maxrad, pd->f_power_r);
}
-static void init_mv_jit(float *jit, int num, int seed2)
+float effector_falloff(PartDeflect *pd, float *eff_velocity, float *vec_to_part)
{
- RNG *rng;
- float *jit2, x, rad1, rad2, rad3;
- int i, num2;
+ float eff_dir[3], temp[3];
+ float falloff=1.0, fac, r_fac;
+
+ if(pd->forcefield==PFIELD_LENNARDJ)
+ return falloff; /* Lennard-Jones field has it's own falloff built in */
+
+ VecCopyf(eff_dir,eff_velocity);
+ Normalize(eff_dir);
+
+ if(pd->flag & PFIELD_POSZ && Inpf(eff_dir,vec_to_part)<0.0f)
+ falloff=0.0f;
+ else switch(pd->falloff){
+ case PFIELD_FALL_SPHERE:
+ fac=VecLength(vec_to_part);
+ falloff= falloff_func_dist(pd, fac);
+ break;
+
+ case PFIELD_FALL_TUBE:
+ fac=Inpf(vec_to_part,eff_dir);
+ falloff= falloff_func_dist(pd, ABS(fac));
+ if(falloff == 0.0f)
+ break;
- if(num==0) return;
+ VECADDFAC(temp,vec_to_part,eff_dir,-fac);
+ r_fac=VecLength(temp);
+ falloff*= falloff_func_rad(pd, r_fac);
+ break;
+ case PFIELD_FALL_CONE:
+ fac=Inpf(vec_to_part,eff_dir);
+ falloff= falloff_func_dist(pd, ABS(fac));
+ if(falloff == 0.0f)
+ break;
- rad1= (float)(1.0/sqrt((float)num));
- rad2= (float)(1.0/((float)num));
- rad3= (float)sqrt((float)num)/((float)num);
+ r_fac=saacos(fac/VecLength(vec_to_part))*180.0f/(float)M_PI;
+ falloff*= falloff_func_rad(pd, r_fac);
- rng = rng_new(31415926 + num + seed2);
- x= 0;
- num2 = 2 * num;
- for(i=0; i<num2; i+=2) {
-
- jit[i]= x + rad1*(0.5f - rng_getFloat(rng));
- jit[i+1]= i/(2.0f*num) + rad1*(0.5f - rng_getFloat(rng));
-
- jit[i]-= (float)floor(jit[i]);
- jit[i+1]-= (float)floor(jit[i+1]);
-
- x+= rad3;
- x -= (float)floor(x);
+ break;
}
- jit2= MEM_mallocN(12 + 2*sizeof(float)*num, "initjit");
-
- for (i=0 ; i<4 ; i++) {
- BLI_jitterate1(jit, jit2, num, rad1);
- BLI_jitterate1(jit, jit2, num, rad1);
- BLI_jitterate2(jit, jit2, num, rad2);
- }
- MEM_freeN(jit2);
- rng_free(rng);
+ return falloff;
}
-#define JIT_RAND 32
-
-/* for a position within a face, tot is total amount of faces */
-static void give_mesh_particle_coord(PartEff *paf, VeNoCo *noco, MFace *mface, int partnr, int subnr, float *co, float *no)
+void do_physical_effector(Object *ob, float *opco, short type, float force_val, float distance, float falloff, float size, float damp, float *eff_velocity, float *vec_to_part, float *velocity, float *field, int planar, struct RNG *rng, float noise_factor, float charge, float pa_size)
{
- static float *jit= NULL;
- static float *trands= NULL;
- static int jitlevel= 1;
- float *v1, *v2, *v3, *v4;
- float u, v;
- float *n1, *n2, *n3, *n4;
-
- /* free signal */
- if(paf==NULL) {
- if(jit) MEM_freeN(jit);
- jit= NULL;
- if(trands) MEM_freeN(trands);
- trands= NULL;
+ float mag_vec[3]={0,0,0};
+ float temp[3], temp2[3];
+ float eff_vel[3];
+ float noise = 0, visibility;
+
+ // calculate visibility
+ visibility = eff_calc_visibility(ob, opco, vec_to_part);
+ if(visibility <= 0.0)
return;
- }
-
- /* first time initialize jitter or trand, partnr then is total amount of particles, subnr total amount of faces */
- if(trands==NULL && jit==NULL) {
- RNG *rng = rng_new(31415926 + paf->seed);
- int i, tot;
-
- if(paf->flag & PAF_TRAND)
- tot= partnr;
- else
- tot= JIT_RAND; /* arbitrary... allows JIT_RAND times more particles in a face for jittered distro */
-
- trands= MEM_callocN(2+2*tot*sizeof(float), "trands");
- for(i=0; i<tot; i++) {
- trands[2*i]= rng_getFloat(rng);
- trands[2*i+1]= rng_getFloat(rng);
- }
- rng_free(rng);
+ falloff *= visibility;
- if((paf->flag & PAF_TRAND)==0) {
- jitlevel= paf->userjit;
+ VecCopyf(eff_vel,eff_velocity);
+ Normalize(eff_vel);
+
+ switch(type){
+ case PFIELD_WIND:
+ VECCOPY(mag_vec,eff_vel);
- if(jitlevel == 0) {
- jitlevel= partnr/subnr;
- if(paf->flag & PAF_EDISTR) jitlevel*= 2; /* looks better in general, not very scietific */
- if(jitlevel<3) jitlevel= 3;
- if(jitlevel>100) jitlevel= 100;
- }
+ // add wind noise here, only if we have wind
+ if((noise_factor > 0.0f) && (force_val > FLT_EPSILON))
+ noise = wind_func(rng, noise_factor);
- jit= MEM_callocN(2+ jitlevel*2*sizeof(float), "jit");
- init_mv_jit(jit, jitlevel, paf->seed);
- BLI_array_randomize(jit, 2*sizeof(float), jitlevel, paf->seed); /* for custom jit or even distribution */
- }
- return;
- }
-
- if(paf->flag & PAF_TRAND) {
- u= trands[2*partnr];
- v= trands[2*partnr+1];
- }
- else {
- /* jittered distribution gets fixed random offset */
- if(subnr>=jitlevel) {
- int jitrand= (subnr/jitlevel) % JIT_RAND;
-
- subnr %= jitlevel;
- u= jit[2*subnr] + trands[2*jitrand];
- v= jit[2*subnr+1] + trands[2*jitrand+1];
- if(u > 1.0f) u-= 1.0f;
- if(v > 1.0f) v-= 1.0f;
- }
- else {
- u= jit[2*subnr];
- v= jit[2*subnr+1];
- }
- }
-
- v1= (noco+(mface->v1))->co;
- v2= (noco+(mface->v2))->co;
- v3= (noco+(mface->v3))->co;
- n1= (noco+(mface->v1))->no;
- n2= (noco+(mface->v2))->no;
- n3= (noco+(mface->v3))->no;
-
- if(mface->v4) {
- float uv= u*v;
- float muv= (1.0f-u)*(v);
- float umv= (u)*(1.0f-v);
- float mumv= (1.0f-u)*(1.0f-v);
-
- v4= (noco+(mface->v4))->co;
- n4= (noco+(mface->v4))->no;
-
- co[0]= mumv*v1[0] + muv*v2[0] + uv*v3[0] + umv*v4[0];
- co[1]= mumv*v1[1] + muv*v2[1] + uv*v3[1] + umv*v4[1];
- co[2]= mumv*v1[2] + muv*v2[2] + uv*v3[2] + umv*v4[2];
+ VecMulf(mag_vec,(force_val+noise)*falloff);
+ VecAddf(field,field,mag_vec);
+ break;
- no[0]= mumv*n1[0] + muv*n2[0] + uv*n3[0] + umv*n4[0];
- no[1]= mumv*n1[1] + muv*n2[1] + uv*n3[1] + umv*n4[1];
- no[2]= mumv*n1[2] + muv*n2[2] + uv*n3[2] + umv*n4[2];
- }
- else {
- /* mirror triangle uv coordinates when on other side */
- if(u + v > 1.0f) {
- u= 1.0f-u;
- v= 1.0f-v;
- }
- co[0]= v1[0] + u*(v3[0]-v1[0]) + v*(v2[0]-v1[0]);
- co[1]= v1[1] + u*(v3[1]-v1[1]) + v*(v2[1]-v1[1]);
- co[2]= v1[2] + u*(v3[2]-v1[2]) + v*(v2[2]-v1[2]);
-
- no[0]= n1[0] + u*(n3[0]-n1[0]) + v*(n2[0]-n1[0]);
- no[1]= n1[1] + u*(n3[1]-n1[1]) + v*(n2[1]-n1[1]);
- no[2]= n1[2] + u*(n3[2]-n1[2]) + v*(n2[2]-n1[2]);
- }
-}
+ case PFIELD_FORCE:
+ if(planar)
+ Projf(mag_vec,vec_to_part,eff_vel);
+ else
+ VecCopyf(mag_vec,vec_to_part);
+ Normalize(mag_vec);
-/* Gets a MDeformVert's weight in group (0 if not in group) */
-/* note; this call could be in mesh.c or deform.c, but OK... it's in armature.c too! (ton) */
-static float vert_weight(MDeformVert *dvert, int group)
-{
- MDeformWeight *dw;
- int i;
-
- if(dvert) {
- dw= dvert->dw;
- for(i= dvert->totweight; i>0; i--, dw++) {
- if(dw->def_nr == group) return dw->weight;
- if(i==1) break; /*otherwise dw will point to somewhere it shouldn't*/
- }
- }
- return 0.0;
-}
+ VecMulf(mag_vec,force_val*falloff);
+ VecAddf(field,field,mag_vec);
+ break;
-/* Gets a faces average weight in a group, helper for below, face and weights are always set */
-static float face_weight(MFace *face, float *weights)
-{
- float tweight;
-
- tweight = weights[face->v1] + weights[face->v2] + weights[face->v3];
-
- if(face->v4) {
- tweight += weights[face->v4];
- tweight /= 4.0;
- }
- else {
- tweight /= 3.0;
- }
+ case PFIELD_VORTEX:
+ Crossf(mag_vec,eff_vel,vec_to_part);
- return tweight;
-}
+ Normalize(mag_vec);
-/* helper function for build_particle_system() */
-static void make_weight_tables(PartEff *paf, Mesh *me, int totpart, VeNoCo *vertlist, int totvert, MFace *facelist, int totface, float **vweights, float **fweights)
-{
- MFace *mface;
- float *foweights=NULL, *voweights=NULL;
- float totvweight=0.0f, totfweight=0.0f;
- int a;
-
- if((paf->flag & PAF_FACE)==0) totface= 0;
-
- /* collect emitting vertices & faces if vert groups used */
- if(paf->vertgroup && me->dvert) {
-
- /* allocate weights array for all vertices, also for lookup of faces later on. note it's a malloc */
- *vweights= voweights= MEM_mallocN( totvert*sizeof(float), "pafvoweights" );
- totvweight= 0.0f;
- for(a=0; a<totvert; a++) {
- voweights[a]= vert_weight(me->dvert+a, paf->vertgroup-1);
- totvweight+= voweights[a];
- }
-
- if(totface) {
- /* allocate weights array for faces, note it's a malloc */
- *fweights= foweights= MEM_mallocN(totface*sizeof(float), "paffoweights" );
- for(a=0, mface=facelist; a<totface; a++, mface++) {
- foweights[a] = face_weight(mface, voweights);
- }
- }
- }
-
- /* make weights for faces or for even area distribution */
- if(totface && (paf->flag & PAF_EDISTR)) {
- float maxfarea= 0.0f, curfarea;
-
- /* two cases for area distro, second case we already have group weights */
- if(foweights==NULL) {
- /* allocate weights array for faces, note it's a malloc */
- *fweights= foweights= MEM_mallocN(totface*sizeof(float), "paffoweights" );
-
- for(a=0, mface=facelist; a<totface; a++, mface++) {
- if (mface->v4)
- curfarea= AreaQ3Dfl(vertlist[mface->v1].co, vertlist[mface->v2].co, vertlist[mface->v3].co, vertlist[mface->v4].co);
- else
- curfarea= AreaT3Dfl(vertlist[mface->v1].co, vertlist[mface->v2].co, vertlist[mface->v3].co);
- if(curfarea>maxfarea)
- maxfarea = curfarea;
- foweights[a]= curfarea;
- }
- }
- else {
- for(a=0, mface=facelist; a<totface; a++, mface++) {
- if(foweights[a]!=0.0f) {
- if (mface->v4)
- curfarea= AreaQ3Dfl(vertlist[mface->v1].co, vertlist[mface->v2].co, vertlist[mface->v3].co, vertlist[mface->v4].co);
- else
- curfarea= AreaT3Dfl(vertlist[mface->v1].co, vertlist[mface->v2].co, vertlist[mface->v3].co);
- if(curfarea>maxfarea)
- maxfarea = curfarea;
- foweights[a]*= curfarea;
- }
- }
- }
-
- /* normalize weights for max face area, calculate tot */
- if(maxfarea!=0.0f) {
- maxfarea= 1.0f/maxfarea;
- for(a=0; a< totface; a++) {
- if(foweights[a]!=0.0) {
- foweights[a] *= maxfarea;
- totfweight+= foweights[a];
- }
- }
- }
- }
- else if(foweights) {
- /* only add totfweight value */
- for(a=0; a< totface; a++) {
- if(foweights[a]!=0.0) {
- totfweight+= foweights[a];
- }
- }
- }
-
- /* if weight arrays, we turn these arrays into the amount of particles */
- if(totvert && voweights) {
- float mult= (float)totpart/totvweight;
-
- for(a=0; a< totvert; a++) {
- if(voweights[a]!=0.0)
- voweights[a] *= mult;
- }
- }
-
- if(totface && foweights) {
- float mult= (float)totpart/totfweight;
-
- for(a=0; a< totface; a++) {
- if(foweights[a]!=0.0)
- foweights[a] *= mult;
- }
- }
-}
+ VecMulf(mag_vec,force_val*distance*falloff);
+ VecAddf(field,field,mag_vec);
-/* helper function for build_particle_system() */
-static void make_length_tables(PartEff *paf, Mesh *me, int totvert, MFace *facelist, int totface, float **vlengths, float **flengths)
-{
- MFace *mface;
- float *folengths=NULL, *volengths=NULL;
- int a;
-
- if((paf->flag & PAF_FACE)==0) totface= 0;
-
- /* collect emitting vertices & faces if vert groups used */
- if(paf->vertgroup_v && me->dvert) {
-
- /* allocate lengths array for all vertices, also for lookup of faces later on. note it's a malloc */
- *vlengths= volengths= MEM_mallocN( totvert*sizeof(float), "pafvolengths" );
- for(a=0; a<totvert; a++) {
- volengths[a]= vert_weight(me->dvert+a, paf->vertgroup_v-1);
- }
-
- if(totface) {
- /* allocate lengths array for faces, note it's a malloc */
- *flengths= folengths= MEM_mallocN(totface*sizeof(float), "paffolengths" );
- for(a=0, mface=facelist; a<totface; a++, mface++) {
- folengths[a] = face_weight(mface, volengths);
- }
- }
- }
-}
+ break;
+ case PFIELD_MAGNET:
+ if(planar)
+ VecCopyf(temp,eff_vel);
+ else
+ /* magnetic field of a moving charge */
+ Crossf(temp,eff_vel,vec_to_part);
+ Normalize(temp);
-/* for paf start to end, store all matrices for objects */
-typedef struct pMatrixCache {
- float obmat[4][4];
- float imat[3][3];
-} pMatrixCache;
+ Crossf(temp2,velocity,temp);
+ VecAddf(mag_vec,mag_vec,temp2);
+ VecMulf(mag_vec,force_val*falloff);
+ VecAddf(field,field,mag_vec);
+ break;
+ case PFIELD_HARMONIC:
+ if(planar)
+ Projf(mag_vec,vec_to_part,eff_vel);
+ else
+ VecCopyf(mag_vec,vec_to_part);
-/* WARN: this function stores data in ob->id.idnew! */
-/* error: this function changes ob->recalc of other objects... */
-static pMatrixCache *cache_object_matrices(Object *ob, int start, int end)
-{
- pMatrixCache *mcache, *mc;
- Group *group= NULL;
- Object *obcopy;
- Base *base;
- float framelenold, cfrao, sfo;
-
- /* object can be linked in group... stupid exception */
- if(NULL==object_in_scene(ob, G.scene))
- group= find_group(ob);
-
- mcache= mc= MEM_mallocN( (end-start+1)*sizeof(pMatrixCache), "ob matrix cache");
-
- framelenold= G.scene->r.framelen;
- G.scene->r.framelen= 1.0f;
- cfrao= G.scene->r.cfra;
- sfo= ob->sf;
- ob->sf= 0.0f;
-
- /* clear storage, copy recalc tag (bad loop) */
- for(obcopy= G.main->object.first; obcopy; obcopy= obcopy->id.next) {
- obcopy->id.newid= NULL;
- obcopy->recalco= obcopy->recalc;
- obcopy->recalc= 0;
- }
-
- /* all objects get tagged recalc that influence this object (does group too) */
- /* note that recalco has the real recalc tags, set by callers of this function */
- ob->recalc |= OB_RECALC_OB; /* make sure a recalc gets flushed */
- DAG_object_update_flags(G.scene, ob, -1);
-
- for(G.scene->r.cfra= start; G.scene->r.cfra<=end; G.scene->r.cfra++, mc++) {
-
- if(group) {
- GroupObject *go;
-
- for(go= group->gobject.first; go; go= go->next) {
- if(go->ob->recalc) {
- where_is_object(go->ob);
-
- do_ob_key(go->ob);
- if(go->ob->type==OB_ARMATURE) {
- do_all_pose_actions(go->ob); // only does this object actions
- where_is_pose(go->ob);
- }
- }
- }
- }
- else {
- for(base= G.scene->base.first; base; base= base->next) {
- if(base->object->recalc) {
- if(base->object->id.newid==NULL)
- base->object->id.newid= MEM_dupallocN(base->object);
-
- where_is_object(base->object);
-
- do_ob_key(base->object);
- if(base->object->type==OB_ARMATURE) {
- do_all_pose_actions(base->object); // only does this object actions
- where_is_pose(base->object);
- }
- }
- }
- }
- Mat4CpyMat4(mc->obmat, ob->obmat);
- Mat4Invert(ob->imat, ob->obmat);
- Mat3CpyMat4(mc->imat, ob->imat);
- Mat3Transp(mc->imat);
- }
-
- /* restore */
- G.scene->r.cfra= cfrao;
- G.scene->r.framelen= framelenold;
- ob->sf= sfo;
-
- if(group) {
- GroupObject *go;
-
- for(go= group->gobject.first; go; go= go->next) {
- if(go->ob->recalc) {
- where_is_object(go->ob);
-
- do_ob_key(go->ob);
- if(go->ob->type==OB_ARMATURE) {
- do_all_pose_actions(go->ob); // only does this object actions
- where_is_pose(go->ob);
- }
- }
- }
- }
- else {
- for(base= G.scene->base.first; base; base= base->next) {
- if(base->object->recalc) {
-
- if(base->object->id.newid) {
- obcopy= (Object *)base->object->id.newid;
- *(base->object) = *(obcopy);
- MEM_freeN(obcopy);
- base->object->id.newid= NULL;
- }
-
- do_ob_key(base->object);
- if(base->object->type==OB_ARMATURE) {
- do_all_pose_actions(base->object); // only does this object actions
- where_is_pose(base->object);
- }
- }
- }
- }
-
- /* copy recalc tag (bad loop) */
- for(obcopy= G.main->object.first; obcopy; obcopy= obcopy->id.next)
- obcopy->recalc= obcopy->recalco;
-
- return mcache;
-}
+ Normalize(mag_vec);
-/* for fluidsim win32 debug messages */
-#if defined(WIN32) && (!(defined snprintf))
-#define snprintf _snprintf
-#endif
+ VecMulf(mag_vec,force_val*falloff);
+ VecSubf(field,field,mag_vec);
-/* main particle building function
- one day particles should become dynamic (realtime) with the current method as a 'bake' (ton) */
-void build_particle_system(Object *ob)
-{
- RNG *rng;
- PartEff *paf;
- Particle *pa;
- Mesh *me;
- Base *base;
- MTex *mtexmove=0, *mtextime=0;
- Material *ma;
- MFace *facelist= NULL;
- pMatrixCache *mcache=NULL, *mcnow, *mcprev;
- ListBase *effectorbase;
- VeNoCo *vertexcosnos;
- double startseconds= PIL_check_seconds_timer();
- float ftime, dtime, force[3], vec[3], fac, co[3], no[3];
- float *voweights= NULL, *foweights= NULL, maxw=1.0f;
- float *volengths= NULL, *folengths= NULL;
- int deform=0, a, totpart, paf_sta, paf_end;
- int waitcursor_set= 0, totvert, totface, curface, curvert;
-#ifndef DISABLE_ELBEEM
- int readMask, activeParts, fileParts;
-#endif
-
- /* return conditions */
- if(ob->type!=OB_MESH) return;
- me= ob->data;
+ VecCopyf(mag_vec,velocity);
+ /* 1.9 is an experimental value to get critical damping at damp=1.0 */
+ VecMulf(mag_vec,damp*1.9f*(float)sqrt(force_val));
+ VecSubf(field,field,mag_vec);
+ break;
+ case PFIELD_CHARGE:
+ if(planar)
+ Projf(mag_vec,vec_to_part,eff_vel);
+ else
+ VecCopyf(mag_vec,vec_to_part);
- paf= give_parteff(ob);
- if(paf==NULL) return;
-
- if(G.rendering==0 && paf->disp==0) return;
-
- if(paf->keys) MEM_freeN(paf->keys); /* free as early as possible, for returns */
- paf->keys= NULL;
-
- //printf("build particles\n");
-
- /* fluid sim particle import handling, actual loading of particles from file */
- #ifndef DISABLE_ELBEEM
- if( (1) && (ob->fluidsimFlag & OB_FLUIDSIM_ENABLE) && // broken, disabled for now!
- (ob->fluidsimSettings) &&
- (ob->fluidsimSettings->type == OB_FLUIDSIM_PARTICLE)) {
- char *suffix = "fluidsurface_particles_#";
- char *suffix2 = ".gz";
- char filename[256];
- char debugStrBuffer[256];
- int curFrame = G.scene->r.cfra -1; // warning - sync with derived mesh fsmesh loading
- int j, numFileParts;
- gzFile gzf;
- float vel[3];
-
- if(ob==G.obedit) { // off...
- paf->totpart = 0; // 1 or 0?
- return;
- }
+ Normalize(mag_vec);
- // ok, start loading
- strcpy(filename, ob->fluidsimSettings->surfdataPath);
- strcat(filename, suffix);
- BLI_convertstringcode(filename, G.sce, curFrame); // fixed #frame-no
- strcat(filename, suffix2);
-
- gzf = gzopen(filename, "rb");
- if (!gzf) {
- snprintf(debugStrBuffer,256,"readFsPartData::error - Unable to open file for reading '%s' \n", filename);
- //elbeemDebugOut(debugStrBuffer);
- paf->totpart = 0;
- return;
- }
+ VecMulf(mag_vec,charge*force_val*falloff);
+ VecAddf(field,field,mag_vec);
+ break;
+ case PFIELD_LENNARDJ:
+ {
+ float fac;
- gzread(gzf, &totpart, sizeof(totpart));
- numFileParts = totpart;
- totpart = (G.rendering)?totpart:(paf->disp*totpart)/100;
- paf->totpart= totpart;
- paf->totkey= 1;
- /* initialize particles */
- new_particle(paf);
- ftime = 0.0; // unused...
-
- // set up reading mask
- readMask = ob->fluidsimSettings->typeFlags;
- activeParts=0;
- fileParts=0;
-
- for(a=0; a<totpart; a++) {
- int ptype=0;
- short shsize=0;
- float convertSize=0.0;
- gzread(gzf, &ptype, sizeof( ptype ));
- if(ptype&readMask) {
- activeParts++;
- pa= new_particle(paf);
- pa->time= ftime;
- pa->lifetime= ftime + 10000.; // add large number to make sure they are displayed, G.scene->r.efra +1.0;
- pa->co[0] = 0.0;
- pa->co[1] =
- pa->co[2] = 1.0*(float)a / (float)totpart;
- pa->no[0] = pa->no[1] = pa->no[2] = 0.0;
- pa->mat_nr= paf->omat;
- gzread(gzf, &convertSize, sizeof( float ));
- // convert range of 1.0-10.0 to shorts 1000-10000)
- shsize = (short)(convertSize*1000.0);
- pa->rt = shsize;
-
- for(j=0; j<3; j++) {
- float wrf;
- gzread(gzf, &wrf, sizeof( wrf ));
- pa->co[j] = wrf;
- //fprintf(stderr,"Rj%d ",j);
- }
- for(j=0; j<3; j++) {
- float wrf;
- gzread(gzf, &wrf, sizeof( wrf ));
- vel[j] = wrf;
- }
- //if(a<25) fprintf(stderr,"FSPARTICLE debug set %s , a%d = %f,%f,%f , life=%f \n", filename, a, pa->co[0],pa->co[1],pa->co[2], pa->lifetime );
- } else {
- // skip...
- for(j=0; j<2*3+1; j++) {
- float wrf; gzread(gzf, &wrf, sizeof( wrf ));
- }
+ if(planar) {
+ Projf(mag_vec,vec_to_part,eff_vel);
+ distance = VecLength(mag_vec);
}
- fileParts++;
- }
- gzclose( gzf );
-
- totpart = paf->totpart = activeParts;
- snprintf(debugStrBuffer,256,"readFsPartData::done - particles:%d, active:%d, file:%d, mask:%d \n", paf->totpart,activeParts,fileParts,readMask);
- elbeemDebugOut(debugStrBuffer);
- return;
- } // fluid sim particles done
- #endif // DISABLE_ELBEEM
-
- if(paf->end < paf->sta) return;
-
- if( (paf->flag & PAF_OFACE) && (paf->flag & PAF_FACE)==0) return;
-
- if(me->totvert==0) return;
-
- if(ob==G.obedit) return;
- totpart= (G.rendering)?paf->totpart:(paf->disp*paf->totpart)/100;
- if(totpart==0) return;
-
- /* No returns after this line! */
-
- /* material */
- ma= give_current_material(ob, paf->omat);
- if(ma) {
- if(paf->speedtex)
- mtexmove= ma->mtex[paf->speedtex-1];
- mtextime= ma->mtex[paf->timetex-1];
- }
+ else
+ VecCopyf(mag_vec,vec_to_part);
- disable_speed_curve(1); /* check this... */
+ /* at this distance the field is 60 times weaker than maximum */
+ if(distance > 2.22 * (size+pa_size))
+ break;
- /* initialize particles */
- new_particle(paf);
+ fac = pow((size+pa_size)/distance,6.0);
+
+ fac = - fac * (1.0 - fac) / distance;
- /* reset deflector cache, sumohandle is free, but its still sorta abuse... (ton) */
- for(base= G.scene->base.first; base; base= base->next)
- base->object->sumohandle= NULL;
+ /* limit the repulsive term drastically to avoid huge forces */
+ fac = ((fac>2.0) ? 2.0 : fac);
- /* all object positions from start to end */
- paf_sta= (int)floor(paf->sta);
- paf_end= (int)ceil(paf->end);
- if((paf->flag & PAF_STATIC)==0)
- mcache= cache_object_matrices(ob, paf_sta, paf_end);
-
- /* mult generations? */
- for(a=0; a<PAF_MAXMULT; a++) {
- if(paf->mult[a]!=0.0) {
- /* interesting formula! this way after 'x' generations the total is paf->totpart */
- totpart= (int)(totpart / (1.0+paf->mult[a]*paf->child[a]));
+ /* 0.003715 is the fac value at 2.22 times (size+pa_size),
+ substracted to avoid discontinuity at the border
+ */
+ VecMulf(mag_vec, force_val * (fac-0.0037315));
+ VecAddf(field,field,mag_vec);
+ break;
}
- else break;
}
+}
- /* for static particles, calculate system on current frame (? ton) */
- if(ma) do_mat_ipo(ma);
-
- /* matrix invert for static too */
- Mat4Invert(ob->imat, ob->obmat);
- Mat4CpyMat4(paf->imat, ob->imat); /* used for duplicators */
-
- /* new random generator */
- rng = rng_new(paf->seed);
-
- /* otherwise it goes way too fast */
- force[0]= paf->force[0]*0.05f;
- force[1]= paf->force[1]*0.05f;
- force[2]= paf->force[2]*0.05f;
-
- if( paf->flag & PAF_STATIC ) deform= 0;
- else {
- Object *parlatt= modifiers_isDeformedByLattice(ob);
- if(parlatt) {
- deform= 1;
- init_latt_deform(parlatt, 0);
- }
- }
-
- /* get the effectors */
- effectorbase= pdInitEffectors(ob, paf->group);
-
- /* init geometry, return is 6 x float * me->totvert in size */
- vertexcosnos= (VeNoCo *)mesh_get_mapped_verts_nors(ob);
- facelist= me->mface;
- totvert= me->totvert;
- totface= me->totface;
-
- /* if vertexweights or even distribution, it makes weight tables, also checks where it emits from */
- make_weight_tables(paf, me, totpart, vertexcosnos, totvert, facelist, totface, &voweights, &foweights);
-
- /* vertexweights can define lengths too */
- make_length_tables(paf, me, totvert, facelist, totface, &volengths, &folengths);
-
- /* now define where to emit from, if there are face weights we skip vertices */
- if(paf->flag & PAF_OFACE) totvert= 0;
- if((paf->flag & PAF_FACE)==0) totface= 0;
- if(foweights) totvert= 0;
-
- /* initialize give_mesh_particle_coord */
- if(totface)
- give_mesh_particle_coord(paf, vertexcosnos, facelist, totpart, totface, NULL, NULL);
-
- /* correction for face timing when using weighted average */
- if(totface && foweights) {
- maxw= (paf->end-paf->sta)/foweights[0];
- }
- else if(totvert && voweights) {
- maxw= (paf->end-paf->sta)/voweights[0];
- }
-
- /* for loop below */
- if (paf->flag & PAF_STATIC) {
- ftime = G.scene->r.cfra;
- dtime= 0.0f;
- } else {
- ftime= paf->sta;
- dtime= (paf->end - paf->sta)/(float)totpart;
- }
-
- curface= curvert= 0;
- for(a=0; a<totpart; a++, ftime+=dtime) {
-
- /* we set waitcursor only when a half second expired, particles now are realtime updated */
- if(waitcursor_set==0 && (a % 256)==255) {
- double seconds= PIL_check_seconds_timer();
- if(seconds - startseconds > 0.5) {
- //XXX waitcursor(1);
- waitcursor_set= 1;
- }
- }
-
- pa= new_particle(paf);
- pa->time= ftime;
+/* -------- pdDoEffectors() --------
+ generic force/speed system, now used for particles and softbodies
+ lb = listbase with objects that take part in effecting
+ opco = global coord, as input
+ force = force accumulator
+ speed = actual current speed which can be altered
+ cur_time = "external" time in frames, is constant for static particles
+ loc_time = "local" time in frames, range <0-1> for the lifetime of particle
+ par_layer = layer the caller is in
+ flags = only used for softbody wind now
+ guide = old speed of particle
- /* get coordinates from faces, only when vertices set to zero */
- if(totvert==0 && totface) {
- int curjit;
-
- /* use weight table, we have to do faces in order to be able to use jitter table... */
- if(foweights) {
-
- if(foweights[curface] < 1.0f) {
- float remainder= 0.0f;
-
- while(remainder + foweights[curface] < 1.0f && curface<totface-1) {
- remainder += foweights[curface];
- curface++;
- }
- /* if this is the last face, the foweights[] can be zero, so we don't add a particle extra */
- if(curface!=totface-1)
- foweights[curface] += remainder;
-
- maxw= (paf->end-paf->sta)/foweights[curface];
- }
+*/
+void pdDoEffectors(ListBase *lb, float *opco, float *force, float *speed, float cur_time, float loc_time, unsigned int flags)
+{
+/*
+ Modifies the force on a particle according to its
+ relation with the effector object
+ Different kind of effectors include:
+ Forcefields: Gravity-like attractor
+ (force power is related to the inverse of distance to the power of a falloff value)
+ Vortex fields: swirling effectors
+ (particles rotate around Z-axis of the object. otherwise, same relation as)
+ (Forcefields, but this is not done through a force/acceleration)
+ Guide: particles on a path
+ (particles are guided along a curve bezier or old nurbs)
+ (is independent of other effectors)
+*/
+ Object *ob;
+ pEffectorCache *ec;
+ PartDeflect *pd;
+
+ float distance, vec_to_part[3];
+ float falloff;
- if(foweights[curface]==0.0f)
- break; /* WARN skips here out of particle generating */
- else {
- if(foweights[curface] >= 1.0f) /* note the >= here, this because of the < 1.0f above, it otherwise will stick to 1 face forever */
- foweights[curface] -= 1.0f;
-
- curjit= (int) foweights[curface];
- give_mesh_particle_coord(paf, vertexcosnos, facelist+curface, a, curjit, co, no);
-
- /* time correction to make particles appear evenly, maxw does interframe (0-1) */
- pa->time= paf->sta + maxw*foweights[curface];
- }
- }
- else {
- curface= a % totface;
- curjit= a/totface;
- give_mesh_particle_coord(paf, vertexcosnos, facelist+curface, a, curjit, co, no);
- }
- }
- /* get coordinates from vertices */
- if(totvert) {
- /* use weight table */
- if(voweights) {
-
- if(voweights[curvert] < 1.0f) {
- float remainder= 0.0f;
-
- while(remainder + voweights[curvert] < 1.0f && curvert<totvert-1) {
- remainder += voweights[curvert];
- curvert++;
- }
- voweights[curvert] += remainder;
- maxw= (paf->end-paf->sta)/voweights[curvert];
- }
-
- if(voweights[curvert]==0.0f)
- break; /* WARN skips here out of particle generating */
- else {
- if(voweights[curvert] > 1.0f)
- voweights[curvert] -= 1.0f;
-
- /* time correction to make particles appear evenly */
- pa->time= paf->sta + maxw*voweights[curvert];
- }
- }
- else {
- curvert= a % totvert;
- if(a >= totvert && totface)
- totvert= 0;
- }
+ /* Cycle through collected objects, get total of (1/(gravity_strength * dist^gravity_power)) */
+ /* Check for min distance here? (yes would be cool to add that, ton) */
+
+ for(ec = lb->first; ec; ec= ec->next) {
+ /* object effectors were fully checked to be OK to evaluate! */
+ ob= ec->ob;
+ pd= ob->pd;
- VECCOPY(co, vertexcosnos[curvert].co);
- VECCOPY(no, vertexcosnos[curvert].no);
- }
-
- VECCOPY(pa->co, co);
-
- /* dynamic options */
- if((paf->flag & PAF_STATIC)==0) {
- int cur;
+ /* Get IPO force strength and fall off values here */
+ where_is_object_time(ob,cur_time);
- /* particle retiming with texture */
- if(mtextime && (paf->flag2 & PAF_TEXTIME)) {
- float tin, tr, tg, tb, ta, orco[3];
-
- /* calculate normalized orco */
- orco[0] = (co[0]-me->loc[0])/me->size[0];
- orco[1] = (co[1]-me->loc[1])/me->size[1];
- orco[2] = (co[2]-me->loc[2])/me->size[2];
- externtex(mtextime, orco, &tin, &tr, &tg, &tb, &ta);
-
- if(paf->flag2neg & PAF_TEXTIME)
- pa->time = paf->sta + (paf->end - paf->sta)*tin;
- else
- pa->time = paf->sta + (paf->end - paf->sta)*(1.0f-tin);
- }
+ /* use center of object for distance calculus */
+ VecSubf(vec_to_part, opco, ob->obmat[3]);
+ distance = VecLength(vec_to_part);
- /* set ob at correct time, we use cached matrices */
- cur= (int)floor(pa->time) + 1 ; /* + 1 has a reason: (obmat/prevobmat) otherwise comet-tails start too late */
-
- if(cur <= paf_end) mcnow= mcache + cur - paf_sta;
- else mcnow= mcache + paf_end - paf_sta;
-
- if(cur > paf_sta) mcprev= mcnow-1;
- else mcprev= mcache;
-
- /* move to global space */
- Mat4MulVecfl(mcnow->obmat, pa->co);
+ falloff=effector_falloff(pd,ob->obmat[2],vec_to_part);
- VECCOPY(vec, co);
- Mat4MulVecfl(mcprev->obmat, vec);
-
- /* first start speed: object */
- VECSUB(pa->no, pa->co, vec);
-
- VecMulf(pa->no, paf->obfac);
-
- /* calculate the correct inter-frame */
- fac= (pa->time- (float)floor(pa->time));
- pa->co[0]= fac*pa->co[0] + (1.0f-fac)*vec[0];
- pa->co[1]= fac*pa->co[1] + (1.0f-fac)*vec[1];
- pa->co[2]= fac*pa->co[2] + (1.0f-fac)*vec[2];
-
- /* start speed: normal */
- if(paf->normfac!=0.0) {
- /* imat is transpose ! */
- VECCOPY(vec, no);
- Mat3MulVecfl(mcnow->imat, vec);
-
- Normalize(vec);
- VecMulf(vec, paf->normfac);
- VECADD(pa->no, pa->no, vec);
- }
- }
+ if(falloff<=0.0f)
+ ; /* don't do anything */
else {
- if(paf->normfac!=0.0) {
- VECCOPY(pa->no, no);
- Normalize(pa->no);
- VecMulf(pa->no, paf->normfac);
- }
- }
-
- pa->lifetime= paf->lifetime;
- if(paf->randlife!=0.0) {
- pa->lifetime*= 1.0f + paf->randlife*(rng_getFloat(rng) - 0.5f);
- }
- pa->mat_nr= paf->omat;
-
- if(folengths)
- pa->lifetime*= folengths[curface];
-
- make_particle_keys(rng, ob, 0, a, paf, pa, force, deform, mtexmove, effectorbase);
- }
-
- /* free stuff */
- give_mesh_particle_coord(NULL, NULL, NULL, 0, 0, NULL, NULL);
- MEM_freeN(vertexcosnos);
- if(voweights) MEM_freeN(voweights);
- if(foweights) MEM_freeN(foweights);
- if(volengths) MEM_freeN(volengths);
- if(folengths) MEM_freeN(folengths);
- if(mcache) MEM_freeN(mcache);
- rng_free(rng);
-
- if(deform) end_latt_deform();
-
- if(effectorbase)
- pdEndEffectors(effectorbase);
-
- /* reset deflector cache */
- for(base= G.scene->base.first; base; base= base->next) {
- if(base->object->sumohandle) {
+ float field[3]={0,0,0}, tmp[3];
+ VECCOPY(field, force);
+ do_physical_effector(ob, opco, pd->forcefield,pd->f_strength,distance,
+ falloff,pd->f_dist,pd->f_damp,ob->obmat[2],vec_to_part,
+ speed,force,pd->flag&PFIELD_PLANAR, pd->rng, pd->f_noise, 0.0f, 0.0f);
- MEM_freeN(base->object->sumohandle);
- base->object->sumohandle= NULL;
+ // for softbody backward compatibility
+ if(flags & PE_WIND_AS_SPEED){
+ VECSUB(tmp, force, field);
+ VECSUB(speed, speed, tmp);
+ }
}
}
-
- disable_speed_curve(0);
-
- //XXX if(waitcursor_set) waitcursor(0);
}
-
diff --git a/source/blender/blenkernel/intern/exotic.c b/source/blender/blenkernel/intern/exotic.c
index 7a138f9ac68..28ed74aa9db 100644
--- a/source/blender/blenkernel/intern/exotic.c
+++ b/source/blender/blenkernel/intern/exotic.c
@@ -76,10 +76,14 @@
#include <fcntl.h>
#include <string.h>
-#ifndef WIN32
+#ifndef _WIN32
#include <unistd.h>
#else
#include <io.h>
+#define open _open
+#define read _read
+#define close _close
+#define write _write
#endif
#include "MEM_guardedalloc.h"
@@ -116,7 +120,9 @@
#include "BKE_curve.h"
#include "BKE_customdata.h"
+#ifndef DISABLE_PYTHON
#include "BPY_extern.h"
+#endif
#include "zlib.h"
@@ -869,7 +875,7 @@ static void read_videoscape_lamp(char *str)
Object *ob;
Lamp *la;
FILE *fp;
- float vec[3], *q1;
+ float vec[3], q1[4];
int tot, val;
char s[50];
@@ -897,7 +903,7 @@ static void read_videoscape_lamp(char *str)
fscanf(fp, "%f %f %f\n", ob->loc, ob->loc+1, ob->loc+2);
val= fscanf(fp, "%f %f %f\n", vec, vec+1, vec+2);
- q1= vectoquat(vec, 5, 2);
+ vectoquat(vec, 5, 2, q1);
QuatToEul(q1, ob->rot);
if(val<=0) break;
@@ -2091,8 +2097,10 @@ static void displist_to_mesh(DispList *dlfirst)
}
for(a=0; a<dl->parts; a++) {
-
- DL_SURFINDEX(dl->flag & DL_CYCL_U, dl->flag & DL_CYCL_V, dl->nr, dl->parts);
+
+ if (surfindex_displist(dl, a, &b, &p1, &p2, &p3, &p4)==0)
+ break;
+
p1+= startve;
p2+= startve;
p3+= startve;
@@ -2419,6 +2427,7 @@ int BKE_read_exotic(char *name)
read_stl_mesh_binary(name);
retval = 1;
}
+#ifndef DISABLE_PYTHON
// TODO: this should not be in the kernel...
else { // unknown format, call Python importloader
if (BPY_call_importloader(name)) {
@@ -2428,6 +2437,7 @@ int BKE_read_exotic(char *name)
}
}
+#endif /* DISABLE_PYTHON */
//XXX waitcursor(0);
}
}
@@ -2626,17 +2636,17 @@ static void write_videoscape_mesh(Object *ob, char *str)
if(evl->v4==0) {
fprintf(fp, "3 %ld %ld %ld 0x%x\n",
- evl->v1->tmp.l,
- evl->v2->tmp.l,
- evl->v3->tmp.l,
+ (long int) evl->v1->tmp.l,
+ (long int) evl->v2->tmp.l,
+ (long int) evl->v3->tmp.l,
kleur[evl->mat_nr]);
}
else {
fprintf(fp, "4 %ld %ld %ld %ld 0x%x\n",
- evl->v1->tmp.l,
- evl->v2->tmp.l,
- evl->v3->tmp.l,
- evl->v4->tmp.l,
+ (long int) evl->v1->tmp.l,
+ (long int) evl->v2->tmp.l,
+ (long int) evl->v3->tmp.l,
+ (long int) evl->v4->tmp.l,
kleur[evl->mat_nr]);
}
evl= evl->next;
diff --git a/source/blender/blenkernel/intern/fluidsim.c b/source/blender/blenkernel/intern/fluidsim.c
new file mode 100644
index 00000000000..29c4e0f2fb5
--- /dev/null
+++ b/source/blender/blenkernel/intern/fluidsim.c
@@ -0,0 +1,660 @@
+/**
+ * fluidsim.c
+ *
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_mesh_types.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_object_force.h" // for pointcache
+#include "DNA_particle_types.h"
+#include "DNA_scene_types.h" // N_T
+
+#include "BLI_arithb.h"
+#include "BLI_blenlib.h"
+
+#include "BKE_cdderivedmesh.h"
+#include "BKE_customdata.h"
+#include "BKE_DerivedMesh.h"
+#include "BKE_fluidsim.h"
+#include "BKE_global.h"
+#include "BKE_modifier.h"
+#include "BKE_mesh.h"
+#include "BKE_pointcache.h"
+#include "BKE_utildefines.h"
+
+// headers for fluidsim bobj meshes
+#include <stdlib.h>
+#include "LBM_fluidsim.h"
+#include "elbeem.h"
+#include <zlib.h>
+#include <string.h>
+#include <stdio.h>
+
+/* ************************* fluidsim bobj file handling **************************** */
+
+// -----------------------------------------
+// forward decleration
+// -----------------------------------------
+
+// -----------------------------------------
+
+void fluidsim_init(FluidsimModifierData *fluidmd)
+{
+#ifndef DISABLE_ELBEEM
+ if(fluidmd)
+ {
+ FluidsimSettings *fss = MEM_callocN(sizeof(FluidsimSettings), "fluidsimsettings");
+
+ fluidmd->fss = fss;
+
+ if(!fss)
+ return;
+
+ fss->type = OB_FSBND_NOSLIP;
+ fss->show_advancedoptions = 0;
+
+ fss->resolutionxyz = 50;
+ fss->previewresxyz = 25;
+ fss->realsize = 0.03;
+ fss->guiDisplayMode = 2; // preview
+ fss->renderDisplayMode = 3; // render
+
+ fss->viscosityMode = 2; // default to water
+ fss->viscosityValue = 1.0;
+ fss->viscosityExponent = 6;
+
+ // dg TODO: change this to []
+ fss->gravx = 0.0;
+ fss->gravy = 0.0;
+ fss->gravz = -9.81;
+ fss->animStart = 0.0;
+ fss->animEnd = 0.30;
+ fss->gstar = 0.005; // used as normgstar
+ fss->maxRefine = -1;
+ // maxRefine is set according to resolutionxyz during bake
+
+ // fluid/inflow settings
+ // fss->iniVel --> automatically set to 0
+
+ /* elubie: changed this to default to the same dir as the render output
+ to prevent saving to C:\ on Windows */
+ BLI_strncpy(fss->surfdataPath, btempdir, FILE_MAX);
+
+ // first init of bounding box
+ // no bounding box needed
+
+ // todo - reuse default init from elbeem!
+ fss->typeFlags = 0;
+ fss->domainNovecgen = 0;
+ fss->volumeInitType = 1; // volume
+ fss->partSlipValue = 0.0;
+
+ fss->generateTracers = 0;
+ fss->generateParticles = 0.0;
+ fss->surfaceSmoothing = 1.0;
+ fss->surfaceSubdivs = 1.0;
+ fss->particleInfSize = 0.0;
+ fss->particleInfAlpha = 0.0;
+
+ // init fluid control settings
+ fss->attractforceStrength = 0.2;
+ fss->attractforceRadius = 0.75;
+ fss->velocityforceStrength = 0.2;
+ fss->velocityforceRadius = 0.75;
+ fss->cpsTimeStart = fss->animStart;
+ fss->cpsTimeEnd = fss->animEnd;
+ fss->cpsQuality = 10.0; // 1.0 / 10.0 => means 0.1 width
+
+ /*
+ BAD TODO: this is done in buttons_object.c in the moment
+ Mesh *mesh = ob->data;
+ // calculate bounding box
+ fluid_get_bb(mesh->mvert, mesh->totvert, ob->obmat, fss->bbStart, fss->bbSize);
+ */
+
+ // (ab)used to store velocities
+ fss->meshSurfNormals = NULL;
+
+ fss->lastgoodframe = -1;
+
+ fss->flag = 0;
+
+ }
+#endif
+ return;
+}
+
+void fluidsim_free(FluidsimModifierData *fluidmd)
+{
+#ifndef DISABLE_ELBEEM
+ if(fluidmd)
+ {
+ if(fluidmd->fss->meshSurfNormals)
+ {
+ MEM_freeN(fluidmd->fss->meshSurfNormals);
+ fluidmd->fss->meshSurfNormals = NULL;
+ }
+ MEM_freeN(fluidmd->fss);
+ }
+#endif
+ return;
+}
+
+DerivedMesh *fluidsimModifier_do(FluidsimModifierData *fluidmd, Object *ob, DerivedMesh *dm, int useRenderParams, int isFinalCalc)
+{
+#ifndef DISABLE_ELBEEM
+ DerivedMesh *result = NULL;
+ int framenr;
+ FluidsimSettings *fss = NULL;
+
+ framenr= (int)G.scene->r.cfra;
+
+ // only handle fluidsim domains
+ if(fluidmd && fluidmd->fss && (fluidmd->fss->type != OB_FLUIDSIM_DOMAIN))
+ return dm;
+
+ // sanity check
+ if(!fluidmd || (fluidmd && !fluidmd->fss))
+ return dm;
+
+ fss = fluidmd->fss;
+
+ // timescale not supported yet
+ // clmd->sim_parms->timescale= timescale;
+
+ // support reversing of baked fluid frames here
+ if((fss->flag & OB_FLUIDSIM_REVERSE) && (fss->lastgoodframe >= 0))
+ {
+ framenr = fss->lastgoodframe - framenr + 1;
+ CLAMP(framenr, 1, fss->lastgoodframe);
+ }
+
+ /* try to read from cache */
+ if(((fss->lastgoodframe >= framenr) || (fss->lastgoodframe < 0)) && (result = fluidsim_read_cache(ob, dm, fluidmd, framenr, useRenderParams)))
+ {
+ // fss->lastgoodframe = framenr; // set also in src/fluidsim.c
+ return result;
+ }
+ else
+ {
+ // display last known good frame
+ if(fss->lastgoodframe >= 0)
+ {
+ if((result = fluidsim_read_cache(ob, dm, fluidmd, fss->lastgoodframe, useRenderParams)))
+ {
+ return result;
+ }
+
+ // it was supposed to be a valid frame but it isn't!
+ fss->lastgoodframe = framenr - 1;
+
+
+ // this could be likely the case when you load an old fluidsim
+ if((result = fluidsim_read_cache(ob, dm, fluidmd, fss->lastgoodframe, useRenderParams)))
+ {
+ return result;
+ }
+ }
+
+ result = CDDM_copy(dm);
+
+ if(result)
+ {
+ return result;
+ }
+ }
+
+ return dm;
+#else
+ return NULL;
+#endif
+}
+
+#ifndef DISABLE_ELBEEM
+/* read .bobj.gz file into a fluidsimDerivedMesh struct */
+static DerivedMesh *fluidsim_read_obj(char *filename)
+{
+ int wri,i,j;
+ float wrf;
+ int gotBytes;
+ gzFile gzf;
+ int numverts = 0, numfaces = 0;
+ DerivedMesh *dm = NULL;
+ MFace *mface;
+ MVert *mvert;
+ short *normals;
+
+ // ------------------------------------------------
+ // get numverts + numfaces first
+ // ------------------------------------------------
+ gzf = gzopen(filename, "rb");
+ if (!gzf)
+ {
+ return NULL;
+ }
+
+ // read numverts
+ gotBytes = gzread(gzf, &wri, sizeof(wri));
+ numverts = wri;
+
+ // skip verts
+ for(i=0; i<numverts*3; i++)
+ {
+ gotBytes = gzread(gzf, &wrf, sizeof( wrf ));
+ }
+
+ // read number of normals
+ gotBytes = gzread(gzf, &wri, sizeof(wri));
+
+ // skip normals
+ for(i=0; i<numverts*3; i++)
+ {
+ gotBytes = gzread(gzf, &wrf, sizeof( wrf ));
+ }
+
+ /* get no. of triangles */
+ gotBytes = gzread(gzf, &wri, sizeof(wri));
+ numfaces = wri;
+
+ gzclose( gzf );
+ // ------------------------------------------------
+
+ if(!numfaces || !numverts)
+ return NULL;
+
+ gzf = gzopen(filename, "rb");
+ if (!gzf)
+ {
+ return NULL;
+ }
+
+ dm = CDDM_new(numverts, 0, numfaces);
+
+ if(!dm)
+ {
+ gzclose( gzf );
+ return NULL;
+ }
+
+ // read numverts
+ gotBytes = gzread(gzf, &wri, sizeof(wri));
+
+ // read vertex position from file
+ mvert = CDDM_get_verts(dm);
+ for(i=0; i<numverts; i++)
+ {
+ MVert *mv = &mvert[i];
+
+ for(j=0; j<3; j++)
+ {
+ gotBytes = gzread(gzf, &wrf, sizeof( wrf ));
+ mv->co[j] = wrf;
+ }
+ }
+
+ // should be the same as numverts
+ gotBytes = gzread(gzf, &wri, sizeof(wri));
+ if(wri != numverts)
+ {
+ if(dm)
+ dm->release(dm);
+ gzclose( gzf );
+ return NULL;
+ }
+
+ normals = MEM_callocN(sizeof(short) * numverts * 3, "fluid_tmp_normals" );
+ if(!normals)
+ {
+ if(dm)
+ dm->release(dm);
+ gzclose( gzf );
+ return NULL;
+ }
+
+ // read normals from file (but don't save them yet)
+ for(i=0; i<numverts*3; i++)
+ {
+ gotBytes = gzread(gzf, &wrf, sizeof( wrf ));
+ normals[i] = (short)(wrf*32767.0f);
+ }
+
+ /* read no. of triangles */
+ gotBytes = gzread(gzf, &wri, sizeof(wri));
+
+ if(wri!=numfaces)
+ printf("Fluidsim: error in reading data from file.\n");
+
+ // read triangles from file
+ mface = CDDM_get_faces(dm);
+ for(i=0; i<numfaces; i++)
+ {
+ int face[4];
+ MFace *mf = &mface[i];
+
+ gotBytes = gzread(gzf, &(face[0]), sizeof( face[0] ));
+ gotBytes = gzread(gzf, &(face[1]), sizeof( face[1] ));
+ gotBytes = gzread(gzf, &(face[2]), sizeof( face[2] ));
+ face[3] = 0;
+
+ // check if 3rd vertex has index 0 (not allowed in blender)
+ if(face[2])
+ {
+ mf->v1 = face[0];
+ mf->v2 = face[1];
+ mf->v3 = face[2];
+ }
+ else
+ {
+ mf->v1 = face[1];
+ mf->v2 = face[2];
+ mf->v3 = face[0];
+ }
+ mf->v4 = face[3];
+
+ test_index_face(mf, NULL, 0, 3);
+ }
+
+ gzclose( gzf );
+
+ CDDM_calc_edges(dm);
+
+ CDDM_apply_vert_normals(dm, (short (*)[3])normals);
+ MEM_freeN(normals);
+
+ // CDDM_calc_normals(result);
+
+ return dm;
+}
+
+DerivedMesh *fluidsim_read_cache(Object *ob, DerivedMesh *orgdm, FluidsimModifierData *fluidmd, int framenr, int useRenderParams)
+{
+ int displaymode = 0;
+ int curFrame = framenr - 1 /*G.scene->r.sfra*/; /* start with 0 at start frame */
+ char targetDir[FILE_MAXFILE+FILE_MAXDIR], targetFile[FILE_MAXFILE+FILE_MAXDIR];
+ FluidsimSettings *fss = fluidmd->fss;
+ DerivedMesh *dm = NULL;
+ MFace *mface;
+ int numfaces;
+ int mat_nr, flag, i;
+
+ if(!useRenderParams) {
+ displaymode = fss->guiDisplayMode;
+ } else {
+ displaymode = fss->renderDisplayMode;
+ }
+
+ strncpy(targetDir, fss->surfdataPath, FILE_MAXDIR);
+
+ // use preview or final mesh?
+ if(displaymode==1)
+ {
+ // just display original object
+ return NULL;
+ }
+ else if(displaymode==2)
+ {
+ strcat(targetDir,"fluidsurface_preview_####");
+ }
+ else
+ { // 3
+ strcat(targetDir,"fluidsurface_final_####");
+ }
+
+ BLI_convertstringcode(targetDir, G.sce);
+ BLI_convertstringframe(targetDir, curFrame); // fixed #frame-no
+
+ strcpy(targetFile,targetDir);
+ strcat(targetFile, ".bobj.gz");
+
+ dm = fluidsim_read_obj(targetFile);
+
+ if(!dm)
+ {
+ // switch, abort background rendering when fluidsim mesh is missing
+ const char *strEnvName2 = "BLENDER_ELBEEMBOBJABORT"; // from blendercall.cpp
+
+ if(G.background==1) {
+ if(getenv(strEnvName2)) {
+ int elevel = atoi(getenv(strEnvName2));
+ if(elevel>0) {
+ printf("Env. var %s set, fluid sim mesh '%s' not found, aborting render...\n",strEnvName2, targetFile);
+ exit(1);
+ }
+ }
+ }
+
+ // display org. object upon failure which is in dm
+ return NULL;
+ }
+
+ // assign material + flags to new dm
+ mface = orgdm->getFaceArray(orgdm);
+ mat_nr = mface[0].mat_nr;
+ flag = mface[0].flag;
+
+ mface = dm->getFaceArray(dm);
+ numfaces = dm->getNumFaces(dm);
+ for(i=0; i<numfaces; i++)
+ {
+ mface[i].mat_nr = mat_nr;
+ mface[i].flag = flag;
+ }
+
+ // load vertex velocities, if they exist...
+ // TODO? use generate flag as loading flag as well?
+ // warning, needs original .bobj.gz mesh loading filename
+ if(displaymode==3)
+ {
+ fluidsim_read_vel_cache(fluidmd, dm, targetFile);
+ }
+ else
+ {
+ if(fss->meshSurfNormals)
+ MEM_freeN(fss->meshSurfNormals);
+
+ fss->meshSurfNormals = NULL;
+ }
+
+ return dm;
+}
+
+
+/* read zipped fluidsim velocities into the co's of the fluidsimsettings normals struct */
+void fluidsim_read_vel_cache(FluidsimModifierData *fluidmd, DerivedMesh *dm, char *filename)
+{
+ int wri, i, j;
+ float wrf;
+ gzFile gzf;
+ FluidsimSettings *fss = fluidmd->fss;
+ int len = strlen(filename);
+ int totvert = dm->getNumVerts(dm);
+ float *velarray = NULL;
+
+ // mesh and vverts have to be valid from loading...
+
+ if(fss->meshSurfNormals)
+ MEM_freeN(fss->meshSurfNormals);
+
+ if(len<7)
+ {
+ return;
+ }
+
+ if(fss->domainNovecgen>0) return;
+
+ // abusing pointer to hold an array of 3d-velocities
+ fss->meshSurfNormals = MEM_callocN(sizeof(float)*3*dm->getNumVerts(dm), "Fluidsim_velocities");
+ // abusing pointer to hold an INT
+ fss->meshSurface = SET_INT_IN_POINTER(totvert);
+
+ velarray = (float *)fss->meshSurfNormals;
+
+ // .bobj.gz , correct filename
+ // 87654321
+ filename[len-6] = 'v';
+ filename[len-5] = 'e';
+ filename[len-4] = 'l';
+
+ gzf = gzopen(filename, "rb");
+ if (!gzf)
+ {
+ MEM_freeN(fss->meshSurfNormals);
+ fss->meshSurfNormals = NULL;
+ return;
+ }
+
+ gzread(gzf, &wri, sizeof( wri ));
+ if(wri != totvert)
+ {
+ MEM_freeN(fss->meshSurfNormals);
+ fss->meshSurfNormals = NULL;
+ return;
+ }
+
+ for(i=0; i<totvert;i++)
+ {
+ for(j=0; j<3; j++)
+ {
+ gzread(gzf, &wrf, sizeof( wrf ));
+ velarray[3*i + j] = wrf;
+ }
+ }
+
+ gzclose(gzf);
+}
+
+void fluid_get_bb(MVert *mvert, int totvert, float obmat[][4],
+ /*RET*/ float start[3], /*RET*/ float size[3] )
+{
+ float bbsx=0.0, bbsy=0.0, bbsz=0.0;
+ float bbex=1.0, bbey=1.0, bbez=1.0;
+ int i;
+ float vec[3];
+
+ VECCOPY(vec, mvert[0].co);
+ Mat4MulVecfl(obmat, vec);
+ bbsx = vec[0]; bbsy = vec[1]; bbsz = vec[2];
+ bbex = vec[0]; bbey = vec[1]; bbez = vec[2];
+
+ for(i = 1; i < totvert; i++) {
+ VECCOPY(vec, mvert[i].co);
+ Mat4MulVecfl(obmat, vec);
+
+ if(vec[0] < bbsx){ bbsx= vec[0]; }
+ if(vec[1] < bbsy){ bbsy= vec[1]; }
+ if(vec[2] < bbsz){ bbsz= vec[2]; }
+ if(vec[0] > bbex){ bbex= vec[0]; }
+ if(vec[1] > bbey){ bbey= vec[1]; }
+ if(vec[2] > bbez){ bbez= vec[2]; }
+ }
+
+ // return values...
+ if(start) {
+ start[0] = bbsx;
+ start[1] = bbsy;
+ start[2] = bbsz;
+ }
+ if(size) {
+ size[0] = bbex-bbsx;
+ size[1] = bbey-bbsy;
+ size[2] = bbez-bbsz;
+ }
+}
+
+//-------------------------------------------------------------------------------
+// old interface
+//-------------------------------------------------------------------------------
+
+
+
+//-------------------------------------------------------------------------------
+// file handling
+//-------------------------------------------------------------------------------
+
+void initElbeemMesh(struct Object *ob,
+ int *numVertices, float **vertices,
+ int *numTriangles, int **triangles,
+ int useGlobalCoords, int modifierIndex)
+{
+ DerivedMesh *dm = NULL;
+ MVert *mvert;
+ MFace *mface;
+ int countTris=0, i, totvert, totface;
+ float *verts;
+ int *tris;
+
+ dm = mesh_create_derived_index_render(ob, CD_MASK_BAREMESH, modifierIndex);
+ //dm = mesh_create_derived_no_deform(ob,NULL);
+
+ mvert = dm->getVertArray(dm);
+ mface = dm->getFaceArray(dm);
+ totvert = dm->getNumVerts(dm);
+ totface = dm->getNumFaces(dm);
+
+ *numVertices = totvert;
+ verts = MEM_callocN( totvert*3*sizeof(float), "elbeemmesh_vertices");
+ for(i=0; i<totvert; i++) {
+ VECCOPY( &verts[i*3], mvert[i].co);
+ if(useGlobalCoords) { Mat4MulVecfl(ob->obmat, &verts[i*3]); }
+ }
+ *vertices = verts;
+
+ for(i=0; i<totface; i++) {
+ countTris++;
+ if(mface[i].v4) { countTris++; }
+ }
+ *numTriangles = countTris;
+ tris = MEM_callocN( countTris*3*sizeof(int), "elbeemmesh_triangles");
+ countTris = 0;
+ for(i=0; i<totface; i++) {
+ int face[4];
+ face[0] = mface[i].v1;
+ face[1] = mface[i].v2;
+ face[2] = mface[i].v3;
+ face[3] = mface[i].v4;
+
+ tris[countTris*3+0] = face[0];
+ tris[countTris*3+1] = face[1];
+ tris[countTris*3+2] = face[2];
+ countTris++;
+ if(face[3]) {
+ tris[countTris*3+0] = face[0];
+ tris[countTris*3+1] = face[2];
+ tris[countTris*3+2] = face[3];
+ countTris++;
+ }
+ }
+ *triangles = tris;
+
+ dm->release(dm);
+}
+
+#endif // DISABLE_ELBEEM
+
diff --git a/source/blender/blenkernel/intern/font.c b/source/blender/blenkernel/intern/font.c
index fb58c076c95..a8a97742c24 100644
--- a/source/blender/blenkernel/intern/font.c
+++ b/source/blender/blenkernel/intern/font.c
@@ -160,41 +160,61 @@ utf8slen(char *src)
return size;
}
-int utf8towchar_(wchar_t *w, char *c)
+
+/* Converts Unicode to wchar
+
+According to RFC 3629 "UTF-8, a transformation format of ISO 10646"
+(http://tools.ietf.org/html/rfc3629), the valid UTF-8 encoding are:
+
+ Char. number range | UTF-8 octet sequence
+ (hexadecimal) | (binary)
+ --------------------+---------------------------------------------
+ 0000 0000-0000 007F | 0xxxxxxx
+ 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
+ 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
+ 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
+
+If the encoding incidated by the first character is incorrect (because the
+1 to 3 following characters do not match 10xxxxxx), the output is a '?' and
+only a single input character is consumed.
+
+*/
+
+int utf8towchar(wchar_t *w, char *c)
{
int len=0;
+
if(w==NULL || c==NULL) return(0);
- //printf("%s\n",c);
- while(*c)
- {
- if(*c & 0x80)
- {
- if(*c & 0x40)
- {
- if(*c & 0x20)
- {
- if(*c & 0x10)
- {
- *w=(c[0] & 0x0f)<<18 | (c[1]&0x1f)<<12 | (c[2]&0x3f)<<6 | (c[3]&0x7f);
- c++;
- }
- else
- *w=(c[0] & 0x1f)<<12 | (c[1]&0x3f)<<6 | (c[2]&0x7f);
- c++;
- }
- else
- *w=(((c[0] &0x3f)<<6) | (c[1]&0x7f));
+
+ while(*c) {
+ if ((*c & 0xe0) == 0xc0) {
+ if((c[1] & 0x80) && (c[1] & 0x40) == 0x00) {
+ *w=((c[0] &0x1f)<<6) | (c[1]&0x3f);
c++;
+ } else {
+ *w = '?';
}
- else
- *w=(c[0] & 0x7f);
+ } else if ((*c & 0xf0) == 0xe0) {
+ if((c[1] & c[2] & 0x80) && ((c[1] | c[2]) & 0x40) == 0x00) {
+ *w=((c[0] & 0x0f)<<12) | ((c[1]&0x3f)<<6) | (c[2]&0x3f);
+ c += 2;
+ } else {
+ *w = '?';
}
- else
- *w=(c[0] & 0x7f);
- c++;
- w++;
- len++;
- }
+ } else if ((*c & 0xf8) == 0xf0) {
+ if((c[1] & c[2] & c[3] & 0x80) && ((c[1] | c[2] | c[3]) & 0x40) == 0x00) {
+ *w=((c[0] & 0x07)<<18) | ((c[1]&0x1f)<<12) | ((c[2]&0x3f)<<6) | (c[3]&0x3f);
+ c += 3;
+ } else {
+ *w = '?';
+ }
+ } else
+ *w=(c[0] & 0x7f);
+
+ c++;
+ w++;
+ len++;
+ }
return len;
}
@@ -443,7 +463,7 @@ static void build_underline(Curve *cu, float x1, float y1, float x2, float y2, i
if (nu2 == NULL) return;
nu2->resolu= cu->resolu;
nu2->bezt = NULL;
- nu2->knotsu = nu2->knotsv = 0;
+ nu2->knotsu = nu2->knotsv = NULL;
nu2->flag= 0;
nu2->charidx = charidx+1000;
if (mat_nr > 0) nu2->mat_nr= mat_nr-1;
@@ -532,7 +552,7 @@ static void buildchar(Curve *cu, unsigned long character, CharInfo *info, float
memcpy(nu2, nu1, sizeof(struct Nurb));
nu2->resolu= cu->resolu;
nu2->bp = 0;
- nu2->knotsu = nu2->knotsv = 0;
+ nu2->knotsu = nu2->knotsv = NULL;
nu2->flag= CU_SMOOTH;
nu2->charidx = charidx;
if (info->mat_nr) {
@@ -664,7 +684,7 @@ struct chartrans *text_to_curve(Object *ob, int mode)
utf8len = utf8slen(cu->str);
tmp = mem = MEM_callocN(((utf8len + 1) * sizeof(wchar_t)), "convertedmem");
- utf8towchar_(mem, cu->str);
+ utf8towchar(mem, cu->str);
// Count the wchar_t string length
slen = wcslen(mem);
diff --git a/source/blender/blenkernel/intern/group.c b/source/blender/blenkernel/intern/group.c
index 201d93220f9..0d2f86bb151 100644
--- a/source/blender/blenkernel/intern/group.c
+++ b/source/blender/blenkernel/intern/group.c
@@ -41,6 +41,7 @@
#include "DNA_object_types.h"
#include "DNA_nla_types.h"
#include "DNA_scene_types.h"
+#include "DNA_particle_types.h"
#include "BLI_blenlib.h"
@@ -77,14 +78,37 @@ void unlink_group(Group *group)
{
Material *ma;
Object *ob;
+ Scene *sce;
+ SceneRenderLayer *srl;
+ ParticleSystem *psys;
for(ma= G.main->mat.first; ma; ma= ma->id.next) {
if(ma->group==group)
ma->group= NULL;
}
+ for(ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if(ma->group==group)
+ ma->group= NULL;
+ }
+ for (sce= G.main->scene.first; sce; sce= sce->id.next) {
+ Base *base= sce->base.first;
+
+ /* ensure objects are not in this group */
+ for(; base; base= base->next) {
+ if(rem_from_group(group, base->object) && find_group(base->object, NULL)==NULL) {
+ base->object->flag &= ~OB_FROMGROUP;
+ base->flag &= ~OB_FROMGROUP;
+ }
+ }
+
+ for(srl= sce->r.layers.first; srl; srl= srl->next) {
+ if (srl->light_override==group)
+ srl->light_override= NULL;
+ }
+ }
+
for(ob= G.main->object.first; ob; ob= ob->id.next) {
bActionStrip *strip;
- PartEff *paf;
if(ob->dup_group==group) {
ob->dup_group= NULL;
@@ -95,13 +119,17 @@ void unlink_group(Group *group)
strip->object= NULL;
}
}
- for(paf= ob->effect.first; paf; paf= paf->next) {
- if(paf->type==EFF_PARTICLE) {
- if(paf->group)
- paf->group= NULL;
- }
+
+ for(psys=ob->particlesystem.first; psys; psys=psys->next){
+ if(psys->part->dup_group==group)
+ psys->part->dup_group= NULL;
+ if(psys->part->eff_group==group)
+ psys->part->eff_group= NULL;
}
}
+
+ /* group stays in library, but no members */
+ free_group(group);
group->id.us= 0;
}
@@ -134,11 +162,11 @@ void add_to_group(Group *group, Object *ob)
}
/* also used for ob==NULL */
-void rem_from_group(Group *group, Object *ob)
+int rem_from_group(Group *group, Object *ob)
{
GroupObject *go, *gon;
-
- if(group==NULL) return;
+ int removed = 0;
+ if(group==NULL) return 0;
go= group->gobject.first;
while(go) {
@@ -146,9 +174,12 @@ void rem_from_group(Group *group, Object *ob)
if(go->ob==ob) {
BLI_remlink(&group->gobject, go);
free_group_object(go);
+ removed = 1;
+ /* should break here since an object being in a group twice cant happen? */
}
go= gon;
}
+ return removed;
}
int object_in_group(Object *ob, Group *group)
@@ -164,9 +195,12 @@ int object_in_group(Object *ob, Group *group)
return 0;
}
-Group *find_group(Object *ob)
+Group *find_group(Object *ob, Group *group)
{
- Group *group= G.main->group.first;
+ if (group)
+ group= group->id.next;
+ else
+ group= G.main->group.first;
while(group) {
if(object_in_group(ob, group))
@@ -188,6 +222,20 @@ void group_tag_recalc(Group *group)
}
}
+int group_is_animated(Object *parent, Group *group)
+{
+ GroupObject *go;
+
+ if(give_timeoffset(parent) != 0.0f || parent->nlastrips.first)
+ return 1;
+
+ for(go= group->gobject.first; go; go= go->next)
+ if(go->ob && go->ob->proxy)
+ return 1;
+
+ return 0;
+}
+
/* only replaces object strips or action when parent nla instructs it */
/* keep checking nla.c though, in case internal structure of strip changes */
static void group_replaces_nla(Object *parent, Object *target, char mode)
@@ -228,7 +276,6 @@ static void group_replaces_nla(Object *parent, Object *target, char mode)
}
}
-
/* puts all group members in local timing system, after this call
you can draw everything, leaves tags in objects to signal it needs further updating */
@@ -238,12 +285,12 @@ void group_handle_recalc_and_update(Object *parent, Group *group)
GroupObject *go;
/* if animated group... */
- if(parent->sf != 0.0f || parent->nlastrips.first) {
+ if(give_timeoffset(parent) != 0.0f || parent->nlastrips.first) {
int cfrao;
/* switch to local time */
cfrao= G.scene->r.cfra;
- G.scene->r.cfra -= (int)parent->sf;
+ G.scene->r.cfra -= (int)give_timeoffset(parent);
/* we need a DAG per group... */
for(go= group->gobject.first; go; go= go->next) {
diff --git a/source/blender/blenkernel/intern/icons.c b/source/blender/blenkernel/intern/icons.c
index f144d2badd1..b9e3c593ddf 100644
--- a/source/blender/blenkernel/intern/icons.c
+++ b/source/blender/blenkernel/intern/icons.c
@@ -48,6 +48,9 @@
#include "BLI_ghash.h"
#include "BKE_icons.h"
+#include "BKE_utildefines.h"
+
+#include "BLO_sys_types.h" // for intptr_t support
#define GS(a) (*((short *)(a)))
@@ -87,7 +90,7 @@ static int get_next_free_id()
return gNextIconId++;
/* now we try to find the smallest icon id not stored in the gIcons hash */
- while (BLI_ghash_lookup(gIcons, (void *)startId) && startId>=gFirstIconId)
+ while (BLI_ghash_lookup(gIcons, SET_INT_IN_POINTER(startId)) && startId>=gFirstIconId)
startId++;
/* if we found a suitable one that isnt used yet, return it */
@@ -216,7 +219,7 @@ void BKE_icon_changed(int id)
if (!id) return;
- icon = BLI_ghash_lookup(gIcons, (void *)id);
+ icon = BLI_ghash_lookup(gIcons, SET_INT_IN_POINTER(id));
if (icon)
{
@@ -258,7 +261,7 @@ int BKE_icon_getid(struct ID* id)
new_icon->drawinfo = 0;
new_icon->drawinfo_free = 0;
- BLI_ghash_insert(gIcons, (void *)id->icon_id, new_icon);
+ BLI_ghash_insert(gIcons, SET_INT_IN_POINTER(id->icon_id), new_icon);
return id->icon_id;
}
@@ -267,7 +270,7 @@ Icon* BKE_icon_get(int icon_id)
{
Icon* icon = 0;
- icon = BLI_ghash_lookup(gIcons, (void*)icon_id);
+ icon = BLI_ghash_lookup(gIcons, SET_INT_IN_POINTER(icon_id));
if (!icon) {
printf("BKE_icon_get: Internal error, no icon for icon ID: %d\n", icon_id);
@@ -281,7 +284,7 @@ void BKE_icon_set(int icon_id, struct Icon* icon)
{
Icon* old_icon = 0;
- old_icon = BLI_ghash_lookup(gIcons, (void*)icon_id);
+ old_icon = BLI_ghash_lookup(gIcons, SET_INT_IN_POINTER(icon_id));
if (old_icon)
{
@@ -289,7 +292,7 @@ void BKE_icon_set(int icon_id, struct Icon* icon)
return;
}
- BLI_ghash_insert(gIcons, (void *)icon_id, icon);
+ BLI_ghash_insert(gIcons, SET_INT_IN_POINTER(icon_id), icon);
}
void BKE_icon_delete(struct ID* id)
@@ -297,6 +300,6 @@ void BKE_icon_delete(struct ID* id)
if (!id->icon_id) return; /* no icon defined for library object */
- BLI_ghash_remove(gIcons, (void*)id->icon_id, 0, icon_free);
+ BLI_ghash_remove(gIcons, SET_INT_IN_POINTER(id->icon_id), 0, icon_free);
id->icon_id = 0;
}
diff --git a/source/blender/blenkernel/intern/idprop.c b/source/blender/blenkernel/intern/idprop.c
index eb633e92cc0..542a1dff651 100644
--- a/source/blender/blenkernel/intern/idprop.c
+++ b/source/blender/blenkernel/intern/idprop.c
@@ -54,7 +54,8 @@ static char idp_size_table[] = {
sizeof(float)*16, /*Matrix type, deprecated*/
0, /*arrays don't have a fixed size*/
sizeof(ListBase), /*Group type*/
- sizeof(void*)
+ sizeof(void*),
+ sizeof(double)
};
@@ -110,6 +111,7 @@ void IDP_ResizeArray(IDProperty *prop, int newlen)
newp->type = prop->type;
newp->flag = prop->flag;
newp->data.val = prop->data.val;
+ newp->data.val2 = prop->data.val2;
return newp;
}
@@ -209,7 +211,8 @@ void IDP_UnlinkID(IDProperty *prop)
IDProperty *IDP_CopyGroup(IDProperty *prop)
{
IDProperty *newp = idp_generic_copy(prop), *link;
-
+ newp->len = prop->len;
+
for (link=prop->data.group.first; link; link=link->next) {
BLI_addtail(&newp->data.group, IDP_CopyProperty(link));
}
@@ -217,6 +220,10 @@ IDProperty *IDP_CopyGroup(IDProperty *prop)
return newp;
}
+/*
+ replaces a property with the same name in a group, or adds
+ it if the propery doesn't exist.
+*/
void IDP_ReplaceInGroup(IDProperty *group, IDProperty *prop)
{
IDProperty *loop;
@@ -224,10 +231,10 @@ void IDP_ReplaceInGroup(IDProperty *group, IDProperty *prop)
if (BSTR_EQ(loop->name, prop->name)) {
if (loop->next) BLI_insertlinkbefore(&group->data.group, loop->next, prop);
else BLI_addtail(&group->data.group, prop);
+
BLI_remlink(&group->data.group, loop);
IDP_FreeProperty(loop);
- MEM_freeN(loop);
- group->len++;
+ MEM_freeN(loop);
return;
}
}
@@ -259,7 +266,7 @@ int IDP_InsertToGroup(IDProperty *group, IDProperty *previous, IDProperty *pnew)
}
group->len++;
-
+
BLI_insertlink(&group->data.group, previous, pnew);
return 1;
}
@@ -314,7 +321,7 @@ void IDP_FreeIterBeforeEnd(void *vself)
This is because all ID Property freeing functions free only direct data (not the ID Property
struct itself), but for Groups the child properties *are* considered
direct data.*/
-void IDP_FreeGroup(IDProperty *prop)
+static void IDP_FreeGroup(IDProperty *prop)
{
IDProperty *loop, *next;
for (loop=prop->data.group.first; loop; loop=next)
@@ -345,6 +352,10 @@ IDProperty *IDP_GetProperties(ID *id, int create_if_needed)
if (create_if_needed) {
id->properties = MEM_callocN(sizeof(IDProperty), "IDProperty");
id->properties->type = IDP_GROUP;
+ /* dont overwite the data's name and type
+ * some functions might need this if they
+ * dont have a real ID, should be named elsewhere - Campbell */
+ /* strcpy(id->name, "top_level_group");*/
}
return id->properties;
}
@@ -363,10 +374,14 @@ IDProperty *IDP_New(int type, IDPropertyTemplate val, char *name)
prop = MEM_callocN(sizeof(IDProperty), "IDProperty float");
*(float*)&prop->data.val = val.f;
break;
+ case IDP_DOUBLE:
+ prop = MEM_callocN(sizeof(IDProperty), "IDProperty float");
+ *(double*)&prop->data.val = val.d;
+ break;
case IDP_ARRAY:
{
- /*for now, we only support float and int arrays*/
- if (val.array.type == IDP_FLOAT || val.array.type == IDP_INT) {
+ /*for now, we only support float and int and double arrays*/
+ if (val.array.type == IDP_FLOAT || val.array.type == IDP_INT || val.array.type == IDP_DOUBLE) {
prop = MEM_callocN(sizeof(IDProperty), "IDProperty array");
prop->len = prop->totallen = val.array.len;
prop->subtype = val.array.type;
@@ -409,10 +424,14 @@ IDProperty *IDP_New(int type, IDPropertyTemplate val, char *name)
prop->type = type;
strncpy(prop->name, name, MAX_IDPROP_NAME);
+
+ /*security null byte*/
+ prop->name[MAX_IDPROP_NAME-1] = 0;
+
return prop;
}
-/*NOTE: this will free all child properties of list arrays and groups!
+/*NOTE: this will free all child properties including list arrays and groups!
Also, note that this does NOT unlink anything! Plus it doesn't free
the actual IDProperty struct either.*/
void IDP_FreeProperty(IDProperty *prop)
@@ -430,7 +449,8 @@ void IDP_FreeProperty(IDProperty *prop)
}
}
-/*Unlinks any IDProperty<->ID linkage that might be going on.*/
+/*Unlinks any IDProperty<->ID linkage that might be going on.
+ note: currently unused.*/
void IDP_UnlinkProperty(IDProperty *prop)
{
switch (prop->type) {
diff --git a/source/blender/blenkernel/intern/image.c b/source/blender/blenkernel/intern/image.c
index a79433fcfa1..de1747e514c 100644
--- a/source/blender/blenkernel/intern/image.c
+++ b/source/blender/blenkernel/intern/image.c
@@ -53,6 +53,7 @@
#include "DNA_packedFile_types.h"
#include "DNA_scene_types.h"
#include "DNA_camera_types.h"
+#include "DNA_sequence_types.h"
#include "DNA_texture_types.h"
#include "DNA_sequence_types.h"
#include "DNA_userdef_types.h"
@@ -81,6 +82,11 @@
/* for stamp drawing to an image */
#include "BMF_Api.h"
+#include "GPU_extensions.h"
+#include "GPU_draw.h"
+
+#include "BLO_sys_types.h" // for intptr_t support
+
/* max int, to indicate we don't store sequences in ibuf */
#define IMA_NO_INDEX 0x7FEFEFEF
@@ -93,32 +99,50 @@
/* used by sequencer and image premul option - IMA_DO_PREMUL */
void converttopremul(struct ImBuf *ibuf)
{
- int x, y, val;
- char *cp;
+ int x, y;
if(ibuf==0) return;
- if(ibuf->depth==24) { /* put alpha at 255 */
-
- cp= (char *)(ibuf->rect);
- for(y=0; y<ibuf->y; y++) {
- for(x=0; x<ibuf->x; x++, cp+=4) {
- cp[3]= 255;
+ if (ibuf->rect) {
+ int val;
+ char *cp;
+ if(ibuf->depth==24) { /* put alpha at 255 */
+ cp= (char *)(ibuf->rect);
+ for(y=0; y<ibuf->y; y++) {
+ for(x=0; x<ibuf->x; x++, cp+=4) {
+ cp[3]= 255;
+ }
+ }
+ } else {
+ cp= (char *)(ibuf->rect);
+ for(y=0; y<ibuf->y; y++) {
+ for(x=0; x<ibuf->x; x++, cp+=4) {
+ val= cp[3];
+ cp[0]= (cp[0]*val)>>8;
+ cp[1]= (cp[1]*val)>>8;
+ cp[2]= (cp[2]*val)>>8;
+ }
}
}
- return;
}
-
- cp= (char *)(ibuf->rect);
- for(y=0; y<ibuf->y; y++) {
- for(x=0; x<ibuf->x; x++, cp+=4) {
- if(cp[3]==0) {
- cp[0]= cp[1]= cp[2]= 0;
+ if (ibuf->rect_float) {
+ float val;
+ float *cp;
+ if(ibuf->depth==24) { /* put alpha at 1.0 */
+ cp= ibuf->rect_float;;
+ for(y=0; y<ibuf->y; y++) {
+ for(x=0; x<ibuf->x; x++, cp+=4) {
+ cp[3]= 1.0;
+ }
}
- else if(cp[3]!=255) {
- val= cp[3];
- cp[0]= (cp[0]*val)>>8;
- cp[1]= (cp[1]*val)>>8;
- cp[2]= (cp[2]*val)>>8;
+ } else {
+ cp= ibuf->rect_float;
+ for(y=0; y<ibuf->y; y++) {
+ for(x=0; x<ibuf->x; x++, cp+=4) {
+ val= cp[3];
+ cp[0]= cp[0]*val;
+ cp[1]= cp[1]*val;
+ cp[2]= cp[2]*val;
+ }
}
}
}
@@ -215,7 +239,7 @@ static void image_free_buffers(Image *ima)
ima->rr= NULL;
}
- //XXX free_realtime_image(ima);
+ GPU_free_image(ima);
ima->ok= IMA_OK;
}
@@ -223,7 +247,6 @@ static void image_free_buffers(Image *ima)
/* called by library too, do not free ima itself */
void free_image(Image *ima)
{
-
image_free_buffers(ima);
if (ima->packedfile) {
freePackedFile(ima->packedfile);
@@ -234,7 +257,6 @@ void free_image(Image *ima)
if (ima->preview) {
BKE_previewimg_free(&ima->preview);
}
-
}
/* only image block itself */
@@ -260,15 +282,19 @@ static Image *image_alloc(const char *name, short source, short type)
/* get the ibuf from an image cache, local use here only */
static ImBuf *image_get_ibuf(Image *ima, int index, int frame)
{
+ /* this function is intended to be thread safe. with IMA_NO_INDEX this
+ * should be OK, but when iterating over the list this is more tricky
+ * */
if(index==IMA_NO_INDEX)
return ima->ibufs.first;
else {
ImBuf *ibuf;
-
+
index= IMA_MAKE_INDEX(frame, index);
for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next)
if(ibuf->index==index)
return ibuf;
+
return NULL;
}
}
@@ -296,19 +322,16 @@ static void image_assign_ibuf(Image *ima, ImBuf *ibuf, int index, int frame)
for(link= ima->ibufs.first; link; link= link->next)
if(link->index>=index)
break;
- /* now we don't want copies? */
- if(link && ibuf->index==link->index) {
- ImBuf *prev= ibuf->prev;
- image_remove_ibuf(ima, link);
- link= prev;
- }
-
+
+ ibuf->index= index;
+
/* this function accepts link==NULL */
BLI_insertlinkbefore(&ima->ibufs, link, ibuf);
-
- ibuf->index= index;
+
+ /* now we don't want copies? */
+ if(link && ibuf->index==link->index)
+ image_remove_ibuf(ima, link);
}
-
}
/* checks if image was already loaded, then returns same image */
@@ -329,7 +352,8 @@ Image *BKE_add_image_file(const char *name)
}
BLI_strncpy(str, name, sizeof(str));
- BLI_convertstringcode(str, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(str, G.sce);
+ BLI_convertstringframe(str, G.scene->r.cfra); /* TODO - should this realy be here? */
/* exists? */
file= open(str, O_BINARY|O_RDONLY);
@@ -340,7 +364,8 @@ Image *BKE_add_image_file(const char *name)
for(ima= G.main->image.first; ima; ima= ima->id.next) {
if(ima->source!=IMA_SRC_VIEWER && ima->source!=IMA_SRC_GENERATED) {
BLI_strncpy(strtest, ima->name, sizeof(ima->name));
- BLI_convertstringcode(strtest, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(strtest, G.sce);
+ BLI_convertstringframe(strtest, G.scene->r.cfra); /* TODO - should this be here? */
if( strcmp(strtest, str)==0 ) {
if(ima->anim==NULL || ima->id.us==0) {
@@ -373,20 +398,27 @@ Image *BKE_add_image_file(const char *name)
return ima;
}
-static ImBuf *add_ibuf_size(int width, int height, char *name, short uvtestgrid, float color[4])
+static ImBuf *add_ibuf_size(int width, int height, char *name, int floatbuf, short uvtestgrid, float color[4])
{
ImBuf *ibuf;
float h=0.0, hoffs=0.0, hue=0.0, s=0.9, v=0.9, r, g, b;
- unsigned char *rect;
+ unsigned char *rect= NULL;
+ float *rect_float= NULL;
int x, y;
int checkerwidth=21, dark=1;
- ibuf= IMB_allocImBuf(width, height, 24, IB_rect, 0);
+ if (floatbuf) {
+ ibuf= IMB_allocImBuf(width, height, 24, IB_rectfloat, 0);
+ rect_float= (float*)ibuf->rect_float;
+ }
+ else {
+ ibuf= IMB_allocImBuf(width, height, 24, IB_rect, 0);
+ rect= (unsigned char*)ibuf->rect;
+ }
+
strcpy(ibuf->name, "Untitled");
ibuf->userflags |= IB_BITMAPDIRTY;
- rect= (unsigned char*)ibuf->rect;
-
if (uvtestgrid) {
/* these two passes could be combined into one, but it's more readable and
* easy to tweak like this, speed isn't really that much of an issue in this situation... */
@@ -395,26 +427,40 @@ static ImBuf *add_ibuf_size(int width, int height, char *name, short uvtestgrid,
for(y=0; y<ibuf->y; y++) {
dark = pow(-1, floor(y / checkerwidth));
- for(x=0; x<ibuf->x; x++, rect+=4) {
+ for(x=0; x<ibuf->x; x++) {
if (x % checkerwidth == 0) dark *= -1;
- if (dark > 0) {
- rect[0] = rect[1] = rect[2] = 64;
- rect[3] = 255;
- } else {
- rect[0] = rect[1] = rect[2] = 150;
- rect[3] = 255;
+ if (floatbuf) {
+ if (dark > 0) {
+ rect_float[0] = rect_float[1] = rect_float[2] = 0.25;
+ rect_float[3] = 1.0;
+ } else {
+ rect_float[0] = rect_float[1] = rect_float[2] = 0.58;
+ rect_float[3] = 1.0;
+ }
+ rect_float+=4;
+ }
+ else {
+ if (dark > 0) {
+ rect[0] = rect[1] = rect[2] = 64;
+ rect[3] = 255;
+ } else {
+ rect[0] = rect[1] = rect[2] = 150;
+ rect[3] = 255;
+ }
+ rect += 4;
}
}
}
/* 2nd pass, colored + */
- rect= (unsigned char*)ibuf->rect;
+ if (floatbuf) rect_float= (float*)ibuf->rect_float;
+ else rect= (unsigned char*)ibuf->rect;
for(y=0; y<ibuf->y; y++) {
hoffs = 0.125 * floor(y / checkerwidth);
- for(x=0; x<ibuf->x; x++, rect+=4) {
+ for(x=0; x<ibuf->x; x++) {
h = 0.125 * floor(x / checkerwidth);
if ((fabs((x % checkerwidth) - (checkerwidth / 2)) < 4) &&
@@ -426,22 +472,44 @@ static ImBuf *add_ibuf_size(int width, int height, char *name, short uvtestgrid,
hue = fmod(fabs(h-hoffs), 1.0);
hsv_to_rgb(hue, s, v, &r, &g, &b);
- rect[0]= (char)(r * 255.0);
- rect[1]= (char)(g * 255.0);
- rect[2]= (char)(b * 255.0);
- rect[3]= 255;
+ if (floatbuf) {
+ rect_float[0]= r;
+ rect_float[1]= g;
+ rect_float[2]= b;
+ rect_float[3]= 1.0;
+ }
+ else {
+ rect[0]= (char)(r * 255.0);
+ rect[1]= (char)(g * 255.0);
+ rect[2]= (char)(b * 255.0);
+ rect[3]= 255;
+ }
}
}
-
+
+ if (floatbuf)
+ rect_float+=4;
+ else
+ rect+=4;
}
}
} else { /* blank image */
for(y=0; y<ibuf->y; y++) {
- for(x=0; x<ibuf->x; x++, rect+=4) {
- rect[0]= (char)(color[0] * 255.0);
- rect[1]= (char)(color[1] * 255.0);
- rect[2]= (char)(color[2] * 255.0);
- rect[3]= (char)(color[3] * 255.0);
+ for(x=0; x<ibuf->x; x++) {
+ if (floatbuf) {
+ rect_float[0]= color[0];
+ rect_float[1]= color[1];
+ rect_float[2]= color[2];
+ rect_float[3]= color[3];
+ rect_float+=4;
+ }
+ else {
+ rect[0]= (char)(color[0] * 255.0);
+ rect[1]= (char)(color[1] * 255.0);
+ rect[2]= (char)(color[2] * 255.0);
+ rect[3]= (char)(color[3] * 255.0);
+ rect+=4;
+ }
}
}
}
@@ -449,7 +517,7 @@ static ImBuf *add_ibuf_size(int width, int height, char *name, short uvtestgrid,
}
/* adds new image block, creates ImBuf and initializes color */
-Image *BKE_add_image_size(int width, int height, char *name, short uvtestgrid, float color[4])
+Image *BKE_add_image_size(int width, int height, char *name, int floatbuf, short uvtestgrid, float color[4])
{
Image *ima;
@@ -464,7 +532,7 @@ Image *BKE_add_image_size(int width, int height, char *name, short uvtestgrid, f
ima->gen_y= height;
ima->gen_type= uvtestgrid;
- ibuf= add_ibuf_size(width, height, name, uvtestgrid, color);
+ ibuf= add_ibuf_size(width, height, name, floatbuf, uvtestgrid, color);
image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
ima->ok= IMA_OK_LOADED;
@@ -515,7 +583,7 @@ void tag_image_time(Image *ima)
ima->lastused = (int)PIL_check_seconds_timer();
}
-void tag_all_images_time()
+static void tag_all_images_time()
{
Image *ima;
int ctime = (int)PIL_check_seconds_timer();
@@ -551,7 +619,7 @@ void free_old_images()
This gives textures a "second chance" to be used before dying.
*/
if(ima->bindcode || ima->repbind) {
- //XXX free_realtime_image(ima);
+ GPU_free_image(ima);
ima->lastused = ctime;
}
/* Otherwise, just kill the buffers */
@@ -563,6 +631,47 @@ void free_old_images()
}
}
+static uintptr_t image_mem_size(Image *ima)
+{
+ ImBuf *ibuf, *ibufm;
+ int level;
+ uintptr_t size = 0;
+
+ size= 0;
+ for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next) {
+ if(ibuf->rect) size += MEM_allocN_len(ibuf->rect);
+ else if(ibuf->rect_float) size += MEM_allocN_len(ibuf->rect_float);
+
+ for(level=0; level<IB_MIPMAP_LEVELS; level++) {
+ ibufm= ibuf->mipmap[level];
+ if(ibufm) {
+ if(ibufm->rect) size += MEM_allocN_len(ibufm->rect);
+ else if(ibufm->rect_float) size += MEM_allocN_len(ibufm->rect_float);
+ }
+ }
+ }
+
+ return size;
+}
+
+void BKE_image_print_memlist(void)
+{
+ Image *ima;
+ uintptr_t size, totsize= 0;
+
+ for(ima= G.main->image.first; ima; ima= ima->id.next)
+ totsize += image_mem_size(ima);
+
+ printf("\ntotal image memory len: %.3lf MB\n", (double)totsize/(double)(1024*1024));
+
+ for(ima= G.main->image.first; ima; ima= ima->id.next) {
+ size= image_mem_size(ima);
+
+ if(size)
+ printf("%s len: %.3f MB\n", ima->id.name+2, (double)size/(double)(1024*1024));
+ }
+}
+
void BKE_image_free_all_textures(void)
{
Tex *tex;
@@ -740,17 +849,13 @@ void BKE_add_image_extension(char *string, int imtype)
if(!BLI_testextensie(string, ".tga"))
extension= ".tga";
}
- else if(ELEM5(imtype, R_MOVIE, R_AVICODEC, R_AVIRAW, R_AVIJPEG, R_JPEG90)) {
- if(!( BLI_testextensie(string, ".jpg") || BLI_testextensie(string, ".jpeg")))
- extension= ".jpg";
- }
else if(imtype==R_BMP) {
if(!BLI_testextensie(string, ".bmp"))
extension= ".bmp";
}
else if(G.have_libtiff && (imtype==R_TIFF)) {
- if(!BLI_testextensie(string, ".tif"))
- extension= ".tif";
+ if(!BLI_testextensie(string, ".tif") &&
+ !BLI_testextensie(string, ".tiff")) extension= ".tif";
}
#ifdef WITH_OPENEXR
else if( ELEM(imtype, R_OPENEXR, R_MULTILAYER)) {
@@ -766,10 +871,14 @@ void BKE_add_image_extension(char *string, int imtype)
if (!BLI_testextensie(string, ".dpx"))
extension= ".dpx";
}
- else { /* targa default */
+ else if(imtype==R_TARGA) {
if(!BLI_testextensie(string, ".tga"))
extension= ".tga";
}
+ else { // R_MOVIE, R_AVICODEC, R_AVIRAW, R_AVIJPEG, R_JPEG90, R_QUICKTIME etc
+ if(!( BLI_testextensie(string, ".jpg") || BLI_testextensie(string, ".jpeg")))
+ extension= ".jpg";
+ }
strcat(string, extension);
}
@@ -799,8 +908,13 @@ static void stampdata(StampData *stamp_data, int do_prefix)
#endif /* WIN32 */
if (G.scene->r.stamp & R_STAMP_FILENAME) {
- if (do_prefix) sprintf(stamp_data->file, "File %s", G.sce);
- else sprintf(stamp_data->file, "%s", G.sce);
+ if (G.relbase_valid) {
+ if (do_prefix) sprintf(stamp_data->file, "File %s", G.sce);
+ else sprintf(stamp_data->file, "%s", G.sce);
+ } else {
+ if (do_prefix) strcpy(stamp_data->file, "File <untitled>");
+ else strcpy(stamp_data->file, "<untitled>");
+ }
stamp_data->note[0] = '\0';
} else {
stamp_data->file[0] = '\0';
@@ -877,8 +991,11 @@ static void stampdata(StampData *stamp_data, int do_prefix)
}
if (G.scene->r.stamp & R_STAMP_CAMERA) {
- if (do_prefix) sprintf(stamp_data->camera, "Camera %s", ((Camera *) G.scene->camera)->id.name+2);
- else sprintf(stamp_data->camera, "%s", ((Camera *) G.scene->camera)->id.name+2);
+ if (G.scene->camera) strcpy(text, ((Camera *) G.scene->camera)->id.name+2);
+ else strcpy(text, "<none>");
+
+ if (do_prefix) sprintf(stamp_data->camera, "Camera %s", text);
+ else sprintf(stamp_data->camera, "%s", text);
} else {
stamp_data->camera[0] = '\0';
}
@@ -903,7 +1020,7 @@ static void stampdata(StampData *stamp_data, int do_prefix)
}
}
-void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height)
+void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height, int channels)
{
struct StampData stamp_data;
@@ -951,7 +1068,7 @@ void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height)
/* Top left corner */
text_width = BMF_GetStringWidth(font, stamp_data.file);
buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
- BMF_DrawStringBuf(font, stamp_data.file, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
+ BMF_DrawStringBuf(font, stamp_data.file, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
y -= font_height+2; /* Top and bottom 1 pix padding each */
}
@@ -959,7 +1076,7 @@ void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height)
if (stamp_data.note[0]) {
text_width = BMF_GetStringWidth(font, stamp_data.note);
buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
- BMF_DrawStringBuf(font, stamp_data.note, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
+ BMF_DrawStringBuf(font, stamp_data.note, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
y -= font_height+2; /* Top and bottom 1 pix padding each */
}
@@ -967,7 +1084,7 @@ void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height)
if (stamp_data.date[0]) {
text_width = BMF_GetStringWidth(font, stamp_data.date);
buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
- BMF_DrawStringBuf(font, stamp_data.date, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
+ BMF_DrawStringBuf(font, stamp_data.date, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
}
/* Bottom left corner, leaving space for timing */
@@ -976,7 +1093,7 @@ void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height)
y = font_height+2+1; /* 2 for padding in TIME|FRAME fields below and 1 for padding in this one */
text_width = BMF_GetStringWidth(font, stamp_data.marker);
buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
- BMF_DrawStringBuf(font, stamp_data.marker, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
+ BMF_DrawStringBuf(font, stamp_data.marker, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
}
/* Left bottom corner */
@@ -985,7 +1102,7 @@ void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height)
y = 1;
text_width = BMF_GetStringWidth(font, stamp_data.time);
buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
- BMF_DrawStringBuf(font, stamp_data.time, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
+ BMF_DrawStringBuf(font, stamp_data.time, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
x += text_width+text_pad+2; /* Both sides have 1 pix additional padding each */
}
@@ -995,7 +1112,7 @@ void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height)
if (!stamp_data.time[0]) x = 1;
y = 1;
buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
- BMF_DrawStringBuf(font, stamp_data.frame, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
+ BMF_DrawStringBuf(font, stamp_data.frame, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
}
if (stamp_data.camera[0]) {
@@ -1004,7 +1121,7 @@ void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height)
x = (width/2) - (BMF_GetStringWidth(font, stamp_data.camera)/2);
y = 1;
buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
- BMF_DrawStringBuf(font, stamp_data.camera, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
+ BMF_DrawStringBuf(font, stamp_data.camera, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
}
if (stamp_data.scene[0]) {
@@ -1013,7 +1130,7 @@ void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height)
x = width - (text_width+1+text_pad);
y = 1;
buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
- BMF_DrawStringBuf(font, stamp_data.scene, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
+ BMF_DrawStringBuf(font, stamp_data.scene, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
}
if (stamp_data.strip[0]) {
@@ -1022,7 +1139,7 @@ void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height)
x = width - (text_width+1+text_pad);
y = height - font_height - 1;
buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
- BMF_DrawStringBuf(font, stamp_data.strip, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
+ BMF_DrawStringBuf(font, stamp_data.strip, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
}
}
@@ -1070,6 +1187,9 @@ int BKE_write_ibuf(ImBuf *ibuf, char *name, int imtype, int subimtype, int quali
}
else if ((G.have_libtiff) && (imtype==R_TIFF)) {
ibuf->ftype= TIF;
+
+ if(subimtype & R_TIFF_16BIT)
+ ibuf->ftype |= TIF_16BIT;
}
#ifdef WITH_OPENEXR
else if (imtype==R_OPENEXR || imtype==R_MULTILAYER) {
@@ -1121,23 +1241,16 @@ int BKE_write_ibuf(ImBuf *ibuf, char *name, int imtype, int subimtype, int quali
void BKE_makepicstring(char *string, char *base, int frame, int imtype)
{
- short i, len, digits= 4; /* digits in G.scene? */
- char num[10];
-
if (string==NULL) return;
BLI_strncpy(string, base, FILE_MAX - 10); /* weak assumption */
- BLI_convertstringcode(string, G.sce, frame);
-
- len= strlen(string);
-
- i= digits - sprintf(num, "%d", frame);
- for(; i>0; i--){
- string[len]= '0';
- len++;
- }
- string[len]= 0;
- strcat(string, num);
+
+ /* if we dont have any #'s to insert numbers into, use 4 numbers by default */
+ if (strchr(string, '#')==NULL)
+ strcat(string, "####"); /* 4 numbers */
+
+ BLI_convertstringcode(string, G.sce);
+ BLI_convertstringframe(string, frame);
if(G.scene->r.scemode & R_EXTENSION)
BKE_add_image_extension(string, imtype);
@@ -1373,9 +1486,11 @@ static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
BLI_strncpy(name, ima->name, sizeof(name));
if(ima->id.lib)
- BLI_convertstringcode(name, ima->id.lib->filename, frame);
+ BLI_convertstringcode(name, ima->id.lib->filename);
else
- BLI_convertstringcode(name, G.sce, frame);
+ BLI_convertstringcode(name, G.sce);
+
+ BLI_convertstringframe(name, frame); /* TODO - should this be here? */
/* read ibuf */
ibuf = IMB_loadiffname(name, IB_rect|IB_multilayer);
@@ -1391,13 +1506,17 @@ static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
ibuf= NULL;
}
else {
- image_assign_ibuf(ima, ibuf, 0, frame);
image_initialize_after_load(ima, ibuf);
+ image_assign_ibuf(ima, ibuf, 0, frame);
}
#else
- image_assign_ibuf(ima, ibuf, 0, frame);
image_initialize_after_load(ima, ibuf);
+ image_assign_ibuf(ima, ibuf, 0, frame);
#endif
+
+ if(ima->flag & IMA_DO_PREMUL)
+ converttopremul(ibuf);
+
}
else
ima->ok= 0;
@@ -1432,8 +1551,9 @@ static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int f
// if(oldrr) printf("freed previous result %p\n", oldrr);
if(oldrr) RE_FreeRenderResult(oldrr);
}
- else
+ else {
ima->rr= oldrr;
+ }
}
if(ima->rr) {
@@ -1448,8 +1568,8 @@ static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int f
ibuf->mall= IB_rectfloat;
ibuf->channels= rpass->channels;
- image_assign_ibuf(ima, ibuf, iuser->multi_index, frame);
image_initialize_after_load(ima, ibuf);
+ image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:0, frame);
}
// else printf("pass not found\n");
@@ -1475,9 +1595,9 @@ static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
BLI_strncpy(str, ima->name, FILE_MAX);
if(ima->id.lib)
- BLI_convertstringcode(str, ima->id.lib->filename, 0);
+ BLI_convertstringcode(str, ima->id.lib->filename);
else
- BLI_convertstringcode(str, G.sce, 0);
+ BLI_convertstringcode(str, G.sce);
ima->anim = openanim(str, IB_cmap | IB_rect);
@@ -1495,8 +1615,8 @@ static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
ibuf = IMB_anim_absolute(ima->anim, fra);
if(ibuf) {
- image_assign_ibuf(ima, ibuf, 0, frame);
image_initialize_after_load(ima, ibuf);
+ image_assign_ibuf(ima, ibuf, 0, frame);
}
else
ima->ok= 0;
@@ -1515,6 +1635,7 @@ static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
{
struct ImBuf *ibuf;
char str[FILE_MAX];
+ int assign = 0;
/* always ensure clean ima */
image_free_buffers(ima);
@@ -1528,9 +1649,11 @@ static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
/* get the right string */
BLI_strncpy(str, ima->name, sizeof(str));
if(ima->id.lib)
- BLI_convertstringcode(str, ima->id.lib->filename, cfra);
+ BLI_convertstringcode(str, ima->id.lib->filename);
else
- BLI_convertstringcode(str, G.sce, cfra);
+ BLI_convertstringcode(str, G.sce);
+
+ BLI_convertstringframe(str, cfra);
/* read ibuf */
ibuf = IMB_loadiffname(str, IB_rect|IB_multilayer|IB_imginfo);
@@ -1545,8 +1668,8 @@ static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
ibuf= NULL;
}
else {
- image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
image_initialize_after_load(ima, ibuf);
+ assign= 1;
/* check if the image is a font image... */
detectBitmapFont(ibuf);
@@ -1562,6 +1685,9 @@ static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
else
ima->ok= 0;
+ if(assign)
+ image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
+
if(iuser)
iuser->ok= ima->ok;
@@ -1585,12 +1711,13 @@ static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
if(rpass) {
ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
- image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
image_initialize_after_load(ima, ibuf);
ibuf->rect_float= rpass->rect;
ibuf->flags |= IB_rectfloat;
ibuf->channels= rpass->channels;
+
+ image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
}
}
@@ -1609,31 +1736,38 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser)
{
RenderResult *rr= RE_GetResult(RE_GetRender(G.scene->id.name));
- if(rr && iuser) {
+ if(rr) {
RenderResult rres;
float *rectf;
unsigned int *rect;
- int channels= 4, layer= iuser->layer;
+ float dither;
+ int channels, layer, pass;
+
+ channels= 4;
+ layer= (iuser)? iuser->layer: 0;
+ pass= (iuser)? iuser->pass: 0;
/* this gives active layer, composite or seqence result */
RE_GetResultImage(RE_GetRender(G.scene->id.name), &rres);
rect= (unsigned int *)rres.rect32;
rectf= rres.rectf;
-
+ dither= G.scene->r.dither_intensity;
+
/* get compo/seq result by default */
if(rr->rectf && layer==0);
else if(rr->layers.first) {
- RenderLayer *rl= BLI_findlink(&rr->layers, iuser->layer-(rr->rectf?1:0));
+ RenderLayer *rl= BLI_findlink(&rr->layers, layer-(rr->rectf?1:0));
if(rl) {
/* there's no combined pass, is in renderlayer itself */
- if(iuser->pass==0) {
+ if(pass==0) {
rectf= rl->rectf;
}
else {
- RenderPass *rpass= BLI_findlink(&rl->passes, iuser->pass-1);
+ RenderPass *rpass= BLI_findlink(&rl->passes, pass-1);
if(rpass) {
channels= rpass->channels;
rectf= rpass->rect;
+ dither= 0.0f; /* don't dither passes */
}
}
}
@@ -1658,6 +1792,9 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser)
ibuf->rect_float= rectf;
ibuf->flags |= IB_rectfloat;
ibuf->channels= channels;
+ ibuf->zbuf_float= rres.rectz;
+ ibuf->flags |= IB_zbuffloat;
+ ibuf->dither= dither;
ima->ok= IMA_OK_LOADED;
return ibuf;
@@ -1667,118 +1804,171 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser)
return NULL;
}
-/* Checks optional ImageUser and verifies/creates ImBuf. */
-/* returns ibuf */
-ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
+static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
{
- ImBuf *ibuf= NULL;
- float color[] = {0, 0, 0, 1};
+ ImBuf *ibuf = NULL;
+ int frame = 0, index = 0;
- /* quick reject tests */
- if(ima==NULL)
- return NULL;
- if(iuser) {
- if(iuser->ok==0)
- return NULL;
- }
- else if(ima->ok==0)
- return NULL;
-
- BLI_lock_thread(LOCK_IMAGE);
-
- /* handle image source and types */
+ /* see if we already have an appropriate ibuf, with image source and type */
if(ima->source==IMA_SRC_MOVIE) {
- /* source is from single file, use flipbook to store ibuf */
- int frame= iuser?iuser->framenr:ima->lastframe;
-
+ frame= iuser?iuser->framenr:ima->lastframe;
ibuf= image_get_ibuf(ima, 0, frame);
- if(ibuf==NULL)
- ibuf= image_load_movie_file(ima, iuser, frame);
}
else if(ima->source==IMA_SRC_SEQUENCE) {
-
if(ima->type==IMA_TYPE_IMAGE) {
- /* regular files, ibufs in flipbook, allows saving */
- int frame= iuser?iuser->framenr:ima->lastframe;
-
+ frame= iuser?iuser->framenr:ima->lastframe;
ibuf= image_get_ibuf(ima, 0, frame);
- if(ibuf==NULL)
- ibuf= image_load_sequence_file(ima, iuser, frame);
- else
- BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
}
- /* no else; on load the ima type can change */
- if(ima->type==IMA_TYPE_MULTILAYER) {
- /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
- int frame= iuser?iuser->framenr:ima->lastframe;
- int index= iuser?iuser->multi_index:IMA_NO_INDEX;
-
+ else if(ima->type==IMA_TYPE_MULTILAYER) {
+ frame= iuser?iuser->framenr:ima->lastframe;
+ index= iuser?iuser->multi_index:IMA_NO_INDEX;
ibuf= image_get_ibuf(ima, index, frame);
- if(G.rt) printf("seq multi fra %d id %d ibuf %p %s\n", frame, index, ibuf, ima->id.name);
- if(ibuf==NULL)
- ibuf= image_load_sequence_multilayer(ima, iuser, frame);
- else
- BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
}
-
}
else if(ima->source==IMA_SRC_FILE) {
-
- if(ima->type==IMA_TYPE_IMAGE) {
+ if(ima->type==IMA_TYPE_IMAGE)
ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
- if(ibuf==NULL)
- ibuf= image_load_image_file(ima, iuser, G.scene->r.cfra); /* cfra only for '#', this global is OK */
- }
- /* no else; on load the ima type can change */
- if(ima->type==IMA_TYPE_MULTILAYER) {
- /* keeps render result, stores ibufs in listbase, allows saving */
+ else if(ima->type==IMA_TYPE_MULTILAYER)
ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
- if(ibuf==NULL)
- ibuf= image_get_ibuf_multilayer(ima, iuser);
- }
-
}
else if(ima->source == IMA_SRC_GENERATED) {
- /* generated is: ibuf is allocated dynamically */
ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
-
- if(ibuf==NULL) {
- if(ima->type==IMA_TYPE_VERSE) {
- /* todo */
- }
- else { /* always fall back to IMA_TYPE_UV_TEST */
- /* UV testgrid or black or solid etc */
- if(ima->gen_x==0) ima->gen_x= 256;
- if(ima->gen_y==0) ima->gen_y= 256;
- ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, ima->gen_type, color);
- image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
- ima->ok= IMA_OK_LOADED;
- }
- }
}
else if(ima->source == IMA_SRC_VIEWER) {
if(ima->type==IMA_TYPE_R_RESULT) {
- /* always verify entirely */
- ibuf= image_get_render_result(ima, iuser);
+ /* always verify entirely, not that this shouldn't happen
+ * during render anyway */
}
else if(ima->type==IMA_TYPE_COMPOSITE) {
- int frame= iuser?iuser->framenr:0;
-
- /* Composite Viewer, all handled in compositor */
+ frame= iuser?iuser->framenr:0;
ibuf= image_get_ibuf(ima, 0, frame);
- if(ibuf==NULL) {
- /* fake ibuf, will be filled in compositor */
- ibuf= IMB_allocImBuf(256, 256, 32, IB_rect, 0);
- image_assign_ibuf(ima, ibuf, 0, frame);
+ }
+ }
+
+ *frame_r = frame;
+ *index_r = index;
+
+ return ibuf;
+}
+
+/* Checks optional ImageUser and verifies/creates ImBuf. */
+/* returns ibuf */
+ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
+{
+ ImBuf *ibuf= NULL;
+ float color[] = {0, 0, 0, 1};
+ int frame= 0, index= 0;
+
+ /* This function is intended to be thread-safe. It postpones the mutex lock
+ * until it needs to load the image, if the image is already there it
+ * should just get the pointer and return. The reason is that a lot of mutex
+ * locks appears to be very slow on certain multicore macs, causing a render
+ * with image textures to actually slow down as more threads are used.
+ *
+ * Note that all the image loading functions should also make sure they do
+ * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
+ * That means, the last two steps must be, 1) add the ibuf to the list and
+ * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
+
+ /* quick reject tests */
+ if(ima==NULL)
+ return NULL;
+ if(iuser) {
+ if(iuser->ok==0)
+ return NULL;
+ }
+ else if(ima->ok==0)
+ return NULL;
+
+ /* try to get the ibuf without locking */
+ ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
+
+ if(ibuf == NULL) {
+ /* couldn't get ibuf and image is not ok, so let's lock and try to
+ * load the image */
+ BLI_lock_thread(LOCK_IMAGE);
+
+ /* need to check ok flag and loading ibuf again, because the situation
+ * might have changed in the meantime */
+ if(iuser) {
+ if(iuser->ok==0) {
+ BLI_unlock_thread(LOCK_IMAGE);
+ return NULL;
}
}
+ else if(ima->ok==0) {
+ BLI_unlock_thread(LOCK_IMAGE);
+ return NULL;
+ }
+
+ ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
+
+ if(ibuf == NULL) {
+ /* we are sure we have to load the ibuf, using source and type */
+ if(ima->source==IMA_SRC_MOVIE) {
+ /* source is from single file, use flipbook to store ibuf */
+ ibuf= image_load_movie_file(ima, iuser, frame);
+ }
+ else if(ima->source==IMA_SRC_SEQUENCE) {
+ if(ima->type==IMA_TYPE_IMAGE) {
+ /* regular files, ibufs in flipbook, allows saving */
+ ibuf= image_load_sequence_file(ima, iuser, frame);
+ }
+ /* no else; on load the ima type can change */
+ if(ima->type==IMA_TYPE_MULTILAYER) {
+ /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
+ ibuf= image_load_sequence_multilayer(ima, iuser, frame);
+ }
+
+ if(ibuf)
+ BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
+ }
+ else if(ima->source==IMA_SRC_FILE) {
+
+ if(ima->type==IMA_TYPE_IMAGE)
+ ibuf= image_load_image_file(ima, iuser, G.scene->r.cfra); /* cfra only for '#', this global is OK */
+ /* no else; on load the ima type can change */
+ if(ima->type==IMA_TYPE_MULTILAYER)
+ /* keeps render result, stores ibufs in listbase, allows saving */
+ ibuf= image_get_ibuf_multilayer(ima, iuser);
+
+ }
+ else if(ima->source == IMA_SRC_GENERATED) {
+ /* generated is: ibuf is allocated dynamically */
+ if(ima->type==IMA_TYPE_VERSE) {
+ /* todo */
+ }
+ else { /* always fall back to IMA_TYPE_UV_TEST */
+ /* UV testgrid or black or solid etc */
+ if(ima->gen_x==0) ima->gen_x= 256;
+ if(ima->gen_y==0) ima->gen_y= 256;
+ ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 0, ima->gen_type, color);
+ image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
+ ima->ok= IMA_OK_LOADED;
+ }
+ }
+ else if(ima->source == IMA_SRC_VIEWER) {
+ if(ima->type==IMA_TYPE_R_RESULT) {
+ /* always verify entirely */
+ ibuf= image_get_render_result(ima, iuser);
+ }
+ else if(ima->type==IMA_TYPE_COMPOSITE) {
+ /* Composite Viewer, all handled in compositor */
+ /* fake ibuf, will be filled in compositor */
+ ibuf= IMB_allocImBuf(256, 256, 32, IB_rect, 0);
+ image_assign_ibuf(ima, ibuf, 0, frame);
+ }
+ }
+ }
+
+ BLI_unlock_thread(LOCK_IMAGE);
}
+ /* we assuming that if it is not rendering, it's also not multithreaded
+ * (a somewhat weak assumption) */
if(G.rendering==0)
tag_image_time(ima);
- BLI_unlock_thread(LOCK_IMAGE);
-
return ibuf;
}
diff --git a/source/blender/blenkernel/intern/implicit.c b/source/blender/blenkernel/intern/implicit.c
new file mode 100644
index 00000000000..93e35a4db06
--- /dev/null
+++ b/source/blender/blenkernel/intern/implicit.c
@@ -0,0 +1,1709 @@
+/* implicit.c
+*
+*
+* ***** BEGIN GPL LICENSE BLOCK *****
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 2
+* of the License, or (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software Foundation,
+* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*
+* The Original Code is Copyright (C) Blender Foundation
+* All rights reserved.
+*
+* The Original Code is: all of this file.
+*
+* Contributor(s): none yet.
+*
+* ***** END GPL LICENSE BLOCK *****
+*/
+
+#include "MEM_guardedalloc.h"
+
+#include "BKE_cloth.h"
+
+#include "DNA_cloth_types.h"
+#include "DNA_scene_types.h"
+
+#include "BKE_effect.h"
+#include "BKE_global.h"
+#include "BKE_cloth.h"
+#include "BKE_utildefines.h"
+
+#ifdef _WIN32
+#include <windows.h>
+static LARGE_INTEGER _itstart, _itend;
+static LARGE_INTEGER ifreq;
+void itstart(void)
+{
+ static int first = 1;
+ if(first) {
+ QueryPerformanceFrequency(&ifreq);
+ first = 0;
+ }
+ QueryPerformanceCounter(&_itstart);
+}
+void itend(void)
+{
+ QueryPerformanceCounter(&_itend);
+}
+double itval()
+{
+ return ((double)_itend.QuadPart -
+ (double)_itstart.QuadPart)/((double)ifreq.QuadPart);
+}
+#else
+#include <sys/time.h>
+// intrinsics need better compile flag checking
+// #include <xmmintrin.h>
+// #include <pmmintrin.h>
+// #include <pthread.h>
+
+ static struct timeval _itstart, _itend;
+ static struct timezone itz;
+ void itstart(void)
+{
+ gettimeofday(&_itstart, &itz);
+}
+void itend(void)
+{
+ gettimeofday(&_itend,&itz);
+}
+double itval()
+{
+ double t1, t2;
+ t1 = (double)_itstart.tv_sec + (double)_itstart.tv_usec/(1000*1000);
+ t2 = (double)_itend.tv_sec + (double)_itend.tv_usec/(1000*1000);
+ return t2-t1;
+}
+#endif
+
+static float I[3][3] = {{1,0,0},{0,1,0},{0,0,1}};
+static float ZERO[3][3] = {{0,0,0}, {0,0,0}, {0,0,0}};
+
+/*
+#define C99
+#ifdef C99
+#defineDO_INLINE inline
+#else
+#defineDO_INLINE static
+#endif
+*/
+struct Cloth;
+
+//////////////////////////////////////////
+/* fast vector / matrix library, enhancements are welcome :) -dg */
+/////////////////////////////////////////
+
+/* DEFINITIONS */
+typedef float lfVector[3];
+typedef struct fmatrix3x3 {
+ float m[3][3]; /* 3x3 matrix */
+ unsigned int c,r; /* column and row number */
+ int pinned; /* is this vertex allowed to move? */
+ float n1,n2,n3; /* three normal vectors for collision constrains */
+ unsigned int vcount; /* vertex count */
+ unsigned int scount; /* spring count */
+} fmatrix3x3;
+
+///////////////////////////
+// float[3] vector
+///////////////////////////
+/* simple vector code */
+/* STATUS: verified */
+DO_INLINE void mul_fvector_S(float to[3], float from[3], float scalar)
+{
+ to[0] = from[0] * scalar;
+ to[1] = from[1] * scalar;
+ to[2] = from[2] * scalar;
+}
+/* simple cross product */
+/* STATUS: verified */
+DO_INLINE void cross_fvector(float to[3], float vectorA[3], float vectorB[3])
+{
+ to[0] = vectorA[1] * vectorB[2] - vectorA[2] * vectorB[1];
+ to[1] = vectorA[2] * vectorB[0] - vectorA[0] * vectorB[2];
+ to[2] = vectorA[0] * vectorB[1] - vectorA[1] * vectorB[0];
+}
+/* simple v^T * v product ("outer product") */
+/* STATUS: HAS TO BE verified (*should* work) */
+DO_INLINE void mul_fvectorT_fvector(float to[3][3], float vectorA[3], float vectorB[3])
+{
+ mul_fvector_S(to[0], vectorB, vectorA[0]);
+ mul_fvector_S(to[1], vectorB, vectorA[1]);
+ mul_fvector_S(to[2], vectorB, vectorA[2]);
+}
+/* simple v^T * v product with scalar ("outer product") */
+/* STATUS: HAS TO BE verified (*should* work) */
+DO_INLINE void mul_fvectorT_fvectorS(float to[3][3], float vectorA[3], float vectorB[3], float aS)
+{
+ mul_fvectorT_fvector(to, vectorA, vectorB);
+
+ mul_fvector_S(to[0], to[0], aS);
+ mul_fvector_S(to[1], to[1], aS);
+ mul_fvector_S(to[2], to[2], aS);
+}
+
+
+/* printf vector[3] on console: for debug output */
+void print_fvector(float m3[3])
+{
+ printf("%f\n%f\n%f\n\n",m3[0],m3[1],m3[2]);
+}
+
+///////////////////////////
+// long float vector float (*)[3]
+///////////////////////////
+/* print long vector on console: for debug output */
+DO_INLINE void print_lfvector(float (*fLongVector)[3], unsigned int verts)
+{
+ unsigned int i = 0;
+ for(i = 0; i < verts; i++)
+ {
+ print_fvector(fLongVector[i]);
+ }
+}
+/* create long vector */
+DO_INLINE lfVector *create_lfvector(unsigned int verts)
+{
+ // TODO: check if memory allocation was successfull */
+ return (lfVector *)MEM_callocN (verts * sizeof(lfVector), "cloth_implicit_alloc_vector");
+ // return (lfVector *)cloth_aligned_malloc(&MEMORY_BASE, verts * sizeof(lfVector));
+}
+/* delete long vector */
+DO_INLINE void del_lfvector(float (*fLongVector)[3])
+{
+ if (fLongVector != NULL)
+ {
+ MEM_freeN (fLongVector);
+ // cloth_aligned_free(&MEMORY_BASE, fLongVector);
+ }
+}
+/* copy long vector */
+DO_INLINE void cp_lfvector(float (*to)[3], float (*from)[3], unsigned int verts)
+{
+ memcpy(to, from, verts * sizeof(lfVector));
+}
+/* init long vector with float[3] */
+DO_INLINE void init_lfvector(float (*fLongVector)[3], float vector[3], unsigned int verts)
+{
+ unsigned int i = 0;
+ for(i = 0; i < verts; i++)
+ {
+ VECCOPY(fLongVector[i], vector);
+ }
+}
+/* zero long vector with float[3] */
+DO_INLINE void zero_lfvector(float (*to)[3], unsigned int verts)
+{
+ memset(to, 0.0f, verts * sizeof(lfVector));
+}
+/* multiply long vector with scalar*/
+DO_INLINE void mul_lfvectorS(float (*to)[3], float (*fLongVector)[3], float scalar, unsigned int verts)
+{
+ unsigned int i = 0;
+
+ for(i = 0; i < verts; i++)
+ {
+ mul_fvector_S(to[i], fLongVector[i], scalar);
+ }
+}
+/* multiply long vector with scalar*/
+/* A -= B * float */
+DO_INLINE void submul_lfvectorS(float (*to)[3], float (*fLongVector)[3], float scalar, unsigned int verts)
+{
+ unsigned int i = 0;
+ for(i = 0; i < verts; i++)
+ {
+ VECSUBMUL(to[i], fLongVector[i], scalar);
+ }
+}
+/* dot product for big vector */
+DO_INLINE float dot_lfvector(float (*fLongVectorA)[3], float (*fLongVectorB)[3], unsigned int verts)
+{
+ long i = 0;
+ float temp = 0.0;
+// schedule(guided, 2)
+#pragma omp parallel for reduction(+: temp)
+ for(i = 0; i < (long)verts; i++)
+ {
+ temp += INPR(fLongVectorA[i], fLongVectorB[i]);
+ }
+ return temp;
+}
+/* A = B + C --> for big vector */
+DO_INLINE void add_lfvector_lfvector(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], unsigned int verts)
+{
+ unsigned int i = 0;
+
+ for(i = 0; i < verts; i++)
+ {
+ VECADD(to[i], fLongVectorA[i], fLongVectorB[i]);
+ }
+
+}
+/* A = B + C * float --> for big vector */
+DO_INLINE void add_lfvector_lfvectorS(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], float bS, unsigned int verts)
+{
+ unsigned int i = 0;
+
+ for(i = 0; i < verts; i++)
+ {
+ VECADDS(to[i], fLongVectorA[i], fLongVectorB[i], bS);
+
+ }
+}
+/* A = B * float + C * float --> for big vector */
+DO_INLINE void add_lfvectorS_lfvectorS(float (*to)[3], float (*fLongVectorA)[3], float aS, float (*fLongVectorB)[3], float bS, unsigned int verts)
+{
+ unsigned int i = 0;
+
+ for(i = 0; i < verts; i++)
+ {
+ VECADDSS(to[i], fLongVectorA[i], aS, fLongVectorB[i], bS);
+ }
+}
+/* A = B - C * float --> for big vector */
+DO_INLINE void sub_lfvector_lfvectorS(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], float bS, unsigned int verts)
+{
+ unsigned int i = 0;
+ for(i = 0; i < verts; i++)
+ {
+ VECSUBS(to[i], fLongVectorA[i], fLongVectorB[i], bS);
+ }
+
+}
+/* A = B - C --> for big vector */
+DO_INLINE void sub_lfvector_lfvector(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], unsigned int verts)
+{
+ unsigned int i = 0;
+
+ for(i = 0; i < verts; i++)
+ {
+ VECSUB(to[i], fLongVectorA[i], fLongVectorB[i]);
+ }
+
+}
+///////////////////////////
+// 3x3 matrix
+///////////////////////////
+/* printf 3x3 matrix on console: for debug output */
+void print_fmatrix(float m3[3][3])
+{
+ printf("%f\t%f\t%f\n",m3[0][0],m3[0][1],m3[0][2]);
+ printf("%f\t%f\t%f\n",m3[1][0],m3[1][1],m3[1][2]);
+ printf("%f\t%f\t%f\n\n",m3[2][0],m3[2][1],m3[2][2]);
+}
+
+/* copy 3x3 matrix */
+DO_INLINE void cp_fmatrix(float to[3][3], float from[3][3])
+{
+ // memcpy(to, from, sizeof (float) * 9);
+ VECCOPY(to[0], from[0]);
+ VECCOPY(to[1], from[1]);
+ VECCOPY(to[2], from[2]);
+}
+
+/* copy 3x3 matrix */
+DO_INLINE void initdiag_fmatrixS(float to[3][3], float aS)
+{
+ cp_fmatrix(to, ZERO);
+
+ to[0][0] = aS;
+ to[1][1] = aS;
+ to[2][2] = aS;
+}
+
+/* calculate determinant of 3x3 matrix */
+DO_INLINE float det_fmatrix(float m[3][3])
+{
+ return m[0][0]*m[1][1]*m[2][2] + m[1][0]*m[2][1]*m[0][2] + m[0][1]*m[1][2]*m[2][0]
+ -m[0][0]*m[1][2]*m[2][1] - m[0][1]*m[1][0]*m[2][2] - m[2][0]*m[1][1]*m[0][2];
+}
+
+DO_INLINE void inverse_fmatrix(float to[3][3], float from[3][3])
+{
+ unsigned int i, j;
+ float d;
+
+ if((d=det_fmatrix(from))==0)
+ {
+ printf("can't build inverse");
+ exit(0);
+ }
+ for(i=0;i<3;i++)
+ {
+ for(j=0;j<3;j++)
+ {
+ int i1=(i+1)%3;
+ int i2=(i+2)%3;
+ int j1=(j+1)%3;
+ int j2=(j+2)%3;
+ // reverse indexs i&j to take transpose
+ to[j][i] = (from[i1][j1]*from[i2][j2]-from[i1][j2]*from[i2][j1])/d;
+ /*
+ if(i==j)
+ to[i][j] = 1.0f / from[i][j];
+ else
+ to[i][j] = 0;
+ */
+ }
+ }
+
+}
+
+/* 3x3 matrix multiplied by a scalar */
+/* STATUS: verified */
+DO_INLINE void mul_fmatrix_S(float matrix[3][3], float scalar)
+{
+ mul_fvector_S(matrix[0], matrix[0],scalar);
+ mul_fvector_S(matrix[1], matrix[1],scalar);
+ mul_fvector_S(matrix[2], matrix[2],scalar);
+}
+
+/* a vector multiplied by a 3x3 matrix */
+/* STATUS: verified */
+DO_INLINE void mul_fvector_fmatrix(float *to, float *from, float matrix[3][3])
+{
+ to[0] = matrix[0][0]*from[0] + matrix[1][0]*from[1] + matrix[2][0]*from[2];
+ to[1] = matrix[0][1]*from[0] + matrix[1][1]*from[1] + matrix[2][1]*from[2];
+ to[2] = matrix[0][2]*from[0] + matrix[1][2]*from[1] + matrix[2][2]*from[2];
+}
+
+/* 3x3 matrix multiplied by a vector */
+/* STATUS: verified */
+DO_INLINE void mul_fmatrix_fvector(float *to, float matrix[3][3], float *from)
+{
+ to[0] = INPR(matrix[0],from);
+ to[1] = INPR(matrix[1],from);
+ to[2] = INPR(matrix[2],from);
+}
+/* 3x3 matrix multiplied by a 3x3 matrix */
+/* STATUS: verified */
+DO_INLINE void mul_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
+{
+ mul_fvector_fmatrix(to[0], matrixA[0],matrixB);
+ mul_fvector_fmatrix(to[1], matrixA[1],matrixB);
+ mul_fvector_fmatrix(to[2], matrixA[2],matrixB);
+}
+/* 3x3 matrix addition with 3x3 matrix */
+DO_INLINE void add_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
+{
+ VECADD(to[0], matrixA[0], matrixB[0]);
+ VECADD(to[1], matrixA[1], matrixB[1]);
+ VECADD(to[2], matrixA[2], matrixB[2]);
+}
+/* 3x3 matrix add-addition with 3x3 matrix */
+DO_INLINE void addadd_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
+{
+ VECADDADD(to[0], matrixA[0], matrixB[0]);
+ VECADDADD(to[1], matrixA[1], matrixB[1]);
+ VECADDADD(to[2], matrixA[2], matrixB[2]);
+}
+/* 3x3 matrix sub-addition with 3x3 matrix */
+DO_INLINE void addsub_fmatrixS_fmatrixS(float to[3][3], float matrixA[3][3], float aS, float matrixB[3][3], float bS)
+{
+ VECADDSUBSS(to[0], matrixA[0], aS, matrixB[0], bS);
+ VECADDSUBSS(to[1], matrixA[1], aS, matrixB[1], bS);
+ VECADDSUBSS(to[2], matrixA[2], aS, matrixB[2], bS);
+}
+/* A -= B + C (3x3 matrix sub-addition with 3x3 matrix) */
+DO_INLINE void subadd_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
+{
+ VECSUBADD(to[0], matrixA[0], matrixB[0]);
+ VECSUBADD(to[1], matrixA[1], matrixB[1]);
+ VECSUBADD(to[2], matrixA[2], matrixB[2]);
+}
+/* A -= B*x + C*y (3x3 matrix sub-addition with 3x3 matrix) */
+DO_INLINE void subadd_fmatrixS_fmatrixS(float to[3][3], float matrixA[3][3], float aS, float matrixB[3][3], float bS)
+{
+ VECSUBADDSS(to[0], matrixA[0], aS, matrixB[0], bS);
+ VECSUBADDSS(to[1], matrixA[1], aS, matrixB[1], bS);
+ VECSUBADDSS(to[2], matrixA[2], aS, matrixB[2], bS);
+}
+/* A = B - C (3x3 matrix subtraction with 3x3 matrix) */
+DO_INLINE void sub_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
+{
+ VECSUB(to[0], matrixA[0], matrixB[0]);
+ VECSUB(to[1], matrixA[1], matrixB[1]);
+ VECSUB(to[2], matrixA[2], matrixB[2]);
+}
+/* A += B - C (3x3 matrix add-subtraction with 3x3 matrix) */
+DO_INLINE void addsub_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
+{
+ VECADDSUB(to[0], matrixA[0], matrixB[0]);
+ VECADDSUB(to[1], matrixA[1], matrixB[1]);
+ VECADDSUB(to[2], matrixA[2], matrixB[2]);
+}
+/////////////////////////////////////////////////////////////////
+// special functions
+/////////////////////////////////////////////////////////////////
+/* a vector multiplied and added to/by a 3x3 matrix */
+DO_INLINE void muladd_fvector_fmatrix(float to[3], float from[3], float matrix[3][3])
+{
+ to[0] += matrix[0][0]*from[0] + matrix[1][0]*from[1] + matrix[2][0]*from[2];
+ to[1] += matrix[0][1]*from[0] + matrix[1][1]*from[1] + matrix[2][1]*from[2];
+ to[2] += matrix[0][2]*from[0] + matrix[1][2]*from[1] + matrix[2][2]*from[2];
+}
+/* 3x3 matrix multiplied and added to/by a 3x3 matrix and added to another 3x3 matrix */
+DO_INLINE void muladd_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
+{
+ muladd_fvector_fmatrix(to[0], matrixA[0],matrixB);
+ muladd_fvector_fmatrix(to[1], matrixA[1],matrixB);
+ muladd_fvector_fmatrix(to[2], matrixA[2],matrixB);
+}
+/* a vector multiplied and sub'd to/by a 3x3 matrix */
+DO_INLINE void mulsub_fvector_fmatrix(float to[3], float from[3], float matrix[3][3])
+{
+ to[0] -= matrix[0][0]*from[0] + matrix[1][0]*from[1] + matrix[2][0]*from[2];
+ to[1] -= matrix[0][1]*from[0] + matrix[1][1]*from[1] + matrix[2][1]*from[2];
+ to[2] -= matrix[0][2]*from[0] + matrix[1][2]*from[1] + matrix[2][2]*from[2];
+}
+/* 3x3 matrix multiplied and sub'd to/by a 3x3 matrix and added to another 3x3 matrix */
+DO_INLINE void mulsub_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
+{
+ mulsub_fvector_fmatrix(to[0], matrixA[0],matrixB);
+ mulsub_fvector_fmatrix(to[1], matrixA[1],matrixB);
+ mulsub_fvector_fmatrix(to[2], matrixA[2],matrixB);
+}
+/* 3x3 matrix multiplied+added by a vector */
+/* STATUS: verified */
+DO_INLINE void muladd_fmatrix_fvector(float to[3], float matrix[3][3], float from[3])
+{
+ to[0] += INPR(matrix[0],from);
+ to[1] += INPR(matrix[1],from);
+ to[2] += INPR(matrix[2],from);
+}
+/* 3x3 matrix multiplied+sub'ed by a vector */
+DO_INLINE void mulsub_fmatrix_fvector(float to[3], float matrix[3][3], float from[3])
+{
+ to[0] -= INPR(matrix[0],from);
+ to[1] -= INPR(matrix[1],from);
+ to[2] -= INPR(matrix[2],from);
+}
+/////////////////////////////////////////////////////////////////
+
+///////////////////////////
+// SPARSE SYMMETRIC big matrix with 3x3 matrix entries
+///////////////////////////
+/* printf a big matrix on console: for debug output */
+void print_bfmatrix(fmatrix3x3 *m3)
+{
+ unsigned int i = 0;
+
+ for(i = 0; i < m3[0].vcount + m3[0].scount; i++)
+ {
+ print_fmatrix(m3[i].m);
+ }
+}
+/* create big matrix */
+DO_INLINE fmatrix3x3 *create_bfmatrix(unsigned int verts, unsigned int springs)
+{
+ // TODO: check if memory allocation was successfull */
+ fmatrix3x3 *temp = (fmatrix3x3 *)MEM_callocN (sizeof (fmatrix3x3) * (verts + springs), "cloth_implicit_alloc_matrix");
+ temp[0].vcount = verts;
+ temp[0].scount = springs;
+ return temp;
+}
+/* delete big matrix */
+DO_INLINE void del_bfmatrix(fmatrix3x3 *matrix)
+{
+ if (matrix != NULL)
+ {
+ MEM_freeN (matrix);
+ }
+}
+
+/* copy big matrix */
+DO_INLINE void cp_bfmatrix(fmatrix3x3 *to, fmatrix3x3 *from)
+{
+ // TODO bounds checking
+ memcpy(to, from, sizeof(fmatrix3x3) * (from[0].vcount+from[0].scount) );
+}
+
+/* init big matrix */
+// slow in parallel
+DO_INLINE void init_bfmatrix(fmatrix3x3 *matrix, float m3[3][3])
+{
+ unsigned int i;
+
+ for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
+ {
+ cp_fmatrix(matrix[i].m, m3);
+ }
+}
+
+/* init the diagonal of big matrix */
+// slow in parallel
+DO_INLINE void initdiag_bfmatrix(fmatrix3x3 *matrix, float m3[3][3])
+{
+ unsigned int i,j;
+ float tmatrix[3][3] = {{0,0,0},{0,0,0},{0,0,0}};
+
+ for(i = 0; i < matrix[0].vcount; i++)
+ {
+ cp_fmatrix(matrix[i].m, m3);
+ }
+ for(j = matrix[0].vcount; j < matrix[0].vcount+matrix[0].scount; j++)
+ {
+ cp_fmatrix(matrix[j].m, tmatrix);
+ }
+}
+
+/* multiply big matrix with scalar*/
+DO_INLINE void mul_bfmatrix_S(fmatrix3x3 *matrix, float scalar)
+{
+ unsigned int i = 0;
+ for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
+ {
+ mul_fmatrix_S(matrix[i].m, scalar);
+ }
+}
+
+/* SPARSE SYMMETRIC multiply big matrix with long vector*/
+/* STATUS: verified */
+DO_INLINE void mul_bfmatrix_lfvector( float (*to)[3], fmatrix3x3 *from, lfVector *fLongVector)
+{
+ unsigned int i = 0;
+ lfVector *temp = create_lfvector(from[0].vcount);
+
+ zero_lfvector(to, from[0].vcount);
+
+#pragma omp parallel sections private(i)
+ {
+#pragma omp section
+ {
+ for(i = from[0].vcount; i < from[0].vcount+from[0].scount; i++)
+ {
+ muladd_fmatrix_fvector(to[from[i].c], from[i].m, fLongVector[from[i].r]);
+ }
+ }
+#pragma omp section
+ {
+ for(i = 0; i < from[0].vcount+from[0].scount; i++)
+ {
+ muladd_fmatrix_fvector(temp[from[i].r], from[i].m, fLongVector[from[i].c]);
+ }
+ }
+ }
+ add_lfvector_lfvector(to, to, temp, from[0].vcount);
+
+ del_lfvector(temp);
+
+
+}
+
+/* SPARSE SYMMETRIC multiply big matrix with long vector (for diagonal preconditioner) */
+/* STATUS: verified */
+DO_INLINE void mul_prevfmatrix_lfvector( float (*to)[3], fmatrix3x3 *from, lfVector *fLongVector)
+{
+ unsigned int i = 0;
+
+ for(i = 0; i < from[0].vcount; i++)
+ {
+ mul_fmatrix_fvector(to[from[i].r], from[i].m, fLongVector[from[i].c]);
+ }
+}
+
+/* SPARSE SYMMETRIC add big matrix with big matrix: A = B + C*/
+DO_INLINE void add_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmatrix3x3 *matrix)
+{
+ unsigned int i = 0;
+
+ /* process diagonal elements */
+ for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
+ {
+ add_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);
+ }
+
+}
+/* SPARSE SYMMETRIC add big matrix with big matrix: A += B + C */
+DO_INLINE void addadd_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmatrix3x3 *matrix)
+{
+ unsigned int i = 0;
+
+ /* process diagonal elements */
+ for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
+ {
+ addadd_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);
+ }
+
+}
+/* SPARSE SYMMETRIC subadd big matrix with big matrix: A -= B + C */
+DO_INLINE void subadd_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmatrix3x3 *matrix)
+{
+ unsigned int i = 0;
+
+ /* process diagonal elements */
+ for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
+ {
+ subadd_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);
+ }
+
+}
+/* A = B - C (SPARSE SYMMETRIC sub big matrix with big matrix) */
+DO_INLINE void sub_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmatrix3x3 *matrix)
+{
+ unsigned int i = 0;
+
+ /* process diagonal elements */
+ for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
+ {
+ sub_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);
+ }
+
+}
+/* SPARSE SYMMETRIC sub big matrix with big matrix S (special constraint matrix with limited entries) */
+DO_INLINE void sub_bfmatrix_Smatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmatrix3x3 *matrix)
+{
+ unsigned int i = 0;
+
+ /* process diagonal elements */
+ for(i = 0; i < matrix[0].vcount; i++)
+ {
+ sub_fmatrix_fmatrix(to[matrix[i].c].m, from[matrix[i].c].m, matrix[i].m);
+ }
+
+}
+/* A += B - C (SPARSE SYMMETRIC addsub big matrix with big matrix) */
+DO_INLINE void addsub_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmatrix3x3 *matrix)
+{
+ unsigned int i = 0;
+
+ /* process diagonal elements */
+ for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
+ {
+ addsub_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);
+ }
+
+}
+/* SPARSE SYMMETRIC sub big matrix with big matrix*/
+/* A -= B * float + C * float --> for big matrix */
+/* VERIFIED */
+DO_INLINE void subadd_bfmatrixS_bfmatrixS( fmatrix3x3 *to, fmatrix3x3 *from, float aS, fmatrix3x3 *matrix, float bS)
+{
+ unsigned int i = 0;
+
+ /* process diagonal elements */
+ for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
+ {
+ subadd_fmatrixS_fmatrixS(to[i].m, from[i].m, aS, matrix[i].m, bS);
+ }
+
+}
+
+///////////////////////////////////////////////////////////////////
+// simulator start
+///////////////////////////////////////////////////////////////////
+typedef struct Implicit_Data
+{
+ lfVector *X, *V, *Xnew, *Vnew, *olddV, *F, *B, *dV, *z;
+ fmatrix3x3 *A, *dFdV, *dFdX, *S, *P, *Pinv, *bigI, *M;
+} Implicit_Data;
+
+int implicit_init (Object *ob, ClothModifierData *clmd)
+{
+ unsigned int i = 0;
+ unsigned int pinned = 0;
+ Cloth *cloth = NULL;
+ ClothVertex *verts = NULL;
+ ClothSpring *spring = NULL;
+ Implicit_Data *id = NULL;
+ LinkNode *search = NULL;
+
+ if(G.rt > 0)
+ printf("implicit_init\n");
+
+ // init memory guard
+ // MEMORY_BASE.first = MEMORY_BASE.last = NULL;
+
+ cloth = (Cloth *)clmd->clothObject;
+ verts = cloth->verts;
+
+ // create implicit base
+ id = (Implicit_Data *)MEM_callocN (sizeof(Implicit_Data), "implicit vecmat");
+ cloth->implicit = id;
+
+ /* process diagonal elements */
+ id->A = create_bfmatrix(cloth->numverts, cloth->numsprings);
+ id->dFdV = create_bfmatrix(cloth->numverts, cloth->numsprings);
+ id->dFdX = create_bfmatrix(cloth->numverts, cloth->numsprings);
+ id->S = create_bfmatrix(cloth->numverts, 0);
+ id->Pinv = create_bfmatrix(cloth->numverts, cloth->numsprings);
+ id->P = create_bfmatrix(cloth->numverts, cloth->numsprings);
+ id->bigI = create_bfmatrix(cloth->numverts, cloth->numsprings); // TODO 0 springs
+ id->M = create_bfmatrix(cloth->numverts, cloth->numsprings);
+ id->X = create_lfvector(cloth->numverts);
+ id->Xnew = create_lfvector(cloth->numverts);
+ id->V = create_lfvector(cloth->numverts);
+ id->Vnew = create_lfvector(cloth->numverts);
+ id->olddV = create_lfvector(cloth->numverts);
+ zero_lfvector(id->olddV, cloth->numverts);
+ id->F = create_lfvector(cloth->numverts);
+ id->B = create_lfvector(cloth->numverts);
+ id->dV = create_lfvector(cloth->numverts);
+ id->z = create_lfvector(cloth->numverts);
+
+ for(i=0;i<cloth->numverts;i++)
+ {
+ id->A[i].r = id->A[i].c = id->dFdV[i].r = id->dFdV[i].c = id->dFdX[i].r = id->dFdX[i].c = id->P[i].c = id->P[i].r = id->Pinv[i].c = id->Pinv[i].r = id->bigI[i].c = id->bigI[i].r = id->M[i].r = id->M[i].c = i;
+
+ if(verts [i].flags & CLOTH_VERT_FLAG_PINNED)
+ {
+ id->S[pinned].pinned = 1;
+ id->S[pinned].c = id->S[pinned].r = i;
+ pinned++;
+ }
+
+ initdiag_fmatrixS(id->M[i].m, verts[i].mass);
+ }
+
+ // S is special and needs specific vcount and scount
+ id->S[0].vcount = pinned; id->S[0].scount = 0;
+
+ // init springs
+ search = cloth->springs;
+ for(i=0;i<cloth->numsprings;i++)
+ {
+ spring = search->link;
+
+ // dFdV_start[i].r = big_I[i].r = big_zero[i].r =
+ id->A[i+cloth->numverts].r = id->dFdV[i+cloth->numverts].r = id->dFdX[i+cloth->numverts].r =
+ id->P[i+cloth->numverts].r = id->Pinv[i+cloth->numverts].r = id->bigI[i+cloth->numverts].r = id->M[i+cloth->numverts].r = spring->ij;
+
+ // dFdV_start[i].c = big_I[i].c = big_zero[i].c =
+ id->A[i+cloth->numverts].c = id->dFdV[i+cloth->numverts].c = id->dFdX[i+cloth->numverts].c =
+ id->P[i+cloth->numverts].c = id->Pinv[i+cloth->numverts].c = id->bigI[i+cloth->numverts].c = id->M[i+cloth->numverts].c = spring->kl;
+
+ spring->matrix_index = i + cloth->numverts;
+
+ search = search->next;
+ }
+
+ initdiag_bfmatrix(id->bigI, I);
+
+ for(i = 0; i < cloth->numverts; i++)
+ {
+ VECCOPY(id->X[i], verts[i].x);
+ }
+
+ return 1;
+}
+int implicit_free (ClothModifierData *clmd)
+{
+ Implicit_Data *id;
+ Cloth *cloth;
+ cloth = (Cloth *)clmd->clothObject;
+
+ if(cloth)
+ {
+ id = cloth->implicit;
+
+ if(id)
+ {
+ del_bfmatrix(id->A);
+ del_bfmatrix(id->dFdV);
+ del_bfmatrix(id->dFdX);
+ del_bfmatrix(id->S);
+ del_bfmatrix(id->P);
+ del_bfmatrix(id->Pinv);
+ del_bfmatrix(id->bigI);
+ del_bfmatrix(id->M);
+
+ del_lfvector(id->X);
+ del_lfvector(id->Xnew);
+ del_lfvector(id->V);
+ del_lfvector(id->Vnew);
+ del_lfvector(id->olddV);
+ del_lfvector(id->F);
+ del_lfvector(id->B);
+ del_lfvector(id->dV);
+ del_lfvector(id->z);
+
+ MEM_freeN(id);
+ }
+ }
+
+ return 1;
+}
+
+DO_INLINE float fb(float length, float L)
+{
+ float x = length/L;
+ return (-11.541f*pow(x,4)+34.193f*pow(x,3)-39.083f*pow(x,2)+23.116f*x-9.713f);
+}
+
+DO_INLINE float fbderiv(float length, float L)
+{
+ float x = length/L;
+
+ return (-46.164f*pow(x,3)+102.579f*pow(x,2)-78.166f*x+23.116f);
+}
+
+DO_INLINE float fbstar(float length, float L, float kb, float cb)
+{
+ float tempfb = kb * fb(length, L);
+
+ float fbstar = cb * (length - L);
+
+ if(tempfb < fbstar)
+ return fbstar;
+ else
+ return tempfb;
+}
+
+// function to calculae bending spring force (taken from Choi & Co)
+DO_INLINE float fbstar_jacobi(float length, float L, float kb, float cb)
+{
+ float tempfb = kb * fb(length, L);
+ float fbstar = cb * (length - L);
+
+ if(tempfb < fbstar)
+ {
+ return cb;
+ }
+ else
+ {
+ return kb * fbderiv(length, L);
+ }
+}
+
+DO_INLINE void filter(lfVector *V, fmatrix3x3 *S)
+{
+ unsigned int i=0;
+
+ for(i=0;i<S[0].vcount;i++)
+ {
+ mul_fvector_fmatrix(V[S[i].r], V[S[i].r], S[i].m);
+ }
+}
+
+int cg_filtered(lfVector *ldV, fmatrix3x3 *lA, lfVector *lB, lfVector *z, fmatrix3x3 *S)
+{
+ // Solves for unknown X in equation AX=B
+ unsigned int conjgrad_loopcount=0, conjgrad_looplimit=100;
+ float conjgrad_epsilon=0.0001f, conjgrad_lasterror=0;
+ lfVector *q, *d, *tmp, *r;
+ float s, starget, a, s_prev;
+ unsigned int numverts = lA[0].vcount;
+ q = create_lfvector(numverts);
+ d = create_lfvector(numverts);
+ tmp = create_lfvector(numverts);
+ r = create_lfvector(numverts);
+
+ // zero_lfvector(ldV, CLOTHPARTICLES);
+ filter(ldV, S);
+
+ add_lfvector_lfvector(ldV, ldV, z, numverts);
+
+ // r = B - Mul(tmp,A,X); // just use B if X known to be zero
+ cp_lfvector(r, lB, numverts);
+ mul_bfmatrix_lfvector(tmp, lA, ldV);
+ sub_lfvector_lfvector(r, r, tmp, numverts);
+
+ filter(r,S);
+
+ cp_lfvector(d, r, numverts);
+
+ s = dot_lfvector(r, r, numverts);
+ starget = s * sqrt(conjgrad_epsilon);
+
+ while((s>starget && conjgrad_loopcount < conjgrad_looplimit))
+ {
+ // Mul(q,A,d); // q = A*d;
+ mul_bfmatrix_lfvector(q, lA, d);
+
+ filter(q,S);
+
+ a = s/dot_lfvector(d, q, numverts);
+
+ // X = X + d*a;
+ add_lfvector_lfvectorS(ldV, ldV, d, a, numverts);
+
+ // r = r - q*a;
+ sub_lfvector_lfvectorS(r, r, q, a, numverts);
+
+ s_prev = s;
+ s = dot_lfvector(r, r, numverts);
+
+ //d = r+d*(s/s_prev);
+ add_lfvector_lfvectorS(d, r, d, (s/s_prev), numverts);
+
+ filter(d,S);
+
+ conjgrad_loopcount++;
+ }
+ conjgrad_lasterror = s;
+
+ del_lfvector(q);
+ del_lfvector(d);
+ del_lfvector(tmp);
+ del_lfvector(r);
+ // printf("W/O conjgrad_loopcount: %d\n", conjgrad_loopcount);
+
+ return conjgrad_loopcount<conjgrad_looplimit; // true means we reached desired accuracy in given time - ie stable
+}
+
+// block diagonalizer
+DO_INLINE void BuildPPinv(fmatrix3x3 *lA, fmatrix3x3 *P, fmatrix3x3 *Pinv)
+{
+ unsigned int i = 0;
+
+ // Take only the diagonal blocks of A
+// #pragma omp parallel for private(i)
+ for(i = 0; i<lA[0].vcount; i++)
+ {
+ // block diagonalizer
+ cp_fmatrix(P[i].m, lA[i].m);
+ inverse_fmatrix(Pinv[i].m, P[i].m);
+
+ }
+}
+/*
+// version 1.3
+int cg_filtered_pre(lfVector *dv, fmatrix3x3 *lA, lfVector *lB, lfVector *z, fmatrix3x3 *S, fmatrix3x3 *P, fmatrix3x3 *Pinv)
+{
+ unsigned int numverts = lA[0].vcount, iterations = 0, conjgrad_looplimit=100;
+ float delta0 = 0, deltaNew = 0, deltaOld = 0, alpha = 0;
+ float conjgrad_epsilon=0.0001; // 0.2 is dt for steps=5
+ lfVector *r = create_lfvector(numverts);
+ lfVector *p = create_lfvector(numverts);
+ lfVector *s = create_lfvector(numverts);
+ lfVector *h = create_lfvector(numverts);
+
+ BuildPPinv(lA, P, Pinv);
+
+ filter(dv, S);
+ add_lfvector_lfvector(dv, dv, z, numverts);
+
+ mul_bfmatrix_lfvector(r, lA, dv);
+ sub_lfvector_lfvector(r, lB, r, numverts);
+ filter(r, S);
+
+ mul_prevfmatrix_lfvector(p, Pinv, r);
+ filter(p, S);
+
+ deltaNew = dot_lfvector(r, p, numverts);
+
+ delta0 = deltaNew * sqrt(conjgrad_epsilon);
+
+ // itstart();
+
+ while ((deltaNew > delta0) && (iterations < conjgrad_looplimit))
+ {
+ iterations++;
+
+ mul_bfmatrix_lfvector(s, lA, p);
+ filter(s, S);
+
+ alpha = deltaNew / dot_lfvector(p, s, numverts);
+
+ add_lfvector_lfvectorS(dv, dv, p, alpha, numverts);
+
+ add_lfvector_lfvectorS(r, r, s, -alpha, numverts);
+
+ mul_prevfmatrix_lfvector(h, Pinv, r);
+ filter(h, S);
+
+ deltaOld = deltaNew;
+
+ deltaNew = dot_lfvector(r, h, numverts);
+
+ add_lfvector_lfvectorS(p, h, p, deltaNew / deltaOld, numverts);
+
+ filter(p, S);
+
+ }
+
+ // itend();
+ // printf("cg_filtered_pre time: %f\n", (float)itval());
+
+ del_lfvector(h);
+ del_lfvector(s);
+ del_lfvector(p);
+ del_lfvector(r);
+
+ printf("iterations: %d\n", iterations);
+
+ return iterations<conjgrad_looplimit;
+}
+*/
+// version 1.4
+int cg_filtered_pre(lfVector *dv, fmatrix3x3 *lA, lfVector *lB, lfVector *z, fmatrix3x3 *S, fmatrix3x3 *P, fmatrix3x3 *Pinv, fmatrix3x3 *bigI)
+{
+ unsigned int numverts = lA[0].vcount, iterations = 0, conjgrad_looplimit=100;
+ float delta0 = 0, deltaNew = 0, deltaOld = 0, alpha = 0, tol = 0;
+ lfVector *r = create_lfvector(numverts);
+ lfVector *p = create_lfvector(numverts);
+ lfVector *s = create_lfvector(numverts);
+ lfVector *h = create_lfvector(numverts);
+ lfVector *bhat = create_lfvector(numverts);
+ lfVector *btemp = create_lfvector(numverts);
+
+ BuildPPinv(lA, P, Pinv);
+
+ initdiag_bfmatrix(bigI, I);
+ sub_bfmatrix_Smatrix(bigI, bigI, S);
+
+ // x = Sx_0+(I-S)z
+ filter(dv, S);
+ add_lfvector_lfvector(dv, dv, z, numverts);
+
+ // b_hat = S(b-A(I-S)z)
+ mul_bfmatrix_lfvector(r, lA, z);
+ mul_bfmatrix_lfvector(bhat, bigI, r);
+ sub_lfvector_lfvector(bhat, lB, bhat, numverts);
+
+ // r = S(b-Ax)
+ mul_bfmatrix_lfvector(r, lA, dv);
+ sub_lfvector_lfvector(r, lB, r, numverts);
+ filter(r, S);
+
+ // p = SP^-1r
+ mul_prevfmatrix_lfvector(p, Pinv, r);
+ filter(p, S);
+
+ // delta0 = bhat^TP^-1bhat
+ mul_prevfmatrix_lfvector(btemp, Pinv, bhat);
+ delta0 = dot_lfvector(bhat, btemp, numverts);
+
+ // deltaNew = r^TP
+ deltaNew = dot_lfvector(r, p, numverts);
+
+ /*
+ filter(dv, S);
+ add_lfvector_lfvector(dv, dv, z, numverts);
+
+ mul_bfmatrix_lfvector(r, lA, dv);
+ sub_lfvector_lfvector(r, lB, r, numverts);
+ filter(r, S);
+
+ mul_prevfmatrix_lfvector(p, Pinv, r);
+ filter(p, S);
+
+ deltaNew = dot_lfvector(r, p, numverts);
+
+ delta0 = deltaNew * sqrt(conjgrad_epsilon);
+ */
+
+ // itstart();
+
+ tol = (0.01*0.2);
+
+ while ((deltaNew > delta0*tol*tol) && (iterations < conjgrad_looplimit))
+ {
+ iterations++;
+
+ mul_bfmatrix_lfvector(s, lA, p);
+ filter(s, S);
+
+ alpha = deltaNew / dot_lfvector(p, s, numverts);
+
+ add_lfvector_lfvectorS(dv, dv, p, alpha, numverts);
+
+ add_lfvector_lfvectorS(r, r, s, -alpha, numverts);
+
+ mul_prevfmatrix_lfvector(h, Pinv, r);
+ filter(h, S);
+
+ deltaOld = deltaNew;
+
+ deltaNew = dot_lfvector(r, h, numverts);
+
+ add_lfvector_lfvectorS(p, h, p, deltaNew / deltaOld, numverts);
+
+ filter(p, S);
+
+ }
+
+ // itend();
+ // printf("cg_filtered_pre time: %f\n", (float)itval());
+
+ del_lfvector(btemp);
+ del_lfvector(bhat);
+ del_lfvector(h);
+ del_lfvector(s);
+ del_lfvector(p);
+ del_lfvector(r);
+
+ // printf("iterations: %d\n", iterations);
+
+ return iterations<conjgrad_looplimit;
+}
+
+// outer product is NOT cross product!!!
+DO_INLINE void dfdx_spring_type1(float to[3][3], float extent[3], float length, float L, float dot, float k)
+{
+ // dir is unit length direction, rest is spring's restlength, k is spring constant.
+ // return (outerprod(dir,dir)*k + (I - outerprod(dir,dir))*(k - ((k*L)/length)));
+ float temp[3][3];
+ float temp1 = k*(1.0 - (L/length));
+
+ mul_fvectorT_fvectorS(temp, extent, extent, 1.0 / dot);
+ sub_fmatrix_fmatrix(to, I, temp);
+ mul_fmatrix_S(to, temp1);
+
+ mul_fvectorT_fvectorS(temp, extent, extent, k/ dot);
+ add_fmatrix_fmatrix(to, to, temp);
+
+ /*
+ mul_fvectorT_fvector(temp, dir, dir);
+ sub_fmatrix_fmatrix(to, I, temp);
+ mul_fmatrix_S(to, k* (1.0f-(L/length)));
+ mul_fmatrix_S(temp, k);
+ add_fmatrix_fmatrix(to, temp, to);
+ */
+}
+
+DO_INLINE void dfdx_spring_type2(float to[3][3], float dir[3], float length, float L, float k, float cb)
+{
+ // return outerprod(dir,dir)*fbstar_jacobi(length, L, k, cb);
+ mul_fvectorT_fvectorS(to, dir, dir, fbstar_jacobi(length, L, k, cb));
+}
+
+DO_INLINE void dfdv_damp(float to[3][3], float dir[3], float damping)
+{
+ // derivative of force wrt velocity.
+ mul_fvectorT_fvectorS(to, dir, dir, damping);
+
+}
+
+DO_INLINE void dfdx_spring(float to[3][3], float dir[3],float length,float L,float k)
+{
+ // dir is unit length direction, rest is spring's restlength, k is spring constant.
+ //return ( (I-outerprod(dir,dir))*Min(1.0f,rest/length) - I) * -k;
+ mul_fvectorT_fvector(to, dir, dir);
+ sub_fmatrix_fmatrix(to, I, to);
+ mul_fmatrix_S(to, (((L/length)> 1.0f) ? (1.0f): (L/length)));
+ sub_fmatrix_fmatrix(to, to, I);
+ mul_fmatrix_S(to, -k);
+}
+
+// unused atm
+DO_INLINE void dfdx_damp(float to[3][3], float dir[3],float length,const float vel[3],float rest,float damping)
+{
+ // inner spring damping vel is the relative velocity of the endpoints.
+ // return (I-outerprod(dir,dir)) * (-damping * -(dot(dir,vel)/Max(length,rest)));
+ mul_fvectorT_fvector(to, dir, dir);
+ sub_fmatrix_fmatrix(to, I, to);
+ mul_fmatrix_S(to, (-damping * -(INPR(dir,vel)/MAX2(length,rest))));
+
+}
+
+DO_INLINE void cloth_calc_spring_force(ClothModifierData *clmd, ClothSpring *s, lfVector *lF, lfVector *X, lfVector *V, fmatrix3x3 *dFdV, fmatrix3x3 *dFdX, float time)
+{
+ Cloth *cloth = clmd->clothObject;
+ ClothVertex *verts = cloth->verts;
+ float extent[3];
+ float length = 0, dot = 0;
+ float dir[3] = {0,0,0};
+ float vel[3];
+ float k = 0.0f;
+ float L = s->restlen;
+ float cb = clmd->sim_parms->structural;
+
+ float nullf[3] = {0,0,0};
+ float stretch_force[3] = {0,0,0};
+ float bending_force[3] = {0,0,0};
+ float damping_force[3] = {0,0,0};
+ float nulldfdx[3][3]={ {0,0,0}, {0,0,0}, {0,0,0}};
+
+ float scaling = 0.0;
+
+ VECCOPY(s->f, nullf);
+ cp_fmatrix(s->dfdx, nulldfdx);
+ cp_fmatrix(s->dfdv, nulldfdx);
+
+ // calculate elonglation
+ VECSUB(extent, X[s->kl], X[s->ij]);
+ VECSUB(vel, V[s->kl], V[s->ij]);
+ dot = INPR(extent, extent);
+ length = sqrt(dot);
+
+ s->flags &= ~CLOTH_SPRING_FLAG_NEEDED;
+
+ if(length > ALMOST_ZERO)
+ {
+ /*
+ if(length>L)
+ {
+ if((clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED)
+ && ((((length-L)*100.0f/L) > clmd->sim_parms->maxspringlen))) // cut spring!
+ {
+ s->flags |= CSPRING_FLAG_DEACTIVATE;
+ return;
+ }
+ }
+ */
+ mul_fvector_S(dir, extent, 1.0f/length);
+ }
+ else
+ {
+ mul_fvector_S(dir, extent, 0.0f);
+ }
+
+ // calculate force of structural + shear springs
+ if((s->type & CLOTH_SPRING_TYPE_STRUCTURAL) || (s->type & CLOTH_SPRING_TYPE_SHEAR))
+ {
+ if(length > L) // only on elonglation
+ {
+ s->flags |= CLOTH_SPRING_FLAG_NEEDED;
+
+ k = clmd->sim_parms->structural;
+
+ scaling = k + s->stiffness * ABS(clmd->sim_parms->max_struct-k);
+
+ k = scaling / (clmd->sim_parms->avg_spring_len + FLT_EPSILON);
+
+ // TODO: verify, half verified (couldn't see error)
+ mul_fvector_S(stretch_force, dir, k*(length-L));
+
+ VECADD(s->f, s->f, stretch_force);
+
+ // Ascher & Boxman, p.21: Damping only during elonglation
+ // something wrong with it...
+ mul_fvector_S(damping_force, dir, clmd->sim_parms->Cdis * INPR(vel,dir));
+ VECADD(s->f, s->f, damping_force);
+
+ /* VERIFIED */
+ dfdx_spring(s->dfdx, dir, length, L, k);
+
+ /* VERIFIED */
+ dfdv_damp(s->dfdv, dir, clmd->sim_parms->Cdis);
+
+ }
+ }
+ else if(s->type & CLOTH_SPRING_TYPE_GOAL)
+ {
+ float tvect[3];
+
+ s->flags |= CLOTH_SPRING_FLAG_NEEDED;
+
+ // current_position = xold + t * (newposition - xold)
+ VECSUB(tvect, verts[s->ij].xconst, verts[s->ij].xold);
+ mul_fvector_S(tvect, tvect, time);
+ VECADD(tvect, tvect, verts[s->ij].xold);
+
+ VECSUB(extent, X[s->ij], tvect);
+
+ dot = INPR(extent, extent);
+ length = sqrt(dot);
+
+ k = clmd->sim_parms->goalspring;
+
+ scaling = k + s->stiffness * ABS(clmd->sim_parms->max_struct-k);
+
+ k = verts [s->ij].goal * scaling / (clmd->sim_parms->avg_spring_len + FLT_EPSILON);
+
+ VECADDS(s->f, s->f, extent, -k);
+
+ mul_fvector_S(damping_force, dir, clmd->sim_parms->goalfrict * 0.01 * INPR(vel,dir));
+ VECADD(s->f, s->f, damping_force);
+
+ // HERE IS THE PROBLEM!!!!
+ // dfdx_spring(s->dfdx, dir, length, 0.0, k);
+ // dfdv_damp(s->dfdv, dir, MIN2(1.0, (clmd->sim_parms->goalfrict/100.0)));
+ }
+ else // calculate force of bending springs
+ {
+ if(length < L)
+ {
+ s->flags |= CLOTH_SPRING_FLAG_NEEDED;
+
+ k = clmd->sim_parms->bending;
+
+ scaling = k + s->stiffness * ABS(clmd->sim_parms->max_bend-k);
+ cb = k = scaling / (20.0*(clmd->sim_parms->avg_spring_len + FLT_EPSILON));
+
+ mul_fvector_S(bending_force, dir, fbstar(length, L, k, cb));
+ VECADD(s->f, s->f, bending_force);
+
+ dfdx_spring_type2(s->dfdx, dir, length,L, k, cb);
+ }
+ }
+}
+
+DO_INLINE void cloth_apply_spring_force(ClothModifierData *clmd, ClothSpring *s, lfVector *lF, lfVector *X, lfVector *V, fmatrix3x3 *dFdV, fmatrix3x3 *dFdX)
+{
+ if(s->flags & CLOTH_SPRING_FLAG_NEEDED)
+ {
+ if(!(s->type & CLOTH_SPRING_TYPE_BENDING))
+ {
+ sub_fmatrix_fmatrix(dFdV[s->ij].m, dFdV[s->ij].m, s->dfdv);
+ sub_fmatrix_fmatrix(dFdV[s->kl].m, dFdV[s->kl].m, s->dfdv);
+ add_fmatrix_fmatrix(dFdV[s->matrix_index].m, dFdV[s->matrix_index].m, s->dfdv);
+ }
+
+ VECADD(lF[s->ij], lF[s->ij], s->f);
+
+ if(!(s->type & CLOTH_SPRING_TYPE_GOAL))
+ VECSUB(lF[s->kl], lF[s->kl], s->f);
+
+ sub_fmatrix_fmatrix(dFdX[s->kl].m, dFdX[s->kl].m, s->dfdx);
+ sub_fmatrix_fmatrix(dFdX[s->ij].m, dFdX[s->ij].m, s->dfdx);
+ add_fmatrix_fmatrix(dFdX[s->matrix_index].m, dFdX[s->matrix_index].m, s->dfdx);
+ }
+}
+
+
+static void CalcFloat( float *v1, float *v2, float *v3, float *n)
+{
+ float n1[3],n2[3];
+
+ n1[0]= v1[0]-v2[0];
+ n2[0]= v2[0]-v3[0];
+ n1[1]= v1[1]-v2[1];
+ n2[1]= v2[1]-v3[1];
+ n1[2]= v1[2]-v2[2];
+ n2[2]= v2[2]-v3[2];
+ n[0]= n1[1]*n2[2]-n1[2]*n2[1];
+ n[1]= n1[2]*n2[0]-n1[0]*n2[2];
+ n[2]= n1[0]*n2[1]-n1[1]*n2[0];
+}
+
+static void CalcFloat4( float *v1, float *v2, float *v3, float *v4, float *n)
+{
+ /* real cross! */
+ float n1[3],n2[3];
+
+ n1[0]= v1[0]-v3[0];
+ n1[1]= v1[1]-v3[1];
+ n1[2]= v1[2]-v3[2];
+
+ n2[0]= v2[0]-v4[0];
+ n2[1]= v2[1]-v4[1];
+ n2[2]= v2[2]-v4[2];
+
+ n[0]= n1[1]*n2[2]-n1[2]*n2[1];
+ n[1]= n1[2]*n2[0]-n1[0]*n2[2];
+ n[2]= n1[0]*n2[1]-n1[1]*n2[0];
+}
+
+float calculateVertexWindForce(float wind[3], float vertexnormal[3])
+{
+ return (INPR(wind, vertexnormal));
+}
+
+void cloth_calc_force(ClothModifierData *clmd, lfVector *lF, lfVector *lX, lfVector *lV, fmatrix3x3 *dFdV, fmatrix3x3 *dFdX, ListBase *effectors, float time, fmatrix3x3 *M)
+{
+ /* Collect forces and derivatives: F,dFdX,dFdV */
+ Cloth *cloth = clmd->clothObject;
+ int i = 0;
+ float spring_air = clmd->sim_parms->Cvi * 0.01f; /* viscosity of air scaled in percent */
+ float gravity[3];
+ float tm2[3][3] = {{-spring_air,0,0}, {0,-spring_air,0},{0,0,-spring_air}};
+ MFace *mfaces = cloth->mfaces;
+ unsigned int numverts = cloth->numverts;
+ LinkNode *search = cloth->springs;
+ lfVector *winvec;
+
+ VECCOPY(gravity, clmd->sim_parms->gravity);
+ mul_fvector_S(gravity, gravity, 0.001f); /* scale gravity force */
+
+ /* set dFdX jacobi matrix to zero */
+ init_bfmatrix(dFdX, ZERO);
+ /* set dFdX jacobi matrix diagonal entries to -spring_air */
+ initdiag_bfmatrix(dFdV, tm2);
+
+ init_lfvector(lF, gravity, numverts);
+
+ /* multiply lF with mass matrix
+ // force = mass * acceleration (in this case: gravity)
+ */
+ for(i = 0; i < numverts; i++)
+ {
+ float temp[3];
+ VECCOPY(temp, lF[i]);
+ mul_fmatrix_fvector(lF[i], M[i].m, temp);
+ }
+
+ submul_lfvectorS(lF, lV, spring_air, numverts);
+
+ /* handle external forces like wind */
+ if(effectors)
+ {
+ // 0 = force, 1 = normalized force
+ winvec = create_lfvector(cloth->numverts);
+
+ if(!winvec)
+ printf("winvec: out of memory in implicit.c\n");
+
+ // precalculate wind forces
+ for(i = 0; i < cloth->numverts; i++)
+ {
+ float speed[3] = {0.0f, 0.0f,0.0f};
+
+ pdDoEffectors(effectors, lX[i], winvec[i], speed, (float)G.scene->r.cfra, 0.0f, 0);
+ }
+
+ for(i = 0; i < cloth->numfaces; i++)
+ {
+ float trinormal[3]={0,0,0}; // normalized triangle normal
+ float triunnormal[3]={0,0,0}; // not-normalized-triangle normal
+ float tmp[3]={0,0,0};
+ float factor = (mfaces[i].v4) ? 0.25 : 1.0 / 3.0;
+ factor *= 0.02;
+
+ // calculate face normal
+ if(mfaces[i].v4)
+ CalcFloat4(lX[mfaces[i].v1],lX[mfaces[i].v2],lX[mfaces[i].v3],lX[mfaces[i].v4],triunnormal);
+ else
+ CalcFloat(lX[mfaces[i].v1],lX[mfaces[i].v2],lX[mfaces[i].v3],triunnormal);
+
+ VECCOPY(trinormal, triunnormal);
+ Normalize(trinormal);
+
+ // add wind from v1
+ VECCOPY(tmp, trinormal);
+ VecMulf(tmp, calculateVertexWindForce(winvec[mfaces[i].v1], triunnormal));
+ VECADDS(lF[mfaces[i].v1], lF[mfaces[i].v1], tmp, factor);
+
+ // add wind from v2
+ VECCOPY(tmp, trinormal);
+ VecMulf(tmp, calculateVertexWindForce(winvec[mfaces[i].v2], triunnormal));
+ VECADDS(lF[mfaces[i].v2], lF[mfaces[i].v2], tmp, factor);
+
+ // add wind from v3
+ VECCOPY(tmp, trinormal);
+ VecMulf(tmp, calculateVertexWindForce(winvec[mfaces[i].v3], triunnormal));
+ VECADDS(lF[mfaces[i].v3], lF[mfaces[i].v3], tmp, factor);
+
+ // add wind from v4
+ if(mfaces[i].v4)
+ {
+ VECCOPY(tmp, trinormal);
+ VecMulf(tmp, calculateVertexWindForce(winvec[mfaces[i].v4], triunnormal));
+ VECADDS(lF[mfaces[i].v4], lF[mfaces[i].v4], tmp, factor);
+ }
+ }
+ del_lfvector(winvec);
+ }
+
+ // calculate spring forces
+ search = cloth->springs;
+ while(search)
+ {
+ // only handle active springs
+ // if(((clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED) && !(springs[i].flags & CSPRING_FLAG_DEACTIVATE))|| !(clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED)){}
+ cloth_calc_spring_force(clmd, search->link, lF, lX, lV, dFdV, dFdX, time);
+
+ search = search->next;
+ }
+
+ // apply spring forces
+ search = cloth->springs;
+ while(search)
+ {
+ // only handle active springs
+ // if(((clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED) && !(springs[i].flags & CSPRING_FLAG_DEACTIVATE))|| !(clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED))
+ cloth_apply_spring_force(clmd, search->link, lF, lX, lV, dFdV, dFdX);
+ search = search->next;
+ }
+ // printf("\n");
+}
+
+void simulate_implicit_euler(lfVector *Vnew, lfVector *lX, lfVector *lV, lfVector *lF, fmatrix3x3 *dFdV, fmatrix3x3 *dFdX, float dt, fmatrix3x3 *A, lfVector *B, lfVector *dV, fmatrix3x3 *S, lfVector *z, lfVector *olddV, fmatrix3x3 *P, fmatrix3x3 *Pinv, fmatrix3x3 *M, fmatrix3x3 *bigI)
+{
+ unsigned int numverts = dFdV[0].vcount;
+
+ lfVector *dFdXmV = create_lfvector(numverts);
+ zero_lfvector(dV, numverts);
+
+ cp_bfmatrix(A, M);
+
+ subadd_bfmatrixS_bfmatrixS(A, dFdV, dt, dFdX, (dt*dt));
+
+ mul_bfmatrix_lfvector(dFdXmV, dFdX, lV);
+
+ add_lfvectorS_lfvectorS(B, lF, dt, dFdXmV, (dt*dt), numverts);
+
+ itstart();
+
+ cg_filtered(dV, A, B, z, S); /* conjugate gradient algorithm to solve Ax=b */
+ // cg_filtered_pre(dV, A, B, z, S, P, Pinv, bigI);
+
+ itend();
+ // printf("cg_filtered calc time: %f\n", (float)itval());
+
+ cp_lfvector(olddV, dV, numverts);
+
+ // advance velocities
+ add_lfvector_lfvector(Vnew, lV, dV, numverts);
+
+
+ del_lfvector(dFdXmV);
+}
+
+int implicit_solver (Object *ob, float frame, ClothModifierData *clmd, ListBase *effectors)
+{
+ unsigned int i=0;
+ float step=0.0f, tf=clmd->sim_parms->timescale;
+ Cloth *cloth = clmd->clothObject;
+ ClothVertex *verts = cloth->verts;
+ unsigned int numverts = cloth->numverts;
+ float dt = clmd->sim_parms->timescale / clmd->sim_parms->stepsPerFrame;
+ Implicit_Data *id = cloth->implicit;
+ int result = 0;
+
+ if(clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL) /* do goal stuff */
+ {
+ for(i = 0; i < numverts; i++)
+ {
+ // update velocities with constrained velocities from pinned verts
+ if(verts [i].flags & CLOTH_VERT_FLAG_PINNED)
+ {
+ VECSUB(id->V[i], verts[i].xconst, verts[i].xold);
+ // VecMulf(id->V[i], clmd->sim_parms->stepsPerFrame);
+ }
+ }
+ }
+
+ while(step < tf)
+ {
+ // calculate forces
+ effectors= pdInitEffectors(ob,NULL);
+ cloth_calc_force(clmd, id->F, id->X, id->V, id->dFdV, id->dFdX, effectors, step, id->M);
+ if(effectors) pdEndEffectors(effectors);
+
+ // calculate new velocity
+ simulate_implicit_euler(id->Vnew, id->X, id->V, id->F, id->dFdV, id->dFdX, dt, id->A, id->B, id->dV, id->S, id->z, id->olddV, id->P, id->Pinv, id->M, id->bigI);
+
+ // advance positions
+ add_lfvector_lfvectorS(id->Xnew, id->X, id->Vnew, dt, numverts);
+
+ /* move pinned verts to correct position */
+ for(i = 0; i < numverts; i++)
+ {
+ if(clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL)
+ {
+ if(verts [i].flags & CLOTH_VERT_FLAG_PINNED)
+ {
+ float tvect[3] = {.0,.0,.0};
+ VECSUB(tvect, verts[i].xconst, verts[i].xold);
+ mul_fvector_S(tvect, tvect, step+dt);
+ VECADD(tvect, tvect, verts[i].xold);
+ VECCOPY(id->Xnew[i], tvect);
+ }
+ }
+
+ VECCOPY(verts[i].txold, id->X[i]);
+ }
+
+ if(clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_ENABLED)
+ {
+ // collisions
+ // itstart();
+
+ // update verts to current positions
+ for(i = 0; i < numverts; i++)
+ {
+ VECCOPY(verts[i].tx, id->Xnew[i]);
+
+ VECSUB(verts[i].tv, verts[i].tx, verts[i].txold);
+ VECCOPY(verts[i].v, verts[i].tv);
+ }
+
+ // call collision function
+ // TODO: check if "step" or "step+dt" is correct - dg
+ result = cloth_bvh_objcollision(ob, clmd, step, dt);
+
+ // correct velocity again, just to be sure we had to change it due to adaptive collisions
+ for(i = 0; i < numverts; i++)
+ {
+ VECSUB(verts[i].tv, verts[i].tx, id->X[i]);
+ }
+
+ // copy corrected positions back to simulation
+ for(i = 0; i < numverts; i++)
+ {
+ if(result)
+ {
+
+ if((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL) && (verts [i].flags & CLOTH_VERT_FLAG_PINNED))
+ continue;
+
+ VECCOPY(id->Xnew[i], verts[i].tx);
+ VECCOPY(id->Vnew[i], verts[i].tv);
+ VecMulf(id->Vnew[i], clmd->sim_parms->stepsPerFrame);
+ }
+ }
+
+ // X = Xnew;
+ cp_lfvector(id->X, id->Xnew, numverts);
+
+ // if there were collisions, advance the velocity from v_n+1/2 to v_n+1
+
+ if(result)
+ {
+ // V = Vnew;
+ cp_lfvector(id->V, id->Vnew, numverts);
+
+ // calculate
+ effectors= pdInitEffectors(ob,NULL);
+ cloth_calc_force(clmd, id->F, id->X, id->V, id->dFdV, id->dFdX, effectors, step+dt, id->M);
+ if(effectors) pdEndEffectors(effectors);
+
+ simulate_implicit_euler(id->Vnew, id->X, id->V, id->F, id->dFdV, id->dFdX, dt / 2.0f, id->A, id->B, id->dV, id->S, id->z, id->olddV, id->P, id->Pinv, id->M, id->bigI);
+ }
+
+ }
+ else
+ {
+ // X = Xnew;
+ cp_lfvector(id->X, id->Xnew, numverts);
+ }
+
+ // itend();
+ // printf("collision time: %f\n", (float)itval());
+
+ // V = Vnew;
+ cp_lfvector(id->V, id->Vnew, numverts);
+
+ step += dt;
+
+ }
+
+ for(i = 0; i < numverts; i++)
+ {
+ if((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL) && (verts [i].flags & CLOTH_VERT_FLAG_PINNED))
+ {
+ VECCOPY(verts[i].txold, verts[i].xconst); // TODO: test --> should be .x
+ VECCOPY(verts[i].x, verts[i].xconst);
+ VECCOPY(verts[i].v, id->V[i]);
+ }
+ else
+ {
+ VECCOPY(verts[i].txold, id->X[i]);
+ VECCOPY(verts[i].x, id->X[i]);
+ VECCOPY(verts[i].v, id->V[i]);
+ }
+ }
+
+ return 1;
+}
+
+void implicit_set_positions (ClothModifierData *clmd)
+{
+ Cloth *cloth = clmd->clothObject;
+ ClothVertex *verts = cloth->verts;
+ unsigned int numverts = cloth->numverts, i;
+ Implicit_Data *id = cloth->implicit;
+
+ for(i = 0; i < numverts; i++)
+ {
+ VECCOPY(id->X[i], verts[i].x);
+ VECCOPY(id->V[i], verts[i].v);
+ }
+ if(G.rt > 0)
+ printf("implicit_set_positions\n");
+}
+
diff --git a/source/blender/blenkernel/intern/ipo.c b/source/blender/blenkernel/intern/ipo.c
index 78e8f2c5ee0..8407c66d584 100644
--- a/source/blender/blenkernel/intern/ipo.c
+++ b/source/blender/blenkernel/intern/ipo.c
@@ -23,7 +23,7 @@
*
* The Original Code is: all of this file.
*
- * Contributor(s): none yet.
+ * Contributor(s): 2008, Joshua Leung (IPO System cleanup)
*
* ***** END GPL LICENSE BLOCK *****
*/
@@ -72,15 +72,23 @@
#include "BKE_main.h"
#include "BKE_mesh.h"
#include "BKE_object.h"
+
+#ifndef DISABLE_PYTHON
#include "BPY_extern.h" /* for BPY_pydriver_eval() */
+#endif
#define SMALL -1.0e-10
+/* ***************************** Adrcode Blocktype Defines ********************************* */
+
/* This array concept was meant to make sure that defines such as OB_LOC_X
don't have to be enumerated, also for backward compatibility, future changes,
and to enable it all can be accessed with a for-next loop.
+
+ This should whole adrcode system should eventually be replaced by a proper Data API
*/
+
int co_ar[CO_TOTIPO]= {
CO_ENFORCE, CO_HEADTAIL
};
@@ -150,9 +158,9 @@ int wo_ar[WO_TOTIPO]= {
};
int la_ar[LA_TOTIPO]= {
- LA_ENERGY, LA_COL_R, LA_COL_G, LA_COL_B,
+ LA_ENERGY, LA_COL_R, LA_COL_G, LA_COL_B,
LA_DIST, LA_SPOTSI, LA_SPOTBL,
- LA_QUAD1, LA_QUAD2, LA_HALOINT,
+ LA_QUAD1, LA_QUAD2, LA_HALOINT,
MA_MAP1+MAP_OFS_X, MA_MAP1+MAP_OFS_Y, MA_MAP1+MAP_OFS_Z,
MA_MAP1+MAP_SIZE_X, MA_MAP1+MAP_SIZE_Y, MA_MAP1+MAP_SIZE_Z,
@@ -174,460 +182,617 @@ int fluidsim_ar[FLUIDSIM_TOTIPO]= {
FLUIDSIM_VISC, FLUIDSIM_TIME,
FLUIDSIM_GRAV_X , FLUIDSIM_GRAV_Y , FLUIDSIM_GRAV_Z ,
FLUIDSIM_VEL_X , FLUIDSIM_VEL_Y , FLUIDSIM_VEL_Z ,
- FLUIDSIM_ACTIVE
+ FLUIDSIM_ACTIVE,
+ FLUIDSIM_ATTR_FORCE_STR, FLUIDSIM_ATTR_FORCE_RADIUS,
+ FLUIDSIM_VEL_FORCE_STR, FLUIDSIM_VEL_FORCE_RADIUS,
};
int part_ar[PART_TOTIPO]= {
PART_EMIT_FREQ, PART_EMIT_LIFE, PART_EMIT_VEL, PART_EMIT_AVE, PART_EMIT_SIZE,
PART_AVE, PART_SIZE, PART_DRAG, PART_BROWN, PART_DAMP, PART_LENGTH, PART_CLUMP,
PART_GRAV_X, PART_GRAV_Y, PART_GRAV_Z, PART_KINK_AMP, PART_KINK_FREQ, PART_KINK_SHAPE,
- PART_BB_TILT
+ PART_BB_TILT, PART_PD_FSTR, PART_PD_FFALL, PART_PD_FMAXD, PART_PD2_FSTR, PART_PD2_FFALL, PART_PD2_FMAXD
};
+/* ************************** Data-Level Functions ************************* */
+
+/* ---------------------- Freeing --------------------------- */
-float frame_to_float(int cfra) /* see also bsystem_time in object.c */
+/* frees the ipo curve itself too */
+void free_ipo_curve (IpoCurve *icu)
{
- extern float bluroffs; /* bad stuff borrowed from object.c */
- extern float fieldoffs;
- float ctime;
+ if (icu == NULL)
+ return;
- ctime= (float)cfra;
- ctime+= bluroffs+fieldoffs;
- ctime*= G.scene->r.framelen;
+ if (icu->bezt)
+ MEM_freeN(icu->bezt);
+ if (icu->driver)
+ MEM_freeN(icu->driver);
- return ctime;
-}
-
-/* includes ipo curve itself */
-void free_ipo_curve(IpoCurve *icu)
-{
- if(icu->bezt) MEM_freeN(icu->bezt);
- if(icu->bp) MEM_freeN(icu->bp);
- if(icu->driver) MEM_freeN(icu->driver);
MEM_freeN(icu);
}
/* do not free ipo itself */
-void free_ipo(Ipo *ipo)
+void free_ipo (Ipo *ipo)
{
- IpoCurve *icu;
+ IpoCurve *icu, *icn;
+
+ if (ipo == NULL)
+ return;
- while( (icu= ipo->curve.first) ) {
+ for (icu= ipo->curve.first; icu; icu= icn) {
+ icn= icu->next;
+
+ /* must remove the link before freeing, as the curve is freed too */
BLI_remlink(&ipo->curve, icu);
free_ipo_curve(icu);
}
}
+/* ---------------------- Init --------------------------- */
+
/* on adding new ipos, or for empty views */
-void ipo_default_v2d_cur(int blocktype, rctf *cur)
+void ipo_default_v2d_cur (int blocktype, rctf *cur)
{
- if(blocktype==ID_CA) {
- cur->xmin= G.scene->r.sfra;
- cur->xmax= G.scene->r.efra;
- cur->ymin= 0.0;
- cur->ymax= 100.0;
- }
- else if ELEM5(blocktype, ID_MA, ID_CU, ID_WO, ID_LA, ID_CO) {
- cur->xmin= (float)G.scene->r.sfra-0.1;
- cur->xmax= G.scene->r.efra;
- cur->ymin= (float)-0.1;
- cur->ymax= (float)+1.1;
- }
- else if(blocktype==ID_TE) {
- cur->xmin= (float)G.scene->r.sfra-0.1;
- cur->xmax= G.scene->r.efra;
- cur->ymin= (float)-0.1;
- cur->ymax= (float)+1.1;
- }
- else if(blocktype==ID_SEQ) {
- cur->xmin= -5.0;
- cur->xmax= 105.0;
- cur->ymin= (float)-0.1;
- cur->ymax= (float)+1.1;
- }
- else if(blocktype==ID_KE) {
- cur->xmin= (float)G.scene->r.sfra-0.1;
- cur->xmax= G.scene->r.efra;
- cur->ymin= (float)-0.1;
- cur->ymax= (float)+2.1;
- }
- else { /* ID_OB and everything else */
- cur->xmin= G.scene->r.sfra;
- cur->xmax= G.scene->r.efra;
- cur->ymin= -5.0;
- cur->ymax= +5.0;
+ switch (blocktype) {
+ case ID_CA:
+ cur->xmin= (float)G.scene->r.sfra;
+ cur->xmax= (float)G.scene->r.efra;
+ cur->ymin= 0.0f;
+ cur->ymax= 100.0f;
+ break;
+
+ case ID_MA: case ID_WO: case ID_LA:
+ case ID_CU: case ID_CO:
+ cur->xmin= (float)(G.scene->r.sfra - 0.1f);
+ cur->xmax= (float)G.scene->r.efra;
+ cur->ymin= (float)-0.1f;
+ cur->ymax= (float)+1.1f;
+ break;
+
+ case ID_TE:
+ cur->xmin= (float)(G.scene->r.sfra - 0.1f);
+ cur->xmax= (float)G.scene->r.efra;
+ cur->ymin= (float)-0.1f;
+ cur->ymax= (float)+1.1f;
+ break;
+
+ case ID_SEQ:
+ cur->xmin= -5.0f;
+ cur->xmax= 105.0f;
+ cur->ymin= (float)-0.1f;
+ cur->ymax= (float)+1.1f;
+ break;
+
+ case ID_KE:
+ cur->xmin= (float)(G.scene->r.sfra - 0.1f);
+ cur->xmax= (float)G.scene->r.efra;
+ cur->ymin= (float)-0.1f;
+ cur->ymax= (float)+2.1f;
+ break;
+
+ default: /* ID_OB and everything else */
+ cur->xmin= (float)G.scene->r.sfra;
+ cur->xmax= (float)G.scene->r.efra;
+ cur->ymin= -5.0f;
+ cur->ymax= +5.0f;
+ break;
}
}
-
-Ipo *add_ipo(char *name, int idcode)
+/* create a new IPO block (allocates the block) */
+Ipo *add_ipo (char name[], int blocktype)
{
Ipo *ipo;
ipo= alloc_libblock(&G.main->ipo, ID_IP, name);
- ipo->blocktype= idcode;
- ipo_default_v2d_cur(idcode, &ipo->cur);
+ ipo->blocktype= blocktype;
+ ipo_default_v2d_cur(blocktype, &ipo->cur);
return ipo;
}
-Ipo *copy_ipo(Ipo *ipo)
+/* ---------------------- Copy --------------------------- */
+
+/* duplicate an IPO block and all its data */
+Ipo *copy_ipo (Ipo *src)
{
- Ipo *ipon;
+ Ipo *dst;
IpoCurve *icu;
- if(ipo==NULL) return 0;
-
- ipon= copy_libblock(ipo);
+ if (src == NULL)
+ return NULL;
- BLI_duplicatelist(&(ipon->curve), &(ipo->curve));
+ dst= copy_libblock(src);
+ BLI_duplicatelist(&dst->curve, &src->curve);
- for(icu= ipo->curve.first; icu; icu= icu->next) {
+ for (icu= src->curve.first; icu; icu= icu->next) {
icu->bezt= MEM_dupallocN(icu->bezt);
- if(icu->driver) icu->driver= MEM_dupallocN(icu->driver);
+
+ if (icu->driver)
+ icu->driver= MEM_dupallocN(icu->driver);
}
- return ipon;
+ return dst;
}
-/* uses id->newid to match pointers with other copied data */
-void ipo_idnew(Ipo *ipo)
+/* ---------------------- Relink --------------------------- */
+
+/* uses id->newid to match pointers with other copied data
+ * - called after single-user or other such
+ */
+void ipo_idnew (Ipo *ipo)
{
- if(ipo) {
+ if (ipo) {
IpoCurve *icu;
- for(icu= ipo->curve.first; icu; icu= icu->next) {
- if(icu->driver) {
+ for (icu= ipo->curve.first; icu; icu= icu->next) {
+ if (icu->driver)
ID_NEW(icu->driver->ob);
- }
}
}
}
-void make_local_obipo(Ipo *ipo)
+/* --------------------- Find + Check ----------------------- */
+
+/* find the IPO-curve within a given IPO-block with the adrcode of interest */
+IpoCurve *find_ipocurve (Ipo *ipo, int adrcode)
+{
+ if (ipo) {
+ IpoCurve *icu;
+
+ for (icu= ipo->curve.first; icu; icu= icu->next) {
+ if (icu->adrcode == adrcode)
+ return icu;
+ }
+ }
+ return NULL;
+}
+
+/* return whether the given IPO block has a IPO-curve with the given adrcode */
+short has_ipo_code(Ipo *ipo, int adrcode)
+{
+ /* return success of faliure from trying to find such an IPO-curve */
+ return (find_ipocurve(ipo, adrcode) != NULL);
+}
+
+/* ---------------------- Make Local --------------------------- */
+
+
+/* make the given IPO local (for Objects)
+ * - only lib users: do nothing
+ * - only local users: set flag
+ * - mixed: make copy
+ */
+void make_local_obipo (Ipo *src)
{
Object *ob;
- Ipo *ipon;
+ Ipo *dst;
int local=0, lib=0;
- /* - only lib users: do nothing
- * - only local users: set flag
- * - mixed: make copy
- */
-
- ob= G.main->object.first;
- while(ob) {
- if(ob->ipo==ipo) {
- if(ob->id.lib) lib= 1;
+ /* check if only local and/or lib */
+ for (ob= G.main->object.first; ob; ob= ob->id.next) {
+ if (ob->ipo == src) {
+ if (ob->id.lib) lib= 1;
else local= 1;
}
- ob= ob->id.next;
}
- if(local && lib==0) {
- ipo->id.lib= 0;
- ipo->id.flag= LIB_LOCAL;
- new_id(0, (ID *)ipo, 0);
+ /* only local - set flag */
+ if (local && lib==0) {
+ src->id.lib= 0;
+ src->id.flag= LIB_LOCAL;
+ new_id(0, (ID *)src, 0);
}
- else if(local && lib) {
- ipon= copy_ipo(ipo);
- ipon->id.us= 0;
+ /* mixed: make copy */
+ else if (local && lib) {
+ dst= copy_ipo(src);
+ dst->id.us= 0;
- ob= G.main->object.first;
- while(ob) {
- if(ob->ipo==ipo) {
-
- if(ob->id.lib==NULL) {
- ob->ipo= ipon;
- ipon->id.us++;
- ipo->id.us--;
+ for (ob= G.main->object.first; ob; ob= ob->id.next) {
+ if (ob->ipo == src) {
+ if (ob->id.lib == NULL) {
+ ob->ipo= dst;
+ dst->id.us++;
+ src->id.us--;
}
}
- ob= ob->id.next;
}
}
}
-void make_local_matipo(Ipo *ipo)
+/* make the given IPO local (for Materials)
+ * - only lib users: do nothing
+ * - only local users: set flag
+ * - mixed: make copy
+ */
+void make_local_matipo (Ipo *src)
{
Material *ma;
- Ipo *ipon;
+ Ipo *dst;
int local=0, lib=0;
-
- /* - only lib users: do nothing
- * - only local users: set flag
- * - mixed: make copy
- */
- ma= G.main->mat.first;
- while(ma) {
- if(ma->ipo==ipo) {
- if(ma->id.lib) lib= 1;
+ /* check if only local and/or lib */
+ for (ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if (ma->ipo == src) {
+ if (ma->id.lib) lib= 1;
else local= 1;
}
- ma= ma->id.next;
}
- if(local && lib==0) {
- ipo->id.lib= 0;
- ipo->id.flag= LIB_LOCAL;
- new_id(0, (ID *)ipo, 0);
+ /* only local - set flag */
+ if (local && lib==0) {
+ src->id.lib= 0;
+ src->id.flag= LIB_LOCAL;
+ new_id(0, (ID *)src, 0);
}
- else if(local && lib) {
- ipon= copy_ipo(ipo);
- ipon->id.us= 0;
+ /* mixed: make copy */
+ else if (local && lib) {
+ dst= copy_ipo(src);
+ dst->id.us= 0;
- ma= G.main->mat.first;
- while(ma) {
- if(ma->ipo==ipo) {
-
- if(ma->id.lib==NULL) {
- ma->ipo= ipon;
- ipon->id.us++;
- ipo->id.us--;
+ for (ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if (ma->ipo == src) {
+ if (ma->id.lib == NULL) {
+ ma->ipo= dst;
+ dst->id.us++;
+ src->id.us--;
}
}
- ma= ma->id.next;
}
}
}
-void make_local_keyipo(Ipo *ipo)
+/* make the given IPO local (for ShapeKeys)
+ * - only lib users: do nothing
+ * - only local users: set flag
+ * - mixed: make copy
+ */
+void make_local_keyipo (Ipo *src)
{
Key *key;
- Ipo *ipon;
+ Ipo *dst;
int local=0, lib=0;
-
- /* - only lib users: do nothing
- * - only local users: set flag
- * - mixed: make copy
- */
- key= G.main->key.first;
- while(key) {
- if(key->ipo==ipo) {
- if(key->id.lib) lib= 1;
+ /* check if only local and/or lib */
+ for (key= G.main->key.first; key; key= key->id.next) {
+ if (key->ipo == src) {
+ if (key->id.lib) lib= 1;
else local= 1;
}
- key= key->id.next;
}
- if(local && lib==0) {
- ipo->id.lib= 0;
- ipo->id.flag= LIB_LOCAL;
- new_id(0, (ID *)ipo, 0);
+ /* only local - set flag */
+ if (local && lib==0) {
+ src->id.lib= 0;
+ src->id.flag= LIB_LOCAL;
+ new_id(0, (ID *)src, 0);
}
- else if(local && lib) {
- ipon= copy_ipo(ipo);
- ipon->id.us= 0;
+ /* mixed: make copy */
+ else if (local && lib) {
+ dst= copy_ipo(src);
+ dst->id.us= 0;
- key= G.main->key.first;
- while(key) {
- if(key->ipo==ipo) {
-
- if(key->id.lib==NULL) {
- key->ipo= ipon;
- ipon->id.us++;
- ipo->id.us--;
+ for (key= G.main->key.first; key; key= key->id.next) {
+ if (key->ipo == src) {
+ if (key->id.lib == NULL) {
+ key->ipo= dst;
+ dst->id.us++;
+ src->id.us--;
}
}
- key= key->id.next;
}
}
}
-void make_local_ipo(Ipo *ipo)
+/* generic call to make IPO's local */
+void make_local_ipo (Ipo *ipo)
{
-
- if(ipo->id.lib==NULL) return;
- if(ipo->id.us==1) {
+ /* can't touch lib-linked data */
+ if (ipo->id.lib == NULL)
+ return;
+
+ /* with only one user, just set local flag */
+ if (ipo->id.us == 1) {
ipo->id.lib= 0;
ipo->id.flag= LIB_LOCAL;
new_id(0, (ID *)ipo, 0);
return;
}
- if(ipo->blocktype==ID_OB) make_local_obipo(ipo);
- else if(ipo->blocktype==ID_MA) make_local_matipo(ipo);
- else if(ipo->blocktype==ID_KE) make_local_keyipo(ipo);
-
+ /* when more than 1 user, can only make local for certain blocktypes */
+ switch (ipo->blocktype) {
+ case ID_OB:
+ make_local_obipo(ipo);
+ break;
+ case ID_MA:
+ make_local_matipo(ipo);
+ break;
+ case ID_KE:
+ make_local_keyipo(ipo);
+ break;
+ }
}
-IpoCurve *find_ipocurve(Ipo *ipo, int adrcode)
+/* ***************************** Keyframe Column Tools ********************************* */
+
+/* add a BezTriple to a column */
+void add_to_cfra_elem(ListBase *lb, BezTriple *bezt)
{
- if(ipo) {
- IpoCurve *icu;
- for(icu= ipo->curve.first; icu; icu= icu->next) {
- if(icu->adrcode==adrcode) return icu;
+ CfraElem *ce, *cen;
+
+ for (ce= lb->first; ce; ce= ce->next) {
+ /* double key? */
+ if (ce->cfra == bezt->vec[1][0]) {
+ if (bezt->f2 & SELECT) ce->sel= bezt->f2;
+ return;
}
+ /* should key be inserted before this column? */
+ else if (ce->cfra > bezt->vec[1][0]) break;
}
- return NULL;
+
+ /* create a new column */
+ cen= MEM_callocN(sizeof(CfraElem), "add_to_cfra_elem");
+ if (ce) BLI_insertlinkbefore(lb, ce, cen);
+ else BLI_addtail(lb, cen);
+
+ cen->cfra= bezt->vec[1][0];
+ cen->sel= bezt->f2;
}
-void calchandles_ipocurve(IpoCurve *icu)
+/* make a list of keyframe 'columns' in an IPO block */
+void make_cfra_list (Ipo *ipo, ListBase *elems)
{
- BezTriple *bezt, *prev, *next;
+ IpoCurve *icu;
+ BezTriple *bezt;
int a;
+
+ for (icu= ipo->curve.first; icu; icu= icu->next) {
+ if (icu->flag & IPO_VISIBLE) {
+ /* ... removed old checks for adrcode types from here ...
+ * - (was this used for IpoKeys in the past?)
+ */
+
+ bezt= icu->bezt;
+ if (bezt) {
+ for (a=0; a < icu->totvert; a++, bezt++) {
+ add_to_cfra_elem(elems, bezt);
+ }
+ }
+ }
+ }
+}
+
+/* ***************************** Timing Stuff ********************************* */
- a= icu->totvert;
+/* This (evil) function is needed to cope with two legacy Blender rendering features
+ * mblur (motion blur that renders 'subframes' and blurs them together), and fields
+ * rendering. Thus, the use of ugly globals from object.c
+ */
+// BAD... EVIL... JUJU...!!!!
+float frame_to_float (int cfra) /* see also bsystem_time in object.c */
+{
+ extern float bluroffs; /* bad stuff borrowed from object.c */
+ extern float fieldoffs;
+ float ctime;
- /* IPO_CONST doesn't have handles */
- if(a<2 || icu->ipo==IPO_CONST) return;
+ ctime= (float)cfra;
+ ctime+= bluroffs+fieldoffs;
+ ctime*= G.scene->r.framelen;
- bezt= icu->bezt;
- prev= 0;
- next= bezt+1;
+ return ctime;
+}
- while(a--) {
+/* ***************************** IPO Curve Sanity ********************************* */
+/* The functions here are used in various parts of Blender, usually after some editing
+ * of keyframe data has occurred. They ensure that keyframe data is properly ordered and
+ * that the handles are correctly
+ */
- if(bezt->vec[0][0]>bezt->vec[1][0]) bezt->vec[0][0]= bezt->vec[1][0];
- if(bezt->vec[2][0]<bezt->vec[1][0]) bezt->vec[2][0]= bezt->vec[1][0];
+/* This function recalculates the handles of an IPO-Curve
+ * If the BezTriples have been rearranged, sort them first before using this.
+ */
+void calchandles_ipocurve (IpoCurve *icu)
+{
+ BezTriple *bezt, *prev, *next;
+ int a= icu->totvert;
- if(icu->flag & IPO_AUTO_HORIZ)
+ /* Error checking:
+ * - need at least two points
+ * - need bezier keys
+ * - only bezier-interpolation has handles (for now)
+ */
+ if (ELEM(NULL, icu, icu->bezt) || (a < 2) || ELEM(icu->ipo, IPO_CONST, IPO_LIN))
+ return;
+
+ /* get initial pointers */
+ bezt= icu->bezt;
+ prev= NULL;
+ next= (bezt + 1);
+
+ /* loop over all beztriples, adjusting handles */
+ while (a--) {
+ /* clamp timing of handles to be on either side of beztriple */
+ if (bezt->vec[0][0] > bezt->vec[1][0]) bezt->vec[0][0]= bezt->vec[1][0];
+ if (bezt->vec[2][0] < bezt->vec[1][0]) bezt->vec[2][0]= bezt->vec[1][0];
+
+ /* calculate autohandles */
+ if (icu->flag & IPO_AUTO_HORIZ)
calchandleNurb(bezt, prev, next, 2); /* 2==special autohandle && keep extrema horizontal */
else
calchandleNurb(bezt, prev, next, 1); /* 1==special autohandle */
-
- prev= bezt;
- if(a==1) {
- next= 0;
- }
- else next++;
-
+
/* for automatic ease in and out */
- if(bezt->h1==HD_AUTO && bezt->h2==HD_AUTO) {
- if(a==0 || a==icu->totvert-1) {
- if(icu->extrap==IPO_HORIZ) {
+ if ((bezt->h1==HD_AUTO) && (bezt->h2==HD_AUTO)) {
+ /* only do this on first or last beztriple */
+ if ((a==0) || (a==icu->totvert-1)) {
+ /* set both handles to have same horizontal value as keyframe */
+ if (icu->extrap==IPO_HORIZ) {
bezt->vec[0][1]= bezt->vec[2][1]= bezt->vec[1][1];
}
}
}
+ /* advance pointers for next iteration */
+ prev= bezt;
+ if (a == 1) next= NULL;
+ else next++;
bezt++;
}
}
-void testhandles_ipocurve(IpoCurve *icu)
+/* Use when IPO-Curve with handles has changed
+ * It treats all BezTriples with the following rules:
+ * - PHASE 1: do types have to be altered?
+ * -> Auto handles: become aligned when selection status is NOT(000 || 111)
+ * -> Vector handles: become 'nothing' when (one half selected AND other not)
+ * - PHASE 2: recalculate handles
+*/
+void testhandles_ipocurve (IpoCurve *icu)
{
- /* use when something has changed with handles.
- it treats all BezTriples with the following rules:
- PHASE 1: do types have to be altered?
- Auto handles: become aligned when selection status is NOT(000 || 111)
- Vector handles: become 'nothing' when (one half selected AND other not)
- PHASE 2: recalculate handles
- */
- BezTriple *bezt;
- int flag, a;
+ BezTriple *bezt;
+ int a;
- bezt= icu->bezt;
- if(bezt==NULL) return;
+ /* only beztriples have handles (bpoints don't though) */
+ if (ELEM(NULL, icu, icu->bezt))
+ return;
- a= icu->totvert;
- while(a--) {
- flag= 0;
- if(bezt->f1 & SELECT) flag++;
- if(bezt->f2 & SELECT) flag += 2;
- if(bezt->f3 & SELECT) flag += 4;
-
- if( !(flag==0 || flag==7) ) {
- if(bezt->h1==HD_AUTO) { /* auto */
+ /* loop over beztriples */
+ for (a=0, bezt=icu->bezt; a < icu->totvert; a++, bezt++) {
+ short flag= 0;
+
+ /* flag is initialised as selection status
+ * of beztriple control-points (labelled 0,1,2)
+ */
+ if (bezt->f1 & SELECT) flag |= (1<<0); // == 1
+ if (bezt->f2 & SELECT) flag |= (1<<1); // == 2
+ if (bezt->f3 & SELECT) flag |= (1<<2); // == 4
+
+ /* one or two handles selected only */
+ if (ELEM(flag, 0, 7)==0) {
+ /* auto handles become aligned */
+ if (bezt->h1==HD_AUTO)
bezt->h1= HD_ALIGN;
- }
- if(bezt->h2==HD_AUTO) { /* auto */
+ if(bezt->h2==HD_AUTO)
bezt->h2= HD_ALIGN;
+
+ /* vector handles become 'free' when only one half selected */
+ if(bezt->h1==HD_VECT) {
+ /* only left half (1 or 2 or 1+2) */
+ if (flag < 4)
+ bezt->h1= 0;
}
-
- if(bezt->h1==HD_VECT) { /* vector */
- if(flag < 4) bezt->h1= 0;
- }
- if(bezt->h2==HD_VECT) { /* vector */
- if( flag > 3) bezt->h2= 0;
+ if(bezt->h2==HD_VECT) {
+ /* only right half (4 or 2+4) */
+ if (flag > 3)
+ bezt->h2= 0;
}
}
- bezt++;
}
+ /* recalculate handles */
calchandles_ipocurve(icu);
}
-
+/* This function sorts BezTriples so that they are arranged in chronological order,
+ * as tools working on IPO-Curves expect that the BezTriples are in order.
+ */
void sort_time_ipocurve(IpoCurve *icu)
{
- BezTriple *bezt;
- int a, ok= 1;
+ short ok= 1;
- while(ok) {
+ /* keep adjusting order of beztriples until nothing moves (bubble-sort) */
+ while (ok) {
ok= 0;
-
- if(icu->bezt) {
- bezt= icu->bezt;
- a= icu->totvert;
- while(a--) {
- if(a>0) {
- if( bezt->vec[1][0] > (bezt+1)->vec[1][0]) {
+
+ /* currently, will only be needed when there are beztriples */
+ if (icu->bezt) {
+ BezTriple *bezt;
+ int a;
+
+ /* loop over ALL points to adjust position in array and recalculate handles */
+ for (a=0, bezt=icu->bezt; a < icu->totvert; a++, bezt++) {
+ /* check if thee's a next beztriple which we could try to swap with current */
+ if (a < (icu->totvert-1)) {
+ /* swap if one is after the other (and indicate that order has changed) */
+ if (bezt->vec[1][0] > (bezt+1)->vec[1][0]) {
SWAP(BezTriple, *bezt, *(bezt+1));
ok= 1;
}
+
+ /* if either one of both of the points exceeds crosses over the keyframe time... */
+ if ( (bezt->vec[0][0] > bezt->vec[1][0]) && (bezt->vec[2][0] < bezt->vec[1][0]) ) {
+ /* swap handles if they have switched sides for some reason */
+ SWAP(float, bezt->vec[0][0], bezt->vec[2][0]);
+ SWAP(float, bezt->vec[0][1], bezt->vec[2][1]);
+ }
+ else {
+ /* clamp handles */
+ if (bezt->vec[0][0] > bezt->vec[1][0])
+ bezt->vec[0][0]= bezt->vec[1][0];
+ if (bezt->vec[2][0] < bezt->vec[1][0])
+ bezt->vec[2][0]= bezt->vec[1][0];
+ }
}
- if(bezt->vec[0][0]>bezt->vec[1][0] && bezt->vec[2][0]<bezt->vec[1][0]) {
- SWAP(float, bezt->vec[0][0], bezt->vec[2][0]);
- SWAP(float, bezt->vec[0][1], bezt->vec[2][1]);
- }
- else {
- if(bezt->vec[0][0]>bezt->vec[1][0]) bezt->vec[0][0]= bezt->vec[1][0];
- if(bezt->vec[2][0]<bezt->vec[1][0]) bezt->vec[2][0]= bezt->vec[1][0];
- }
- bezt++;
}
}
- else {
-
- }
}
}
-int test_time_ipocurve(IpoCurve *icu)
+/* This function tests if any BezTriples are out of order, thus requiring a sort */
+int test_time_ipocurve (IpoCurve *icu)
{
- BezTriple *bezt;
int a;
- if(icu->bezt) {
- bezt= icu->bezt;
- a= icu->totvert-1;
- while(a--) {
- if( bezt->vec[1][0] > (bezt+1)->vec[1][0]) {
- return 1;
- }
- bezt++;
- }
- }
- else {
+ /* currently, only need to test beztriples */
+ if (icu->bezt) {
+ BezTriple *bezt;
+ /* loop through all beztriples, stopping when one exceeds the one after it */
+ for (a=0, bezt= icu->bezt; a < (icu->totvert - 1); a++, bezt++) {
+ if (bezt->vec[1][0] > (bezt+1)->vec[1][0])
+ return 1;
+ }
}
-
+
+ /* none need any swapping */
return 0;
}
-void correct_bezpart(float *v1, float *v2, float *v3, float *v4)
+/* --------- */
+
+/* The total length of the handles is not allowed to be more
+ * than the horizontal distance between (v1-v4).
+ * This is to prevent curve loops.
+*/
+void correct_bezpart (float *v1, float *v2, float *v3, float *v4)
{
- /* the total length of the handles is not allowed to be more
- * than the horizontal distance between (v1-v4)
- * this to prevent curve loops
- */
float h1[2], h2[2], len1, len2, len, fac;
+ /* calculate handle deltas */
h1[0]= v1[0]-v2[0];
h1[1]= v1[1]-v2[1];
h2[0]= v4[0]-v3[0];
h2[1]= v4[1]-v3[1];
+ /* calculate distances:
+ * - len = span of time between keyframes
+ * - len1 = length of handle of start key
+ * - len2 = length of handle of end key
+ */
len= v4[0]- v1[0];
len1= (float)fabs(h1[0]);
len2= (float)fabs(h2[0]);
- if(len1+len2==0.0) return;
- if(len1+len2 > len) {
+ /* if the handles have no length, no need to do any corrections */
+ if ((len1+len2) == 0.0)
+ return;
+
+ /* the two handles cross over each other, so force them
+ * apart using the proportion they overlap
+ */
+ if ((len1+len2) > len) {
fac= len/(len1+len2);
v2[0]= (v1[0]-fac*h1[0]);
@@ -635,57 +800,86 @@ void correct_bezpart(float *v1, float *v2, float *v3, float *v4)
v3[0]= (v4[0]-fac*h2[0]);
v3[1]= (v4[1]-fac*h2[1]);
-
}
}
-/* *********************** ARITH *********************** */
+#if 0 // TODO: enable when we have per-segment interpolation
+/* This function sets the interpolation mode for an entire Ipo-Curve.
+ * It is primarily used for patching old files, but is also used in the interface
+ * to make sure that all segments of the curve use the same interpolation.
+ */
+void set_interpolation_ipocurve (IpoCurve *icu, short ipo)
+{
+ BezTriple *bezt;
+ int a;
+
+ /* validate arguments */
+ if (icu == NULL) return;
+ if (ELEM3(ipo, IPO_CONST, IPO_LIN, IPO_BEZ)==0) return;
-int findzero(float x, float q0, float q1, float q2, float q3, float *o)
+ /* set interpolation mode for whole curve */
+ icu->ipo= ipo;
+
+ /* set interpolation mode of all beztriples */
+ for (a=0, bezt=icu->bezt; a<icu->totvert; a++, bezt++)
+ bezt->ipo= ipo;
+}
+#endif // TODO: enable when we have per-segment interpolation
+
+/* ***************************** Curve Calculations ********************************* */
+
+/* find root/zero */
+int findzero (float x, float q0, float q1, float q2, float q3, float *o)
{
double c0, c1, c2, c3, a, b, c, p, q, d, t, phi;
int nr= 0;
- c0= q0-x;
- c1= 3*(q1-q0);
- c2= 3*(q0-2*q1+q2);
- c3= q3-q0+3*(q1-q2);
+ c0= q0 - x;
+ c1= 3 * (q1 - q0);
+ c2= 3 * (q0 - 2*q1 + q2);
+ c3= q3 - q0 + 3 * (q1 - q2);
- if(c3!=0.0) {
+ if (c3 != 0.0) {
a= c2/c3;
b= c1/c3;
c= c0/c3;
a= a/3;
-
- p= b/3-a*a;
- q= (2*a*a*a-a*b+c)/2;
- d= q*q+p*p*p;
-
- if(d>0.0) {
+
+ p= b/3 - a*a;
+ q= (2*a*a*a - a*b + c) / 2;
+ d= q*q + p*p*p;
+
+ if (d > 0.0) {
t= sqrt(d);
- o[0]= (float)(Sqrt3d(-q+t)+Sqrt3d(-q-t)-a);
- if(o[0]>= SMALL && o[0]<=1.000001) return 1;
+ o[0]= (float)(Sqrt3d(-q+t) + Sqrt3d(-q-t) - a);
+
+ if ((o[0] >= SMALL) && (o[0] <= 1.000001)) return 1;
else return 0;
}
- else if(d==0.0) {
+ else if (d == 0.0) {
t= Sqrt3d(-q);
- o[0]= (float)(2*t-a);
- if(o[0]>=SMALL && o[0]<=1.000001) nr++;
+ o[0]= (float)(2*t - a);
+
+ if ((o[0] >= SMALL) && (o[0] <= 1.000001)) nr++;
o[nr]= (float)(-t-a);
- if(o[nr]>=SMALL && o[nr]<=1.000001) return nr+1;
+
+ if ((o[nr] >= SMALL) && (o[nr] <= 1.000001)) return nr+1;
else return nr;
}
else {
- phi= acos(-q/sqrt(-(p*p*p)));
+ phi= acos(-q / sqrt(-(p*p*p)));
t= sqrt(-p);
p= cos(phi/3);
- q= sqrt(3-3*p*p);
- o[0]= (float)(2*t*p-a);
- if(o[0]>=SMALL && o[0]<=1.000001) nr++;
- o[nr]= (float)(-t*(p+q)-a);
- if(o[nr]>=SMALL && o[nr]<=1.000001) nr++;
- o[nr]= (float)(-t*(p-q)-a);
- if(o[nr]>=SMALL && o[nr]<=1.000001) return nr+1;
+ q= sqrt(3 - 3*p*p);
+ o[0]= (float)(2*t*p - a);
+
+ if ((o[0] >= SMALL) && (o[0] <= 1.000001)) nr++;
+ o[nr]= (float)(-t * (p + q) - a);
+
+ if ((o[nr] >= SMALL) && (o[nr] <= 1.000001)) nr++;
+ o[nr]= (float)(-t * (p - q) - a);
+
+ if ((o[nr] >= SMALL) && (o[nr] <= 1.000001)) return nr+1;
else return nr;
}
}
@@ -694,83 +888,97 @@ int findzero(float x, float q0, float q1, float q2, float q3, float *o)
b=c1;
c=c0;
- if(a!=0.0) {
- p=b*b-4*a*c;
- if(p>0) {
+ if (a != 0.0) {
+ // discriminant
+ p= b*b - 4*a*c;
+
+ if (p > 0) {
p= sqrt(p);
- o[0]= (float)((-b-p)/(2*a));
- if(o[0]>=SMALL && o[0]<=1.000001) nr++;
+ o[0]= (float)((-b-p) / (2 * a));
+
+ if ((o[0] >= SMALL) && (o[0] <= 1.000001)) nr++;
o[nr]= (float)((-b+p)/(2*a));
- if(o[nr]>=SMALL && o[nr]<=1.000001) return nr+1;
+
+ if ((o[nr] >= SMALL) && (o[nr] <= 1.000001)) return nr+1;
else return nr;
}
- else if(p==0) {
- o[0]= (float)(-b/(2*a));
- if(o[0]>=SMALL && o[0]<=1.000001) return 1;
+ else if (p == 0) {
+ o[0]= (float)(-b / (2 * a));
+ if ((o[0] >= SMALL) && (o[0] <= 1.000001)) return 1;
else return 0;
}
}
- else if(b!=0.0) {
+ else if (b != 0.0) {
o[0]= (float)(-c/b);
- if(o[0]>=SMALL && o[0]<=1.000001) return 1;
+
+ if ((o[0] >= SMALL) && (o[0] <= 1.000001)) return 1;
else return 0;
}
- else if(c==0.0) {
+ else if (c == 0.0) {
o[0]= 0.0;
return 1;
}
+
return 0;
}
}
-void berekeny(float f1, float f2, float f3, float f4, float *o, int b)
+void berekeny (float f1, float f2, float f3, float f4, float *o, int b)
{
float t, c0, c1, c2, c3;
int a;
c0= f1;
- c1= 3.0f*(f2 - f1);
- c2= 3.0f*(f1 - 2.0f*f2 + f3);
- c3= f4 - f1 + 3.0f*(f2-f3);
+ c1= 3.0f * (f2 - f1);
+ c2= 3.0f * (f1 - 2.0f*f2 + f3);
+ c3= f4 - f1 + 3.0f * (f2 - f3);
- for(a=0; a<b; a++) {
+ for (a=0; a < b; a++) {
t= o[a];
- o[a]= c0+t*c1+t*t*c2+t*t*t*c3;
+ o[a]= c0 + t*c1 + t*t*c2 + t*t*t*c3;
}
}
-void berekenx(float *f, float *o, int b)
+void berekenx (float *f, float *o, int b)
{
float t, c0, c1, c2, c3;
int a;
c0= f[0];
- c1= 3*(f[3]-f[0]);
- c2= 3*(f[0]-2*f[3]+f[6]);
- c3= f[9]-f[0]+3*(f[3]-f[6]);
- for(a=0; a<b; a++) {
+ c1= 3 * (f[3] - f[0]);
+ c2= 3 * (f[0] - 2*f[3] + f[6]);
+ c3= f[9] - f[0] + 3 * (f[3] - f[6]);
+
+ for (a=0; a < b; a++) {
t= o[a];
- o[a]= c0+t*c1+t*t*c2+t*t*t*c3;
+ o[a]= c0 + t*c1 + t*t*c2 + t*t*t*c3;
}
}
-/* we need the local transform = current transform - (parent transform + bone transform) */
-/* (local transform is on action channel level) */
-static void posechannel_get_local_transform(bPoseChannel *pchan, float *loc, float *eul, float *size)
+/* ***************************** IPO - Calculations ********************************* */
+
+/* ---------------------- Curve Evaluation --------------------------- */
+
+/* helper function for evaluating drivers:
+ * - we need the local transform = current transform - (parent transform + bone transform)
+ * - (local transform is on action channel level)
+ */
+static void posechannel_get_local_transform (bPoseChannel *pchan, float loc[], float eul[], float size[])
{
- float diff_mat[4][4];
float parmat[4][4], offs_bone[4][4], imat[4][4];
+ float diff_mat[4][4];
+ /* get first the parent + bone transform in parmat */
if (pchan->parent) {
- /* get first the parent + bone transform in parmat */
-
/* bone transform itself */
Mat4CpyMat3(offs_bone, pchan->bone->bone_mat);
+
/* The bone's root offset (is in the parent's coordinate system) */
VECCOPY(offs_bone[3], pchan->bone->head);
+
/* Get the length translation of parent (length along y axis) */
offs_bone[3][1]+= pchan->parent->bone->length;
-
+
Mat4MulSerie(parmat, pchan->parent->pose_mat, offs_bone, NULL, NULL, NULL, NULL, NULL, NULL);
/* invert it */
@@ -779,64 +987,83 @@ static void posechannel_get_local_transform(bPoseChannel *pchan, float *loc, flo
else {
Mat4CpyMat3(offs_bone, pchan->bone->bone_mat);
VECCOPY(offs_bone[3], pchan->bone->head);
-
+
/* invert it */
Mat4Invert(imat, offs_bone);
-
}
/* difference: current transform - (parent transform + bone transform) */
Mat4MulMat4(diff_mat, pchan->pose_mat, imat);
- if(loc)
+ /* extract relevant components */
+ if (loc)
VECCOPY(loc, diff_mat[3]);
- if(eul)
+ if (eul)
Mat4ToEul(diff_mat, eul);
- if(size)
+ if (size)
Mat4ToSize(diff_mat, size);
-
}
-/* has to return a float value */
-static float eval_driver(IpoDriver *driver, float ipotime)
+/* evaluate an IPO-driver to get a 'time' value to use instead of "ipotime"
+ * - "ipotime" is the frame at which IPO-curve is being evaluated
+ * - has to return a float value
+ */
+static float eval_driver (IpoDriver *driver, float ipotime)
{
-
- if(driver->type == IPO_DRIVER_TYPE_PYTHON) {
+#ifndef DISABLE_PYTHON
+ /* currently, drivers are either PyDrivers (evaluating a PyExpression, or Object/Pose-Channel transforms) */
+ if (driver->type == IPO_DRIVER_TYPE_PYTHON) {
/* check for empty or invalid expression */
- if ((driver->name[0] == '\0') ||
- (driver->flag & IPO_DRIVER_FLAG_INVALID))
+ if ( (driver->name[0] == '\0') ||
+ (driver->flag & IPO_DRIVER_FLAG_INVALID) )
+ {
return 0.0f;
- /* this evals the expression and returns its result:
- * (on errors it reports, then returns 0.0f) */
+ }
+
+ /* this evaluates the expression using Python,and returns its result:
+ * - on errors it reports, then returns 0.0f
+ */
return BPY_pydriver_eval(driver);
}
- else {
- Object *ob= driver->ob;
+ else
+#endif /* DISABLE_PYTHON */
+ {
- if(ob==NULL) return 0.0f;
- if(ob->proxy_from)
+ Object *ob= driver->ob;
+
+ /* must have an object to evaluate */
+ if (ob == NULL)
+ return 0.0f;
+
+ /* if a proxy, use the proxy source*/
+ if (ob->proxy_from)
ob= ob->proxy_from;
- if(driver->blocktype==ID_OB) {
- /* depsgraph failure; ob ipos are calculated in where_is_object, this might get called too late */
- if(ob->ipo && ob->ctime!=ipotime) {
+ /* use given object as driver */
+ if (driver->blocktype == ID_OB) {
+ /* depsgraph failure: ob ipos are calculated in where_is_object, this might get called too late */
+ if ((ob->ipo) && (ob->ctime != ipotime)) {
+ /* calculate the value of relevant channel on the Object, but do not write the value
+ * calculated on to the Object but onto "ipotime" instead
+ */
calc_ipo_spec(ob->ipo, driver->adrcode, &ipotime);
return ipotime;
}
- switch(driver->adrcode) {
+ /* return the value of the relevant channel */
+ switch (driver->adrcode) {
case OB_LOC_X:
return ob->loc[0];
case OB_LOC_Y:
return ob->loc[1];
case OB_LOC_Z:
return ob->loc[2];
- case OB_ROT_X:
- return ob->rot[0]/(M_PI_2/9.0);
- case OB_ROT_Y:
- return ob->rot[1]/(M_PI_2/9.0);
- case OB_ROT_Z:
- return ob->rot[2]/(M_PI_2/9.0);
+ case OB_ROT_X: /* hack: euler rotations are divided by 10 deg to fit on same axes as other channels */
+ return (float)( ob->rot[0]/(M_PI_2/9.0) );
+ case OB_ROT_Y: /* hack: euler rotations are divided by 10 deg to fit on same axes as other channels */
+ return (float)( ob->rot[1]/(M_PI_2/9.0) );
+ case OB_ROT_Z: /* hack: euler rotations are divided by 10 deg to fit on same axes as other channels */
+ return (float)( ob->rot[2]/(M_PI_2/9.0) );
case OB_SIZE_X:
return ob->size[0];
case OB_SIZE_Y:
@@ -845,14 +1072,20 @@ static float eval_driver(IpoDriver *driver, float ipotime)
return ob->size[2];
}
}
+
+ /* use given pose-channel as driver */
else { /* ID_AR */
bPoseChannel *pchan= get_pose_channel(ob->pose, driver->name);
- if(pchan && pchan->bone) {
-
- /* rotation difference is not a simple driver (i.e. value drives value), but the angle between 2 bones is driving stuff... which is useful */
- if(driver->adrcode==OB_ROT_DIFF) {
+
+ /* must have at least 1 bone to use */
+ if (pchan && pchan->bone) {
+ /* rotation difference is not a simple driver (i.e. value drives value), but the angle between 2 bones is driving stuff...
+ * - the name of the second pchan is also stored in driver->name, but packed after the other one by DRIVER_NAME_OFFS chars
+ */
+ if (driver->adrcode == OB_ROT_DIFF) {
bPoseChannel *pchan2= get_pose_channel(ob->pose, driver->name+DRIVER_NAME_OFFS);
- if(pchan2 && pchan2->bone) {
+
+ if (pchan2 && pchan2->bone) {
float q1[4], q2[4], quat[4], angle;
Mat4ToQuat(pchan->pose_mat, q1);
@@ -863,27 +1096,33 @@ static float eval_driver(IpoDriver *driver, float ipotime)
angle = 2.0f * (saacos(quat[0]));
angle= ABS(angle);
- return angle>M_PI?2.0f*M_PI-angle:angle;
+ return (angle > M_PI) ? (float)((2.0f * M_PI) - angle) : (float)(angle);
}
}
+
+ /* standard driver */
else {
float loc[3], eul[3], size[3];
+ /* retrieve local transforms to return
+ * - we use eulers here NOT quats, so that Objects can be driven by bones easily
+ * also, this way is more understandable for users
+ */
posechannel_get_local_transform(pchan, loc, eul, size);
-
- switch(driver->adrcode) {
+
+ switch (driver->adrcode) {
case OB_LOC_X:
return loc[0];
case OB_LOC_Y:
return loc[1];
case OB_LOC_Z:
return loc[2];
- case OB_ROT_X:
- return eul[0]/(M_PI_2/9.0);
- case OB_ROT_Y:
- return eul[1]/(M_PI_2/9.0);
- case OB_ROT_Z:
- return eul[2]/(M_PI_2/9.0);
+ case OB_ROT_X: /* hack: euler rotations are divided by 10 deg to fit on same axes as other channels */
+ return (float)( eul[0]/(M_PI_2/9.0) );
+ case OB_ROT_Y: /* hack: euler rotations are divided by 10 deg to fit on same axes as other channels */
+ return (float)( eul[1]/(M_PI_2/9.0) );
+ case OB_ROT_Z: /* hack: euler rotations are divided by 10 deg to fit on same axes as other channels */
+ return (float)( eul[2]/(M_PI_2/9.0) );
case OB_SIZE_X:
return size[0];
case OB_SIZE_Y:
@@ -895,227 +1134,722 @@ static float eval_driver(IpoDriver *driver, float ipotime)
}
}
}
+
+ /* return 0.0f, as couldn't find relevant data to use */
return 0.0f;
}
-float eval_icu(IpoCurve *icu, float ipotime)
+/* evaluate and return the value of the given IPO-curve at the specified frame ("evaltime") */
+float eval_icu(IpoCurve *icu, float evaltime)
{
- BezTriple *bezt, *prevbezt;
- float v1[2], v2[2], v3[2], v4[2], opl[32], dx, fac;
- float cycdx, cycdy, ofs, cycyofs, cvalue = 0.0;
- int a, b;
+ float cvalue = 0.0f;
- cycyofs= 0.0;
-
- if(icu->driver) {
+ /* if there is a driver, evaluate it to find value to use as "evaltime"
+ * - this value will also be returned as the value of the 'curve', if there are no keyframes
+ */
+ if (icu->driver) {
/* ipotime now serves as input for the curve */
- ipotime= cvalue= eval_driver(icu->driver, ipotime);
+ evaltime= cvalue= eval_driver(icu->driver, evaltime);
}
- if(icu->bezt) {
+
+ /* there are keyframes (in the form of BezTriples) which can be interpolated between */
+ if (icu->bezt) {
+ /* get pointers */
+ BezTriple *bezt, *prevbezt, *lastbezt;
+ float v1[2], v2[2], v3[2], v4[2], opl[32], dx, fac;
+ float cycdx, cycdy, ofs, cycyofs= 0.0;
+ int a, b;
+
+ /* get pointers */
+ a= icu->totvert-1;
prevbezt= icu->bezt;
bezt= prevbezt+1;
- a= icu->totvert-1;
+ lastbezt= prevbezt + a;
- /* cyclic? */
- if(icu->extrap & IPO_CYCL) {
- ofs= icu->bezt->vec[1][0];
- cycdx= (icu->bezt+icu->totvert-1)->vec[1][0] - ofs;
- cycdy= (icu->bezt+icu->totvert-1)->vec[1][1] - icu->bezt->vec[1][1];
- if(cycdx!=0.0) {
-
- if(icu->extrap & IPO_DIR) {
- cycyofs= (float)floor((ipotime-ofs)/cycdx);
- cycyofs*= cycdy;
+ /* extrapolation mode is 'cyclic' - find relative place within a cycle */
+ if (icu->extrap & IPO_CYCL) {
+ /* ofs is start frame of cycle */
+ ofs= prevbezt->vec[1][0];
+
+ /* calculate period and amplitude (total height) of a cycle */
+ cycdx= lastbezt->vec[1][0] - prevbezt->vec[1][0];
+ cycdy= lastbezt->vec[1][1] - prevbezt->vec[1][1];
+
+ /* cycle occurs over some period of time (cycdx should be positive all the time) */
+ if (cycdx) {
+ /* check if 'cyclic extrapolation', and thus calculate y-offset for this cycle
+ * - IPO_CYCLX = (IPO_CYCL + IPO_DIR)
+ */
+ if (icu->extrap & IPO_DIR) {
+ cycyofs = (float)floor((evaltime - ofs) / cycdx);
+ cycyofs *= cycdy;
}
-
- ipotime= (float)(fmod(ipotime-ofs, cycdx)+ofs);
- if(ipotime<ofs) ipotime+= cycdx;
+
+ /* calculate where in the cycle we are (overwrite evaltime to reflect this) */
+ evaltime= (float)(fmod(evaltime-ofs, cycdx) + ofs);
+ if (evaltime < ofs) evaltime += cycdx;
}
}
- /* endpoints? */
-
- if(prevbezt->vec[1][0]>=ipotime) {
- if( (icu->extrap & IPO_DIR) && icu->ipo!=IPO_CONST) {
- dx= prevbezt->vec[1][0]-ipotime;
- fac= prevbezt->vec[1][0]-prevbezt->vec[0][0];
- if(fac!=0.0) {
- fac= (prevbezt->vec[1][1]-prevbezt->vec[0][1])/fac;
- cvalue= prevbezt->vec[1][1]-fac*dx;
+ /* evaluation time at or past endpoints? */
+ // TODO: for per-bezt interpolation, replace all icu->ipo with (bezt)->ipo
+ if (prevbezt->vec[1][0] >= evaltime) {
+ /* before or on first keyframe */
+ if ((icu->extrap & IPO_DIR) && (icu->ipo != IPO_CONST)) {
+ /* linear or bezier interpolation */
+ if (icu->ipo==IPO_LIN) {
+ /* Use the next center point instead of our own handle for
+ * linear interpolated extrapolate
+ */
+ if (icu->totvert == 1)
+ cvalue= prevbezt->vec[1][1];
+ else {
+ bezt = prevbezt+1;
+ dx= prevbezt->vec[1][0] - evaltime;
+ fac= bezt->vec[1][0] - prevbezt->vec[1][0];
+
+ /* prevent division by zero */
+ if (fac) {
+ fac= (bezt->vec[1][1] - prevbezt->vec[1][1]) / fac;
+ cvalue= prevbezt->vec[1][1] - (fac * dx);
+ }
+ else
+ cvalue= prevbezt->vec[1][1];
+ }
+ }
+ else {
+ /* Use the first handle (earlier) of first BezTriple to calculate the
+ * gradient and thus the value of the curve at evaltime
+ */
+ dx= prevbezt->vec[1][0] - evaltime;
+ fac= prevbezt->vec[1][0] - prevbezt->vec[0][0];
+
+ /* prevent division by zero */
+ if (fac) {
+ fac= (prevbezt->vec[1][1] - prevbezt->vec[0][1]) / fac;
+ cvalue= prevbezt->vec[1][1] - (fac * dx);
+ }
+ else
+ cvalue= prevbezt->vec[1][1];
}
- else cvalue= prevbezt->vec[1][1];
}
- else cvalue= prevbezt->vec[1][1];
-
- cvalue+= cycyofs;
+ else {
+ /* constant (IPO_HORIZ) extrapolation or constant interpolation,
+ * so just extend first keyframe's value
+ */
+ cvalue= prevbezt->vec[1][1];
+ }
}
- else if( (prevbezt+a)->vec[1][0]<=ipotime) {
- if( (icu->extrap & IPO_DIR) && icu->ipo!=IPO_CONST) {
- prevbezt+= a;
- dx= ipotime-prevbezt->vec[1][0];
- fac= prevbezt->vec[2][0]-prevbezt->vec[1][0];
-
- if(fac!=0) {
- fac= (prevbezt->vec[2][1]-prevbezt->vec[1][1])/fac;
- cvalue= prevbezt->vec[1][1]+fac*dx;
+ else if (lastbezt->vec[1][0] <= evaltime) {
+ /* after or on last keyframe */
+ if( (icu->extrap & IPO_DIR) && (icu->ipo != IPO_CONST)) {
+ /* linear or bezier interpolation */
+ if (icu->ipo==IPO_LIN) {
+ /* Use the next center point instead of our own handle for
+ * linear interpolated extrapolate
+ */
+ if (icu->totvert == 1)
+ cvalue= lastbezt->vec[1][1];
+ else {
+ prevbezt = lastbezt - 1;
+ dx= evaltime - lastbezt->vec[1][0];
+ fac= lastbezt->vec[1][0] - prevbezt->vec[1][0];
+
+ /* prevent division by zero */
+ if (fac) {
+ fac= (lastbezt->vec[1][1] - prevbezt->vec[1][1]) / fac;
+ cvalue= lastbezt->vec[1][1] + (fac * dx);
+ }
+ else
+ cvalue= lastbezt->vec[1][1];
+ }
+ }
+ else {
+ /* Use the gradient of the second handle (later) of last BezTriple to calculate the
+ * gradient and thus the value of the curve at evaltime
+ */
+ dx= evaltime - lastbezt->vec[1][0];
+ fac= lastbezt->vec[2][0] - lastbezt->vec[1][0];
+
+ /* prevent division by zero */
+ if (fac) {
+ fac= (lastbezt->vec[2][1] - lastbezt->vec[1][1]) / fac;
+ cvalue= lastbezt->vec[1][1] + (fac * dx);
+ }
+ else
+ cvalue= lastbezt->vec[1][1];
}
- else cvalue= prevbezt->vec[1][1];
}
- else cvalue= (prevbezt+a)->vec[1][1];
-
- cvalue+= cycyofs;
+ else {
+ /* constant (IPO_HORIZ) extrapolation or constant interpolation,
+ * so just extend last keyframe's value
+ */
+ cvalue= lastbezt->vec[1][1];
+ }
}
else {
- while(a--) {
- if(prevbezt->vec[1][0]<=ipotime && bezt->vec[1][0]>=ipotime) {
- if(icu->ipo==IPO_CONST) {
- cvalue= prevbezt->vec[1][1]+cycyofs;
+ /* evaltime occurs somewhere in the middle of the curve */
+ // TODO: chould be optimised by using a binary search instead???
+ for (a=0; prevbezt && bezt && (a < icu->totvert-1); a++, prevbezt=bezt, bezt++) {
+ /* evaltime occurs within the interval defined by these two keyframes */
+ if ((prevbezt->vec[1][0] <= evaltime) && (bezt->vec[1][0] >= evaltime)) {
+ /* value depends on interpolation mode */
+ if (icu->ipo == IPO_CONST) {
+ /* constant (evaltime not relevant, so no interpolation needed) */
+ cvalue= prevbezt->vec[1][1];
}
- else if(icu->ipo==IPO_LIN) {
- fac= bezt->vec[1][0]-prevbezt->vec[1][0];
- if(fac==0) cvalue= cycyofs+prevbezt->vec[1][1];
- else {
- fac= (ipotime-prevbezt->vec[1][0])/fac;
- cvalue= cycyofs+prevbezt->vec[1][1]+ fac*(bezt->vec[1][1]-prevbezt->vec[1][1]);
+ else if (icu->ipo == IPO_LIN) {
+ /* linear - interpolate between values of the two keyframes */
+ fac= bezt->vec[1][0] - prevbezt->vec[1][0];
+
+ /* prevent division by zero */
+ if (fac) {
+ fac= (evaltime - prevbezt->vec[1][0]) / fac;
+ cvalue= prevbezt->vec[1][1] + (fac * (bezt->vec[1][1] - prevbezt->vec[1][1]));
}
+ else
+ cvalue= prevbezt->vec[1][1];
}
else {
+ /* bezier interpolation */
+ /* v1,v2 are the first keyframe and its 2nd handle */
v1[0]= prevbezt->vec[1][0];
v1[1]= prevbezt->vec[1][1];
v2[0]= prevbezt->vec[2][0];
v2[1]= prevbezt->vec[2][1];
-
+ /* v3,v4 are the last keyframe's 1st handle + the last keyframe */
v3[0]= bezt->vec[0][0];
v3[1]= bezt->vec[0][1];
v4[0]= bezt->vec[1][0];
v4[1]= bezt->vec[1][1];
-
+
+ /* adjust handles so that they don't overlap (forming a loop) */
correct_bezpart(v1, v2, v3, v4);
- b= findzero(ipotime, v1[0], v2[0], v3[0], v4[0], opl);
- if(b) {
+ /* try to get a value for this position - if failure, try another set of points */
+ b= findzero(evaltime, v1[0], v2[0], v3[0], v4[0], opl);
+ if (b) {
berekeny(v1[1], v2[1], v3[1], v4[1], opl, 1);
- cvalue= opl[0]+cycyofs;
+ cvalue= opl[0];
break;
}
}
}
- prevbezt= bezt;
- bezt++;
}
}
+
+ /* apply y-offset (for 'cyclic extrapolation') to calculated value */
+ cvalue+= cycyofs;
}
-
- if(icu->ymin < icu->ymax) {
- if(cvalue < icu->ymin) cvalue= icu->ymin;
- else if(cvalue > icu->ymax) cvalue= icu->ymax;
+
+ /* clamp evaluated value to lie within allowable value range for this channel */
+ if (icu->ymin < icu->ymax) {
+ CLAMP(cvalue, icu->ymin, icu->ymax);
}
+ /* return evaluated value */
return cvalue;
}
-void calc_icu(IpoCurve *icu, float ctime)
+/* ------------------- IPO-Block/Curve Calculation - General API ----------------------- */
+
+/* calculate the value of the given IPO-curve at the current frame, and set its curval */
+void calc_icu (IpoCurve *icu, float ctime)
{
+ /* calculate and set curval (evaluates driver too) */
icu->curval= eval_icu(icu, ctime);
}
-float calc_ipo_time(Ipo *ipo, float ctime)
+/* calculate for the current frame, all IPO-curves in IPO-block that can be evaluated
+ * - icu->curval is set for all IPO-curves which are evaluated!
+ */
+void calc_ipo (Ipo *ipo, float ctime)
{
+ IpoCurve *icu;
+
+ /* if there is no IPO block to evaluate, or whole block is "muted" */
+ if (ipo == NULL) return;
+ if (ipo->muteipo) return;
+
+ /* loop over all curves */
+ for (icu= ipo->curve.first; icu; icu= icu->next) {
+ /* only evaluated curve if allowed to:
+ * - Muted channels should not be evaluated as they shouldn't have any effect
+ * --> user explictly turned them off!
+ * - Drivers should be evaluated at all updates
+ * --> TODO Note: drivers should be separated from standard channels
+ * - IPO_LOCK is not set, as it is set by some internal mechanisms to prevent
+ * IPO-curve from overwriting data (currently only used for IPO-Record).
+ */
+ if ((icu->driver) || (icu->flag & IPO_LOCK)==0) {
+ if ((icu->flag & IPO_MUTE)==0)
+ calc_icu(icu, ctime);
+ }
+ }
+}
- if(ipo && ipo->blocktype==ID_OB) {
- IpoCurve *icu= ipo->curve.first;
+/* ------------------- IPO-Block/Curve Calculation - Special Hacks ----------------------- */
- while(icu) {
- if (icu->adrcode==OB_TIME) {
- calc_icu(icu, ctime);
- return 10.0f*icu->curval;
- }
- icu= icu->next;
- }
+/* Calculate and return the value of the 'Time' Ipo-Curve from an Object,
+ * OR return the current time if not found
+ * - used in object.c -> bsystem_time()
+ */
+float calc_ipo_time (Ipo *ipo, float ctime)
+{
+ /* only Time IPO from Object IPO-blocks are relevant */
+ if ((ipo) && (ipo->blocktype == ID_OB)) {
+ IpoCurve *icu= find_ipocurve(ipo, OB_TIME);
+
+ /* only calculate (and set icu->curval) for time curve */
+ if (icu) {
+ calc_icu(icu, ctime);
+ return (10.0f * icu->curval);
+ }
}
+ /* no appropriate time-curve found */
return ctime;
}
-void calc_ipo(Ipo *ipo, float ctime)
+/* Evaluate the specified channel in the given IPO block on the specified frame (ctime),
+ * writing the value into that channel's icu->curval, but ALSO dumping it in ctime.
+ * - Returns success and modifies ctime!
+ */
+short calc_ipo_spec (Ipo *ipo, int adrcode, float *ctime)
+{
+ IpoCurve *icu= find_ipocurve(ipo, adrcode);
+
+ /* only evaluate if found */
+ if (icu) {
+ /* only calculate if allowed to (not locked and not muted)
+ * - drivers not taken into account, because this may be called when calculating a driver
+ */
+ if ((icu->flag & (IPO_LOCK|IPO_MUTE))==0)
+ calc_icu(icu, *ctime);
+
+ /* value resulting from calculations is written into ctime! */
+ *ctime= icu->curval;
+ return 1;
+ }
+
+ /* couldn't evaluate */
+ return 0;
+}
+
+/* ***************************** IPO - DataAPI ********************************* */
+
+/* --------------------- Flush/Execute IPO Values ----------------------------- */
+
+/* Flush IpoCurve->curvals to the data they affect (defined by ID)
+ * - not for Actions or Constraints! (those have their own special handling)
+ */
+void execute_ipo (ID *id, Ipo *ipo)
{
IpoCurve *icu;
+ void *poin;
+ int type;
- if(ipo==NULL) return;
- if(ipo->muteipo) return;
+ /* don't do anything without an IPO block */
+ if (ipo == NULL)
+ return;
- for(icu= ipo->curve.first; icu; icu= icu->next) {
- if(icu->driver || (icu->flag & IPO_LOCK)==0) {
- if((icu->flag & IPO_MUTE)==0)
- calc_icu(icu, ctime);
+ /* loop over IPO Curves, getting pointer to var to affect, and write into that pointer */
+ for (icu= ipo->curve.first; icu; icu= icu->next) {
+ poin= get_ipo_poin(id, icu, &type);
+ if (poin) write_ipo_poin(poin, type, icu->curval);
+ }
+}
+
+/* Flush Action-Channel IPO data to Pose Channel */
+void execute_action_ipo (bActionChannel *achan, bPoseChannel *pchan)
+{
+ /* only do this if there's an Action Channel and Pose Channel to use */
+ if (achan && achan->ipo && pchan) {
+ IpoCurve *icu;
+
+ /* loop over IPO-curves, getting a pointer to pchan var to write to
+ * - assume for now that only 'float' channels will ever get written into
+ */
+ for (icu= achan->ipo->curve.first; icu; icu= icu->next) {
+ void *poin= get_pchan_ipo_poin(pchan, icu->adrcode);
+ if (poin) write_ipo_poin(poin, IPO_FLOAT, icu->curval);
}
}
}
-/* ************************************** */
-/* DO THE IPO! */
-/* ************************************** */
-void write_ipo_poin(void *poin, int type, float val)
+/* --------------------- Force Calculation + Flush IPO Values ----------------------------- */
+
+/* Calculate values for given IPO block, then flush to all of block's users
+ * - for general usage
+ */
+void do_ipo (Ipo *ipo)
+{
+ if (ipo) {
+ float ctime= frame_to_float(G.scene->r.cfra);
+
+ /* calculate values, then flush to all users of this IPO block */
+ calc_ipo(ipo, ctime);
+ do_ipo_nocalc(ipo);
+ }
+}
+
+/* Calculate values for given Material's IPO block, then flush to given Material only */
+void do_mat_ipo (Material *ma)
{
+ float ctime;
+
+ if (ELEM(NULL, ma, ma->ipo))
+ return;
+
+ ctime= frame_to_float(G.scene->r.cfra);
+ /* if(ob->ipoflag & OB_OFFS_OB) ctime-= ob->sf; */
+
+ /* calculate values for current time, then flush values to given material only */
+ calc_ipo(ma->ipo, ctime);
+ execute_ipo((ID *)ma, ma->ipo);
+}
- switch(type) {
- case IPO_FLOAT:
- *( (float *)poin)= val;
- break;
- case IPO_FLOAT_DEGR:
- *( (float *)poin)= (float)(val*M_PI_2/9.0);
- break;
- case IPO_INT:
- case IPO_INT_BIT:
- case IPO_LONG:
- *( (int *)poin)= (int)val;
- break;
- case IPO_SHORT:
- case IPO_SHORT_BIT:
- *( (short *)poin)= (short)val;
- break;
- case IPO_CHAR:
- case IPO_CHAR_BIT:
- *( (char *)poin)= (char)val;
- break;
+/* Calculate values for given Object's IPO block, then flush to given Object only
+ * - there's also some funky stuff that looks like it's for scene layers
+ */
+void do_ob_ipo (Object *ob)
+{
+ float ctime;
+ unsigned int lay;
+
+ if (ob->ipo == NULL)
+ return;
+
+ /* do not set ob->ctime here: for example when parent in invisible layer */
+ ctime= bsystem_time(ob, (float) G.scene->r.cfra, 0.0);
+
+ /* calculate values of */
+ calc_ipo(ob->ipo, ctime);
+
+ /* Patch: remember localview */
+ lay= ob->lay & 0xFF000000;
+
+ /* flush IPO values to this object only */
+ execute_ipo((ID *)ob, ob->ipo);
+
+ /* hack: for layer animation??? - is this what this is? (Aligorith, 28Sep2008) */
+ ob->lay |= lay;
+ if ((ob->id.name[2]=='S') && (ob->id.name[3]=='C') && (ob->id.name[4]=='E')) {
+ if (strcmp(G.scene->id.name+2, ob->id.name+6)==0) {
+ G.scene->lay= ob->lay;
+ //XXX copy_view3d_lock(0);
+ /* no redraw here! creates too many calls */
+ }
}
}
-float read_ipo_poin(void *poin, int type)
+/* Only execute those IPO-Curves with drivers, on the current frame, for the given Object
+ * - TODO: Drivers should really be made separate from standard anim channels
+ */
+void do_ob_ipodrivers (Object *ob, Ipo *ipo, float ctime)
{
- float val = 0.0;
+ IpoCurve *icu;
+ void *poin;
+ int type;
- switch(type) {
- case IPO_FLOAT:
- val= *( (float *)poin);
+ for (icu= ipo->curve.first; icu; icu= icu->next) {
+ if (icu->driver) {
+ icu->curval= eval_icu(icu, ctime);
+
+ poin= get_ipo_poin((ID *)ob, icu, &type);
+ if (poin) write_ipo_poin(poin, type, icu->curval);
+ }
+ }
+}
+
+/* Special variation to calculate IPO values for Sequence + perform other stuff */
+void do_seq_ipo (Sequence *seq, int cfra)
+{
+ float ctime, div;
+
+ /* seq_ipo has an exception: calc both fields immediately */
+ if (seq->ipo) {
+ if ((seq->flag & SEQ_IPO_FRAME_LOCKED) != 0) {
+ ctime = frame_to_float(cfra);
+ div = 1.0;
+ }
+ else {
+ ctime= frame_to_float(cfra - seq->startdisp);
+ div= (seq->enddisp - seq->startdisp) / 100.0f;
+ if (div == 0.0) return;
+ }
+
+ /* 2nd field */
+ calc_ipo(seq->ipo, (ctime+0.5f)/div);
+ execute_ipo((ID *)seq, seq->ipo);
+ seq->facf1= seq->facf0;
+
+ /* 1st field */
+ calc_ipo(seq->ipo, ctime/div);
+ execute_ipo((ID *)seq, seq->ipo);
+ }
+ else
+ seq->facf1= seq->facf0= 1.0f;
+}
+
+/* --------- */
+
+
+/* exception: it does calc for objects...
+ * now find out why this routine was used anyway!
+ */
+void do_ipo_nocalc (Ipo *ipo)
+{
+ Object *ob;
+ Material *ma;
+ Tex *tex;
+ World *wo;
+ Lamp *la;
+ Camera *ca;
+ bSound *snd;
+
+ if (ipo == NULL)
+ return;
+
+ /* only flush IPO values (without calculating first/again) on
+ * to the datablocks that use the given IPO block
+ */
+ switch (ipo->blocktype) {
+ case ID_OB:
+ for (ob= G.main->object.first; ob; ob= ob->id.next) {
+ if (ob->ipo == ipo) do_ob_ipo(ob);
+ }
break;
- case IPO_FLOAT_DEGR:
- val= *( (float *)poin);
- val = (float)(val/(M_PI_2/9.0));
+ case ID_MA:
+ for (ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if (ma->ipo == ipo) execute_ipo((ID *)ma, ipo);
+ }
break;
- case IPO_INT:
- case IPO_INT_BIT:
- case IPO_LONG:
- val= (float)(*( (int *)poin));
+ case ID_TE:
+ for (tex= G.main->tex.first; tex; tex= tex->id.next) {
+ if (tex->ipo == ipo) execute_ipo((ID *)tex, ipo);
+ }
break;
- case IPO_SHORT:
- case IPO_SHORT_BIT:
- val= *( (short *)poin);
+ case ID_WO:
+ for (wo= G.main->world.first; wo; wo= wo->id.next) {
+ if (wo->ipo == ipo) execute_ipo((ID *)wo, ipo);
+ }
break;
- case IPO_CHAR:
- case IPO_CHAR_BIT:
- val= *( (char *)poin);
+ case ID_LA:
+ for (la= G.main->lamp.first; la; la= la->id.next) {
+ if (la->ipo == ipo) execute_ipo((ID *)la, ipo);
+ }
+ break;
+ case ID_CA:
+ for (ca= G.main->camera.first; ca; ca= ca->id.next) {
+ if (ca->ipo == ipo) execute_ipo((ID *)ca, ipo);
+ }
+ break;
+ case ID_SO:
+ for (snd= G.main->sound.first; snd; snd= snd->id.next) {
+ if (snd->ipo == ipo) execute_ipo((ID *)snd, ipo);
+ }
break;
}
- return val;
}
-static void *give_tex_poin(Tex *tex, int adrcode, int *type )
+/* Executes IPO's for whole database on frame change, in a specified order,
+ * with datablocks being calculated in alphabetical order
+ * - called on scene_update_for_newframe() only
+ */
+void do_all_data_ipos ()
{
- void *poin=0;
+ Material *ma;
+ Tex *tex;
+ World *wo;
+ Ipo *ipo;
+ Lamp *la;
+ Key *key;
+ Camera *ca;
+ bSound *snd;
+ Sequence *seq;
+ Editing *ed;
+ Base *base;
+ float ctime;
+
+ ctime= frame_to_float(G.scene->r.cfra);
+
+ /* this exception cannot be depgraphed yet... what todo with objects in other layers?... */
+ for (base= G.scene->base.first; base; base= base->next) {
+ Object *ob= base->object;
+
+ /* only update layer when an ipo */
+ if (has_ipo_code(ob->ipo, OB_LAY)) {
+ do_ob_ipo(ob);
+ base->lay= ob->lay;
+ }
+ }
+
+ /* layers for the set...*/
+ if (G.scene->set) {
+ for (base= G.scene->set->base.first; base; base= base->next) {
+ Object *ob= base->object;
+
+ if (has_ipo_code(ob->ipo, OB_LAY)) {
+ do_ob_ipo(ob);
+ base->lay= ob->lay;
+ }
+ }
+ }
+
+ /* Calculate all IPO blocks in use, execept those for Objects */
+ for (ipo= G.main->ipo.first; ipo; ipo= ipo->id.next) {
+ if ((ipo->id.us) && (ipo->blocktype != ID_OB)) {
+ calc_ipo(ipo, ctime);
+ }
+ }
- switch(adrcode) {
+ /* Texture Blocks */
+ for (tex= G.main->tex.first; tex; tex= tex->id.next) {
+ if (tex->ipo) execute_ipo((ID *)tex, tex->ipo);
+ }
+
+ /* Material Blocks */
+ for (ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if (ma->ipo) execute_ipo((ID *)ma, ma->ipo);
+ }
+
+ /* World Blocks */
+ for (wo= G.main->world.first; wo; wo= wo->id.next) {
+ if (wo->ipo) execute_ipo((ID *)wo, wo->ipo);
+ }
+
+ /* ShapeKey Blocks */
+ for (key= G.main->key.first; key; key= key->id.next) {
+ if (key->ipo) execute_ipo((ID *)key, key->ipo);
+ }
+
+ /* Lamp Blocks */
+ for (la= G.main->lamp.first; la; la= la->id.next) {
+ if (la->ipo) execute_ipo((ID *)la, la->ipo);
+ }
+
+ /* Camera Blocks */
+ for (ca= G.main->camera.first; ca; ca= ca->id.next) {
+ if (ca->ipo) execute_ipo((ID *)ca, ca->ipo);
+ }
+
+ /* Sound Blocks (Old + Unused) */
+ for (snd= G.main->sound.first; snd; snd= snd->id.next) {
+ if (snd->ipo) execute_ipo((ID *)snd, snd->ipo);
+ }
+
+ /* Sequencer: process FAC Ipos used as volume envelopes */
+ ed= G.scene->ed;
+ if (ed) {
+ for (seq= ed->seqbasep->first; seq; seq= seq->next) {
+ if ( ((seq->type == SEQ_RAM_SOUND) || (seq->type == SEQ_HD_SOUND)) &&
+ (seq->startdisp <= G.scene->r.cfra+2) &&
+ (seq->enddisp>G.scene->r.cfra) &&
+ (seq->ipo) )
+ {
+ do_seq_ipo(seq, G.scene->r.cfra);
+ }
+ }
+ }
+}
+
+
+/* --------------------- Assorted ----------------------------- */
+
+/* clear delta-transforms on all Objects which use the given IPO block */
+void clear_delta_obipo(Ipo *ipo)
+{
+ Object *ob;
+
+ /* only search if there's an IPO */
+ if (ipo == NULL)
+ return;
+
+ /* search through all objects in database */
+ for (ob= G.main->object.first; ob; ob= ob->id.next) {
+ /* can only update if not a library */
+ if (ob->id.lib == NULL) {
+ if (ob->ipo == ipo) {
+ memset(&ob->dloc, 0, 12);
+ memset(&ob->drot, 0, 12);
+ memset(&ob->dsize, 0, 12);
+ }
+ }
+ }
+}
+
+/* ***************************** IPO - DataAPI ********************************* */
+
+// !!!!!!!!!!!!!!!!!!!!!!!!!!!! FIXME - BAD CRUFT WARNING !!!!!!!!!!!!!!!!!!!!!!!
+
+/* These functions here should be replaced eventually by the Data API, as this is
+ * inflexible duplication...
+ */
+
+/* --------------------- Get Pointer API ----------------------------- */
+
+/* get pointer to pose-channel's channel, but set appropriate flags first */
+void *get_pchan_ipo_poin (bPoseChannel *pchan, int adrcode)
+{
+ void *poin= NULL;
+
+ switch (adrcode) {
+ case AC_QUAT_W:
+ poin= &(pchan->quat[0]);
+ pchan->flag |= POSE_ROT;
+ break;
+ case AC_QUAT_X:
+ poin= &(pchan->quat[1]);
+ pchan->flag |= POSE_ROT;
+ break;
+ case AC_QUAT_Y:
+ poin= &(pchan->quat[2]);
+ pchan->flag |= POSE_ROT;
+ break;
+ case AC_QUAT_Z:
+ poin= &(pchan->quat[3]);
+ pchan->flag |= POSE_ROT;
+ break;
+
+ case AC_LOC_X:
+ poin= &(pchan->loc[0]);
+ pchan->flag |= POSE_LOC;
+ break;
+ case AC_LOC_Y:
+ poin= &(pchan->loc[1]);
+ pchan->flag |= POSE_LOC;
+ break;
+ case AC_LOC_Z:
+ poin= &(pchan->loc[2]);
+ pchan->flag |= POSE_LOC;
+ break;
+
+ case AC_SIZE_X:
+ poin= &(pchan->size[0]);
+ pchan->flag |= POSE_SIZE;
+ break;
+ case AC_SIZE_Y:
+ poin= &(pchan->size[1]);
+ pchan->flag |= POSE_SIZE;
+ break;
+ case AC_SIZE_Z:
+ poin= &(pchan->size[2]);
+ pchan->flag |= POSE_SIZE;
+ break;
+ }
+
+ /* return pointer */
+ return poin;
+}
+
+/* get texture channel */
+static void *give_tex_poin (Tex *tex, int adrcode, int *type )
+{
+ void *poin= NULL;
+
+ switch (adrcode) {
case TE_NSIZE:
poin= &(tex->noisesize); break;
case TE_TURB:
@@ -1168,17 +1902,18 @@ static void *give_tex_poin(Tex *tex, int adrcode, int *type )
poin= &(tex->bright); break;
case TE_CONTRA:
poin= &(tex->contrast); break;
-
}
+ /* return pointer */
return poin;
}
-void *give_mtex_poin(MTex *mtex, int adrcode )
+/* get texture-slot/mapping channel */
+void *give_mtex_poin (MTex *mtex, int adrcode)
{
- void *poin=0;
-
- switch(adrcode) {
+ void *poin= NULL;
+
+ switch (adrcode) {
case MAP_OFS_X:
poin= &(mtex->ofs[0]); break;
case MAP_OFS_Y:
@@ -1209,6 +1944,7 @@ void *give_mtex_poin(MTex *mtex, int adrcode )
poin= &(mtex->dispfac); break;
}
+ /* return pointer */
return poin;
}
@@ -1225,1280 +1961,923 @@ void *give_mtex_poin(MTex *mtex, int adrcode )
/* from misc_util: flip the bytes from x */
/* #define GS(x) (((unsigned char *)(x))[0] << 8 | ((unsigned char *)(x))[1]) */
-void *get_ipo_poin(ID *id, IpoCurve *icu, int *type)
+
+/* general function to get pointer to source/destination data */
+void *get_ipo_poin (ID *id, IpoCurve *icu, int *type)
{
void *poin= NULL;
- Object *ob;
- Material *ma;
- MTex *mtex;
- Tex *tex;
- Lamp *la;
- Sequence *seq;
- World *wo;
- ParticleSettings *part;
+ MTex *mtex= NULL;
+ /* most channels will have float data, but those with other types will override this */
*type= IPO_FLOAT;
- if( GS(id->name)==ID_OB) {
-
- ob= (Object *)id;
-
- switch(icu->adrcode) {
- case OB_LOC_X:
- poin= &(ob->loc[0]); break;
- case OB_LOC_Y:
- poin= &(ob->loc[1]); break;
- case OB_LOC_Z:
- poin= &(ob->loc[2]); break;
- case OB_DLOC_X:
- poin= &(ob->dloc[0]); break;
- case OB_DLOC_Y:
- poin= &(ob->dloc[1]); break;
- case OB_DLOC_Z:
- poin= &(ob->dloc[2]); break;
-
- case OB_ROT_X:
- poin= &(ob->rot[0]); *type= IPO_FLOAT_DEGR; break;
- case OB_ROT_Y:
- poin= &(ob->rot[1]); *type= IPO_FLOAT_DEGR; break;
- case OB_ROT_Z:
- poin= &(ob->rot[2]); *type= IPO_FLOAT_DEGR; break;
- case OB_DROT_X:
- poin= &(ob->drot[0]); *type= IPO_FLOAT_DEGR; break;
- case OB_DROT_Y:
- poin= &(ob->drot[1]); *type= IPO_FLOAT_DEGR; break;
- case OB_DROT_Z:
- poin= &(ob->drot[2]); *type= IPO_FLOAT_DEGR; break;
+ /* data is divided into 'blocktypes' based on ID-codes */
+ switch (GS(id->name)) {
+ case ID_OB: /* object channels ----------------------------- */
+ {
+ Object *ob= (Object *)id;
- case OB_SIZE_X:
- poin= &(ob->size[0]); break;
- case OB_SIZE_Y:
- poin= &(ob->size[1]); break;
- case OB_SIZE_Z:
- poin= &(ob->size[2]); break;
- case OB_DSIZE_X:
- poin= &(ob->dsize[0]); break;
- case OB_DSIZE_Y:
- poin= &(ob->dsize[1]); break;
- case OB_DSIZE_Z:
- poin= &(ob->dsize[2]); break;
-
- case OB_LAY:
- poin= &(ob->lay); *type= IPO_INT_BIT; break;
+ switch (icu->adrcode) {
+ case OB_LOC_X:
+ poin= &(ob->loc[0]); break;
+ case OB_LOC_Y:
+ poin= &(ob->loc[1]); break;
+ case OB_LOC_Z:
+ poin= &(ob->loc[2]); break;
+ case OB_DLOC_X:
+ poin= &(ob->dloc[0]); break;
+ case OB_DLOC_Y:
+ poin= &(ob->dloc[1]); break;
+ case OB_DLOC_Z:
+ poin= &(ob->dloc[2]); break;
- case OB_COL_R:
- poin= &(ob->col[0]);
- break;
- case OB_COL_G:
- poin= &(ob->col[1]);
- break;
- case OB_COL_B:
- poin= &(ob->col[2]);
- break;
- case OB_COL_A:
- poin= &(ob->col[3]);
- break;
- case OB_PD_FSTR:
- if(ob->pd) poin= &(ob->pd->f_strength);
- break;
- case OB_PD_FFALL:
- if(ob->pd) poin= &(ob->pd->f_power);
- break;
- case OB_PD_SDAMP:
- if(ob->pd) poin= &(ob->pd->pdef_damp);
- break;
- case OB_PD_RDAMP:
- if(ob->pd) poin= &(ob->pd->pdef_rdamp);
- break;
- case OB_PD_PERM:
- if(ob->pd) poin= &(ob->pd->pdef_perm);
- break;
- case OB_PD_FMAXD:
- if(ob->pd) poin= &(ob->pd->maxdist);
- break;
- }
- }
- else if( GS(id->name)==ID_MA) {
-
- ma= (Material *)id;
-
- switch(icu->adrcode) {
- case MA_COL_R:
- poin= &(ma->r); break;
- case MA_COL_G:
- poin= &(ma->g); break;
- case MA_COL_B:
- poin= &(ma->b); break;
- case MA_SPEC_R:
- poin= &(ma->specr); break;
- case MA_SPEC_G:
- poin= &(ma->specg); break;
- case MA_SPEC_B:
- poin= &(ma->specb); break;
- case MA_MIR_R:
- poin= &(ma->mirr); break;
- case MA_MIR_G:
- poin= &(ma->mirg); break;
- case MA_MIR_B:
- poin= &(ma->mirb); break;
- case MA_REF:
- poin= &(ma->ref); break;
- case MA_ALPHA:
- poin= &(ma->alpha); break;
- case MA_EMIT:
- poin= &(ma->emit); break;
- case MA_AMB:
- poin= &(ma->amb); break;
- case MA_SPEC:
- poin= &(ma->spec); break;
- case MA_HARD:
- poin= &(ma->har); *type= IPO_SHORT; break;
- case MA_SPTR:
- poin= &(ma->spectra); break;
- case MA_IOR:
- poin= &(ma->ang); break;
- case MA_MODE:
- poin= &(ma->mode); *type= IPO_INT_BIT; break;
- case MA_HASIZE:
- poin= &(ma->hasize); break;
- case MA_TRANSLU:
- poin= &(ma->translucency); break;
- case MA_RAYM:
- poin= &(ma->ray_mirror); break;
- case MA_FRESMIR:
- poin= &(ma->fresnel_mir); break;
- case MA_FRESMIRI:
- poin= &(ma->fresnel_mir_i); break;
- case MA_FRESTRA:
- poin= &(ma->fresnel_tra); break;
- case MA_FRESTRAI:
- poin= &(ma->fresnel_tra_i); break;
- case MA_ADD:
- poin= &(ma->add); break;
- }
-
- if(poin==NULL) {
- mtex= 0;
- if(icu->adrcode & MA_MAP1) mtex= ma->mtex[0];
- else if(icu->adrcode & MA_MAP2) mtex= ma->mtex[1];
- else if(icu->adrcode & MA_MAP3) mtex= ma->mtex[2];
- else if(icu->adrcode & MA_MAP4) mtex= ma->mtex[3];
- else if(icu->adrcode & MA_MAP5) mtex= ma->mtex[4];
- else if(icu->adrcode & MA_MAP6) mtex= ma->mtex[5];
- else if(icu->adrcode & MA_MAP7) mtex= ma->mtex[6];
- else if(icu->adrcode & MA_MAP8) mtex= ma->mtex[7];
- else if(icu->adrcode & MA_MAP9) mtex= ma->mtex[8];
- else if(icu->adrcode & MA_MAP10) mtex= ma->mtex[9];
+ case OB_ROT_X:
+ poin= &(ob->rot[0]); *type= IPO_FLOAT_DEGR; break;
+ case OB_ROT_Y:
+ poin= &(ob->rot[1]); *type= IPO_FLOAT_DEGR; break;
+ case OB_ROT_Z:
+ poin= &(ob->rot[2]); *type= IPO_FLOAT_DEGR; break;
+ case OB_DROT_X:
+ poin= &(ob->drot[0]); *type= IPO_FLOAT_DEGR; break;
+ case OB_DROT_Y:
+ poin= &(ob->drot[1]); *type= IPO_FLOAT_DEGR; break;
+ case OB_DROT_Z:
+ poin= &(ob->drot[2]); *type= IPO_FLOAT_DEGR; break;
+
+ case OB_SIZE_X:
+ poin= &(ob->size[0]); break;
+ case OB_SIZE_Y:
+ poin= &(ob->size[1]); break;
+ case OB_SIZE_Z:
+ poin= &(ob->size[2]); break;
+ case OB_DSIZE_X:
+ poin= &(ob->dsize[0]); break;
+ case OB_DSIZE_Y:
+ poin= &(ob->dsize[1]); break;
+ case OB_DSIZE_Z:
+ poin= &(ob->dsize[2]); break;
- if(mtex) {
- poin= give_mtex_poin(mtex, icu->adrcode & (MA_MAP1-1) );
- }
- }
- }
- else if( GS(id->name)==ID_TE) {
- tex= (Tex *)id;
-
- if(tex) poin= give_tex_poin(tex, icu->adrcode, type);
- }
- else if( GS(id->name)==ID_SEQ) {
- seq= (Sequence *)id;
-
- switch(icu->adrcode) {
- case SEQ_FAC1:
- poin= &(seq->facf0); break;
- }
- }
- else if( GS(id->name)==ID_CU) {
-
- poin= &(icu->curval);
-
- }
- else if( GS(id->name)==ID_KE) {
- KeyBlock *kb= ((Key *)id)->block.first;
-
- for(; kb; kb= kb->next)
- if(kb->adrcode==icu->adrcode)
+ case OB_LAY:
+ poin= &(ob->lay); *type= IPO_INT_BIT; break;
+
+ case OB_COL_R:
+ poin= &(ob->col[0]); break;
+ case OB_COL_G:
+ poin= &(ob->col[1]); break;
+ case OB_COL_B:
+ poin= &(ob->col[2]); break;
+ case OB_COL_A:
+ poin= &(ob->col[3]); break;
+
+ case OB_PD_FSTR:
+ if (ob->pd) poin= &(ob->pd->f_strength);
+ break;
+ case OB_PD_FFALL:
+ if (ob->pd) poin= &(ob->pd->f_power);
+ break;
+ case OB_PD_SDAMP:
+ if (ob->pd) poin= &(ob->pd->pdef_damp);
+ break;
+ case OB_PD_RDAMP:
+ if (ob->pd) poin= &(ob->pd->pdef_rdamp);
+ break;
+ case OB_PD_PERM:
+ if (ob->pd) poin= &(ob->pd->pdef_perm);
+ break;
+ case OB_PD_FMAXD:
+ if (ob->pd) poin= &(ob->pd->maxdist);
break;
- if(kb)
- poin= &(kb->curval);
-
- }
- else if(GS(id->name)==ID_WO) {
-
- wo= (World *)id;
-
- switch(icu->adrcode) {
- case WO_HOR_R:
- poin= &(wo->horr); break;
- case WO_HOR_G:
- poin= &(wo->horg); break;
- case WO_HOR_B:
- poin= &(wo->horb); break;
- case WO_ZEN_R:
- poin= &(wo->zenr); break;
- case WO_ZEN_G:
- poin= &(wo->zeng); break;
- case WO_ZEN_B:
- poin= &(wo->zenb); break;
-
- case WO_EXPOS:
- poin= &(wo->exposure); break;
-
- case WO_MISI:
- poin= &(wo->misi); break;
- case WO_MISTDI:
- poin= &(wo->mistdist); break;
- case WO_MISTSTA:
- poin= &(wo->miststa); break;
- case WO_MISTHI:
- poin= &(wo->misthi); break;
-
- case WO_STAR_R:
- poin= &(wo->starr); break;
- case WO_STAR_G:
- poin= &(wo->starg); break;
- case WO_STAR_B:
- poin= &(wo->starb); break;
-
- case WO_STARDIST:
- poin= &(wo->stardist); break;
- case WO_STARSIZE:
- poin= &(wo->starsize); break;
- }
-
- if(poin==NULL) {
- mtex= 0;
- if(icu->adrcode & MA_MAP1) mtex= wo->mtex[0];
- else if(icu->adrcode & MA_MAP2) mtex= wo->mtex[1];
- else if(icu->adrcode & MA_MAP3) mtex= wo->mtex[2];
- else if(icu->adrcode & MA_MAP4) mtex= wo->mtex[3];
- else if(icu->adrcode & MA_MAP5) mtex= wo->mtex[4];
- else if(icu->adrcode & MA_MAP6) mtex= wo->mtex[5];
- else if(icu->adrcode & MA_MAP7) mtex= wo->mtex[6];
- else if(icu->adrcode & MA_MAP8) mtex= wo->mtex[7];
- else if(icu->adrcode & MA_MAP9) mtex= wo->mtex[8];
- else if(icu->adrcode & MA_MAP10) mtex= wo->mtex[9];
-
- if(mtex) {
- poin= give_mtex_poin(mtex, icu->adrcode & (MA_MAP1-1) );
- }
- }
- }
- else if( GS(id->name)==ID_LA) {
-
- la= (Lamp *)id;
-
- switch(icu->adrcode) {
- case LA_ENERGY:
- poin= &(la->energy); break;
- case LA_COL_R:
- poin= &(la->r); break;
- case LA_COL_G:
- poin= &(la->g); break;
- case LA_COL_B:
- poin= &(la->b); break;
- case LA_DIST:
- poin= &(la->dist); break;
- case LA_SPOTSI:
- poin= &(la->spotsize); break;
- case LA_SPOTBL:
- poin= &(la->spotblend); break;
- case LA_QUAD1:
- poin= &(la->att1); break;
- case LA_QUAD2:
- poin= &(la->att2); break;
- case LA_HALOINT:
- poin= &(la->haint); break;
- }
-
- if(poin==NULL) {
- mtex= 0;
- if(icu->adrcode & MA_MAP1) mtex= la->mtex[0];
- else if(icu->adrcode & MA_MAP2) mtex= la->mtex[1];
- else if(icu->adrcode & MA_MAP3) mtex= la->mtex[2];
- else if(icu->adrcode & MA_MAP4) mtex= la->mtex[3];
- else if(icu->adrcode & MA_MAP5) mtex= la->mtex[4];
- else if(icu->adrcode & MA_MAP6) mtex= la->mtex[5];
- else if(icu->adrcode & MA_MAP7) mtex= la->mtex[6];
- else if(icu->adrcode & MA_MAP8) mtex= la->mtex[7];
- else if(icu->adrcode & MA_MAP9) mtex= la->mtex[8];
- else if(icu->adrcode & MA_MAP10) mtex= la->mtex[9];
-
- if(mtex) {
- poin= give_mtex_poin(mtex, icu->adrcode & (MA_MAP1-1) );
}
}
- }
- else if(GS(id->name)==ID_CA) {
- Camera *ca= (Camera *)id;
-
- /* yafray: aperture & focal distance params */
- switch(icu->adrcode) {
- case CAM_LENS:
- if(ca->type==CAM_ORTHO)
- poin= &(ca->ortho_scale);
- else
- poin= &(ca->lens);
break;
- case CAM_STA:
- poin= &(ca->clipsta); break;
- case CAM_END:
- poin= &(ca->clipend); break;
- case CAM_YF_APERT:
- poin= &(ca->YF_aperture); break;
- case CAM_YF_FDIST:
- poin= &(ca->YF_dofdist); break;
- case CAM_SHIFT_X:
- poin= &(ca->shiftx); break;
- case CAM_SHIFT_Y:
- poin= &(ca->shifty); break;
- }
- }
- else if(GS(id->name)==ID_SO) {
- bSound *snd= (bSound *)id;
-
- switch(icu->adrcode) {
- case SND_VOLUME:
- poin= &(snd->volume); break;
- case SND_PITCH:
- poin= &(snd->pitch); break;
- case SND_PANNING:
- poin= &(snd->panning); break;
- case SND_ATTEN:
- poin= &(snd->attenuation); break;
- }
- }
- else if( GS(id->name)==ID_PA) {
-
- part= (ParticleSettings *)id;
-
- switch(icu->adrcode) {
- case PART_EMIT_FREQ:
- case PART_EMIT_LIFE:
- case PART_EMIT_VEL:
- case PART_EMIT_AVE:
- case PART_EMIT_SIZE:
- poin= NULL; break;
- case PART_CLUMP:
- poin= &(part->clumpfac); break;
- case PART_AVE:
- poin= &(part->avefac); break;
- case PART_SIZE:
- poin= &(part->size); break;
- case PART_DRAG:
- poin= &(part->dragfac); break;
- case PART_BROWN:
- poin= &(part->brownfac); break;
- case PART_DAMP:
- poin= &(part->dampfac); break;
- case PART_LENGTH:
- poin= &(part->length); break;
- case PART_GRAV_X:
- poin= &(part->acc[0]); break;
- case PART_GRAV_Y:
- poin= &(part->acc[1]); break;
- case PART_GRAV_Z:
- poin= &(part->acc[2]); break;
- case PART_KINK_AMP:
- poin= &(part->kink_amp); break;
- case PART_KINK_FREQ:
- poin= &(part->kink_freq); break;
- case PART_KINK_SHAPE:
- poin= &(part->kink_shape); break;
- case PART_BB_TILT:
- poin= &(part->bb_tilt); break;
- }
- }
-
- return poin;
-}
-
-void set_icu_vars(IpoCurve *icu)
-{
- /* defaults. 0.0 for y-extents makes these ignored */
- icu->ymin= icu->ymax= 0.0;
- icu->ipo= IPO_BEZ;
-
- if(icu->blocktype==ID_OB) {
-
- if(icu->adrcode==OB_LAY) {
- icu->ipo= IPO_CONST;
- icu->vartype= IPO_BITS;
- }
-
- }
- else if(icu->blocktype==ID_MA) {
-
- if(icu->adrcode < MA_MAP1) {
- switch(icu->adrcode) {
- case MA_HASIZE:
- icu->ymax= 10000.0; break;
- case MA_HARD:
- icu->ymax= 511.0; break;
+ case ID_MA: /* material channels ----------------------------- */
+ {
+ Material *ma= (Material *)id;
+
+ switch (icu->adrcode) {
+ case MA_COL_R:
+ poin= &(ma->r); break;
+ case MA_COL_G:
+ poin= &(ma->g); break;
+ case MA_COL_B:
+ poin= &(ma->b); break;
+ case MA_SPEC_R:
+ poin= &(ma->specr); break;
+ case MA_SPEC_G:
+ poin= &(ma->specg); break;
+ case MA_SPEC_B:
+ poin= &(ma->specb); break;
+ case MA_MIR_R:
+ poin= &(ma->mirr); break;
+ case MA_MIR_G:
+ poin= &(ma->mirg); break;
+ case MA_MIR_B:
+ poin= &(ma->mirb); break;
+ case MA_REF:
+ poin= &(ma->ref); break;
+ case MA_ALPHA:
+ poin= &(ma->alpha); break;
+ case MA_EMIT:
+ poin= &(ma->emit); break;
+ case MA_AMB:
+ poin= &(ma->amb); break;
case MA_SPEC:
- icu->ymax= 2.0; break;
+ poin= &(ma->spec); break;
+ case MA_HARD:
+ poin= &(ma->har); *type= IPO_SHORT; break;
+ case MA_SPTR:
+ poin= &(ma->spectra); break;
+ case MA_IOR:
+ poin= &(ma->ang); break;
case MA_MODE:
- icu->ipo= IPO_CONST;
- icu->vartype= IPO_BITS; break;
- case MA_RAYM:
- icu->ymax= 1.0; break;
+ poin= &(ma->mode); *type= IPO_INT_BIT; break; // evil... dumping bitflags directly to user!
+ case MA_HASIZE:
+ poin= &(ma->hasize); break;
case MA_TRANSLU:
- icu->ymax= 1.0; break;
- case MA_IOR:
- icu->ymin= 1.0;
- icu->ymax= 3.0; break;
+ poin= &(ma->translucency); break;
+ case MA_RAYM:
+ poin= &(ma->ray_mirror); break;
case MA_FRESMIR:
- icu->ymax= 5.0; break;
+ poin= &(ma->fresnel_mir); break;
case MA_FRESMIRI:
- icu->ymin= 1.0;
- icu->ymax= 5.0; break;
+ poin= &(ma->fresnel_mir_i); break;
case MA_FRESTRA:
- icu->ymax= 5.0; break;
+ poin= &(ma->fresnel_tra); break;
case MA_FRESTRAI:
- icu->ymin= 1.0;
- icu->ymax= 5.0; break;
+ poin= &(ma->fresnel_tra_i); break;
case MA_ADD:
- icu->ymax= 1.0; break;
- default:
- icu->ymax= 1.0; break;
+ poin= &(ma->add); break;
+ }
+
+ if (poin == NULL) {
+ if (icu->adrcode & MA_MAP1) mtex= ma->mtex[0];
+ else if (icu->adrcode & MA_MAP2) mtex= ma->mtex[1];
+ else if (icu->adrcode & MA_MAP3) mtex= ma->mtex[2];
+ else if (icu->adrcode & MA_MAP4) mtex= ma->mtex[3];
+ else if (icu->adrcode & MA_MAP5) mtex= ma->mtex[4];
+ else if (icu->adrcode & MA_MAP6) mtex= ma->mtex[5];
+ else if (icu->adrcode & MA_MAP7) mtex= ma->mtex[6];
+ else if (icu->adrcode & MA_MAP8) mtex= ma->mtex[7];
+ else if (icu->adrcode & MA_MAP9) mtex= ma->mtex[8];
+ else if (icu->adrcode & MA_MAP10) mtex= ma->mtex[9];
+ else if (icu->adrcode & MA_MAP12) mtex= ma->mtex[11];
+ else if (icu->adrcode & MA_MAP11) mtex= ma->mtex[10];
+ else if (icu->adrcode & MA_MAP13) mtex= ma->mtex[12];
+ else if (icu->adrcode & MA_MAP14) mtex= ma->mtex[13];
+ else if (icu->adrcode & MA_MAP15) mtex= ma->mtex[14];
+ else if (icu->adrcode & MA_MAP16) mtex= ma->mtex[15];
+ else if (icu->adrcode & MA_MAP17) mtex= ma->mtex[16];
+ else if (icu->adrcode & MA_MAP18) mtex= ma->mtex[17];
+
+ if (mtex)
+ poin= give_mtex_poin(mtex, (icu->adrcode & (MA_MAP1-1)));
}
}
- else {
- switch(icu->adrcode & (MA_MAP1-1)) {
- case MAP_OFS_X:
- case MAP_OFS_Y:
- case MAP_OFS_Z:
- case MAP_SIZE_X:
- case MAP_SIZE_Y:
- case MAP_SIZE_Z:
- icu->ymax= 1000.0;
- icu->ymin= -1000.0;
+ break;
+ case ID_TE: /* texture channels ----------------------------- */
+ {
+ Tex *tex= (Tex *)id;
- break;
- case MAP_R:
- case MAP_G:
- case MAP_B:
- case MAP_DVAR:
- case MAP_COLF:
- case MAP_VARF:
- case MAP_DISP:
- icu->ymax= 1.0;
- break;
- case MAP_NORF:
- icu->ymax= 25.0;
- break;
+ if (tex)
+ poin= give_tex_poin(tex, icu->adrcode, type);
+ }
+ break;
+ case ID_SEQ: /* sequence channels ----------------------------- */
+ {
+ Sequence *seq= (Sequence *)id;
+
+ switch (icu->adrcode) {
+ case SEQ_FAC1:
+ poin= &(seq->facf0); break;
}
}
- }
- else if(icu->blocktype==ID_TE) {
- switch(icu->adrcode & (MA_MAP1-1)) {
- case TE_NSIZE:
- icu->ymin= 0.0001;
- icu->ymax= 2.0; break;
- case TE_NDEPTH:
- icu->vartype= IPO_SHORT;
- icu->ipo= IPO_CONST;
- icu->ymax= 6.0; break;
- case TE_NTYPE:
- icu->vartype= IPO_SHORT;
- icu->ipo= IPO_CONST;
- icu->ymax= 1.0; break;
- case TE_TURB:
- icu->ymax= 200.0; break;
- case TE_VNW1:
- case TE_VNW2:
- case TE_VNW3:
- case TE_VNW4:
- icu->ymax= 2.0;
- icu->ymin= -2.0; break;
- case TE_VNMEXP:
- icu->ymax= 10.0;
- icu->ymin= 0.01; break;
- case TE_VN_DISTM:
- icu->vartype= IPO_SHORT;
- icu->ipo= IPO_CONST;
- icu->ymax= 6.0; break;
- case TE_VN_COLT:
- icu->vartype= IPO_SHORT;
- icu->ipo= IPO_CONST;
- icu->ymax= 3.0; break;
- case TE_ISCA:
- icu->ymax= 10.0;
- icu->ymin= 0.01; break;
- case TE_DISTA:
- icu->ymax= 10.0; break;
- case TE_MG_TYP:
- icu->vartype= IPO_SHORT;
- icu->ipo= IPO_CONST;
- icu->ymax= 6.0; break;
- case TE_MGH:
- icu->ymin= 0.0001;
- icu->ymax= 2.0; break;
- case TE_MG_LAC:
- case TE_MG_OFF:
- case TE_MG_GAIN:
- icu->ymax= 6.0; break;
- case TE_MG_OCT:
- icu->ymax= 8.0; break;
- case TE_N_BAS1:
- case TE_N_BAS2:
- icu->vartype= IPO_SHORT;
- icu->ipo= IPO_CONST;
- icu->ymax= 8.0; break;
- case TE_COL_R:
- icu->ymax= 0.0; break;
- case TE_COL_G:
- icu->ymax= 2.0; break;
- case TE_COL_B:
- icu->ymax= 2.0; break;
- case TE_BRIGHT:
- icu->ymax= 2.0; break;
- case TE_CONTRA:
- icu->ymax= 5.0; break;
-
+ break;
+ case ID_CU: /* curve channels ----------------------------- */
+ {
+ poin= &(icu->curval);
}
- }
- else if(icu->blocktype==ID_SEQ) {
-
- icu->ymax= 1.0;
-
- }
- else if(icu->blocktype==ID_CU) {
-
- icu->ymax= 1.0;
-
- }
- else if(icu->blocktype==ID_WO) {
-
- if(icu->adrcode < MA_MAP1) {
- switch(icu->adrcode) {
+ break;
+ case ID_KE: /* shapekey channels ----------------------------- */
+ {
+ Key *key= (Key *)id;
+ KeyBlock *kb;
+
+ for(kb= key->block.first; kb; kb= kb->next) {
+ if (kb->adrcode == icu->adrcode)
+ break;
+ }
+
+ if (kb)
+ poin= &(kb->curval);
+ }
+ break;
+ case ID_WO: /* world channels ----------------------------- */
+ {
+ World *wo= (World *)id;
+
+ switch (icu->adrcode) {
+ case WO_HOR_R:
+ poin= &(wo->horr); break;
+ case WO_HOR_G:
+ poin= &(wo->horg); break;
+ case WO_HOR_B:
+ poin= &(wo->horb); break;
+ case WO_ZEN_R:
+ poin= &(wo->zenr); break;
+ case WO_ZEN_G:
+ poin= &(wo->zeng); break;
+ case WO_ZEN_B:
+ poin= &(wo->zenb); break;
+
case WO_EXPOS:
- icu->ymax= 5.0; break;
+ poin= &(wo->exposure); break;
+
+ case WO_MISI:
+ poin= &(wo->misi); break;
case WO_MISTDI:
+ poin= &(wo->mistdist); break;
case WO_MISTSTA:
+ poin= &(wo->miststa); break;
case WO_MISTHI:
+ poin= &(wo->misthi); break;
+
+ case WO_STAR_R:
+ poin= &(wo->starr); break;
+ case WO_STAR_G:
+ poin= &(wo->starg); break;
+ case WO_STAR_B:
+ poin= &(wo->starb); break;
+
case WO_STARDIST:
+ poin= &(wo->stardist); break;
case WO_STARSIZE:
- break;
-
- default:
- icu->ymax= 1.0;
- break;
+ poin= &(wo->starsize); break;
}
- }
- else {
- switch(icu->adrcode & (MA_MAP1-1)) {
- case MAP_OFS_X:
- case MAP_OFS_Y:
- case MAP_OFS_Z:
- case MAP_SIZE_X:
- case MAP_SIZE_Y:
- case MAP_SIZE_Z:
- icu->ymax= 100.0;
- icu->ymin= -100.0;
- break;
- case MAP_R:
- case MAP_G:
- case MAP_B:
- case MAP_DVAR:
- case MAP_COLF:
- case MAP_NORF:
- case MAP_VARF:
- case MAP_DISP:
- icu->ymax= 1.0;
+ if (poin == NULL) {
+ if (icu->adrcode & MA_MAP1) mtex= wo->mtex[0];
+ else if (icu->adrcode & MA_MAP2) mtex= wo->mtex[1];
+ else if (icu->adrcode & MA_MAP3) mtex= wo->mtex[2];
+ else if (icu->adrcode & MA_MAP4) mtex= wo->mtex[3];
+ else if (icu->adrcode & MA_MAP5) mtex= wo->mtex[4];
+ else if (icu->adrcode & MA_MAP6) mtex= wo->mtex[5];
+ else if (icu->adrcode & MA_MAP7) mtex= wo->mtex[6];
+ else if (icu->adrcode & MA_MAP8) mtex= wo->mtex[7];
+ else if (icu->adrcode & MA_MAP9) mtex= wo->mtex[8];
+ else if (icu->adrcode & MA_MAP10) mtex= wo->mtex[9];
+ else if (icu->adrcode & MA_MAP11) mtex= wo->mtex[10];
+ else if (icu->adrcode & MA_MAP12) mtex= wo->mtex[11];
+ else if (icu->adrcode & MA_MAP13) mtex= wo->mtex[12];
+ else if (icu->adrcode & MA_MAP14) mtex= wo->mtex[13];
+ else if (icu->adrcode & MA_MAP15) mtex= wo->mtex[14];
+ else if (icu->adrcode & MA_MAP16) mtex= wo->mtex[15];
+ else if (icu->adrcode & MA_MAP17) mtex= wo->mtex[16];
+ else if (icu->adrcode & MA_MAP18) mtex= wo->mtex[17];
+
+ if (mtex)
+ poin= give_mtex_poin(mtex, (icu->adrcode & (MA_MAP1-1)));
}
}
- }
- else if(icu->blocktype==ID_LA) {
- if(icu->adrcode < MA_MAP1) {
- switch(icu->adrcode) {
+ break;
+ case ID_LA: /* lamp channels ----------------------------- */
+ {
+ Lamp *la= (Lamp *)id;
+
+ switch (icu->adrcode) {
case LA_ENERGY:
- case LA_DIST:
- break;
-
+ poin= &(la->energy); break;
case LA_COL_R:
+ poin= &(la->r); break;
case LA_COL_G:
+ poin= &(la->g); break;
case LA_COL_B:
+ poin= &(la->b); break;
+ case LA_DIST:
+ poin= &(la->dist); break;
+ case LA_SPOTSI:
+ poin= &(la->spotsize); break;
case LA_SPOTBL:
+ poin= &(la->spotblend); break;
case LA_QUAD1:
+ poin= &(la->att1); break;
case LA_QUAD2:
- icu->ymax= 1.0; break;
- case LA_SPOTSI:
- icu->ymax= 180.0; break;
+ poin= &(la->att2); break;
case LA_HALOINT:
- icu->ymax= 5.0; break;
+ poin= &(la->haint); break;
+ }
+
+ if (poin == NULL) {
+ if (icu->adrcode & MA_MAP1) mtex= la->mtex[0];
+ else if (icu->adrcode & MA_MAP2) mtex= la->mtex[1];
+ else if (icu->adrcode & MA_MAP3) mtex= la->mtex[2];
+ else if (icu->adrcode & MA_MAP4) mtex= la->mtex[3];
+ else if (icu->adrcode & MA_MAP5) mtex= la->mtex[4];
+ else if (icu->adrcode & MA_MAP6) mtex= la->mtex[5];
+ else if (icu->adrcode & MA_MAP7) mtex= la->mtex[6];
+ else if (icu->adrcode & MA_MAP8) mtex= la->mtex[7];
+ else if (icu->adrcode & MA_MAP9) mtex= la->mtex[8];
+ else if (icu->adrcode & MA_MAP10) mtex= la->mtex[9];
+ else if (icu->adrcode & MA_MAP11) mtex= la->mtex[10];
+ else if (icu->adrcode & MA_MAP12) mtex= la->mtex[11];
+ else if (icu->adrcode & MA_MAP13) mtex= la->mtex[12];
+ else if (icu->adrcode & MA_MAP14) mtex= la->mtex[13];
+ else if (icu->adrcode & MA_MAP15) mtex= la->mtex[14];
+ else if (icu->adrcode & MA_MAP16) mtex= la->mtex[15];
+ else if (icu->adrcode & MA_MAP17) mtex= la->mtex[16];
+ else if (icu->adrcode & MA_MAP18) mtex= la->mtex[17];
+
+ if (mtex)
+ poin= give_mtex_poin(mtex, (icu->adrcode & (MA_MAP1-1)));
}
}
- else {
- switch(icu->adrcode & (MA_MAP1-1)) {
- case MAP_OFS_X:
- case MAP_OFS_Y:
- case MAP_OFS_Z:
- case MAP_SIZE_X:
- case MAP_SIZE_Y:
- case MAP_SIZE_Z:
- icu->ymax= 100.0;
- icu->ymin= -100.0;
+ break;
+ case ID_CA: /* camera channels ----------------------------- */
+ {
+ Camera *ca= (Camera *)id;
+
+ switch (icu->adrcode) {
+ case CAM_LENS:
+ if (ca->type == CAM_ORTHO)
+ poin= &(ca->ortho_scale);
+ else
+ poin= &(ca->lens);
break;
- case MAP_R:
- case MAP_G:
- case MAP_B:
- case MAP_DVAR:
- case MAP_COLF:
- case MAP_NORF:
- case MAP_VARF:
- case MAP_DISP:
- icu->ymax= 1.0;
+ case CAM_STA:
+ poin= &(ca->clipsta); break;
+ case CAM_END:
+ poin= &(ca->clipend); break;
+
+ case CAM_YF_APERT:
+ poin= &(ca->YF_aperture); break;
+ case CAM_YF_FDIST:
+ poin= &(ca->YF_dofdist); break;
+
+ case CAM_SHIFT_X:
+ poin= &(ca->shiftx); break;
+ case CAM_SHIFT_Y:
+ poin= &(ca->shifty); break;
}
}
- }
- else if(icu->blocktype==ID_CA) {
-
- /* yafray: aperture & focal distance params */
- switch(icu->adrcode) {
- case CAM_LENS:
- icu->ymin= 5.0;
- icu->ymax= 1000.0;
- break;
- case CAM_STA:
- icu->ymin= 0.001f;
- break;
- case CAM_END:
- icu->ymin= 0.1f;
- break;
- case CAM_YF_APERT:
- icu->ymin = 0.0;
- icu->ymax = 2.0;
- break;
- case CAM_YF_FDIST:
- icu->ymin = 0.0;
- icu->ymax = 5000.0;
break;
+ case ID_SO: /* sound channels ----------------------------- */
+ {
+ bSound *snd= (bSound *)id;
- case CAM_SHIFT_X:
- case CAM_SHIFT_Y:
- icu->ymin= -2.0f;
- icu->ymax= 2.0f;
- break;
+ switch (icu->adrcode) {
+ case SND_VOLUME:
+ poin= &(snd->volume); break;
+ case SND_PITCH:
+ poin= &(snd->pitch); break;
+ case SND_PANNING:
+ poin= &(snd->panning); break;
+ case SND_ATTEN:
+ poin= &(snd->attenuation); break;
+ }
}
- }
- else if(icu->blocktype==ID_SO) {
-
- switch(icu->adrcode) {
- case SND_VOLUME:
- icu->ymin= 0.0;
- icu->ymax= 1.0;
- break;
- case SND_PITCH:
- icu->ymin= -12.0;
- icu->ymin= 12.0;
- break;
- case SND_PANNING:
- icu->ymin= 0.0;
- icu->ymax= 1.0;
- break;
- case SND_ATTEN:
- icu->ymin= 0.0;
- icu->ymin= 1.0;
break;
+ case ID_PA: /* particle channels ----------------------------- */
+ {
+ ParticleSettings *part= (ParticleSettings *)id;
+
+ switch (icu->adrcode) {
+ case PART_EMIT_FREQ:
+ case PART_EMIT_LIFE:
+ case PART_EMIT_VEL:
+ case PART_EMIT_AVE:
+ case PART_EMIT_SIZE:
+ poin= NULL;
+ break;
+
+ case PART_CLUMP:
+ poin= &(part->clumpfac); break;
+ case PART_AVE:
+ poin= &(part->avefac); break;
+ case PART_SIZE:
+ poin= &(part->size); break;
+ case PART_DRAG:
+ poin= &(part->dragfac); break;
+ case PART_BROWN:
+ poin= &(part->brownfac); break;
+ case PART_DAMP:
+ poin= &(part->dampfac); break;
+ case PART_LENGTH:
+ poin= &(part->length); break;
+ case PART_GRAV_X:
+ poin= &(part->acc[0]); break;
+ case PART_GRAV_Y:
+ poin= &(part->acc[1]); break;
+ case PART_GRAV_Z:
+ poin= &(part->acc[2]); break;
+ case PART_KINK_AMP:
+ poin= &(part->kink_amp); break;
+ case PART_KINK_FREQ:
+ poin= &(part->kink_freq); break;
+ case PART_KINK_SHAPE:
+ poin= &(part->kink_shape); break;
+ case PART_BB_TILT:
+ poin= &(part->bb_tilt); break;
+
+ case PART_PD_FSTR:
+ if (part->pd) poin= &(part->pd->f_strength);
+ break;
+ case PART_PD_FFALL:
+ if (part->pd) poin= &(part->pd->f_power);
+ break;
+ case PART_PD_FMAXD:
+ if (part->pd) poin= &(part->pd->maxdist);
+ break;
+ case PART_PD2_FSTR:
+ if (part->pd2) poin= &(part->pd2->f_strength);
+ break;
+ case PART_PD2_FFALL:
+ if (part->pd2) poin= &(part->pd2->f_power);
+ break;
+ case PART_PD2_FMAXD:
+ if (part->pd2) poin= &(part->pd2->maxdist);
+ break;
+ }
}
- }
- else if(icu->blocktype==ID_PA){
-
- switch(icu->adrcode) {
- case PART_EMIT_LIFE:
- case PART_SIZE:
- case PART_KINK_FREQ:
- case PART_EMIT_VEL:
- case PART_EMIT_AVE:
- case PART_EMIT_SIZE:
- icu->ymin= 0.0;
break;
- case PART_CLUMP:
- case PART_DRAG:
- case PART_DAMP:
- case PART_LENGTH:
- icu->ymin= 0.0;
- icu->ymax= 1.0;
- break;
- case PART_KINK_SHAPE:
- icu->ymin= -0.999;
- icu->ymax= 0.999;
- }
- }
- else if(icu->blocktype==ID_CO) {
- icu->ymin= 0.0;
- icu->ymax= 1.0f;
}
-
- /* by default, slider limits will be icu->ymin and icu->ymax */
- icu->slide_min= icu->ymin;
- icu->slide_max= icu->ymax;
-}
-/* not for actions or constraints! */
-void execute_ipo(ID *id, Ipo *ipo)
-{
- IpoCurve *icu;
- void *poin;
- int type;
-
- if(ipo==NULL) return;
-
- for(icu= ipo->curve.first; icu; icu= icu->next) {
- poin= get_ipo_poin(id, icu, &type);
- if(poin) write_ipo_poin(poin, type, icu->curval);
- }
+ /* return pointer */
+ return poin;
}
-void *get_pchan_ipo_poin(bPoseChannel *pchan, int adrcode)
+/* --------------------- IPO-Curve Limits ----------------------------- */
+
+/* set limits for IPO-curve
+ * Note: must be synced with UI and PyAPI
+ */
+void set_icu_vars (IpoCurve *icu)
{
- void *poin= NULL;
+ /* defaults. 0.0 for y-extents makes these ignored */
+ icu->ymin= icu->ymax= 0.0;
+ icu->ipo= IPO_BEZ;
- switch (adrcode) {
- case AC_QUAT_W:
- poin= &(pchan->quat[0]);
- pchan->flag |= POSE_ROT;
+ switch (icu->blocktype) {
+ case ID_OB: /* object channels ----------------------------- */
+ {
+ if (icu->adrcode == OB_LAY) {
+ icu->ipo= IPO_CONST;
+ icu->vartype= IPO_BITS;
+ }
+ }
break;
- case AC_QUAT_X:
- poin= &(pchan->quat[1]);
- pchan->flag |= POSE_ROT;
+ case ID_MA: /* material channels ----------------------------- */
+ {
+ if (icu->adrcode < MA_MAP1) {
+ switch (icu->adrcode) {
+ case MA_HASIZE:
+ icu->ymax= 10000.0; break;
+ case MA_HARD:
+ icu->ymax= 511.0; break;
+ case MA_SPEC:
+ icu->ymax= 2.0; break;
+ case MA_MODE:
+ icu->ipo= IPO_CONST;
+ icu->vartype= IPO_BITS; break;
+ case MA_RAYM:
+ icu->ymax= 1.0; break;
+ case MA_TRANSLU:
+ icu->ymax= 1.0; break;
+ case MA_IOR:
+ icu->ymin= 1.0;
+ icu->ymax= 3.0; break;
+ case MA_FRESMIR:
+ icu->ymax= 5.0; break;
+ case MA_FRESMIRI:
+ icu->ymin= 1.0;
+ icu->ymax= 5.0; break;
+ case MA_FRESTRA:
+ icu->ymax= 5.0; break;
+ case MA_FRESTRAI:
+ icu->ymin= 1.0;
+ icu->ymax= 5.0; break;
+ case MA_ADD:
+ icu->ymax= 1.0; break;
+ case MA_EMIT:
+ icu->ymax= 2.0; break;
+ default:
+ icu->ymax= 1.0; break;
+ }
+ }
+ else {
+ switch (icu->adrcode & (MA_MAP1-1)) {
+ case MAP_OFS_X:
+ case MAP_OFS_Y:
+ case MAP_OFS_Z:
+ case MAP_SIZE_X:
+ case MAP_SIZE_Y:
+ case MAP_SIZE_Z:
+ icu->ymax= 1000.0;
+ icu->ymin= -1000.0;
+ break;
+ case MAP_R:
+ case MAP_G:
+ case MAP_B:
+ case MAP_DVAR:
+ case MAP_COLF:
+ case MAP_VARF:
+ case MAP_DISP:
+ icu->ymax= 1.0;
+ break;
+ case MAP_NORF:
+ icu->ymax= 25.0;
+ break;
+ }
+ }
+ }
break;
- case AC_QUAT_Y:
- poin= &(pchan->quat[2]);
- pchan->flag |= POSE_ROT;
+ case ID_TE: /* texture channels ----------------------------- */
+ {
+ switch (icu->adrcode & (MA_MAP1-1)) {
+ case TE_NSIZE:
+ icu->ymin= 0.0001f;
+ icu->ymax= 2.0f;
+ break;
+ case TE_NDEPTH:
+ icu->vartype= IPO_SHORT;
+ icu->ipo= IPO_CONST;
+ icu->ymax= 6.0f;
+ break;
+ case TE_NTYPE:
+ icu->vartype= IPO_SHORT;
+ icu->ipo= IPO_CONST;
+ icu->ymax= 1.0f;
+ break;
+ case TE_TURB:
+ icu->ymax= 200.0f;
+ break;
+ case TE_VNW1:
+ case TE_VNW2:
+ case TE_VNW3:
+ case TE_VNW4:
+ icu->ymax= 2.0f;
+ icu->ymin= -2.0f;
+ break;
+ case TE_VNMEXP:
+ icu->ymax= 10.0f;
+ icu->ymin= 0.01f;
+ break;
+ case TE_VN_DISTM:
+ icu->vartype= IPO_SHORT;
+ icu->ipo= IPO_CONST;
+ icu->ymax= 6.0f;
+ break;
+ case TE_VN_COLT:
+ icu->vartype= IPO_SHORT;
+ icu->ipo= IPO_CONST;
+ icu->ymax= 3.0f;
+ break;
+ case TE_ISCA:
+ icu->ymax= 10.0f;
+ icu->ymin= 0.01f;
+ break;
+ case TE_DISTA:
+ icu->ymax= 10.0f;
+ break;
+ case TE_MG_TYP:
+ icu->vartype= IPO_SHORT;
+ icu->ipo= IPO_CONST;
+ icu->ymax= 6.0f;
+ break;
+ case TE_MGH:
+ icu->ymin= 0.0001f;
+ icu->ymax= 2.0f;
+ break;
+ case TE_MG_LAC:
+ case TE_MG_OFF:
+ case TE_MG_GAIN:
+ icu->ymax= 6.0f; break;
+ case TE_MG_OCT:
+ icu->ymax= 8.0f; break;
+ case TE_N_BAS1:
+ case TE_N_BAS2:
+ icu->vartype= IPO_SHORT;
+ icu->ipo= IPO_CONST;
+ icu->ymax= 8.0f;
+ break;
+ case TE_COL_R:
+ icu->ymax= 0.0f; break;
+ case TE_COL_G:
+ icu->ymax= 2.0f; break;
+ case TE_COL_B:
+ icu->ymax= 2.0f; break;
+ case TE_BRIGHT:
+ icu->ymax= 2.0f; break;
+ case TE_CONTRA:
+ icu->ymax= 5.0f; break;
+ }
+ }
break;
- case AC_QUAT_Z:
- poin= &(pchan->quat[3]);
- pchan->flag |= POSE_ROT;
+ case ID_SEQ: /* sequence channels ----------------------------- */
+ {
+ icu->ymax= 1.0f;
+ }
break;
- case AC_LOC_X:
- poin= &(pchan->loc[0]);
- pchan->flag |= POSE_LOC;
+ case ID_CU: /* curve channels ----------------------------- */
+ {
+ icu->ymax= 1.0f;
+ }
break;
- case AC_LOC_Y:
- poin= &(pchan->loc[1]);
- pchan->flag |= POSE_LOC;
+ case ID_WO: /* world channels ----------------------------- */
+ {
+ if (icu->adrcode < MA_MAP1) {
+ switch (icu->adrcode) {
+ case WO_EXPOS:
+ icu->ymax= 5.0f; break;
+
+ case WO_MISTDI:
+ case WO_MISTSTA:
+ case WO_MISTHI:
+ case WO_STARDIST:
+ case WO_STARSIZE:
+ break;
+
+ default:
+ icu->ymax= 1.0f;
+ break;
+ }
+ }
+ else {
+ switch (icu->adrcode & (MA_MAP1-1)) {
+ case MAP_OFS_X:
+ case MAP_OFS_Y:
+ case MAP_OFS_Z:
+ case MAP_SIZE_X:
+ case MAP_SIZE_Y:
+ case MAP_SIZE_Z:
+ icu->ymax= 100.0f;
+ icu->ymin= -100.0f;
+ break;
+ case MAP_R:
+ case MAP_G:
+ case MAP_B:
+ case MAP_DVAR:
+ case MAP_COLF:
+ case MAP_NORF:
+ case MAP_VARF:
+ case MAP_DISP:
+ icu->ymax= 1.0f;
+ }
+ }
+ }
break;
- case AC_LOC_Z:
- poin= &(pchan->loc[2]);
- pchan->flag |= POSE_LOC;
- break;
- case AC_SIZE_X:
- poin= &(pchan->size[0]);
- pchan->flag |= POSE_SIZE;
+ case ID_LA: /* lamp channels ----------------------------- */
+ {
+ if (icu->adrcode < MA_MAP1) {
+ switch (icu->adrcode) {
+ case LA_ENERGY:
+ case LA_DIST:
+ break;
+
+ case LA_COL_R:
+ case LA_COL_G:
+ case LA_COL_B:
+ case LA_SPOTBL:
+ case LA_QUAD1:
+ case LA_QUAD2:
+ icu->ymax= 1.0f; break;
+
+ case LA_SPOTSI:
+ icu->ymax= 180.0f; break;
+
+ case LA_HALOINT:
+ icu->ymax= 5.0f; break;
+ }
+ }
+ else {
+ switch (icu->adrcode & (MA_MAP1-1)) {
+ case MAP_OFS_X:
+ case MAP_OFS_Y:
+ case MAP_OFS_Z:
+ case MAP_SIZE_X:
+ case MAP_SIZE_Y:
+ case MAP_SIZE_Z:
+ icu->ymax= 100.0f;
+ icu->ymin= -100.0f;
+ break;
+ case MAP_R:
+ case MAP_G:
+ case MAP_B:
+ case MAP_DVAR:
+ case MAP_COLF:
+ case MAP_NORF:
+ case MAP_VARF:
+ case MAP_DISP:
+ icu->ymax= 1.0f;
+ }
+ }
+ }
break;
- case AC_SIZE_Y:
- poin= &(pchan->size[1]);
- pchan->flag |= POSE_SIZE;
+ case ID_CA: /* camera channels ----------------------------- */
+ {
+ switch (icu->adrcode) {
+ case CAM_LENS:
+ icu->ymin= 1.0f;
+ icu->ymax= 1000.0f;
+ break;
+ case CAM_STA:
+ icu->ymin= 0.001f;
+ break;
+ case CAM_END:
+ icu->ymin= 0.1f;
+ break;
+
+ case CAM_YF_APERT:
+ icu->ymin = 0.0f;
+ icu->ymax = 2.0f;
+ break;
+ case CAM_YF_FDIST:
+ icu->ymin = 0.0f;
+ icu->ymax = 5000.0f;
+ break;
+
+ case CAM_SHIFT_X:
+ case CAM_SHIFT_Y:
+ icu->ymin= -2.0f;
+ icu->ymax= 2.0f;
+ break;
+ }
+ }
break;
- case AC_SIZE_Z:
- poin= &(pchan->size[2]);
- pchan->flag |= POSE_SIZE;
+ case ID_SO: /* sound channels ----------------------------- */
+ {
+ switch (icu->adrcode) {
+ case SND_VOLUME:
+ icu->ymin= 0.0f;
+ icu->ymax= 1.0f;
+ break;
+ case SND_PITCH:
+ icu->ymin= -12.0f;
+ icu->ymin= 12.0f;
+ break;
+ case SND_PANNING:
+ icu->ymin= 0.0f;
+ icu->ymax= 1.0f;
+ break;
+ case SND_ATTEN:
+ icu->ymin= 0.0f;
+ icu->ymin= 1.0f;
+ break;
+ }
+ }
break;
- }
- return poin;
-}
-
-void execute_action_ipo(bActionChannel *achan, bPoseChannel *pchan)
-{
-
- if(achan && achan->ipo) {
- IpoCurve *icu;
- for(icu= achan->ipo->curve.first; icu; icu= icu->next) {
- void *poin= get_pchan_ipo_poin(pchan, icu->adrcode);
- if(poin) {
- write_ipo_poin(poin, IPO_FLOAT, icu->curval);
- //printf("execute_action_ipo wrote_ipo_poin: %f\n", icu->curval);
- //printf("%s has poin %p value %f\n", achan->name, poin, icu->curval);
+ case ID_PA: /* particle channels ----------------------------- */
+ {
+ switch (icu->adrcode) {
+ case PART_EMIT_LIFE:
+ case PART_SIZE:
+ case PART_KINK_FREQ:
+ case PART_EMIT_VEL:
+ case PART_EMIT_AVE:
+ case PART_EMIT_SIZE:
+ icu->ymin= 0.0f;
+ break;
+ case PART_CLUMP:
+ icu->ymin= -1.0f;
+ icu->ymax= 1.0f;
+ break;
+ case PART_DRAG:
+ case PART_DAMP:
+ case PART_LENGTH:
+ icu->ymin= 0.0f;
+ icu->ymax= 1.0f;
+ break;
+ case PART_KINK_SHAPE:
+ icu->ymin= -0.999f;
+ icu->ymax= 0.999f;
+ break;
}
}
+ break;
+ case ID_CO: /* constraint channels ----------------------------- */
+ {
+ icu->ymin= 0.0f;
+ icu->ymax= 1.0f;
+ }
+ break;
}
+
+ /* by default, slider limits will be icu->ymin and icu->ymax */
+ icu->slide_min= icu->ymin;
+ icu->slide_max= icu->ymax;
}
-/* exception: it does calc for objects...
- * now find out why this routine was used anyway!
- */
-void do_ipo_nocalc(Ipo *ipo)
+/* --------------------- Pointer I/O API ----------------------------- */
+
+/* write the given value directly into the given pointer */
+void write_ipo_poin (void *poin, int type, float val)
{
- Object *ob;
- Material *ma;
- Tex *tex;
- World *wo;
- Lamp *la;
- Camera *ca;
- bSound *snd;
-
- if(ipo==NULL) return;
-
- switch(ipo->blocktype) {
- case ID_OB:
- ob= G.main->object.first;
- while(ob) {
- if(ob->ipo==ipo) {
- do_ob_ipo(ob);
- /* execute_ipo((ID *)ob, ipo); */
- }
- ob= ob->id.next;
- }
- break;
- case ID_MA:
- ma= G.main->mat.first;
- while(ma) {
- if(ma->ipo==ipo) execute_ipo((ID *)ma, ipo);
- ma= ma->id.next;
- }
- break;
- case ID_TE:
- tex= G.main->tex.first;
- while(tex) {
- if(tex->ipo==ipo) execute_ipo((ID *)tex, ipo);
- tex=tex->id.next;
- }
+ /* Note: we only support a limited number of types, with the value
+ * to set needing to be cast to the appropriate type first
+ * -> (float to integer conversions could be slow)
+ */
+ switch(type) {
+ case IPO_FLOAT:
+ *((float *)poin)= val;
break;
- case ID_WO:
- wo= G.main->world.first;
- while(wo) {
- if(wo->ipo==ipo) execute_ipo((ID *)wo, ipo);
- wo= wo->id.next;
- }
+
+ case IPO_FLOAT_DEGR: /* special hack for rotation so that it fits on same axis as other transforms */
+ *((float *)poin)= (float)(val * M_PI_2 / 9.0);
break;
- case ID_LA:
- la= G.main->lamp.first;
- while(la) {
- if(la->ipo==ipo) execute_ipo((ID *)la, ipo);
- la= la->id.next;
- }
+
+ case IPO_INT:
+ case IPO_INT_BIT: // fixme... directly revealing bitflag combinations is evil!
+ case IPO_LONG:
+ *((int *)poin)= (int)val;
break;
- case ID_CA:
- ca= G.main->camera.first;
- while(ca) {
- if(ca->ipo==ipo) execute_ipo((ID *)ca, ipo);
- ca= ca->id.next;
- }
+
+ case IPO_SHORT:
+ case IPO_SHORT_BIT: // fixme... directly revealing bitflag combinations is evil!
+ *((short *)poin)= (short)val;
break;
- case ID_SO:
- snd= G.main->sound.first;
- while(snd) {
- if(snd->ipo==ipo) execute_ipo((ID *)snd, ipo);
- snd= snd->id.next;
- }
+
+ case IPO_CHAR:
+ case IPO_CHAR_BIT: // fixme... directly revealing bitflag combinations is evil!
+ *((char *)poin)= (char)val;
break;
}
}
-void do_ipo(Ipo *ipo)
-{
- if(ipo) {
- float ctime= frame_to_float(G.scene->r.cfra);
- calc_ipo(ipo, ctime);
-
- do_ipo_nocalc(ipo);
- }
-}
-
-
-
-void do_mat_ipo(Material *ma)
-{
- float ctime;
-
- if(ma==NULL || ma->ipo==NULL) return;
-
- ctime= frame_to_float(G.scene->r.cfra);
- /* if(ob->ipoflag & OB_OFFS_OB) ctime-= ob->sf; */
-
- calc_ipo(ma->ipo, ctime);
-
- execute_ipo((ID *)ma, ma->ipo);
-}
-
-void do_ob_ipo(Object *ob)
-{
- float ctime;
- unsigned int lay;
-
- if(ob->ipo==NULL) return;
-
- /* do not set ob->ctime here: for example when parent in invisible layer */
-
- ctime= bsystem_time(ob, (float) G.scene->r.cfra, 0.0);
-
- calc_ipo(ob->ipo, ctime);
-
- /* Patch: remember localview */
- lay= ob->lay & 0xFF000000;
-
- execute_ipo((ID *)ob, ob->ipo);
-
- ob->lay |= lay;
- if(ob->id.name[2]=='S' && ob->id.name[3]=='C' && ob->id.name[4]=='E') {
- if(strcmp(G.scene->id.name+2, ob->id.name+6)==0) {
- G.scene->lay= ob->lay;
- //XXX copy_view3d_lock(0);
- /* no redraw here! creates too many calls */
- }
- }
-}
-
-void do_ob_ipodrivers(Object *ob, Ipo *ipo, float ctime)
+/* read the value from the pointer that was obtained */
+float read_ipo_poin (void *poin, int type)
{
- IpoCurve *icu;
- void *poin;
- int type;
-
- for(icu= ipo->curve.first; icu; icu= icu->next) {
- if(icu->driver) {
- icu->curval= eval_icu(icu, ctime);
- poin= get_ipo_poin((ID *)ob, icu, &type);
- if(poin) write_ipo_poin(poin, type, icu->curval);
- }
- }
-}
-
-void do_seq_ipo(Sequence *seq, int cfra)
-{
- float ctime, div;
-
- /* seq_ipo has an exception: calc both fields immediately */
+ float val = 0.0;
- if(seq->ipo) {
- if((seq->flag & SEQ_IPO_FRAME_LOCKED) != 0) {
- ctime = frame_to_float(cfra);
- div = 1.0;
- } else {
- ctime= frame_to_float(cfra - seq->startdisp);
- div= (seq->enddisp - seq->startdisp)/100.0f;
- if(div==0.0) return;
- }
+ /* Note: we only support a limited number of types, with the value
+ * to set needing to be cast to the appropriate type first
+ * -> (int to float conversions may loose accuracy in rare cases)
+ */
+ switch (type) {
+ case IPO_FLOAT:
+ val= *((float *)poin);
+ break;
- /* 2nd field */
- calc_ipo(seq->ipo, (ctime+0.5f)/div);
- execute_ipo((ID *)seq, seq->ipo);
- seq->facf1= seq->facf0;
-
- /* 1st field */
- calc_ipo(seq->ipo, ctime/div);
- execute_ipo((ID *)seq, seq->ipo);
-
- }
- else seq->facf1= seq->facf0= 1.0f;
-}
-
-int has_ipo_code(Ipo *ipo, int code)
-{
- IpoCurve *icu;
-
- if(ipo==NULL) return 0;
-
- for(icu= ipo->curve.first; icu; icu= icu->next) {
- if(icu->adrcode==code) return 1;
- }
- return 0;
-}
-
-void do_all_data_ipos()
-{
- Material *ma;
- Tex *tex;
- World *wo;
- Ipo *ipo;
- Lamp *la;
- Key *key;
- Camera *ca;
- bSound *snd;
- Sequence *seq;
- Editing *ed;
- Base *base;
- float ctime;
-
- ctime= frame_to_float(G.scene->r.cfra);
-
- /* this exception cannot be depgraphed yet... what todo with objects in other layers?... */
- for(base= G.scene->base.first; base; base= base->next) {
- /* only update layer when an ipo */
- if( has_ipo_code(base->object->ipo, OB_LAY) ) {
- do_ob_ipo(base->object);
- base->lay= base->object->lay;
- }
- }
-
- /* layers for the set...*/
- if(G.scene->set) {
- for(base= G.scene->set->base.first; base; base= base->next) {
- if( has_ipo_code(base->object->ipo, OB_LAY) ) {
- do_ob_ipo(base->object);
- base->lay= base->object->lay;
- }
- }
- }
-
-
- ipo= G.main->ipo.first;
- while(ipo) {
- if(ipo->id.us && ipo->blocktype!=ID_OB) {
- calc_ipo(ipo, ctime);
- }
- ipo= ipo->id.next;
- }
-
- for(tex= G.main->tex.first; tex; tex= tex->id.next) {
- if(tex->ipo) execute_ipo((ID *)tex, tex->ipo);
- }
-
- for(ma= G.main->mat.first; ma; ma= ma->id.next) {
- if(ma->ipo) execute_ipo((ID *)ma, ma->ipo);
- }
-
- for(wo= G.main->world.first; wo; wo= wo->id.next) {
- if(wo->ipo) execute_ipo((ID *)wo, wo->ipo);
- }
-
- for(key= G.main->key.first; key; key= key->id.next) {
- if(key->ipo) execute_ipo((ID *)key, key->ipo);
- }
-
- la= G.main->lamp.first;
- while(la) {
- if(la->ipo) execute_ipo((ID *)la, la->ipo);
- la= la->id.next;
- }
-
- ca= G.main->camera.first;
- while(ca) {
- if(ca->ipo) execute_ipo((ID *)ca, ca->ipo);
- ca= ca->id.next;
- }
-
- snd= G.main->sound.first;
- while(snd) {
- if(snd->ipo) execute_ipo((ID *)snd, snd->ipo);
- snd= snd->id.next;
- }
-
- /* process FAC Ipos used as volume envelopes */
- ed= G.scene->ed;
- if (ed) {
- seq= ed->seqbasep->first;
- while(seq) {
- if ((seq->type == SEQ_RAM_SOUND
- || seq->type == SEQ_HD_SOUND) && (seq->ipo) &&
- (seq->startdisp<=G.scene->r.cfra+2) &&
- (seq->enddisp>G.scene->r.cfra))
- do_seq_ipo(seq, G.scene->r.cfra);
- seq= seq->next;
- }
- }
-
-}
-
-
-int calc_ipo_spec(Ipo *ipo, int adrcode, float *ctime)
-{
- IpoCurve *icu;
-
- if(ipo==NULL) return 0;
-
- for(icu= ipo->curve.first; icu; icu= icu->next) {
- if(icu->adrcode == adrcode) {
- if(icu->flag & IPO_LOCK);
- else calc_icu(icu, *ctime);
-
- *ctime= icu->curval;
- return 1;
- }
- }
-
- return 0;
-}
-
-
-/* ************************** */
-
-void clear_delta_obipo(Ipo *ipo)
-{
- Object *ob;
+ case IPO_FLOAT_DEGR: /* special hack for rotation so that it fits on same axis as other transforms */
+ val= *( (float *)poin);
+ val = (float)(val / (M_PI_2/9.0));
+ break;
- if(ipo==NULL) return;
+ case IPO_INT:
+ case IPO_INT_BIT: // fixme... directly revealing bitflag combinations is evil!
+ case IPO_LONG:
+ val= (float)( *((int *)poin) );
+ break;
+
+ case IPO_SHORT:
+ case IPO_SHORT_BIT: // fixme... directly revealing bitflag combinations is evil!
+ val= *((short *)poin);
+ break;
- ob= G.main->object.first;
- while(ob) {
- if(ob->id.lib==NULL) {
- if(ob->ipo==ipo) {
- memset(&ob->dloc, 0, 12);
- memset(&ob->drot, 0, 12);
- memset(&ob->dsize, 0, 12);
- }
- }
- ob= ob->id.next;
+ case IPO_CHAR:
+ case IPO_CHAR_BIT: // fixme... directly revealing bitflag combinations is evil
+ val= *((char *)poin);
+ break;
}
-}
-
-void add_to_cfra_elem(ListBase *lb, BezTriple *bezt)
-{
- CfraElem *ce, *cen;
-
- ce= lb->first;
- while(ce) {
-
- if( ce->cfra==bezt->vec[1][0] ) {
- /* do because of double keys */
- if(bezt->f2 & SELECT) ce->sel= bezt->f2;
- return;
- }
- else if(ce->cfra > bezt->vec[1][0]) break;
-
- ce= ce->next;
- }
- cen= MEM_callocN(sizeof(CfraElem), "add_to_cfra_elem");
- if(ce) BLI_insertlinkbefore(lb, ce, cen);
- else BLI_addtail(lb, cen);
-
- cen->cfra= bezt->vec[1][0];
- cen->sel= bezt->f2;
+ /* return value */
+ return val;
}
+// !!!!!!!!!!!!!!!!!!!!!!!!!!!! FIXME - BAD CRUFT WARNING !!!!!!!!!!!!!!!!!!!!!!!
-void make_cfra_list(Ipo *ipo, ListBase *elems)
-{
- IpoCurve *icu;
- BezTriple *bezt;
- int a;
-
- if(ipo->blocktype==ID_OB) {
- for(icu= ipo->curve.first; icu; icu= icu->next) {
- if(icu->flag & IPO_VISIBLE) {
- switch(icu->adrcode) {
- case OB_DLOC_X:
- case OB_DLOC_Y:
- case OB_DLOC_Z:
- case OB_DROT_X:
- case OB_DROT_Y:
- case OB_DROT_Z:
- case OB_DSIZE_X:
- case OB_DSIZE_Y:
- case OB_DSIZE_Z:
-
- case OB_LOC_X:
- case OB_LOC_Y:
- case OB_LOC_Z:
- case OB_ROT_X:
- case OB_ROT_Y:
- case OB_ROT_Z:
- case OB_SIZE_X:
- case OB_SIZE_Y:
- case OB_SIZE_Z:
- case OB_PD_FSTR:
- case OB_PD_FFALL:
- case OB_PD_SDAMP:
- case OB_PD_RDAMP:
- case OB_PD_PERM:
- case OB_PD_FMAXD:
- bezt= icu->bezt;
- if(bezt) {
- a= icu->totvert;
- while(a--) {
- add_to_cfra_elem(elems, bezt);
- bezt++;
- }
- }
- break;
- }
- }
- }
- }
- else if(ipo->blocktype==ID_AC) {
- for(icu= ipo->curve.first; icu; icu= icu->next) {
- if(icu->flag & IPO_VISIBLE) {
- switch(icu->adrcode) {
- case AC_LOC_X:
- case AC_LOC_Y:
- case AC_LOC_Z:
- case AC_SIZE_X:
- case AC_SIZE_Y:
- case AC_SIZE_Z:
- case AC_QUAT_W:
- case AC_QUAT_X:
- case AC_QUAT_Y:
- case AC_QUAT_Z:
- bezt= icu->bezt;
- if(bezt) {
- a= icu->totvert;
- while(a--) {
- add_to_cfra_elem(elems, bezt);
- bezt++;
- }
- }
- break;
- }
- }
- }
- }
- else {
- for(icu= ipo->curve.first; icu; icu= icu->next) {
- if(icu->flag & IPO_VISIBLE) {
- bezt= icu->bezt;
- if(bezt) {
- a= icu->totvert;
- while(a--) {
- add_to_cfra_elem(elems, bezt);
- bezt++;
- }
- }
- }
- }
- }
-
- /* what's the point of this little block of code? */
-#if 0
- if(ipo->showkey==0) {
- /* deselect all keys */
- ce= elems->first;
- while(ce) {
- ce->sel= 0;
- ce= ce->next;
- }
- }
-#endif
-}
-
-/* *********************** INTERFACE FOR KETSJI ********** */
-
+/* ***************************** IPO <--> GameEngine Interface ********************************* */
-int IPO_GetChannels(Ipo *ipo, IPO_Channel *channels)
+/* channels is max 32 items, allocated by calling function */
+short IPO_GetChannels (Ipo *ipo, IPO_Channel *channels)
{
- /* channels is max 32 items, allocated by calling function */
-
IpoCurve *icu;
- int total=0;
+ int total = 0;
- if(ipo==NULL) return 0;
+ /* don't do anything with no IPO-block */
+ if (ipo == NULL)
+ return 0;
- for(icu= ipo->curve.first; icu; icu= icu->next) {
+ /* store the IPO-curve's adrcode in the relevant channel slot */
+ for (icu=ipo->curve.first; (icu) && (total < 31); icu=icu->next, total++)
channels[total]= icu->adrcode;
- total++;
- if(total>31) break;
- }
+ /* return the number of channels stored */
return total;
}
-
-
/* Get the float value for channel 'channel' at time 'ctime' */
-
-float IPO_GetFloatValue(Ipo *ipo, IPO_Channel channel, float ctime)
+float IPO_GetFloatValue (Ipo *ipo, IPO_Channel channel, float ctime)
{
- if(ipo==NULL) return 0;
+ /* don't evaluate if no IPO to use */
+ if (ipo == NULL)
+ return 0;
+ /* only calculate the specified channel */
calc_ipo_spec(ipo, channel, &ctime);
- if (OB_ROT_X <= channel && channel <= OB_DROT_Z) {
+ /* unapply rotation hack, as gameengine doesn't use it */
+ if ((OB_ROT_X <= channel) && (channel <= OB_DROT_Z))
ctime *= (float)(M_PI_2/9.0);
- }
+ /* return the value of this channel */
return ctime;
}
diff --git a/source/blender/blenkernel/intern/key.c b/source/blender/blenkernel/intern/key.c
index dd5adac29b0..a34da4377b1 100644
--- a/source/blender/blenkernel/intern/key.c
+++ b/source/blender/blenkernel/intern/key.c
@@ -281,10 +281,10 @@ void set_four_ipo(float d, float *data, int type)
}
else if(type==KEY_BSPLINE) {
- data[0]= -0.1666f*d3 +0.5f*d2 -0.5f*d +0.16666f;
- data[1]= 0.5f*d3 -d2 +0.6666f;
- data[2]= -0.5f*d3 +0.5f*d2 +0.5f*d +0.1666f;
- data[3]= 0.1666f*d3 ;
+ data[0]= -0.16666666f*d3 +0.5f*d2 -0.5f*d +0.16666666f;
+ data[1]= 0.5f*d3 -d2 +0.6666666f;
+ data[2]= -0.5f*d3 +0.5f*d2 +0.5f*d +0.16666666f;
+ data[3]= 0.16666666f*d3 ;
}
}
}
@@ -310,10 +310,10 @@ void set_afgeleide_four_ipo(float d, float *data, int type)
}
else if(type==KEY_BSPLINE) {
- data[0]= -0.1666f*3.0f*d2 +d -0.5f;
+ data[0]= -0.16666666f*3.0f*d2 +d -0.5f;
data[1]= 1.5f*d2 -2.0f*d;
data[2]= -1.5f*d2 +d +0.5f;
- data[3]= 0.1666f*3.0f*d2 ;
+ data[3]= 0.16666666f*3.0f*d2 ;
}
}
}
@@ -539,26 +539,26 @@ static void cp_key(int start, int end, int tot, char *poin, Key *key, KeyBlock *
case IPO_FLOAT:
if(weights) {
- memcpy(poin, kref, 4*cp[0]);
+ memcpy(poin, kref, sizeof(float)*cp[0]);
if(*weights!=0.0f)
rel_flerp(cp[0], (float *)poin, (float *)kref, (float *)k1, *weights);
weights++;
}
else
- memcpy(poin, k1, 4*cp[0]);
+ memcpy(poin, k1, sizeof(float)*cp[0]);
poin+= ofsp[0];
break;
case IPO_BPOINT:
- memcpy(poin, k1, 3*4);
- memcpy(poin+16, k1+12, 4);
+ memcpy(poin, k1, 3*sizeof(float));
+ memcpy(poin+4*sizeof(float), k1+3*sizeof(float), sizeof(float));
poin+= ofsp[0];
break;
case IPO_BEZTRIPLE:
- memcpy(poin, k1, 4*12);
+ memcpy(poin, k1, sizeof(float)*10);
poin+= ofsp[0];
break;
@@ -627,7 +627,7 @@ void cp_cu_key(Curve *cu, KeyBlock *kb, int start, int end)
}
-static void do_rel_key(int start, int end, int tot, char *basispoin, Key *key, int mode)
+void do_rel_key(int start, int end, int tot, char *basispoin, Key *key, int mode)
{
KeyBlock *kb;
int *ofsp, ofs[3], elemsize, b;
diff --git a/source/blender/blenkernel/intern/lattice.c b/source/blender/blenkernel/intern/lattice.c
index aaacba97d35..3f9143bb405 100644
--- a/source/blender/blenkernel/intern/lattice.c
+++ b/source/blender/blenkernel/intern/lattice.c
@@ -514,7 +514,7 @@ static int where_on_path_deform(Object *ob, float ctime, float *vec, float *dir)
/* co: local coord, result local too */
/* returns quaternion for rotation, using cd->no_rot_axis */
/* axis is using another define!!! */
-static float *calc_curve_deform(Object *par, float *co, short axis, CurveDeform *cd)
+static int calc_curve_deform(Object *par, float *co, short axis, CurveDeform *cd, float *quatp)
{
Curve *cu= par->data;
float fac, loc[4], dir[3], cent[3];
@@ -544,7 +544,7 @@ static float *calc_curve_deform(Object *par, float *co, short axis, CurveDeform
/* to be sure, mostly after file load */
if(cu->path==NULL) {
makeDispListCurveTypes(par, 0);
- if(cu->path==NULL) return NULL; // happens on append...
+ if(cu->path==NULL) return 0; // happens on append...
}
/* options */
@@ -570,14 +570,13 @@ static float *calc_curve_deform(Object *par, float *co, short axis, CurveDeform
}
if( where_on_path_deform(par, fac, loc, dir)) { /* returns OK */
- float q[4], mat[3][3];
- float *quat;
+ float q[4], mat[3][3], quat[4];
if(cd->no_rot_axis) /* set by caller */
dir[cd->no_rot_axis-1]= 0.0f;
/* -1 for compatibility with old track defines */
- quat= vectoquat(dir, axis-1, upflag); /* gives static quat */
+ vectoquat(dir, axis-1, upflag, quat);
/* the tilt */
if(loc[3]!=0.0) {
@@ -597,18 +596,26 @@ static float *calc_curve_deform(Object *par, float *co, short axis, CurveDeform
/* translation */
VECADD(co, cent, loc);
- return quat;
+ if(quatp)
+ QUATCOPY(quatp, quat);
+
+ return 1;
}
- return NULL;
+ return 0;
}
void curve_deform_verts(Object *cuOb, Object *target, DerivedMesh *dm, float (*vertexCos)[3], int numVerts, char *vgroup, short defaxis)
{
- Curve *cu = cuOb->data;
- int a, flag = cu->flag;
+ Curve *cu;
+ int a, flag;
CurveDeform cd;
int use_vgroups;
-
+
+ if(cuOb->type != OB_CURVE)
+ return;
+
+ cu = cuOb->data;
+ flag = cu->flag;
cu->flag |= (CU_PATH|CU_FOLLOW); // needed for path & bevlist
init_curve_deform(cuOb, target, &cd, (cu->flag & CU_STRETCH)==0);
@@ -663,7 +670,7 @@ void curve_deform_verts(Object *cuOb, Object *target, DerivedMesh *dm, float (*v
for(j = 0; j < dvert->totweight; j++) {
if(dvert->dw[j].def_nr == index) {
VECCOPY(vec, vertexCos[a]);
- calc_curve_deform(cuOb, vec, defaxis, &cd);
+ calc_curve_deform(cuOb, vec, defaxis, &cd, NULL);
VecLerpf(vertexCos[a], vertexCos[a], vec,
dvert->dw[j].weight);
Mat4MulVecfl(cd.objectspace, vertexCos[a]);
@@ -681,7 +688,7 @@ void curve_deform_verts(Object *cuOb, Object *target, DerivedMesh *dm, float (*v
}
for(a = 0; a < numVerts; a++) {
- calc_curve_deform(cuOb, vertexCos[a], defaxis, &cd);
+ calc_curve_deform(cuOb, vertexCos[a], defaxis, &cd, NULL);
Mat4MulVecfl(cd.objectspace, vertexCos[a]);
}
}
@@ -694,8 +701,13 @@ void curve_deform_verts(Object *cuOb, Object *target, DerivedMesh *dm, float (*v
void curve_deform_vector(Object *cuOb, Object *target, float *orco, float *vec, float mat[][3], int no_rot_axis)
{
CurveDeform cd;
- float *quat;
+ float quat[4];
+ if(cuOb->type != OB_CURVE) {
+ Mat3One(mat);
+ return;
+ }
+
init_curve_deform(cuOb, target, &cd, 0); /* 0 no dloc */
cd.no_rot_axis= no_rot_axis; /* option to only rotate for XY, for example */
@@ -704,8 +716,7 @@ void curve_deform_vector(Object *cuOb, Object *target, float *orco, float *vec,
Mat4MulVecfl(cd.curvespace, vec);
- quat= calc_curve_deform(cuOb, vec, target->trackflag+1, &cd);
- if(quat) {
+ if(calc_curve_deform(cuOb, vec, target->trackflag+1, &cd, quat)) {
float qmat[3][3];
QuatToMat3(quat, qmat);
@@ -724,6 +735,9 @@ void lattice_deform_verts(Object *laOb, Object *target, DerivedMesh *dm,
int a;
int use_vgroups;
+ if(laOb->type != OB_LATTICE)
+ return;
+
init_latt_deform(laOb, target);
/* check whether to use vertex groups (only possible if target is a Mesh)
@@ -899,7 +913,10 @@ void lattice_calc_modifiers(Object *ob)
mti->deformVerts(md, ob, NULL, vertexCos, numVerts);
}
- if (vertexCos) {
+ /* always displist to make this work like derivedmesh */
+ if (!vertexCos) vertexCos = lattice_getVertexCos(ob, &numVerts);
+
+ {
DispList *dl = MEM_callocN(sizeof(*dl), "lt_dl");
dl->type = DL_VERTS;
dl->parts = 1;
@@ -909,3 +926,15 @@ void lattice_calc_modifiers(Object *ob)
BLI_addtail(&ob->disp, dl);
}
}
+
+struct MDeformVert* lattice_get_deform_verts(struct Object *oblatt)
+{
+ if(oblatt->type == OB_LATTICE)
+ {
+ Lattice *lt = (oblatt==G.obedit)?editLatt:(Lattice*)oblatt->data;
+ return lt->dvert;
+ }
+
+ return NULL;
+}
+
diff --git a/source/blender/blenkernel/intern/library.c b/source/blender/blenkernel/intern/library.c
index f0dd3d1ec4b..3acc10e8022 100644
--- a/source/blender/blenkernel/intern/library.c
+++ b/source/blender/blenkernel/intern/library.c
@@ -76,6 +76,7 @@
#include "DNA_effect_types.h"
#include "DNA_brush_types.h"
#include "DNA_particle_types.h"
+#include "DNA_space_types.h"
#include "DNA_windowmanager_types.h"
#include "BLI_blenlib.h"
@@ -111,8 +112,6 @@
#include "BKE_idprop.h"
#include "BKE_particle.h"
-//XXX #include "BPI_script.h"
-
#define MAX_IDPUP 60 /* was 24 */
/* ************* general ************************ */
@@ -226,49 +225,51 @@ void flag_all_listbases_ids(short flag, short value)
/* note: MAX_LIBARRAY define should match this code */
int set_listbasepointers(Main *main, ListBase **lb)
{
+ int a = 0;
+
/* BACKWARDS! also watch order of free-ing! (mesh<->mat) */
- lb[0]= &(main->ipo);
- lb[1]= &(main->key);
- lb[2]= &(main->image);
- lb[3]= &(main->tex);
- lb[4]= &(main->mat);
- lb[5]= &(main->vfont);
+ lb[a++]= &(main->ipo);
+ lb[a++]= &(main->key);
+ lb[a++]= &(main->nodetree);
+ lb[a++]= &(main->image);
+ lb[a++]= &(main->tex);
+ lb[a++]= &(main->mat);
+ lb[a++]= &(main->vfont);
/* Important!: When adding a new object type,
* the specific data should be inserted here
*/
- lb[6]= &(main->armature);
- lb[7]= &(main->action);
+ lb[a++]= &(main->armature);
+ lb[a++]= &(main->action);
- lb[8]= &(main->mesh);
- lb[9]= &(main->curve);
- lb[10]= &(main->mball);
+ lb[a++]= &(main->mesh);
+ lb[a++]= &(main->curve);
+ lb[a++]= &(main->mball);
- lb[11]= &(main->wave);
- lb[12]= &(main->latt);
- lb[13]= &(main->lamp);
- lb[14]= &(main->camera);
+ lb[a++]= &(main->wave);
+ lb[a++]= &(main->latt);
+ lb[a++]= &(main->lamp);
+ lb[a++]= &(main->camera);
- lb[15]= &(main->text);
- lb[16]= &(main->sound);
- lb[17]= &(main->group);
- lb[18]= &(main->nodetree);
- lb[19]= &(main->brush);
- lb[20]= &(main->script);
- lb[21]= &(main->particle);
+ lb[a++]= &(main->text);
+ lb[a++]= &(main->sound);
+ lb[a++]= &(main->group);
+ lb[a++]= &(main->brush);
+ lb[a++]= &(main->script);
+ lb[a++]= &(main->particle);
- lb[22]= &(main->world);
- lb[23]= &(main->screen);
- lb[24]= &(main->object);
- lb[25]= &(main->scene);
- lb[26]= &(main->library);
- lb[27]= &(main->wm);
+ lb[a++]= &(main->world);
+ lb[a++]= &(main->screen);
+ lb[a++]= &(main->object);
+ lb[a++]= &(main->scene);
+ lb[a++]= &(main->library);
+ lb[a++]= &(main->wm);
- lb[28]= NULL;
+ lb[a]= NULL;
- return 28;
+ return a;
}
/* *********** ALLOC AND FREE *****************
@@ -411,6 +412,10 @@ void *copy_libblock(void *rt)
lb= wich_libbase(G.main, GS(id->name));
idn= alloc_libblock(lb, GS(id->name), id->name+2);
+ if(idn==NULL) {
+ printf("ERROR: Illegal ID name for %s (Crashing now)\n", id->name);
+ }
+
idn_len= MEM_allocN_len(idn);
if(idn_len - sizeof(ID) > 0) {
cp= (char *)id;
@@ -951,7 +956,7 @@ int new_id(ListBase *lb, ID *id, const char *tname)
}
/* if result > 21, strncpy don't put the final '\0' to name. */
- if( result > 21 ) name[21]= 0;
+ if( result >= 21 ) name[21]= 0;
result = check_for_dupid( lb, id, name );
strcpy( id->name+2, name );
@@ -991,7 +996,7 @@ static void image_fix_relative_path(Image *ima)
{
if(ima->id.lib==NULL) return;
if(strncmp(ima->name, "//", 2)==0) {
- BLI_convertstringcode(ima->name, ima->id.lib->filename, 0);
+ BLI_convertstringcode(ima->name, ima->id.lib->filename);
BLI_makestringcode(G.sce, ima->name);
}
}
@@ -1008,7 +1013,7 @@ static void lib_indirect_test_id(ID *id)
Object *ob= (Object *)id;
bActionStrip *strip;
Mesh *me;
- PartEff *paf;
+
int a;
for (strip=ob->nlastrips.first; strip; strip=strip->next){
@@ -1020,10 +1025,6 @@ static void lib_indirect_test_id(ID *id)
for(a=0; a<ob->totcol; a++) {
LIBTAG(ob->mat[a]);
}
-
- paf = give_parteff(ob);
- if (paf)
- LIBTAG(paf->group);
LIBTAG(ob->dup_group);
LIBTAG(ob->proxy);
diff --git a/source/blender/blenkernel/intern/material.c b/source/blender/blenkernel/intern/material.c
index baaa5becd44..95534deae66 100644
--- a/source/blender/blenkernel/intern/material.c
+++ b/source/blender/blenkernel/intern/material.c
@@ -58,7 +58,11 @@
#include "BKE_node.h"
#include "BKE_utildefines.h"
+#ifndef DISABLE_PYTHON
#include "BPY_extern.h"
+#endif
+
+#include "GPU_material.h"
/* used in UI and render */
Material defmaterial;
@@ -75,7 +79,9 @@ void free_material(Material *ma)
MTex *mtex;
int a;
+#ifndef DISABLE_PYTHON
BPY_free_scriptlink(&ma->scriptlink);
+#endif
for(a=0; a<MAX_MTEX; a++) {
mtex= ma->mtex[a];
@@ -95,6 +101,9 @@ void free_material(Material *ma)
ntreeFreeTree(ma->nodetree);
MEM_freeN(ma->nodetree);
}
+
+ if(ma->gpumaterial.first)
+ GPU_material_free(ma);
}
void init_material(Material *ma)
@@ -195,8 +204,10 @@ Material *copy_material(Material *ma)
id_us_plus((ID *)man->mtex[a]->tex);
}
}
-
+
+#ifndef DISABLE_PYTHON
BPY_copy_scriptlink(&ma->scriptlink);
+#endif
if(ma->ramp_col) man->ramp_col= MEM_dupallocN(ma->ramp_col);
if(ma->ramp_spec) man->ramp_spec= MEM_dupallocN(ma->ramp_spec);
@@ -206,6 +217,8 @@ Material *copy_material(Material *ma)
if(ma->nodetree) {
man->nodetree= ntreeCopyTree(ma->nodetree, 0); /* 0 == full new tree */
}
+
+ man->gpumaterial.first= man->gpumaterial.last= NULL;
return man;
}
@@ -629,9 +642,7 @@ static void do_init_render_material(Material *ma, int r_mode, float *amb)
if(ma->flarec==0) ma->flarec= 1;
- /* add all texcoflags from mtex */
- ma->texco= 0;
- ma->mapto= 0;
+ /* add all texcoflags from mtex, texco and mapto were cleared in advance */
for(a=0; a<MAX_MTEX; a++) {
/* separate tex switching */
@@ -726,6 +737,16 @@ void init_render_materials(int r_mode, float *amb)
{
Material *ma;
+ /* clear these flags before going over materials, to make sure they
+ * are cleared only once, otherwise node materials contained in other
+ * node materials can go wrong */
+ for(ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if(ma->id.us) {
+ ma->texco= 0;
+ ma->mapto= 0;
+ }
+ }
+
/* two steps, first initialize, then or the flags for layers */
for(ma= G.main->mat.first; ma; ma= ma->id.next) {
/* is_used flag comes back in convertblender.c */
diff --git a/source/blender/blenkernel/intern/mball.c b/source/blender/blenkernel/intern/mball.c
index a2a1c5dcfa6..d84ad0a5215 100644
--- a/source/blender/blenkernel/intern/mball.c
+++ b/source/blender/blenkernel/intern/mball.c
@@ -229,14 +229,14 @@ void tex_space_mball(Object *ob)
boundbox_set_from_min_max(bb, min, max);
}
-void make_orco_mball(Object *ob)
+float *make_orco_mball(Object *ob)
{
BoundBox *bb;
DispList *dl;
- float *data;
+ float *data, *orco, *orcodata;
float loc[3], size[3];
int a;
-
+
/* restore size and loc */
bb= ob->bb;
loc[0]= (bb->vec[0][0]+bb->vec[4][0])/2.0f;
@@ -247,15 +247,21 @@ void make_orco_mball(Object *ob)
size[2]= bb->vec[1][2]-loc[2];
dl= ob->disp.first;
+ orcodata= MEM_mallocN(sizeof(float)*3*dl->nr, "MballOrco");
+
data= dl->verts;
+ orco= orcodata;
a= dl->nr;
while(a--) {
- data[0]= (data[0]-loc[0])/size[0];
- data[1]= (data[1]-loc[1])/size[1];
- data[2]= (data[2]-loc[2])/size[2];
+ orco[0]= (data[0]-loc[0])/size[0];
+ orco[1]= (data[1]-loc[1])/size[1];
+ orco[2]= (data[2]-loc[2])/size[2];
data+= 3;
+ orco+= 3;
}
+
+ return orcodata;
}
/** \brief Test, if Object *ob is basic MetaBall.
*
@@ -369,7 +375,7 @@ Object *find_basis_mball(Object *basis)
#define RTF 7 /* right top far corner */
/* the LBN corner of cube (i, j, k), corresponds with location
- * (start.x+(i-0.5)*size, start.y+(j-0.5)*size, start.z+(k-0.5)*size) */
+ * (i-0.5)*size, (j-0.5)*size, (k-0.5)*size) */
#define HASHBIT (5)
#define HASHSIZE (size_t)(1<<(3*HASHBIT)) /*! < hash table size (32768) */
@@ -830,11 +836,11 @@ CORNER *setcorner (PROCESS* p, int i, int j, int k)
c = (CORNER *) new_pgn_element(sizeof(CORNER));
c->i = i;
- c->x = p->start.x+((float)i-0.5f)*p->size;
+ c->x = ((float)i-0.5f)*p->size;
c->j = j;
- c->y = p->start.y+((float)j-0.5f)*p->size;
+ c->y = ((float)j-0.5f)*p->size;
c->k = k;
- c->z = p->start.z+((float)k-0.5f)*p->size;
+ c->z = ((float)k-0.5f)*p->size;
c->value = p->function(c->x, c->y, c->z);
c->next = p->corners[index];
@@ -1208,8 +1214,8 @@ void converge (MB_POINT *p1, MB_POINT *p2, float v1, float v2,
p->y = neg.y;
p->z = neg.z;
while (1) {
- p->x = 0.5f*(pos.x + neg.x);
if (i++ == RES) return;
+ p->x = 0.5f*(pos.x + neg.x);
if ((function(p->x,p->y,p->z)) > 0.0) pos.x = p->x; else neg.x = p->x;
}
}
@@ -1218,8 +1224,8 @@ void converge (MB_POINT *p1, MB_POINT *p2, float v1, float v2,
p->x = neg.x;
p->z = neg.z;
while (1) {
- p->y = 0.5f*(pos.y + neg.y);
if (i++ == RES) return;
+ p->y = 0.5f*(pos.y + neg.y);
if ((function(p->x,p->y,p->z)) > 0.0) pos.y = p->y; else neg.y = p->y;
}
}
@@ -1228,8 +1234,8 @@ void converge (MB_POINT *p1, MB_POINT *p2, float v1, float v2,
p->x = neg.x;
p->y = neg.y;
while (1) {
- p->z = 0.5f*(pos.z + neg.z);
if (i++ == RES) return;
+ p->z = 0.5f*(pos.z + neg.z);
if ((function(p->x,p->y,p->z)) > 0.0) pos.z = p->z; else neg.z = p->z;
}
}
@@ -1294,6 +1300,8 @@ void find_first_points(PROCESS *mbproc, MetaBall *mb, int a)
int index[3]={1,0,-1};
float f =0.0f;
float in_v, out_v;
+ MB_POINT workp;
+ float tmp_v, workp_v, max_len, len, dx, dy, dz, nx, ny, nz, MAXN;
ml = mainb[a];
@@ -1354,24 +1362,50 @@ void find_first_points(PROCESS *mbproc, MetaBall *mb, int a)
out_v = mbproc->function(out.x, out.y, out.z);
- /* find "first point" on Implicit Surface of MetaElemnt ml */
- converge(&in, &out, in_v, out_v, mbproc->function, &mbproc->start, mb, 0);
-
- /* indexes of CUBE, which includes "first point" */
- c_i= (int)floor(mbproc->start.x/mbproc->size );
- c_j= (int)floor(mbproc->start.y/mbproc->size );
- c_k= (int)floor(mbproc->start.z/mbproc->size );
-
- mbproc->start.x= mbproc->start.y= mbproc->start.z= 0.0;
-
- /* add CUBE (with indexes c_i, c_j, c_k) to the stack,
- * this cube includes found point of Implicit Surface */
- if (ml->flag & MB_NEGATIVE)
- add_cube(mbproc, c_i, c_j, c_k, 2);
- else
- add_cube(mbproc, c_i, c_j, c_k, 1);
-
+ /* find "first points" on Implicit Surface of MetaElemnt ml */
+ workp.x = in.x;
+ workp.y = in.y;
+ workp.z = in.z;
+ workp_v = in_v;
+ max_len = sqrt((out.x-in.x)*(out.x-in.x) + (out.y-in.y)*(out.y-in.y) + (out.z-in.z)*(out.z-in.z));
+
+ nx = abs((out.x - in.x)/mbproc->size);
+ ny = abs((out.y - in.y)/mbproc->size);
+ nz = abs((out.z - in.z)/mbproc->size);
+ MAXN = MAX3(nx,ny,nz);
+ if(MAXN!=0.0f) {
+ dx = (out.x - in.x)/MAXN;
+ dy = (out.y - in.y)/MAXN;
+ dz = (out.z - in.z)/MAXN;
+
+ len = 0.0;
+ while(len<=max_len) {
+ workp.x += dx;
+ workp.y += dy;
+ workp.z += dz;
+ /* compute value of implicite function */
+ tmp_v = mbproc->function(workp.x, workp.y, workp.z);
+ /* add cube to the stack, when value of implicite function crosses zero value */
+ if((tmp_v<0.0 && workp_v>=0.0)||(tmp_v>0.0 && workp_v<=0.0)) {
+
+ /* indexes of CUBE, which includes "first point" */
+ c_i= (int)floor(workp.x/mbproc->size);
+ c_j= (int)floor(workp.y/mbproc->size);
+ c_k= (int)floor(workp.z/mbproc->size);
+
+ /* add CUBE (with indexes c_i, c_j, c_k) to the stack,
+ * this cube includes found point of Implicit Surface */
+ if (ml->flag & MB_NEGATIVE)
+ add_cube(mbproc, c_i, c_j, c_k, 2);
+ else
+ add_cube(mbproc, c_i, c_j, c_k, 1);
+ }
+ len = sqrt((workp.x-in.x)*(workp.x-in.x) + (workp.y-in.y)*(workp.y-in.y) + (workp.z-in.z)*(workp.z-in.z));
+ workp_v = tmp_v;
+
+ }
+ }
}
}
}
@@ -1677,15 +1711,13 @@ void fill_metaball_octal_node(octal_node *node, MetaElem *ml, short i)
* +------+------+
*
*/
-void subdivide_metaball_octal_node(octal_node *node, float *size, short depth)
+void subdivide_metaball_octal_node(octal_node *node, float size_x, float size_y, float size_z, short depth)
{
MetaElem *ml;
ml_pointer *ml_p;
float x,y,z;
int a,i;
- if(depth==0) return;
-
/* create new nodes */
for(a=0;a<8;a++){
node->nodes[a]= MEM_mallocN(sizeof(octal_node),"octal_node");
@@ -1699,45 +1731,71 @@ void subdivide_metaball_octal_node(octal_node *node, float *size, short depth)
node->nodes[a]->pos= 0;
}
- size[0]/=2; size[1]/=2; size[2]/=2;
+ size_x /= 2;
+ size_y /= 2;
+ size_z /= 2;
/* center of node */
- node->x= x= node->x_min + size[0];
- node->y= y= node->y_min + size[1];
- node->z= z= node->z_min + size[2];
+ node->x = x = node->x_min + size_x;
+ node->y = y = node->y_min + size_y;
+ node->z = z = node->z_min + size_z;
/* setting up of border points of new nodes */
- node->nodes[0]->x_min= node->x_min;
- node->nodes[0]->y_min= node->y_min;
- node->nodes[0]->z_min= node->z_min;
-
- node->nodes[1]->x_min= x;
- node->nodes[1]->y_min= node->y_min;
- node->nodes[1]->z_min= node->z_min;
-
- node->nodes[2]->x_min= x;
- node->nodes[2]->y_min= y;
- node->nodes[2]->z_min= node->z_min;
-
- node->nodes[3]->x_min= node->x_min;
- node->nodes[3]->y_min= y;
- node->nodes[3]->z_min= node->z_min;
-
- node->nodes[4]->x_min= node->x_min;
- node->nodes[4]->y_min= node->y_min;
- node->nodes[4]->z_min= z;
-
- node->nodes[5]->x_min= x;
- node->nodes[5]->y_min= node->y_min;
- node->nodes[5]->z_min= z;
-
- node->nodes[6]->x_min= x;
- node->nodes[6]->y_min= y;
- node->nodes[6]->z_min= z;
-
- node->nodes[7]->x_min= node->x_min;
- node->nodes[7]->y_min= y;
- node->nodes[7]->z_min= z;
+ node->nodes[0]->x_min = node->x_min;
+ node->nodes[0]->y_min = node->y_min;
+ node->nodes[0]->z_min = node->z_min;
+ node->nodes[0]->x = node->nodes[0]->x_min + size_x/2;
+ node->nodes[0]->y = node->nodes[0]->y_min + size_y/2;
+ node->nodes[0]->z = node->nodes[0]->z_min + size_z/2;
+
+ node->nodes[1]->x_min = x;
+ node->nodes[1]->y_min = node->y_min;
+ node->nodes[1]->z_min = node->z_min;
+ node->nodes[1]->x = node->nodes[1]->x_min + size_x/2;
+ node->nodes[1]->y = node->nodes[1]->y_min + size_y/2;
+ node->nodes[1]->z = node->nodes[1]->z_min + size_z/2;
+
+ node->nodes[2]->x_min = x;
+ node->nodes[2]->y_min = y;
+ node->nodes[2]->z_min = node->z_min;
+ node->nodes[2]->x = node->nodes[2]->x_min + size_x/2;
+ node->nodes[2]->y = node->nodes[2]->y_min + size_y/2;
+ node->nodes[2]->z = node->nodes[2]->z_min + size_z/2;
+
+ node->nodes[3]->x_min = node->x_min;
+ node->nodes[3]->y_min = y;
+ node->nodes[3]->z_min = node->z_min;
+ node->nodes[3]->x = node->nodes[3]->x_min + size_x/2;
+ node->nodes[3]->y = node->nodes[3]->y_min + size_y/2;
+ node->nodes[3]->z = node->nodes[3]->z_min + size_z/2;
+
+ node->nodes[4]->x_min = node->x_min;
+ node->nodes[4]->y_min = node->y_min;
+ node->nodes[4]->z_min = z;
+ node->nodes[4]->x = node->nodes[4]->x_min + size_x/2;
+ node->nodes[4]->y = node->nodes[4]->y_min + size_y/2;
+ node->nodes[4]->z = node->nodes[4]->z_min + size_z/2;
+
+ node->nodes[5]->x_min = x;
+ node->nodes[5]->y_min = node->y_min;
+ node->nodes[5]->z_min = z;
+ node->nodes[5]->x = node->nodes[5]->x_min + size_x/2;
+ node->nodes[5]->y = node->nodes[5]->y_min + size_y/2;
+ node->nodes[5]->z = node->nodes[5]->z_min + size_z/2;
+
+ node->nodes[6]->x_min = x;
+ node->nodes[6]->y_min = y;
+ node->nodes[6]->z_min = z;
+ node->nodes[6]->x = node->nodes[6]->x_min + size_x/2;
+ node->nodes[6]->y = node->nodes[6]->y_min + size_y/2;
+ node->nodes[6]->z = node->nodes[6]->z_min + size_z/2;
+
+ node->nodes[7]->x_min = node->x_min;
+ node->nodes[7]->y_min = y;
+ node->nodes[7]->z_min = z;
+ node->nodes[7]->x = node->nodes[7]->x_min + size_x/2;
+ node->nodes[7]->y = node->nodes[7]->y_min + size_y/2;
+ node->nodes[7]->z = node->nodes[7]->z_min + size_z/2;
ml_p= node->elems.first;
@@ -1904,7 +1962,7 @@ void subdivide_metaball_octal_node(octal_node *node, float *size, short depth)
if(depth>0){
for(a=0;a<8;a++){
if(node->nodes[a]->count > 0) /* if node is not empty, then it is subdivided */
- subdivide_metaball_octal_node(node->nodes[a], size, depth);
+ subdivide_metaball_octal_node(node->nodes[a], size_x, size_y, size_z, depth);
}
}
}
@@ -1976,7 +2034,7 @@ void init_metaball_octal_tree(int depth)
size[2]= node->z_max - node->z_min;
/* first node is subdivided recursively */
- subdivide_metaball_octal_node(node, size, metaball_tree->depth);
+ subdivide_metaball_octal_node(node, size[0], size[1], size[2], metaball_tree->depth);
}
void metaball_polygonize(Object *ob)
diff --git a/source/blender/blenkernel/intern/mesh.c b/source/blender/blenkernel/intern/mesh.c
index 1632f57c66e..07a1a5c5f44 100644
--- a/source/blender/blenkernel/intern/mesh.c
+++ b/source/blender/blenkernel/intern/mesh.c
@@ -78,45 +78,6 @@
#include "BLI_editVert.h"
#include "BLI_arithb.h"
-int update_realtime_texture(MTFace *tface, double time)
-{
- Image *ima;
- int inc = 0;
- float diff;
- int newframe;
-
- ima = tface->tpage;
-
- if (!ima)
- return 0;
-
- if (ima->lastupdate<0)
- ima->lastupdate = 0;
-
- if (ima->lastupdate>time)
- ima->lastupdate=(float)time;
-
- if(ima->tpageflag & IMA_TWINANIM) {
- if(ima->twend >= ima->xrep*ima->yrep) ima->twend= ima->xrep*ima->yrep-1;
-
- /* check: is the bindcode not in the array? Then free. (still to do) */
-
- diff = (float)(time-ima->lastupdate);
-
- inc = (int)(diff*(float)ima->animspeed);
-
- ima->lastupdate+=((float)inc/(float)ima->animspeed);
-
- newframe = ima->lastframe+inc;
-
- if (newframe > (int)ima->twend)
- newframe = (int)ima->twsta-1 + (newframe-ima->twend)%(ima->twend-ima->twsta);
-
- ima->lastframe = newframe;
- }
- return inc;
-}
-
void mesh_update_customdata_pointers(Mesh *me)
{
me->mvert = CustomData_get_layer(&me->vdata, CD_MVERT);
@@ -526,7 +487,7 @@ void transform_mesh_orco_verts(Mesh *me, float (*orco)[3], int totvert, int inve
/* rotates the vertices of a face in case v[2] or v[3] (vertex index) is = 0.
this is necessary to make the if(mface->v4) check for quads work */
-void test_index_face(MFace *mface, CustomData *fdata, int mfindex, int nr)
+int test_index_face(MFace *mface, CustomData *fdata, int mfindex, int nr)
{
/* first test if the face is legal */
if(mface->v3 && mface->v3==mface->v4) {
@@ -568,6 +529,8 @@ void test_index_face(MFace *mface, CustomData *fdata, int mfindex, int nr)
CustomData_swap(fdata, mfindex, corner_indices);
}
}
+
+ return nr;
}
Mesh *get_mesh(Object *ob)
@@ -764,8 +727,7 @@ void mball_to_mesh(ListBase *lb, Mesh *me)
mface->v4= index[3];
mface->flag= ME_SMOOTH;
- if(mface->v3==mface->v4)
- mface->v4= 0;
+ test_index_face(mface, NULL, 0, (mface->v3==mface->v4)? 3: 4);
mface++;
index+= 4;
@@ -1104,9 +1066,13 @@ float (*mesh_getRefKeyCos(Mesh *me, int *numVerts_r))[3]
if(me->key && me->key->refkey) {
if(numVerts_r) *numVerts_r= me->totvert;
- cos= MEM_mallocN(sizeof(*cos)*me->totvert, "vertexcos1");
-
+
kb= me->key->refkey;
+
+ /* prevent accessing invalid memory */
+ if (me->totvert > kb->totelem) cos= MEM_callocN(sizeof(*cos)*me->totvert, "vertexcos1");
+ else cos= MEM_mallocN(sizeof(*cos)*me->totvert, "vertexcos1");
+
totvert= MIN2(kb->totelem, me->totvert);
memcpy(cos, kb->data, sizeof(*cos)*totvert);
@@ -1136,12 +1102,12 @@ UvVertMap *make_uv_vert_map(struct MFace *mface, struct MTFace *tface, unsigned
if(totuv==0)
return NULL;
- vmap= (UvVertMap*)MEM_mallocN(sizeof(*vmap), "UvVertMap");
+ vmap= (UvVertMap*)MEM_callocN(sizeof(*vmap), "UvVertMap");
if (!vmap)
return NULL;
vmap->vert= (UvMapVert**)MEM_callocN(sizeof(*vmap->vert)*totvert, "UvMapVert*");
- buf= vmap->buf= (UvMapVert*)MEM_mallocN(sizeof(*vmap->buf)*totuv, "UvMapVert");
+ buf= vmap->buf= (UvMapVert*)MEM_callocN(sizeof(*vmap->buf)*totuv, "UvMapVert");
if (!vmap->vert || !vmap->buf) {
free_uv_vert_map(vmap);
diff --git a/source/blender/blenkernel/intern/modifier.c b/source/blender/blenkernel/intern/modifier.c
index 9b9e94774bc..eebd5e6d056 100644
--- a/source/blender/blenkernel/intern/modifier.c
+++ b/source/blender/blenkernel/intern/modifier.c
@@ -40,9 +40,11 @@
#include "stdarg.h"
#include "math.h"
#include "float.h"
+#include "ctype.h"
#include "BLI_arithb.h"
#include "BLI_blenlib.h"
+#include "BLI_kdopbvh.h"
#include "BLI_kdtree.h"
#include "BLI_linklist.h"
#include "BLI_rand.h"
@@ -52,7 +54,11 @@
#include "MEM_guardedalloc.h"
+#include "DNA_action_types.h"
#include "DNA_armature_types.h"
+#include "DNA_camera_types.h"
+#include "DNA_cloth_types.h"
+#include "DNA_curve_types.h"
#include "DNA_effect_types.h"
#include "DNA_material_types.h"
#include "DNA_mesh_types.h"
@@ -63,8 +69,6 @@
#include "DNA_particle_types.h"
#include "DNA_scene_types.h"
#include "DNA_texture_types.h"
-#include "DNA_curve_types.h"
-#include "DNA_camera_types.h"
#include "BLI_editVert.h"
@@ -73,25 +77,34 @@
#include "BKE_main.h"
#include "BKE_anim.h"
+#include "BKE_bmesh.h"
+#include "BKE_booleanops.h"
+#include "BKE_cloth.h"
+#include "BKE_collision.h"
+#include "BKE_cdderivedmesh.h"
#include "BKE_curve.h"
#include "BKE_customdata.h"
-#include "BKE_global.h"
-#include "BKE_cdderivedmesh.h"
#include "BKE_DerivedMesh.h"
-#include "BKE_booleanops.h"
#include "BKE_displist.h"
-#include "BKE_modifier.h"
+#include "BKE_fluidsim.h"
+#include "BKE_global.h"
#include "BKE_lattice.h"
#include "BKE_library.h"
-#include "BKE_subsurf.h"
-#include "BKE_object.h"
-#include "BKE_mesh.h"
-#include "BKE_softbody.h"
#include "BKE_material.h"
+#include "BKE_mesh.h"
+#include "BKE_modifier.h"
+#include "BKE_object.h"
#include "BKE_particle.h"
#include "BKE_pointcache.h"
+#include "BKE_softbody.h"
+#include "BKE_subsurf.h"
+#include "BKE_texture.h"
#include "BKE_utildefines.h"
+
#include "depsgraph_private.h"
+#include "BKE_deform.h"
+#include "BKE_shrinkwrap.h"
+#include "BKE_simple_deform.h"
//XXX #include "LOD_DependKludge.h"
#include "LOD_decimation.h"
@@ -147,9 +160,9 @@ static int curveModifier_isDisabled(ModifierData *md)
}
static void curveModifier_foreachObjectLink(
- ModifierData *md, Object *ob,
- void (*walk)(void *userData, Object *ob, Object **obpoin),
- void *userData)
+ ModifierData *md, Object *ob,
+ void (*walk)(void *userData, Object *ob, Object **obpoin),
+ void *userData)
{
CurveModifierData *cmd = (CurveModifierData*) md;
@@ -157,8 +170,8 @@ static void curveModifier_foreachObjectLink(
}
static void curveModifier_updateDepgraph(
- ModifierData *md, DagForest *forest,
- Object *ob, DagNode *obNode)
+ ModifierData *md, DagForest *forest,
+ Object *ob, DagNode *obNode)
{
CurveModifierData *cmd = (CurveModifierData*) md;
@@ -166,23 +179,23 @@ static void curveModifier_updateDepgraph(
DagNode *curNode = dag_get_node(forest, cmd->object);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Curve Modifier");
}
}
static void curveModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
CurveModifierData *cmd = (CurveModifierData*) md;
curve_deform_verts(cmd->object, ob, derivedData, vertexCos, numVerts,
- cmd->name, cmd->defaxis);
+ cmd->name, cmd->defaxis);
}
static void curveModifier_deformVertsEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm = derivedData;
@@ -223,9 +236,9 @@ static int latticeModifier_isDisabled(ModifierData *md)
}
static void latticeModifier_foreachObjectLink(
- ModifierData *md, Object *ob,
- void (*walk)(void *userData, Object *ob, Object **obpoin),
- void *userData)
+ ModifierData *md, Object *ob,
+ void (*walk)(void *userData, Object *ob, Object **obpoin),
+ void *userData)
{
LatticeModifierData *lmd = (LatticeModifierData*) md;
@@ -233,7 +246,7 @@ static void latticeModifier_foreachObjectLink(
}
static void latticeModifier_updateDepgraph(ModifierData *md, DagForest *forest,
- Object *ob, DagNode *obNode)
+ Object *ob, DagNode *obNode)
{
LatticeModifierData *lmd = (LatticeModifierData*) md;
@@ -241,7 +254,7 @@ static void latticeModifier_updateDepgraph(ModifierData *md, DagForest *forest,
DagNode *latNode = dag_get_node(forest, lmd->object);
dag_add_relation(forest, latNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Lattice Modifier");
}
}
@@ -260,8 +273,8 @@ static void modifier_vgroup_cache(ModifierData *md, float (*vertexCos)[3])
static void latticeModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
LatticeModifierData *lmd = (LatticeModifierData*) md;
@@ -269,12 +282,12 @@ static void latticeModifier_deformVerts(
modifier_vgroup_cache(md, vertexCos); /* if next modifier needs original vertices */
lattice_deform_verts(lmd->object, ob, derivedData,
- vertexCos, numVerts, lmd->name);
+ vertexCos, numVerts, lmd->name);
}
static void latticeModifier_deformVertsEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm = derivedData;
@@ -320,28 +333,28 @@ static void subsurfModifier_freeData(ModifierData *md)
}
static DerivedMesh *subsurfModifier_applyModifier(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- int useRenderParams, int isFinalCalc)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
{
SubsurfModifierData *smd = (SubsurfModifierData*) md;
DerivedMesh *result;
result = subsurf_make_derived_from_derived(derivedData, smd,
- useRenderParams, NULL,
- isFinalCalc, 0);
+ useRenderParams, NULL,
+ isFinalCalc, 0);
return result;
}
static DerivedMesh *subsurfModifier_applyModifierEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData)
{
SubsurfModifierData *smd = (SubsurfModifierData*) md;
DerivedMesh *result;
result = subsurf_make_derived_from_derived(derivedData, smd, 0,
- NULL, 0, 1);
+ NULL, 0, 1);
return result;
}
@@ -373,8 +386,8 @@ static int buildModifier_dependsOnTime(ModifierData *md)
}
static DerivedMesh *buildModifier_applyModifier(ModifierData *md, Object *ob,
- DerivedMesh *derivedData,
- int useRenderParams, int isFinalCalc)
+ DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
{
DerivedMesh *dm = derivedData;
DerivedMesh *result;
@@ -387,29 +400,29 @@ static DerivedMesh *buildModifier_applyModifier(ModifierData *md, Object *ob,
GHashIterator *hashIter;
/* maps vert indices in old mesh to indices in new mesh */
GHash *vertHash = BLI_ghash_new(BLI_ghashutil_inthash,
- BLI_ghashutil_intcmp);
+ BLI_ghashutil_intcmp);
/* maps edge indices in new mesh to indices in old mesh */
GHash *edgeHash = BLI_ghash_new(BLI_ghashutil_inthash,
- BLI_ghashutil_intcmp);
+ BLI_ghashutil_intcmp);
maxVerts = dm->getNumVerts(dm);
vertMap = MEM_callocN(sizeof(*vertMap) * maxVerts,
- "build modifier vertMap");
+ "build modifier vertMap");
for(i = 0; i < maxVerts; ++i) vertMap[i] = i;
maxEdges = dm->getNumEdges(dm);
edgeMap = MEM_callocN(sizeof(*edgeMap) * maxEdges,
- "build modifier edgeMap");
+ "build modifier edgeMap");
for(i = 0; i < maxEdges; ++i) edgeMap[i] = i;
maxFaces = dm->getNumFaces(dm);
faceMap = MEM_callocN(sizeof(*faceMap) * maxFaces,
- "build modifier faceMap");
+ "build modifier faceMap");
for(i = 0; i < maxFaces; ++i) faceMap[i] = i;
if (ob) {
frac = bsystem_time(ob, (float)G.scene->r.cfra,
- bmd->start - 1.0f) / bmd->length;
+ bmd->start - 1.0f) / bmd->length;
} else {
frac = G.scene->r.cfra - bmd->start / bmd->length;
}
@@ -424,156 +437,511 @@ static DerivedMesh *buildModifier_applyModifier(ModifierData *md, Object *ob,
if(bmd->randomize)
BLI_array_randomize(faceMap, sizeof(*faceMap),
- maxFaces, bmd->seed);
+ maxFaces, bmd->seed);
/* get the set of all vert indices that will be in the final mesh,
- * mapped to the new indices
- */
+ * mapped to the new indices
+ */
for(i = 0; i < numFaces; ++i) {
MFace mf;
dm->getFace(dm, faceMap[i], &mf);
- if(!BLI_ghash_haskey(vertHash, (void *)mf.v1))
- BLI_ghash_insert(vertHash, (void *)mf.v1,
- (void *)BLI_ghash_size(vertHash));
- if(!BLI_ghash_haskey(vertHash, (void *)mf.v2))
- BLI_ghash_insert(vertHash, (void *)mf.v2,
- (void *)BLI_ghash_size(vertHash));
- if(!BLI_ghash_haskey(vertHash, (void *)mf.v3))
- BLI_ghash_insert(vertHash, (void *)mf.v3,
- (void *)BLI_ghash_size(vertHash));
- if(mf.v4 && !BLI_ghash_haskey(vertHash, (void *)mf.v4))
- BLI_ghash_insert(vertHash, (void *)mf.v4,
- (void *)BLI_ghash_size(vertHash));
+ if(!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v1)))
+ BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(mf.v1),
+ SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
+ if(!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v2)))
+ BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(mf.v2),
+ SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
+ if(!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v3)))
+ BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(mf.v3),
+ SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
+ if(mf.v4 && !BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v4)))
+ BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(mf.v4),
+ SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
}
/* get the set of edges that will be in the new mesh (i.e. all edges
- * that have both verts in the new mesh)
- */
+ * that have both verts in the new mesh)
+ */
maxEdges = dm->getNumEdges(dm);
for(i = 0; i < maxEdges; ++i) {
MEdge me;
dm->getEdge(dm, i, &me);
- if(BLI_ghash_haskey(vertHash, (void *)me.v1)
- && BLI_ghash_haskey(vertHash, (void *)me.v2))
+ if(BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v1))
+ && BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v2)))
BLI_ghash_insert(edgeHash,
- (void *)BLI_ghash_size(edgeHash), (void *)i);
+ SET_INT_IN_POINTER(BLI_ghash_size(edgeHash)), SET_INT_IN_POINTER(i));
}
} else if(numEdges) {
if(bmd->randomize)
BLI_array_randomize(edgeMap, sizeof(*edgeMap),
- maxEdges, bmd->seed);
+ maxEdges, bmd->seed);
/* get the set of all vert indices that will be in the final mesh,
- * mapped to the new indices
- */
+ * mapped to the new indices
+ */
for(i = 0; i < numEdges; ++i) {
MEdge me;
dm->getEdge(dm, edgeMap[i], &me);
- if(!BLI_ghash_haskey(vertHash, (void *)me.v1))
- BLI_ghash_insert(vertHash, (void *)me.v1,
- (void *)BLI_ghash_size(vertHash));
- if(!BLI_ghash_haskey(vertHash, (void *)me.v2))
- BLI_ghash_insert(vertHash, (void *)me.v2,
- (void *)BLI_ghash_size(vertHash));
+ if(!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v1)))
+ BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(me.v1),
+ SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
+ if(!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v2)))
+ BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(me.v2),
+ SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
}
/* get the set of edges that will be in the new mesh
- */
+ */
for(i = 0; i < numEdges; ++i) {
MEdge me;
dm->getEdge(dm, edgeMap[i], &me);
- BLI_ghash_insert(edgeHash, (void *)BLI_ghash_size(edgeHash),
- (void *)edgeMap[i]);
+ BLI_ghash_insert(edgeHash, SET_INT_IN_POINTER(BLI_ghash_size(edgeHash)),
+ SET_INT_IN_POINTER(edgeMap[i]));
}
} else {
int numVerts = dm->getNumVerts(dm) * frac;
if(bmd->randomize)
BLI_array_randomize(vertMap, sizeof(*vertMap),
- maxVerts, bmd->seed);
+ maxVerts, bmd->seed);
/* get the set of all vert indices that will be in the final mesh,
- * mapped to the new indices
- */
+ * mapped to the new indices
+ */
for(i = 0; i < numVerts; ++i)
- BLI_ghash_insert(vertHash, (void *)vertMap[i], (void *)i);
+ BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(vertMap[i]), SET_INT_IN_POINTER(i));
}
/* now we know the number of verts, edges and faces, we can create
- * the mesh
- */
+ * the mesh
+ */
result = CDDM_from_template(dm, BLI_ghash_size(vertHash),
- BLI_ghash_size(edgeHash), numFaces);
+ BLI_ghash_size(edgeHash), numFaces);
/* copy the vertices across */
for(hashIter = BLI_ghashIterator_new(vertHash);
- !BLI_ghashIterator_isDone(hashIter);
- BLI_ghashIterator_step(hashIter)) {
+ !BLI_ghashIterator_isDone(hashIter);
+ BLI_ghashIterator_step(hashIter)) {
+ MVert source;
+ MVert *dest;
+ int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
+ int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
+
+ dm->getVert(dm, oldIndex, &source);
+ dest = CDDM_get_vert(result, newIndex);
+
+ DM_copy_vert_data(dm, result, oldIndex, newIndex, 1);
+ *dest = source;
+ }
+ BLI_ghashIterator_free(hashIter);
+
+ /* copy the edges across, remapping indices */
+ for(i = 0; i < BLI_ghash_size(edgeHash); ++i) {
+ MEdge source;
+ MEdge *dest;
+ int oldIndex = GET_INT_FROM_POINTER(BLI_ghash_lookup(edgeHash, SET_INT_IN_POINTER(i)));
+
+ dm->getEdge(dm, oldIndex, &source);
+ dest = CDDM_get_edge(result, i);
+
+ source.v1 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v1)));
+ source.v2 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v2)));
+
+ DM_copy_edge_data(dm, result, oldIndex, i, 1);
+ *dest = source;
+ }
+
+ /* copy the faces across, remapping indices */
+ for(i = 0; i < numFaces; ++i) {
+ MFace source;
+ MFace *dest;
+ int orig_v4;
+
+ dm->getFace(dm, faceMap[i], &source);
+ dest = CDDM_get_face(result, i);
+
+ orig_v4 = source.v4;
+
+ source.v1 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v1)));
+ source.v2 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v2)));
+ source.v3 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v3)));
+ if(source.v4)
+ source.v4 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v4)));
+
+ DM_copy_face_data(dm, result, faceMap[i], i, 1);
+ *dest = source;
+
+ test_index_face(dest, &result->faceData, i, (orig_v4 ? 4 : 3));
+ }
+
+ CDDM_calc_normals(result);
+
+ BLI_ghash_free(vertHash, NULL, NULL);
+ BLI_ghash_free(edgeHash, NULL, NULL);
+
+ MEM_freeN(vertMap);
+ MEM_freeN(edgeMap);
+ MEM_freeN(faceMap);
+
+ return result;
+}
+
+/* Mask */
+
+static void maskModifier_copyData(ModifierData *md, ModifierData *target)
+{
+ MaskModifierData *mmd = (MaskModifierData*) md;
+ MaskModifierData *tmmd = (MaskModifierData*) target;
+
+ strcpy(tmmd->vgroup, mmd->vgroup);
+}
+
+static CustomDataMask maskModifier_requiredDataMask(ModifierData *md)
+{
+ return (1 << CD_MDEFORMVERT);
+}
+
+static void maskModifier_foreachObjectLink(
+ ModifierData *md, Object *ob,
+ void (*walk)(void *userData, Object *ob, Object **obpoin),
+ void *userData)
+{
+ MaskModifierData *mmd = (MaskModifierData *)md;
+ walk(userData, ob, &mmd->ob_arm);
+}
+
+static void maskModifier_updateDepgraph(ModifierData *md, DagForest *forest,
+ Object *ob, DagNode *obNode)
+{
+ MaskModifierData *mmd = (MaskModifierData *)md;
+
+ if (mmd->ob_arm)
+ {
+ DagNode *armNode = dag_get_node(forest, mmd->ob_arm);
+
+ dag_add_relation(forest, armNode, obNode,
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Mask Modifier");
+ }
+}
+
+static DerivedMesh *maskModifier_applyModifier(ModifierData *md, Object *ob,
+ DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
+{
+ MaskModifierData *mmd= (MaskModifierData *)md;
+ DerivedMesh *dm= derivedData, *result= NULL;
+ GHash *vertHash=NULL, *edgeHash, *faceHash;
+ GHashIterator *hashIter;
+ MDeformVert *dvert= NULL;
+ int numFaces=0, numEdges=0, numVerts=0;
+ int maxVerts, maxEdges, maxFaces;
+ int i;
+
+ /* Overview of Method:
+ * 1. Get the vertices that are in the vertexgroup of interest
+ * 2. Filter out unwanted geometry (i.e. not in vertexgroup), by populating mappings with new vs old indices
+ * 3. Make a new mesh containing only the mapping data
+ */
+
+ /* get original number of verts, edges, and faces */
+ maxVerts= dm->getNumVerts(dm);
+ maxEdges= dm->getNumEdges(dm);
+ maxFaces= dm->getNumFaces(dm);
+
+ /* check if we can just return the original mesh
+ * - must have verts and therefore verts assigned to vgroups to do anything useful
+ */
+ if ( !(ELEM(mmd->mode, MOD_MASK_MODE_ARM, MOD_MASK_MODE_VGROUP)) ||
+ (maxVerts == 0) || (ob->defbase.first == NULL) )
+ {
+ return derivedData;
+ }
+
+ /* if mode is to use selected armature bones, aggregate the bone groups */
+ if (mmd->mode == MOD_MASK_MODE_ARM) /* --- using selected bones --- */
+ {
+ GHash *vgroupHash, *boneHash;
+ Object *oba= mmd->ob_arm;
+ bPoseChannel *pchan;
+ bDeformGroup *def;
+
+ /* check that there is armature object with bones to use, otherwise return original mesh */
+ if (ELEM(NULL, mmd->ob_arm, mmd->ob_arm->pose))
+ return derivedData;
+
+ /* hashes for finding mapping of:
+ * - vgroups to indicies -> vgroupHash (string, int)
+ * - bones to vgroup indices -> boneHash (index of vgroup, dummy)
+ */
+ vgroupHash= BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp);
+ boneHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp);
+
+ /* build mapping of names of vertex groups to indices */
+ for (i = 0, def = ob->defbase.first; def; def = def->next, i++)
+ BLI_ghash_insert(vgroupHash, def->name, SET_INT_IN_POINTER(i));
+
+ /* get selected-posechannel <-> vertexgroup index mapping */
+ for (pchan= oba->pose->chanbase.first; pchan; pchan= pchan->next)
+ {
+ /* check if bone is selected */
+ // TODO: include checks for visibility too?
+ // FIXME: the depsgraph needs extensions to make this work in realtime...
+ if ( (pchan->bone) && (pchan->bone->flag & BONE_SELECTED) )
+ {
+ /* check if hash has group for this bone */
+ if (BLI_ghash_haskey(vgroupHash, pchan->name))
+ {
+ int defgrp_index= GET_INT_FROM_POINTER(BLI_ghash_lookup(vgroupHash, pchan->name));
+
+ /* add index to hash (store under key only) */
+ BLI_ghash_insert(boneHash, SET_INT_IN_POINTER(defgrp_index), pchan);
+ }
+ }
+ }
+
+ /* if no bones selected, free hashes and return original mesh */
+ if (BLI_ghash_size(boneHash) == 0)
+ {
+ BLI_ghash_free(vgroupHash, NULL, NULL);
+ BLI_ghash_free(boneHash, NULL, NULL);
+
+ return derivedData;
+ }
+
+ /* repeat the previous check, but for dverts */
+ dvert= dm->getVertDataArray(dm, CD_MDEFORMVERT);
+ if (dvert == NULL)
+ {
+ BLI_ghash_free(vgroupHash, NULL, NULL);
+ BLI_ghash_free(boneHash, NULL, NULL);
+
+ return derivedData;
+ }
+
+ /* hashes for quickly providing a mapping from old to new - use key=oldindex, value=newindex */
+ vertHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp);
+
+ /* add vertices which exist in vertexgroups into vertHash for filtering */
+ for (i = 0; i < maxVerts; i++)
+ {
+ MDeformWeight *def_weight = NULL;
+ int j;
+
+ for (j= 0; j < dvert[i].totweight; j++)
+ {
+ if (BLI_ghash_haskey(boneHash, SET_INT_IN_POINTER(dvert[i].dw[j].def_nr)))
+ {
+ def_weight = &dvert[i].dw[j];
+ break;
+ }
+ }
+
+ /* check if include vert in vertHash */
+ if (mmd->flag & MOD_MASK_INV) {
+ /* if this vert is in the vgroup, don't include it in vertHash */
+ if (def_weight) continue;
+ }
+ else {
+ /* if this vert isn't in the vgroup, don't include it in vertHash */
+ if (!def_weight) continue;
+ }
+
+ /* add to ghash for verts (numVerts acts as counter for mapping) */
+ BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numVerts));
+ numVerts++;
+ }
+
+ /* free temp hashes */
+ BLI_ghash_free(vgroupHash, NULL, NULL);
+ BLI_ghash_free(boneHash, NULL, NULL);
+ }
+ else /* --- Using Nominated VertexGroup only --- */
+ {
+ int defgrp_index = -1;
+
+ /* get index of vertex group */
+ if (mmd->vgroup[0])
+ {
+ bDeformGroup *def;
+
+ /* find index by comparing names - SLOW... */
+ for (i = 0, def = ob->defbase.first; def; def = def->next, i++)
+ {
+ if (!strcmp(def->name, mmd->vgroup))
+ {
+ defgrp_index = i;
+ break;
+ }
+ }
+ }
+
+ /* get dverts */
+ if (defgrp_index >= 0)
+ dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
+
+ /* if no vgroup (i.e. dverts) found, return the initial mesh */
+ if ((defgrp_index < 0) || (dvert == NULL))
+ return dm;
+
+ /* hashes for quickly providing a mapping from old to new - use key=oldindex, value=newindex */
+ vertHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp);
+
+ /* add vertices which exist in vertexgroup into ghash for filtering */
+ for (i = 0; i < maxVerts; i++)
+ {
+ MDeformWeight *def_weight = NULL;
+ int j;
+
+ for (j= 0; j < dvert[i].totweight; j++)
+ {
+ if (dvert[i].dw[j].def_nr == defgrp_index)
+ {
+ def_weight = &dvert[i].dw[j];
+ break;
+ }
+ }
+
+ /* check if include vert in vertHash */
+ if (mmd->flag & MOD_MASK_INV) {
+ /* if this vert is in the vgroup, don't include it in vertHash */
+ if (def_weight) continue;
+ }
+ else {
+ /* if this vert isn't in the vgroup, don't include it in vertHash */
+ if (!def_weight) continue;
+ }
+
+ /* add to ghash for verts (numVerts acts as counter for mapping) */
+ BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numVerts));
+ numVerts++;
+ }
+ }
+
+ /* hashes for quickly providing a mapping from old to new - use key=oldindex, value=newindex */
+ edgeHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp);
+ faceHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp);
+
+ /* loop over edges and faces, and do the same thing to
+ * ensure that they only reference existing verts
+ */
+ for (i = 0; i < maxEdges; i++)
+ {
+ MEdge me;
+ dm->getEdge(dm, i, &me);
+
+ /* only add if both verts will be in new mesh */
+ if ( BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v1)) &&
+ BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v2)) )
+ {
+ BLI_ghash_insert(edgeHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numEdges));
+ numEdges++;
+ }
+ }
+ for (i = 0; i < maxFaces; i++)
+ {
+ MFace mf;
+ dm->getFace(dm, i, &mf);
+
+ /* all verts must be available */
+ if ( BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v1)) &&
+ BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v2)) &&
+ BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v3)) &&
+ (mf.v4==0 || BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v4))) )
+ {
+ BLI_ghash_insert(faceHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numFaces));
+ numFaces++;
+ }
+ }
+
+
+ /* now we know the number of verts, edges and faces,
+ * we can create the new (reduced) mesh
+ */
+ result = CDDM_from_template(dm, numVerts, numEdges, numFaces);
+
+
+ /* using ghash-iterators, map data into new mesh */
+ /* vertices */
+ for ( hashIter = BLI_ghashIterator_new(vertHash);
+ !BLI_ghashIterator_isDone(hashIter);
+ BLI_ghashIterator_step(hashIter) )
+ {
MVert source;
MVert *dest;
- int oldIndex = (int)BLI_ghashIterator_getKey(hashIter);
- int newIndex = (int)BLI_ghashIterator_getValue(hashIter);
-
+ int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
+ int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
+
dm->getVert(dm, oldIndex, &source);
dest = CDDM_get_vert(result, newIndex);
-
+
DM_copy_vert_data(dm, result, oldIndex, newIndex, 1);
*dest = source;
}
BLI_ghashIterator_free(hashIter);
-
- /* copy the edges across, remapping indices */
- for(i = 0; i < BLI_ghash_size(edgeHash); ++i) {
+
+ /* edges */
+ for ( hashIter = BLI_ghashIterator_new(edgeHash);
+ !BLI_ghashIterator_isDone(hashIter);
+ BLI_ghashIterator_step(hashIter) )
+ {
MEdge source;
MEdge *dest;
- int oldIndex = (int)BLI_ghash_lookup(edgeHash, (void *)i);
-
+ int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
+ int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
+
dm->getEdge(dm, oldIndex, &source);
- dest = CDDM_get_edge(result, i);
-
- source.v1 = (int)BLI_ghash_lookup(vertHash, (void *)source.v1);
- source.v2 = (int)BLI_ghash_lookup(vertHash, (void *)source.v2);
-
- DM_copy_edge_data(dm, result, oldIndex, i, 1);
+ dest = CDDM_get_edge(result, newIndex);
+
+ source.v1 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v1)));
+ source.v2 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v2)));
+
+ DM_copy_edge_data(dm, result, oldIndex, newIndex, 1);
*dest = source;
}
-
- /* copy the faces across, remapping indices */
- for(i = 0; i < numFaces; ++i) {
+ BLI_ghashIterator_free(hashIter);
+
+ /* faces */
+ for ( hashIter = BLI_ghashIterator_new(faceHash);
+ !BLI_ghashIterator_isDone(hashIter);
+ BLI_ghashIterator_step(hashIter) )
+ {
MFace source;
MFace *dest;
+ int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
+ int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
int orig_v4;
-
- dm->getFace(dm, faceMap[i], &source);
- dest = CDDM_get_face(result, i);
-
+
+ dm->getFace(dm, oldIndex, &source);
+ dest = CDDM_get_face(result, newIndex);
+
orig_v4 = source.v4;
-
- source.v1 = (int)BLI_ghash_lookup(vertHash, (void *)source.v1);
- source.v2 = (int)BLI_ghash_lookup(vertHash, (void *)source.v2);
- source.v3 = (int)BLI_ghash_lookup(vertHash, (void *)source.v3);
- if(source.v4)
- source.v4 = (int)BLI_ghash_lookup(vertHash, (void *)source.v4);
-
- DM_copy_face_data(dm, result, faceMap[i], i, 1);
+
+ source.v1 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v1)));
+ source.v2 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v2)));
+ source.v3 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v3)));
+ if (source.v4)
+ source.v4 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v4)));
+
+ DM_copy_face_data(dm, result, oldIndex, newIndex, 1);
*dest = source;
-
- test_index_face(dest, &result->faceData, i, (orig_v4 ? 4 : 3));
+
+ test_index_face(dest, &result->faceData, newIndex, (orig_v4 ? 4 : 3));
}
-
+ BLI_ghashIterator_free(hashIter);
+
+ /* recalculate normals */
CDDM_calc_normals(result);
-
+
+ /* free hashes */
BLI_ghash_free(vertHash, NULL, NULL);
BLI_ghash_free(edgeHash, NULL, NULL);
-
- MEM_freeN(vertMap);
- MEM_freeN(edgeMap);
- MEM_freeN(faceMap);
-
+ BLI_ghash_free(faceHash, NULL, NULL);
+
+ /* return the new mesh */
return result;
}
@@ -586,7 +954,7 @@ static void arrayModifier_initData(ModifierData *md)
ArrayModifierData *amd = (ArrayModifierData*) md;
/* default to 2 duplicates distributed along the x-axis by an
- offset of 1 object-width
+ offset of 1 object-width
*/
amd->start_cap = amd->end_cap = amd->curve_ob = amd->offset_ob = NULL;
amd->count = 2;
@@ -620,9 +988,9 @@ static void arrayModifier_copyData(ModifierData *md, ModifierData *target)
}
static void arrayModifier_foreachObjectLink(
- ModifierData *md, Object *ob,
- void (*walk)(void *userData, Object *ob, Object **obpoin),
- void *userData)
+ ModifierData *md, Object *ob,
+ void (*walk)(void *userData, Object *ob, Object **obpoin),
+ void *userData)
{
ArrayModifierData *amd = (ArrayModifierData*) md;
@@ -633,7 +1001,7 @@ static void arrayModifier_foreachObjectLink(
}
static void arrayModifier_updateDepgraph(ModifierData *md, DagForest *forest,
- Object *ob, DagNode *obNode)
+ Object *ob, DagNode *obNode)
{
ArrayModifierData *amd = (ArrayModifierData*) md;
@@ -641,25 +1009,25 @@ static void arrayModifier_updateDepgraph(ModifierData *md, DagForest *forest,
DagNode *curNode = dag_get_node(forest, amd->start_cap);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Array Modifier");
}
if (amd->end_cap) {
DagNode *curNode = dag_get_node(forest, amd->end_cap);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Array Modifier");
}
if (amd->curve_ob) {
DagNode *curNode = dag_get_node(forest, amd->curve_ob);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Array Modifier");
}
if (amd->offset_ob) {
DagNode *curNode = dag_get_node(forest, amd->offset_ob);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Array Modifier");
}
}
@@ -686,12 +1054,12 @@ typedef struct IndexMapEntry {
/* the new vert index that this old vert index maps to */
int new;
/* -1 if this vert isn't merged, otherwise the old vert index it
- * should be replaced with
- */
+ * should be replaced with
+ */
int merge;
/* 1 if this vert's first copy is merged with the last copy of its
- * merge target, otherwise 0
- */
+ * merge target, otherwise 0
+ */
short merge_final;
} IndexMapEntry;
@@ -710,19 +1078,19 @@ static int calc_mapping(IndexMapEntry *indexMap, int oldIndex, int copyNum)
} else {
/* vert was merged with another vert */
/* follow the chain of merges to the end, or until we've passed
- * a number of vertices equal to the copy number
- */
+ * a number of vertices equal to the copy number
+ */
if(copyNum <= 0)
return indexMap[oldIndex].new;
else
return calc_mapping(indexMap, indexMap[oldIndex].merge,
- copyNum - 1);
+ copyNum - 1);
}
}
static DerivedMesh *arrayModifier_doArray(ArrayModifierData *amd,
- Object *ob, DerivedMesh *dm,
- int initFlags)
+ Object *ob, DerivedMesh *dm,
+ int initFlags)
{
int i, j;
/* offset matrix */
@@ -752,7 +1120,7 @@ static DerivedMesh *arrayModifier_doArray(ArrayModifierData *amd,
MTC_Mat4One(offset);
indexMap = MEM_callocN(sizeof(*indexMap) * dm->getNumVerts(dm),
- "indexmap");
+ "indexmap");
src_mvert = dm->getVertArray(dm);
@@ -763,7 +1131,7 @@ static DerivedMesh *arrayModifier_doArray(ArrayModifierData *amd,
if(amd->offset_type & MOD_ARR_OFF_RELATIVE) {
for(j = 0; j < 3; j++)
offset[3][j] += amd->scale[j] * vertarray_size(src_mvert,
- maxVerts, j);
+ maxVerts, j);
}
if((amd->offset_type & MOD_ARR_OFF_OBJ) && (amd->offset_ob)) {
@@ -776,472 +1144,509 @@ static DerivedMesh *arrayModifier_doArray(ArrayModifierData *amd,
MTC_Mat4One(obinv);
MTC_Mat4MulSerie(result_mat, offset,
- obinv, amd->offset_ob->obmat,
- NULL, NULL, NULL, NULL, NULL);
+ obinv, amd->offset_ob->obmat,
+ NULL, NULL, NULL, NULL, NULL);
MTC_Mat4CpyMat4(offset, result_mat);
}
if(amd->fit_type == MOD_ARR_FITCURVE && amd->curve_ob) {
Curve *cu = amd->curve_ob->data;
if(cu) {
+ float tmp_mat[3][3];
+ float scale;
+
+ object_to_mat3(amd->curve_ob, tmp_mat);
+ scale = Mat3ToScalef(tmp_mat);
+
if(!cu->path) {
cu->flag |= CU_PATH; // needed for path & bevlist
makeDispListCurveTypes(amd->curve_ob, 0);
}
if(cu->path)
- length = cu->path->totdist;
+ length = scale*cu->path->totdist;
}
}
/* calculate the maximum number of copies which will fit within the
- prescribed length */
+ prescribed length */
if(amd->fit_type == MOD_ARR_FITLENGTH
- || amd->fit_type == MOD_ARR_FITCURVE) {
+ || amd->fit_type == MOD_ARR_FITCURVE) {
float dist = sqrt(MTC_dot3Float(offset[3], offset[3]));
- if(dist > FLT_EPSILON)
+ if(dist > 1e-6f)
/* this gives length = first copy start to last copy end
- add a tiny offset for floating point rounding errors */
- count = (length + FLT_EPSILON) / dist;
+ add a tiny offset for floating point rounding errors */
+ count = (length + 1e-6f) / dist;
else
/* if the offset has no translation, just make one copy */
count = 1;
- }
+ }
- if(count < 1)
- count = 1;
+ if(count < 1)
+ count = 1;
/* allocate memory for count duplicates (including original) plus
- * start and end caps
- */
- finalVerts = dm->getNumVerts(dm) * count;
- finalEdges = dm->getNumEdges(dm) * count;
- finalFaces = dm->getNumFaces(dm) * count;
- if(start_cap) {
- finalVerts += start_cap->getNumVerts(start_cap);
- finalEdges += start_cap->getNumEdges(start_cap);
- finalFaces += start_cap->getNumFaces(start_cap);
- }
- if(end_cap) {
- finalVerts += end_cap->getNumVerts(end_cap);
- finalEdges += end_cap->getNumEdges(end_cap);
- finalFaces += end_cap->getNumFaces(end_cap);
- }
- result = CDDM_from_template(dm, finalVerts, finalEdges, finalFaces);
-
- /* calculate the offset matrix of the final copy (for merging) */
- MTC_Mat4One(final_offset);
-
- for(j=0; j < count - 1; j++) {
- MTC_Mat4MulMat4(tmp_mat, final_offset, offset);
- MTC_Mat4CpyMat4(final_offset, tmp_mat);
- }
-
- numVerts = numEdges = numFaces = 0;
- mvert = CDDM_get_verts(result);
-
- for (i = 0; i < maxVerts; i++) {
- MVert *inMV;
- MVert *mv = &mvert[numVerts];
- MVert *mv2;
- float co[3];
-
- inMV = &src_mvert[i];
-
- DM_copy_vert_data(dm, result, i, numVerts, 1);
- *mv = *inMV;
- numVerts++;
-
- indexMap[i].new = numVerts - 1;
- indexMap[i].merge = -1; /* default to no merge */
- indexMap[i].merge_final = 0; /* default to no merge */
-
- VECCOPY(co, mv->co);
+ * start and end caps
+ */
+ finalVerts = dm->getNumVerts(dm) * count;
+ finalEdges = dm->getNumEdges(dm) * count;
+ finalFaces = dm->getNumFaces(dm) * count;
+ if(start_cap) {
+ finalVerts += start_cap->getNumVerts(start_cap);
+ finalEdges += start_cap->getNumEdges(start_cap);
+ finalFaces += start_cap->getNumFaces(start_cap);
+ }
+ if(end_cap) {
+ finalVerts += end_cap->getNumVerts(end_cap);
+ finalEdges += end_cap->getNumEdges(end_cap);
+ finalFaces += end_cap->getNumFaces(end_cap);
+ }
+ result = CDDM_from_template(dm, finalVerts, finalEdges, finalFaces);
+
+ /* calculate the offset matrix of the final copy (for merging) */
+ MTC_Mat4One(final_offset);
+
+ for(j=0; j < count - 1; j++) {
+ MTC_Mat4MulMat4(tmp_mat, final_offset, offset);
+ MTC_Mat4CpyMat4(final_offset, tmp_mat);
+ }
+
+ numVerts = numEdges = numFaces = 0;
+ mvert = CDDM_get_verts(result);
+
+ for (i = 0; i < maxVerts; i++) {
+ indexMap[i].merge = -1; /* default to no merge */
+ indexMap[i].merge_final = 0; /* default to no merge */
+ }
+
+ for (i = 0; i < maxVerts; i++) {
+ MVert *inMV;
+ MVert *mv = &mvert[numVerts];
+ MVert *mv2;
+ float co[3];
+
+ inMV = &src_mvert[i];
+
+ DM_copy_vert_data(dm, result, i, numVerts, 1);
+ *mv = *inMV;
+ numVerts++;
+
+ indexMap[i].new = numVerts - 1;
+
+ VECCOPY(co, mv->co);
/* Attempts to merge verts from one duplicate with verts from the
- * next duplicate which are closer than amd->merge_dist.
- * Only the first such vert pair is merged.
- * If verts are merged in the first duplicate pair, they are merged
- * in all pairs.
- */
- if((count > 1) && (amd->flags & MOD_ARR_MERGE)) {
- float tmp_co[3];
- VECCOPY(tmp_co, mv->co);
- MTC_Mat4MulVecfl(offset, tmp_co);
-
- for(j = 0; j < maxVerts; j++) {
- inMV = &src_mvert[j];
- /* if this vert is within merge limit, merge */
- if(VecLenCompare(tmp_co, inMV->co, amd->merge_dist)) {
- indexMap[i].merge = j;
-
- /* test for merging with final copy of merge target */
- if(amd->flags & MOD_ARR_MERGEFINAL) {
- VECCOPY(tmp_co, inMV->co);
- inMV = &src_mvert[i];
- MTC_Mat4MulVecfl(final_offset, tmp_co);
- if(VecLenCompare(tmp_co, inMV->co, amd->merge_dist))
- indexMap[i].merge_final = 1;
- }
- break;
- }
- }
- }
-
- /* if no merging, generate copies of this vert */
- if(indexMap[i].merge < 0) {
- for(j=0; j < count - 1; j++) {
- mv2 = &mvert[numVerts];
-
- DM_copy_vert_data(result, result, numVerts - 1, numVerts, 1);
- *mv2 = *mv;
- numVerts++;
-
- MTC_Mat4MulVecfl(offset, co);
- VECCOPY(mv2->co, co);
- }
- } else if(indexMap[i].merge != i && indexMap[i].merge_final) {
+ * next duplicate which are closer than amd->merge_dist.
+ * Only the first such vert pair is merged.
+ * If verts are merged in the first duplicate pair, they are merged
+ * in all pairs.
+ */
+ if((count > 1) && (amd->flags & MOD_ARR_MERGE)) {
+ float tmp_co[3];
+ VECCOPY(tmp_co, mv->co);
+ MTC_Mat4MulVecfl(offset, tmp_co);
+
+ for(j = 0; j < maxVerts; j++) {
+ /* if vertex already merged, don't use it */
+ if( indexMap[j].merge != -1 ) continue;
+
+ inMV = &src_mvert[j];
+ /* if this vert is within merge limit, merge */
+ if(VecLenCompare(tmp_co, inMV->co, amd->merge_dist)) {
+ indexMap[i].merge = j;
+
+ /* test for merging with final copy of merge target */
+ if(amd->flags & MOD_ARR_MERGEFINAL) {
+ VECCOPY(tmp_co, inMV->co);
+ inMV = &src_mvert[i];
+ MTC_Mat4MulVecfl(final_offset, tmp_co);
+ if(VecLenCompare(tmp_co, inMV->co, amd->merge_dist))
+ indexMap[i].merge_final = 1;
+ }
+ break;
+ }
+ }
+ }
+
+ /* if no merging, generate copies of this vert */
+ if(indexMap[i].merge < 0) {
+ for(j=0; j < count - 1; j++) {
+ mv2 = &mvert[numVerts];
+
+ DM_copy_vert_data(result, result, numVerts - 1, numVerts, 1);
+ *mv2 = *mv;
+ numVerts++;
+
+ MTC_Mat4MulVecfl(offset, co);
+ VECCOPY(mv2->co, co);
+ }
+ } else if(indexMap[i].merge != i && indexMap[i].merge_final) {
/* if this vert is not merging with itself, and it is merging
- * with the final copy of its merge target, remove the first copy
- */
- numVerts--;
- DM_free_vert_data(result, numVerts, 1);
- }
- }
-
- /* make a hashtable so we can avoid duplicate edges from merging */
- edges = BLI_edgehash_new();
-
- maxEdges = dm->getNumEdges(dm);
- medge = CDDM_get_edges(result);
- for(i = 0; i < maxEdges; i++) {
- MEdge inMED;
- MEdge med;
- MEdge *med2;
- int vert1, vert2;
-
- dm->getEdge(dm, i, &inMED);
-
- med = inMED;
- med.v1 = indexMap[inMED.v1].new;
- med.v2 = indexMap[inMED.v2].new;
+ * with the final copy of its merge target, remove the first copy
+ */
+ numVerts--;
+ DM_free_vert_data(result, numVerts, 1);
+ }
+ }
+
+ /* make a hashtable so we can avoid duplicate edges from merging */
+ edges = BLI_edgehash_new();
+
+ maxEdges = dm->getNumEdges(dm);
+ medge = CDDM_get_edges(result);
+ for(i = 0; i < maxEdges; i++) {
+ MEdge inMED;
+ MEdge med;
+ MEdge *med2;
+ int vert1, vert2;
+
+ dm->getEdge(dm, i, &inMED);
+
+ med = inMED;
+ med.v1 = indexMap[inMED.v1].new;
+ med.v2 = indexMap[inMED.v2].new;
/* if vertices are to be merged with the final copies of their
- * merge targets, calculate that final copy
- */
- if(indexMap[inMED.v1].merge_final) {
- med.v1 = calc_mapping(indexMap, indexMap[inMED.v1].merge,
- count - 1);
- }
- if(indexMap[inMED.v2].merge_final) {
- med.v2 = calc_mapping(indexMap, indexMap[inMED.v2].merge,
- count - 1);
- }
-
- if (initFlags) {
- med.flag |= ME_EDGEDRAW | ME_EDGERENDER;
- }
-
- if(!BLI_edgehash_haskey(edges, med.v1, med.v2)) {
- DM_copy_edge_data(dm, result, i, numEdges, 1);
- medge[numEdges] = med;
- numEdges++;
-
- BLI_edgehash_insert(edges, med.v1, med.v2, NULL);
- }
-
- for(j = 1; j < count; j++)
- {
- vert1 = calc_mapping(indexMap, inMED.v1, j);
- vert2 = calc_mapping(indexMap, inMED.v2, j);
- /* avoid duplicate edges */
- if(!BLI_edgehash_haskey(edges, vert1, vert2)) {
- med2 = &medge[numEdges];
-
- DM_copy_edge_data(dm, result, i, numEdges, 1);
- *med2 = med;
- numEdges++;
-
- med2->v1 = vert1;
- med2->v2 = vert2;
-
- BLI_edgehash_insert(edges, med2->v1, med2->v2, NULL);
- }
- }
- }
-
- maxFaces = dm->getNumFaces(dm);
- mface = CDDM_get_faces(result);
- for (i=0; i < maxFaces; i++) {
- MFace inMF;
- MFace *mf = &mface[numFaces];
-
- dm->getFace(dm, i, &inMF);
-
- DM_copy_face_data(dm, result, i, numFaces, 1);
- *mf = inMF;
-
- mf->v1 = indexMap[inMF.v1].new;
- mf->v2 = indexMap[inMF.v2].new;
- mf->v3 = indexMap[inMF.v3].new;
- if(inMF.v4)
- mf->v4 = indexMap[inMF.v4].new;
+ * merge targets, calculate that final copy
+ */
+ if(indexMap[inMED.v1].merge_final) {
+ med.v1 = calc_mapping(indexMap, indexMap[inMED.v1].merge,
+ count - 1);
+ }
+ if(indexMap[inMED.v2].merge_final) {
+ med.v2 = calc_mapping(indexMap, indexMap[inMED.v2].merge,
+ count - 1);
+ }
+
+ if(med.v1 == med.v2) continue;
+
+ if (initFlags) {
+ med.flag |= ME_EDGEDRAW | ME_EDGERENDER;
+ }
+
+ if(!BLI_edgehash_haskey(edges, med.v1, med.v2)) {
+ DM_copy_edge_data(dm, result, i, numEdges, 1);
+ medge[numEdges] = med;
+ numEdges++;
+
+ BLI_edgehash_insert(edges, med.v1, med.v2, NULL);
+ }
+
+ for(j = 1; j < count; j++)
+ {
+ vert1 = calc_mapping(indexMap, inMED.v1, j);
+ vert2 = calc_mapping(indexMap, inMED.v2, j);
+ /* avoid duplicate edges */
+ if(!BLI_edgehash_haskey(edges, vert1, vert2)) {
+ med2 = &medge[numEdges];
+
+ DM_copy_edge_data(dm, result, i, numEdges, 1);
+ *med2 = med;
+ numEdges++;
+
+ med2->v1 = vert1;
+ med2->v2 = vert2;
+
+ BLI_edgehash_insert(edges, med2->v1, med2->v2, NULL);
+ }
+ }
+ }
+
+ maxFaces = dm->getNumFaces(dm);
+ mface = CDDM_get_faces(result);
+ for (i=0; i < maxFaces; i++) {
+ MFace inMF;
+ MFace *mf = &mface[numFaces];
+
+ dm->getFace(dm, i, &inMF);
+
+ DM_copy_face_data(dm, result, i, numFaces, 1);
+ *mf = inMF;
+
+ mf->v1 = indexMap[inMF.v1].new;
+ mf->v2 = indexMap[inMF.v2].new;
+ mf->v3 = indexMap[inMF.v3].new;
+ if(inMF.v4)
+ mf->v4 = indexMap[inMF.v4].new;
/* if vertices are to be merged with the final copies of their
- * merge targets, calculate that final copy
- */
- if(indexMap[inMF.v1].merge_final)
- mf->v1 = calc_mapping(indexMap, indexMap[inMF.v1].merge, count-1);
- if(indexMap[inMF.v2].merge_final)
- mf->v2 = calc_mapping(indexMap, indexMap[inMF.v2].merge, count-1);
- if(indexMap[inMF.v3].merge_final)
- mf->v3 = calc_mapping(indexMap, indexMap[inMF.v3].merge, count-1);
- if(inMF.v4 && indexMap[inMF.v4].merge_final)
- mf->v4 = calc_mapping(indexMap, indexMap[inMF.v4].merge, count-1);
-
- test_index_face(mf, &result->faceData, numFaces, inMF.v4?4:3);
- numFaces++;
-
- /* if the face has fewer than 3 vertices, don't create it */
- if(mf->v3 == 0) {
- numFaces--;
- DM_free_face_data(result, numFaces, 1);
- }
-
- for(j = 1; j < count; j++)
- {
- MFace *mf2 = &mface[numFaces];
-
- DM_copy_face_data(dm, result, i, numFaces, 1);
- *mf2 = *mf;
-
- mf2->v1 = calc_mapping(indexMap, inMF.v1, j);
- mf2->v2 = calc_mapping(indexMap, inMF.v2, j);
- mf2->v3 = calc_mapping(indexMap, inMF.v3, j);
- if (inMF.v4)
- mf2->v4 = calc_mapping(indexMap, inMF.v4, j);
-
- test_index_face(mf2, &result->faceData, numFaces, inMF.v4?4:3);
- numFaces++;
-
- /* if the face has fewer than 3 vertices, don't create it */
- if(mf2->v3 == 0) {
- numFaces--;
- DM_free_face_data(result, numFaces, 1);
- }
- }
- }
-
- /* add start and end caps */
- if(start_cap) {
- float startoffset[4][4];
- MVert *cap_mvert;
- MEdge *cap_medge;
- MFace *cap_mface;
- int *origindex;
- int *vert_map;
- int capVerts, capEdges, capFaces;
-
- capVerts = start_cap->getNumVerts(start_cap);
- capEdges = start_cap->getNumEdges(start_cap);
- capFaces = start_cap->getNumFaces(start_cap);
- cap_mvert = start_cap->getVertArray(start_cap);
- cap_medge = start_cap->getEdgeArray(start_cap);
- cap_mface = start_cap->getFaceArray(start_cap);
-
- Mat4Invert(startoffset, offset);
-
- vert_map = MEM_callocN(sizeof(*vert_map) * capVerts,
- "arrayModifier_doArray vert_map");
-
- origindex = result->getVertDataArray(result, CD_ORIGINDEX);
- for(i = 0; i < capVerts; i++) {
- MVert *mv = &cap_mvert[i];
- short merged = 0;
-
- if(amd->flags & MOD_ARR_MERGE) {
- float tmp_co[3];
- MVert *in_mv;
- int j;
-
- VECCOPY(tmp_co, mv->co);
- Mat4MulVecfl(startoffset, tmp_co);
-
- for(j = 0; j < maxVerts; j++) {
- in_mv = &src_mvert[j];
- /* if this vert is within merge limit, merge */
- if(VecLenCompare(tmp_co, in_mv->co, amd->merge_dist)) {
- vert_map[i] = calc_mapping(indexMap, j, 0);
- merged = 1;
- break;
- }
- }
- }
-
- if(!merged) {
- DM_copy_vert_data(start_cap, result, i, numVerts, 1);
- mvert[numVerts] = *mv;
- Mat4MulVecfl(startoffset, mvert[numVerts].co);
- origindex[numVerts] = ORIGINDEX_NONE;
-
- vert_map[i] = numVerts;
-
- numVerts++;
- }
- }
- origindex = result->getEdgeDataArray(result, CD_ORIGINDEX);
- for(i = 0; i < capEdges; i++) {
- int v1, v2;
-
- v1 = vert_map[cap_medge[i].v1];
- v2 = vert_map[cap_medge[i].v2];
-
- if(!BLI_edgehash_haskey(edges, v1, v2)) {
- DM_copy_edge_data(start_cap, result, i, numEdges, 1);
- medge[numEdges] = cap_medge[i];
- medge[numEdges].v1 = v1;
- medge[numEdges].v2 = v2;
- origindex[numEdges] = ORIGINDEX_NONE;
-
- numEdges++;
- }
- }
- origindex = result->getFaceDataArray(result, CD_ORIGINDEX);
- for(i = 0; i < capFaces; i++) {
- DM_copy_face_data(start_cap, result, i, numFaces, 1);
- mface[numFaces] = cap_mface[i];
- mface[numFaces].v1 = vert_map[mface[numFaces].v1];
- mface[numFaces].v2 = vert_map[mface[numFaces].v2];
- mface[numFaces].v3 = vert_map[mface[numFaces].v3];
- if(mface[numFaces].v4)
- mface[numFaces].v4 = vert_map[mface[numFaces].v4];
- origindex[numFaces] = ORIGINDEX_NONE;
-
- numFaces++;
- }
-
- MEM_freeN(vert_map);
- start_cap->release(start_cap);
- }
-
- if(end_cap) {
- float endoffset[4][4];
- MVert *cap_mvert;
- MEdge *cap_medge;
- MFace *cap_mface;
- int *origindex;
- int *vert_map;
- int capVerts, capEdges, capFaces;
-
- capVerts = end_cap->getNumVerts(end_cap);
- capEdges = end_cap->getNumEdges(end_cap);
- capFaces = end_cap->getNumFaces(end_cap);
- cap_mvert = end_cap->getVertArray(end_cap);
- cap_medge = end_cap->getEdgeArray(end_cap);
- cap_mface = end_cap->getFaceArray(end_cap);
-
- Mat4MulMat4(endoffset, final_offset, offset);
-
- vert_map = MEM_callocN(sizeof(*vert_map) * capVerts,
- "arrayModifier_doArray vert_map");
-
- origindex = result->getVertDataArray(result, CD_ORIGINDEX);
- for(i = 0; i < capVerts; i++) {
- MVert *mv = &cap_mvert[i];
- short merged = 0;
-
- if(amd->flags & MOD_ARR_MERGE) {
- float tmp_co[3];
- MVert *in_mv;
- int j;
-
- VECCOPY(tmp_co, mv->co);
- Mat4MulVecfl(offset, tmp_co);
-
- for(j = 0; j < maxVerts; j++) {
- in_mv = &src_mvert[j];
- /* if this vert is within merge limit, merge */
- if(VecLenCompare(tmp_co, in_mv->co, amd->merge_dist)) {
- vert_map[i] = calc_mapping(indexMap, j, count - 1);
- merged = 1;
- break;
- }
- }
- }
-
- if(!merged) {
- DM_copy_vert_data(end_cap, result, i, numVerts, 1);
- mvert[numVerts] = *mv;
- Mat4MulVecfl(endoffset, mvert[numVerts].co);
- origindex[numVerts] = ORIGINDEX_NONE;
-
- vert_map[i] = numVerts;
-
- numVerts++;
- }
- }
- origindex = result->getEdgeDataArray(result, CD_ORIGINDEX);
- for(i = 0; i < capEdges; i++) {
- int v1, v2;
-
- v1 = vert_map[cap_medge[i].v1];
- v2 = vert_map[cap_medge[i].v2];
-
- if(!BLI_edgehash_haskey(edges, v1, v2)) {
- DM_copy_edge_data(end_cap, result, i, numEdges, 1);
- medge[numEdges] = cap_medge[i];
- medge[numEdges].v1 = v1;
- medge[numEdges].v2 = v2;
- origindex[numEdges] = ORIGINDEX_NONE;
-
- numEdges++;
- }
- }
- origindex = result->getFaceDataArray(result, CD_ORIGINDEX);
- for(i = 0; i < capFaces; i++) {
- DM_copy_face_data(end_cap, result, i, numFaces, 1);
- mface[numFaces] = cap_mface[i];
- mface[numFaces].v1 = vert_map[mface[numFaces].v1];
- mface[numFaces].v2 = vert_map[mface[numFaces].v2];
- mface[numFaces].v3 = vert_map[mface[numFaces].v3];
- if(mface[numFaces].v4)
- mface[numFaces].v4 = vert_map[mface[numFaces].v4];
- origindex[numFaces] = ORIGINDEX_NONE;
-
- numFaces++;
- }
-
- MEM_freeN(vert_map);
- end_cap->release(end_cap);
- }
-
- BLI_edgehash_free(edges, NULL);
- MEM_freeN(indexMap);
-
- CDDM_lower_num_verts(result, numVerts);
- CDDM_lower_num_edges(result, numEdges);
- CDDM_lower_num_faces(result, numFaces);
-
- return result;
+ * merge targets, calculate that final copy
+ */
+ if(indexMap[inMF.v1].merge_final)
+ mf->v1 = calc_mapping(indexMap, indexMap[inMF.v1].merge, count-1);
+ if(indexMap[inMF.v2].merge_final)
+ mf->v2 = calc_mapping(indexMap, indexMap[inMF.v2].merge, count-1);
+ if(indexMap[inMF.v3].merge_final)
+ mf->v3 = calc_mapping(indexMap, indexMap[inMF.v3].merge, count-1);
+ if(inMF.v4 && indexMap[inMF.v4].merge_final)
+ mf->v4 = calc_mapping(indexMap, indexMap[inMF.v4].merge, count-1);
+
+ if(test_index_face(mf, &result->faceData, numFaces, inMF.v4?4:3) < 3)
+ continue;
+
+ numFaces++;
+
+ /* if the face has fewer than 3 vertices, don't create it */
+ if(mf->v3 == 0 || (mf->v1 && (mf->v1 == mf->v3 || mf->v1 == mf->v4))) {
+ numFaces--;
+ DM_free_face_data(result, numFaces, 1);
+ }
+
+ for(j = 1; j < count; j++)
+ {
+ MFace *mf2 = &mface[numFaces];
+
+ DM_copy_face_data(dm, result, i, numFaces, 1);
+ *mf2 = *mf;
+
+ mf2->v1 = calc_mapping(indexMap, inMF.v1, j);
+ mf2->v2 = calc_mapping(indexMap, inMF.v2, j);
+ mf2->v3 = calc_mapping(indexMap, inMF.v3, j);
+ if (inMF.v4)
+ mf2->v4 = calc_mapping(indexMap, inMF.v4, j);
+
+ test_index_face(mf2, &result->faceData, numFaces, inMF.v4?4:3);
+ numFaces++;
+
+ /* if the face has fewer than 3 vertices, don't create it */
+ if(mf2->v3 == 0 || (mf2->v1 && (mf2->v1 == mf2->v3 || mf2->v1 ==
+ mf2->v4))) {
+ numFaces--;
+ DM_free_face_data(result, numFaces, 1);
+ }
+ }
+ }
+
+ /* add start and end caps */
+ if(start_cap) {
+ float startoffset[4][4];
+ MVert *cap_mvert;
+ MEdge *cap_medge;
+ MFace *cap_mface;
+ int *origindex;
+ int *vert_map;
+ int capVerts, capEdges, capFaces;
+
+ capVerts = start_cap->getNumVerts(start_cap);
+ capEdges = start_cap->getNumEdges(start_cap);
+ capFaces = start_cap->getNumFaces(start_cap);
+ cap_mvert = start_cap->getVertArray(start_cap);
+ cap_medge = start_cap->getEdgeArray(start_cap);
+ cap_mface = start_cap->getFaceArray(start_cap);
+
+ Mat4Invert(startoffset, offset);
+
+ vert_map = MEM_callocN(sizeof(*vert_map) * capVerts,
+ "arrayModifier_doArray vert_map");
+
+ origindex = result->getVertDataArray(result, CD_ORIGINDEX);
+ for(i = 0; i < capVerts; i++) {
+ MVert *mv = &cap_mvert[i];
+ short merged = 0;
+
+ if(amd->flags & MOD_ARR_MERGE) {
+ float tmp_co[3];
+ MVert *in_mv;
+ int j;
+
+ VECCOPY(tmp_co, mv->co);
+ Mat4MulVecfl(startoffset, tmp_co);
+
+ for(j = 0; j < maxVerts; j++) {
+ in_mv = &src_mvert[j];
+ /* if this vert is within merge limit, merge */
+ if(VecLenCompare(tmp_co, in_mv->co, amd->merge_dist)) {
+ vert_map[i] = calc_mapping(indexMap, j, 0);
+ merged = 1;
+ break;
+ }
+ }
+ }
+
+ if(!merged) {
+ DM_copy_vert_data(start_cap, result, i, numVerts, 1);
+ mvert[numVerts] = *mv;
+ Mat4MulVecfl(startoffset, mvert[numVerts].co);
+ origindex[numVerts] = ORIGINDEX_NONE;
+
+ vert_map[i] = numVerts;
+
+ numVerts++;
+ }
+ }
+ origindex = result->getEdgeDataArray(result, CD_ORIGINDEX);
+ for(i = 0; i < capEdges; i++) {
+ int v1, v2;
+
+ v1 = vert_map[cap_medge[i].v1];
+ v2 = vert_map[cap_medge[i].v2];
+
+ if(!BLI_edgehash_haskey(edges, v1, v2)) {
+ DM_copy_edge_data(start_cap, result, i, numEdges, 1);
+ medge[numEdges] = cap_medge[i];
+ medge[numEdges].v1 = v1;
+ medge[numEdges].v2 = v2;
+ origindex[numEdges] = ORIGINDEX_NONE;
+
+ numEdges++;
+ }
+ }
+ origindex = result->getFaceDataArray(result, CD_ORIGINDEX);
+ for(i = 0; i < capFaces; i++) {
+ DM_copy_face_data(start_cap, result, i, numFaces, 1);
+ mface[numFaces] = cap_mface[i];
+ mface[numFaces].v1 = vert_map[mface[numFaces].v1];
+ mface[numFaces].v2 = vert_map[mface[numFaces].v2];
+ mface[numFaces].v3 = vert_map[mface[numFaces].v3];
+ if(mface[numFaces].v4) {
+ mface[numFaces].v4 = vert_map[mface[numFaces].v4];
+
+ test_index_face(&mface[numFaces], &result->faceData,
+ numFaces, 4);
+ }
+ else
+ {
+ test_index_face(&mface[numFaces], &result->faceData,
+ numFaces, 3);
+ }
+
+ origindex[numFaces] = ORIGINDEX_NONE;
+
+ numFaces++;
+ }
+
+ MEM_freeN(vert_map);
+ start_cap->release(start_cap);
+ }
+
+ if(end_cap) {
+ float endoffset[4][4];
+ MVert *cap_mvert;
+ MEdge *cap_medge;
+ MFace *cap_mface;
+ int *origindex;
+ int *vert_map;
+ int capVerts, capEdges, capFaces;
+
+ capVerts = end_cap->getNumVerts(end_cap);
+ capEdges = end_cap->getNumEdges(end_cap);
+ capFaces = end_cap->getNumFaces(end_cap);
+ cap_mvert = end_cap->getVertArray(end_cap);
+ cap_medge = end_cap->getEdgeArray(end_cap);
+ cap_mface = end_cap->getFaceArray(end_cap);
+
+ Mat4MulMat4(endoffset, final_offset, offset);
+
+ vert_map = MEM_callocN(sizeof(*vert_map) * capVerts,
+ "arrayModifier_doArray vert_map");
+
+ origindex = result->getVertDataArray(result, CD_ORIGINDEX);
+ for(i = 0; i < capVerts; i++) {
+ MVert *mv = &cap_mvert[i];
+ short merged = 0;
+
+ if(amd->flags & MOD_ARR_MERGE) {
+ float tmp_co[3];
+ MVert *in_mv;
+ int j;
+
+ VECCOPY(tmp_co, mv->co);
+ Mat4MulVecfl(offset, tmp_co);
+
+ for(j = 0; j < maxVerts; j++) {
+ in_mv = &src_mvert[j];
+ /* if this vert is within merge limit, merge */
+ if(VecLenCompare(tmp_co, in_mv->co, amd->merge_dist)) {
+ vert_map[i] = calc_mapping(indexMap, j, count - 1);
+ merged = 1;
+ break;
+ }
+ }
+ }
+
+ if(!merged) {
+ DM_copy_vert_data(end_cap, result, i, numVerts, 1);
+ mvert[numVerts] = *mv;
+ Mat4MulVecfl(endoffset, mvert[numVerts].co);
+ origindex[numVerts] = ORIGINDEX_NONE;
+
+ vert_map[i] = numVerts;
+
+ numVerts++;
+ }
+ }
+ origindex = result->getEdgeDataArray(result, CD_ORIGINDEX);
+ for(i = 0; i < capEdges; i++) {
+ int v1, v2;
+
+ v1 = vert_map[cap_medge[i].v1];
+ v2 = vert_map[cap_medge[i].v2];
+
+ if(!BLI_edgehash_haskey(edges, v1, v2)) {
+ DM_copy_edge_data(end_cap, result, i, numEdges, 1);
+ medge[numEdges] = cap_medge[i];
+ medge[numEdges].v1 = v1;
+ medge[numEdges].v2 = v2;
+ origindex[numEdges] = ORIGINDEX_NONE;
+
+ numEdges++;
+ }
+ }
+ origindex = result->getFaceDataArray(result, CD_ORIGINDEX);
+ for(i = 0; i < capFaces; i++) {
+ DM_copy_face_data(end_cap, result, i, numFaces, 1);
+ mface[numFaces] = cap_mface[i];
+ mface[numFaces].v1 = vert_map[mface[numFaces].v1];
+ mface[numFaces].v2 = vert_map[mface[numFaces].v2];
+ mface[numFaces].v3 = vert_map[mface[numFaces].v3];
+ if(mface[numFaces].v4) {
+ mface[numFaces].v4 = vert_map[mface[numFaces].v4];
+
+ test_index_face(&mface[numFaces], &result->faceData,
+ numFaces, 4);
+ }
+ else
+ {
+ test_index_face(&mface[numFaces], &result->faceData,
+ numFaces, 3);
+ }
+ origindex[numFaces] = ORIGINDEX_NONE;
+
+ numFaces++;
+ }
+
+ MEM_freeN(vert_map);
+ end_cap->release(end_cap);
+ }
+
+ BLI_edgehash_free(edges, NULL);
+ MEM_freeN(indexMap);
+
+ CDDM_lower_num_verts(result, numVerts);
+ CDDM_lower_num_edges(result, numEdges);
+ CDDM_lower_num_faces(result, numFaces);
+
+ return result;
}
static DerivedMesh *arrayModifier_applyModifier(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- int useRenderParams, int isFinalCalc)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
{
DerivedMesh *result;
ArrayModifierData *amd = (ArrayModifierData*) md;
result = arrayModifier_doArray(amd, ob, derivedData, 0);
- CDDM_calc_normals(result);
+ if(result != derivedData)
+ CDDM_calc_normals(result);
return result;
}
static DerivedMesh *arrayModifier_applyModifierEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData)
{
return arrayModifier_applyModifier(md, ob, derivedData, 0, 1);
}
@@ -1252,7 +1657,7 @@ static void mirrorModifier_initData(ModifierData *md)
{
MirrorModifierData *mmd = (MirrorModifierData*) md;
- mmd->flag |= MOD_MIR_AXIS_X;
+ mmd->flag |= (MOD_MIR_AXIS_X | MOD_MIR_VGROUP);
mmd->tolerance = 0.001;
mmd->mirror_ob = NULL;
}
@@ -1269,9 +1674,9 @@ static void mirrorModifier_copyData(ModifierData *md, ModifierData *target)
}
static void mirrorModifier_foreachObjectLink(
- ModifierData *md, Object *ob,
- void (*walk)(void *userData, Object *ob, Object **obpoin),
- void *userData)
+ ModifierData *md, Object *ob,
+ void (*walk)(void *userData, Object *ob, Object **obpoin),
+ void *userData)
{
MirrorModifierData *mmd = (MirrorModifierData*) md;
@@ -1279,7 +1684,7 @@ static void mirrorModifier_foreachObjectLink(
}
static void mirrorModifier_updateDepgraph(ModifierData *md, DagForest *forest,
- Object *ob, DagNode *obNode)
+ Object *ob, DagNode *obNode)
{
MirrorModifierData *mmd = (MirrorModifierData*) md;
@@ -1287,15 +1692,127 @@ static void mirrorModifier_updateDepgraph(ModifierData *md, DagForest *forest,
DagNode *latNode = dag_get_node(forest, mmd->mirror_ob);
dag_add_relation(forest, latNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Mirror Modifier");
}
}
+/* finds the best possible flipped name. For renaming; check for unique names afterwards */
+/* if strip_number: removes number extensions */
+void vertgroup_flip_name (char *name, int strip_number)
+{
+ int len;
+ char prefix[128]={""}; /* The part before the facing */
+ char suffix[128]={""}; /* The part after the facing */
+ char replace[128]={""}; /* The replacement string */
+ char number[128]={""}; /* The number extension string */
+ char *index=NULL;
+
+ len= strlen(name);
+ if(len<3) return; // we don't do names like .R or .L
+
+ /* We first check the case with a .### extension, let's find the last period */
+ if(isdigit(name[len-1])) {
+ index= strrchr(name, '.'); // last occurrance
+ if (index && isdigit(index[1]) ) { // doesnt handle case bone.1abc2 correct..., whatever!
+ if(strip_number==0)
+ strcpy(number, index);
+ *index= 0;
+ len= strlen(name);
+ }
+ }
+
+ strcpy (prefix, name);
+
+#define IS_SEPARATOR(a) ((a)=='.' || (a)==' ' || (a)=='-' || (a)=='_')
+
+ /* first case; separator . - _ with extensions r R l L */
+ if( IS_SEPARATOR(name[len-2]) ) {
+ switch(name[len-1]) {
+ case 'l':
+ prefix[len-1]= 0;
+ strcpy(replace, "r");
+ break;
+ case 'r':
+ prefix[len-1]= 0;
+ strcpy(replace, "l");
+ break;
+ case 'L':
+ prefix[len-1]= 0;
+ strcpy(replace, "R");
+ break;
+ case 'R':
+ prefix[len-1]= 0;
+ strcpy(replace, "L");
+ break;
+ }
+ }
+ /* case; beginning with r R l L , with separator after it */
+ else if( IS_SEPARATOR(name[1]) ) {
+ switch(name[0]) {
+ case 'l':
+ strcpy(replace, "r");
+ strcpy(suffix, name+1);
+ prefix[0]= 0;
+ break;
+ case 'r':
+ strcpy(replace, "l");
+ strcpy(suffix, name+1);
+ prefix[0]= 0;
+ break;
+ case 'L':
+ strcpy(replace, "R");
+ strcpy(suffix, name+1);
+ prefix[0]= 0;
+ break;
+ case 'R':
+ strcpy(replace, "L");
+ strcpy(suffix, name+1);
+ prefix[0]= 0;
+ break;
+ }
+ }
+ else if(len > 5) {
+ /* hrms, why test for a separator? lets do the rule 'ultimate left or right' */
+ index = BLI_strcasestr(prefix, "right");
+ if (index==prefix || index==prefix+len-5) {
+ if(index[0]=='r')
+ strcpy (replace, "left");
+ else {
+ if(index[1]=='I')
+ strcpy (replace, "LEFT");
+ else
+ strcpy (replace, "Left");
+ }
+ *index= 0;
+ strcpy (suffix, index+5);
+ }
+ else {
+ index = BLI_strcasestr(prefix, "left");
+ if (index==prefix || index==prefix+len-4) {
+ if(index[0]=='l')
+ strcpy (replace, "right");
+ else {
+ if(index[1]=='E')
+ strcpy (replace, "RIGHT");
+ else
+ strcpy (replace, "Right");
+ }
+ *index= 0;
+ strcpy (suffix, index+4);
+ }
+ }
+ }
+
+#undef IS_SEPARATOR
+
+ sprintf (name, "%s%s%s%s", prefix, replace, suffix, number);
+}
+
static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
- Object *ob,
- DerivedMesh *dm,
- int initFlags,
- int axis)
+ Object *ob,
+ DerivedMesh *dm,
+ int initFlags,
+ int axis)
{
int i;
float tolerance = mmd->tolerance;
@@ -1304,6 +1821,9 @@ static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
int maxVerts = dm->getNumVerts(dm);
int maxEdges = dm->getNumEdges(dm);
int maxFaces = dm->getNumFaces(dm);
+ int vector_size=0, j, a, b;
+ bDeformGroup *def, *defb;
+ bDeformGroup **vector_def = NULL;
int (*indexMap)[2];
float mtx[4][4], imtx[4][4];
@@ -1313,9 +1833,24 @@ static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
result = CDDM_from_template(dm, maxVerts * 2, maxEdges * 2, maxFaces * 2);
+
+ if (mmd->flag & MOD_MIR_VGROUP) {
+ /* calculate the number of deformedGroups */
+ for(vector_size = 0, def = ob->defbase.first; def;
+ def = def->next, vector_size++);
+
+ /* load the deformedGroups for fast access */
+ vector_def =
+ (bDeformGroup **)MEM_mallocN(sizeof(bDeformGroup*) * vector_size,
+ "group_index");
+ for(a = 0, def = ob->defbase.first; def; def = def->next, a++) {
+ vector_def[a] = def;
+ }
+ }
+
if (mmd->mirror_ob) {
float obinv[4][4];
-
+
Mat4Invert(obinv, mmd->mirror_ob->obmat);
Mat4MulMat4(mtx, ob->obmat, obinv);
Mat4Invert(imtx, mtx);
@@ -1326,27 +1861,27 @@ static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
MVert *mv = CDDM_get_vert(result, numVerts);
int isShared;
float co[3];
-
+
dm->getVert(dm, i, &inMV);
-
+
VecCopyf(co, inMV.co);
-
+
if (mmd->mirror_ob) {
VecMat4MulVecfl(co, mtx, co);
}
isShared = ABS(co[axis])<=tolerance;
-
+
/* Because the topology result (# of vertices) must be the same if
- * the mesh data is overridden by vertex cos, have to calc sharedness
- * based on original coordinates. This is why we test before copy.
- */
+ * the mesh data is overridden by vertex cos, have to calc sharedness
+ * based on original coordinates. This is why we test before copy.
+ */
DM_copy_vert_data(dm, result, i, numVerts, 1);
*mv = inMV;
numVerts++;
-
+
indexMap[i][0] = numVerts - 1;
indexMap[i][1] = !isShared;
-
+
if(isShared) {
co[axis] = 0;
if (mmd->mirror_ob) {
@@ -1357,41 +1892,73 @@ static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
mv->flag |= ME_VERT_MERGED;
} else {
MVert *mv2 = CDDM_get_vert(result, numVerts);
-
+ MDeformVert *dvert = NULL;
+
DM_copy_vert_data(dm, result, i, numVerts, 1);
*mv2 = *mv;
- numVerts++;
-
+
co[axis] = -co[axis];
if (mmd->mirror_ob) {
VecMat4MulVecfl(co, imtx, co);
}
VecCopyf(mv2->co, co);
+
+ if (mmd->flag & MOD_MIR_VGROUP){
+ dvert = DM_get_vert_data(result, numVerts, CD_MDEFORMVERT);
+
+ if (dvert)
+ {
+ for(j = 0; j < dvert[0].totweight; ++j)
+ {
+ char tmpname[32];
+
+ if(dvert->dw[j].def_nr < 0 ||
+ dvert->dw[j].def_nr >= vector_size)
+ continue;
+
+ def = vector_def[dvert->dw[j].def_nr];
+ strcpy(tmpname, def->name);
+ vertgroup_flip_name(tmpname,0);
+
+ for(b = 0, defb = ob->defbase.first; defb;
+ defb = defb->next, b++)
+ {
+ if(!strcmp(defb->name, tmpname))
+ {
+ dvert->dw[j].def_nr = b;
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ numVerts++;
}
}
for(i = 0; i < maxEdges; i++) {
MEdge inMED;
MEdge *med = CDDM_get_edge(result, numEdges);
-
+
dm->getEdge(dm, i, &inMED);
-
+
DM_copy_edge_data(dm, result, i, numEdges, 1);
*med = inMED;
numEdges++;
-
+
med->v1 = indexMap[inMED.v1][0];
med->v2 = indexMap[inMED.v2][0];
if(initFlags)
med->flag |= ME_EDGEDRAW | ME_EDGERENDER;
-
+
if(indexMap[inMED.v1][1] || indexMap[inMED.v2][1]) {
MEdge *med2 = CDDM_get_edge(result, numEdges);
-
+
DM_copy_edge_data(dm, result, i, numEdges, 1);
*med2 = *med;
numEdges++;
-
+
med2->v1 += indexMap[inMED.v1][1];
med2->v2 += indexMap[inMED.v2][1];
}
@@ -1400,33 +1967,33 @@ static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
for(i = 0; i < maxFaces; i++) {
MFace inMF;
MFace *mf = CDDM_get_face(result, numFaces);
-
+
dm->getFace(dm, i, &inMF);
-
+
DM_copy_face_data(dm, result, i, numFaces, 1);
*mf = inMF;
numFaces++;
-
+
mf->v1 = indexMap[inMF.v1][0];
mf->v2 = indexMap[inMF.v2][0];
mf->v3 = indexMap[inMF.v3][0];
mf->v4 = indexMap[inMF.v4][0];
if(indexMap[inMF.v1][1]
- || indexMap[inMF.v2][1]
- || indexMap[inMF.v3][1]
- || (mf->v4 && indexMap[inMF.v4][1])) {
+ || indexMap[inMF.v2][1]
+ || indexMap[inMF.v3][1]
+ || (mf->v4 && indexMap[inMF.v4][1])) {
MFace *mf2 = CDDM_get_face(result, numFaces);
static int corner_indices[4] = {2, 1, 0, 3};
-
+
DM_copy_face_data(dm, result, i, numFaces, 1);
*mf2 = *mf;
-
+
mf2->v1 += indexMap[inMF.v1][1];
mf2->v2 += indexMap[inMF.v2][1];
mf2->v3 += indexMap[inMF.v3][1];
if(inMF.v4) mf2->v4 += indexMap[inMF.v4][1];
-
+
/* mirror UVs if enabled */
if(mmd->flag & (MOD_MIR_MIRROR_U | MOD_MIR_MIRROR_V)) {
MTFace *tf = result->getFaceData(result, numFaces, CD_MTFACE);
@@ -1440,16 +2007,18 @@ static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
}
}
}
-
+
/* Flip face normal */
SWAP(int, mf2->v1, mf2->v3);
DM_swap_face_data(result, numFaces, corner_indices);
-
+
test_index_face(mf2, &result->faceData, numFaces, inMF.v4?4:3);
numFaces++;
}
}
+ if (vector_def) MEM_freeN(vector_def);
+
MEM_freeN(indexMap);
CDDM_lower_num_verts(result, numVerts);
@@ -1460,8 +2029,8 @@ static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
}
static DerivedMesh *mirrorModifier__doMirror(MirrorModifierData *mmd,
- Object *ob, DerivedMesh *dm,
- int initFlags)
+ Object *ob, DerivedMesh *dm,
+ int initFlags)
{
DerivedMesh *result = dm;
@@ -1484,22 +2053,23 @@ static DerivedMesh *mirrorModifier__doMirror(MirrorModifierData *mmd,
}
static DerivedMesh *mirrorModifier_applyModifier(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- int useRenderParams, int isFinalCalc)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
{
DerivedMesh *result;
MirrorModifierData *mmd = (MirrorModifierData*) md;
result = mirrorModifier__doMirror(mmd, ob, derivedData, 0);
- CDDM_calc_normals(result);
+ if(result != derivedData)
+ CDDM_calc_normals(result);
return result;
}
static DerivedMesh *mirrorModifier_applyModifierEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData)
{
return mirrorModifier_applyModifier(md, ob, derivedData, 0, 1);
}
@@ -1570,6 +2140,8 @@ typedef struct SmoothMesh {
DerivedMesh *dm;
float threshold; /* the cosine of the smoothing angle */
int flags;
+ MemArena *arena;
+ ListBase propagatestack, reusestack;
} SmoothMesh;
static SmoothVert *smoothvert_copy(SmoothVert *vert, SmoothMesh *mesh)
@@ -1622,15 +2194,15 @@ static int smoothedge_has_vert(SmoothEdge *edge, SmoothVert *vert)
}
static SmoothMesh *smoothmesh_new(int num_verts, int num_edges, int num_faces,
- int max_verts, int max_edges, int max_faces)
+ int max_verts, int max_edges, int max_faces)
{
SmoothMesh *mesh = MEM_callocN(sizeof(*mesh), "smoothmesh");
mesh->verts = MEM_callocN(sizeof(*mesh->verts) * max_verts,
- "SmoothMesh.verts");
+ "SmoothMesh.verts");
mesh->edges = MEM_callocN(sizeof(*mesh->edges) * max_edges,
- "SmoothMesh.edges");
+ "SmoothMesh.edges");
mesh->faces = MEM_callocN(sizeof(*mesh->faces) * max_faces,
- "SmoothMesh.faces");
+ "SmoothMesh.faces");
mesh->num_verts = num_verts;
mesh->num_edges = num_edges;
@@ -1652,6 +2224,9 @@ static void smoothmesh_free(SmoothMesh *mesh)
for(i = 0; i < mesh->num_edges; ++i)
BLI_linklist_free(mesh->edges[i].faces, NULL);
+
+ if(mesh->arena)
+ BLI_memarena_free(mesh->arena);
MEM_freeN(mesh->verts);
MEM_freeN(mesh->edges);
@@ -1729,7 +2304,7 @@ static void smoothmesh_print(SmoothMesh *mesh)
printf("%3d: ind={%3d, %3d}, pos={% 5.1f, % 5.1f, % 5.1f}",
i, vert->oldIndex, vert->newIndex,
- mv.co[0], mv.co[1], mv.co[2]);
+ mv.co[0], mv.co[1], mv.co[2]);
printf(", faces={");
for(node = vert->faces; node != NULL; node = node->next) {
printf(" %d", ((SmoothFace *)node->link)->newIndex);
@@ -1744,8 +2319,8 @@ static void smoothmesh_print(SmoothMesh *mesh)
printf("%4d: indices={%4d, %4d}, verts={%4d, %4d}",
i,
- edge->oldIndex, edge->newIndex,
- edge->verts[0]->newIndex, edge->verts[1]->newIndex);
+ edge->oldIndex, edge->newIndex,
+ edge->verts[0]->newIndex, edge->verts[1]->newIndex);
if(edge->verts[0] == edge->verts[1]) printf(" <- DUPLICATE VERTEX");
printf(", faces={");
for(node = edge->faces; node != NULL; node = node->next) {
@@ -1787,7 +2362,7 @@ static SmoothMesh *smoothmesh_from_derivedmesh(DerivedMesh *dm)
totface = dm->getNumFaces(dm);
mesh = smoothmesh_new(totvert, totedge, totface,
- totvert, totedge, totface);
+ totvert, totedge, totface);
mesh->dm = dm;
@@ -1857,9 +2432,9 @@ static SmoothMesh *smoothmesh_from_derivedmesh(DerivedMesh *dm)
static DerivedMesh *CDDM_from_smoothmesh(SmoothMesh *mesh)
{
DerivedMesh *result = CDDM_from_template(mesh->dm,
- mesh->num_verts,
- mesh->num_edges,
- mesh->num_faces);
+ mesh->num_verts,
+ mesh->num_edges,
+ mesh->num_faces);
MVert *new_verts = CDDM_get_verts(result);
MEdge *new_edges = CDDM_get_edges(result);
MFace *new_faces = CDDM_get_faces(result);
@@ -1870,7 +2445,7 @@ static DerivedMesh *CDDM_from_smoothmesh(SmoothMesh *mesh)
MVert *newMV = &new_verts[vert->newIndex];
DM_copy_vert_data(mesh->dm, result,
- vert->oldIndex, vert->newIndex, 1);
+ vert->oldIndex, vert->newIndex, 1);
mesh->dm->getVert(mesh->dm, vert->oldIndex, newMV);
}
@@ -1879,7 +2454,7 @@ static DerivedMesh *CDDM_from_smoothmesh(SmoothMesh *mesh)
MEdge *newME = &new_edges[edge->newIndex];
DM_copy_edge_data(mesh->dm, result,
- edge->oldIndex, edge->newIndex, 1);
+ edge->oldIndex, edge->newIndex, 1);
mesh->dm->getEdge(mesh->dm, edge->oldIndex, newME);
newME->v1 = edge->verts[0]->newIndex;
newME->v2 = edge->verts[1]->newIndex;
@@ -1890,7 +2465,7 @@ static DerivedMesh *CDDM_from_smoothmesh(SmoothMesh *mesh)
MFace *newMF = &new_faces[face->newIndex];
DM_copy_face_data(mesh->dm, result,
- face->oldIndex, face->newIndex, 1);
+ face->oldIndex, face->newIndex, 1);
mesh->dm->getFace(mesh->dm, face->oldIndex, newMF);
newMF->v1 = face->edges[0]->verts[face->flip[0]]->newIndex;
@@ -1920,7 +2495,7 @@ static SmoothVert *other_vert(SmoothEdge *edge, SmoothVert *vert)
* (this should never happen)
*/
static SmoothEdge *other_edge(SmoothFace *face, SmoothVert *vert,
- SmoothEdge *edge)
+ SmoothEdge *edge)
{
int i,j;
for(i = 0; i < SMOOTHFACE_MAX_EDGES && face->edges[i]; i++) {
@@ -1932,8 +2507,8 @@ static SmoothEdge *other_edge(SmoothFace *face, SmoothVert *vert,
}
/* if we get to here, something's wrong (there should always be 2 edges
- * which use the same vert in a face)
- */
+ * which use the same vert in a face)
+ */
return NULL;
}
@@ -1962,18 +2537,18 @@ static void linklist_copy(LinkNode **target, LinkNode *source)
for(; source; source = source->next) {
if(node) {
node->next = MEM_mallocN(sizeof(*node->next), "nlink_copy");
- node = node->next;
- } else {
- node = *target = MEM_mallocN(sizeof(**target), "nlink_copy");
- }
- node->link = source->link;
- node->next = NULL;
- }
+ node = node->next;
+} else {
+ node = *target = MEM_mallocN(sizeof(**target), "nlink_copy");
+}
+ node->link = source->link;
+ node->next = NULL;
+}
}
#endif
-/* appends source to target if it's not already in target */
-static void linklist_append_unique(LinkNode **target, void *source)
+ /* appends source to target if it's not already in target */
+ static void linklist_append_unique(LinkNode **target, void *source)
{
LinkNode *node;
LinkNode *prev = NULL;
@@ -2007,7 +2582,7 @@ static void linklist_prepend_linklist(LinkNode **list, LinkNode *prepend)
node->next = *list;
*list = prepend;
- }
+}
}
#endif
@@ -2050,7 +2625,7 @@ static void linklist_empty(LinkNode **list, LinkNodeFreeFP freefunc)
* frees the pointer with freefunc if freefunc is not NULL
*/
static void linklist_remove_first(LinkNode **list, void *value,
- LinkNodeFreeFP freefunc)
+ LinkNodeFreeFP freefunc)
{
LinkNode *node = *list;
LinkNode *prev = NULL;
@@ -2075,7 +2650,7 @@ static void linklist_remove_first(LinkNode **list, void *value,
/* removes all elements in source from target */
static void linklist_remove_list(LinkNode **target, LinkNode *source,
- LinkNodeFreeFP freefunc)
+ LinkNodeFreeFP freefunc)
{
for(; source; source = source->next)
linklist_remove_first(target, source->link, freefunc);
@@ -2150,15 +2725,15 @@ static void face_replace_edge(void *ptr, void *userdata)
#ifdef EDGESPLIT_DEBUG_3
printf("replacing edge %4d with %4d in face %4d",
- find->newIndex, replace->newIndex, face->newIndex);
+ find->newIndex, replace->newIndex, face->newIndex);
if(face->edges[3])
printf(": {%2d %2d %2d %2d}",
face->edges[0]->newIndex, face->edges[1]->newIndex,
- face->edges[2]->newIndex, face->edges[3]->newIndex);
+ face->edges[2]->newIndex, face->edges[3]->newIndex);
else
printf(": {%2d %2d %2d}",
face->edges[0]->newIndex, face->edges[1]->newIndex,
- face->edges[2]->newIndex);
+ face->edges[2]->newIndex);
#endif
for(i = 0; i < SMOOTHFACE_MAX_EDGES && face->edges[i]; i++) {
@@ -2173,11 +2748,11 @@ static void face_replace_edge(void *ptr, void *userdata)
if(face->edges[3])
printf(" -> {%2d %2d %2d %2d}\n",
face->edges[0]->newIndex, face->edges[1]->newIndex,
- face->edges[2]->newIndex, face->edges[3]->newIndex);
+ face->edges[2]->newIndex, face->edges[3]->newIndex);
else
printf(" -> {%2d %2d %2d}\n",
face->edges[0]->newIndex, face->edges[1]->newIndex,
- face->edges[2]->newIndex);
+ face->edges[2]->newIndex);
#endif
}
@@ -2187,7 +2762,7 @@ static int edge_is_loose(SmoothEdge *edge)
}
static int edge_is_sharp(SmoothEdge *edge, int flags,
- float threshold)
+ float threshold)
{
#ifdef EDGESPLIT_DEBUG_1
printf("edge %d: ", edge->newIndex);
@@ -2218,7 +2793,7 @@ static int edge_is_sharp(SmoothEdge *edge, int flags,
* - returns to the start edge (NULL is returned)
*/
static SmoothEdge *find_other_sharp_edge(SmoothVert *vert, SmoothEdge *edge,
- LinkNode **visited_faces, float threshold, int flags)
+ LinkNode **visited_faces, float threshold, int flags)
{
SmoothFace *face = NULL;
SmoothEdge *edge2 = NULL;
@@ -2244,10 +2819,10 @@ static SmoothEdge *find_other_sharp_edge(SmoothVert *vert, SmoothEdge *edge,
BLI_linklist_prepend(visited_faces, face);
/* search until we hit a loose edge or a sharp edge or an edge we've
- * seen before
- */
+ * seen before
+ */
while(face && !edge_is_sharp(edge2, flags, threshold)
- && !linklist_contains(visited_edges, edge2)) {
+ && !linklist_contains(visited_edges, edge2)) {
#ifdef EDGESPLIT_DEBUG_3
printf("current face %4d; current edge %4d\n", face->newIndex,
edge2->newIndex);
@@ -2273,25 +2848,25 @@ static SmoothEdge *find_other_sharp_edge(SmoothVert *vert, SmoothEdge *edge,
printf("loose edge: %4d\n", edge2->newIndex);
#endif
}
- }
+ }
- /* either we came back to the start edge or we found a sharp/loose edge */
- if(linklist_contains(visited_edges, edge2))
- /* we came back to the start edge */
- edge2 = NULL;
+ /* either we came back to the start edge or we found a sharp/loose edge */
+ if(linklist_contains(visited_edges, edge2))
+ /* we came back to the start edge */
+ edge2 = NULL;
- BLI_linklist_free(visited_edges, NULL);
+ BLI_linklist_free(visited_edges, NULL);
#ifdef EDGESPLIT_DEBUG_1
- printf("=== END === find_other_sharp_edge(edge = %4d, vert = %4d), "
- "returning edge %d\n",
- edge->newIndex, vert->newIndex, edge2 ? edge2->newIndex : -1);
+ printf("=== END === find_other_sharp_edge(edge = %4d, vert = %4d), "
+ "returning edge %d\n",
+ edge->newIndex, vert->newIndex, edge2 ? edge2->newIndex : -1);
#endif
- return edge2;
+ return edge2;
}
static void split_single_vert(SmoothVert *vert, SmoothFace *face,
- SmoothMesh *mesh)
+ SmoothMesh *mesh)
{
SmoothVert *copy_vert;
ReplaceData repdata;
@@ -2303,10 +2878,53 @@ static void split_single_vert(SmoothVert *vert, SmoothFace *face,
face_replace_vert(face, &repdata);
}
+typedef struct PropagateEdge {
+ struct PropagateEdge *next, *prev;
+ SmoothEdge *edge;
+ SmoothVert *vert;
+} PropagateEdge;
+
+static void push_propagate_stack(SmoothEdge *edge, SmoothVert *vert, SmoothMesh *mesh)
+{
+ PropagateEdge *pedge = mesh->reusestack.first;
+
+ if(pedge) {
+ BLI_remlink(&mesh->reusestack, pedge);
+ }
+ else {
+ if(!mesh->arena) {
+ mesh->arena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
+ BLI_memarena_use_calloc(mesh->arena);
+ }
+
+ pedge = BLI_memarena_alloc(mesh->arena, sizeof(PropagateEdge));
+ }
+
+ pedge->edge = edge;
+ pedge->vert = vert;
+ BLI_addhead(&mesh->propagatestack, pedge);
+}
+
+static void pop_propagate_stack(SmoothEdge **edge, SmoothVert **vert, SmoothMesh *mesh)
+{
+ PropagateEdge *pedge = mesh->propagatestack.first;
+
+ if(pedge) {
+ *edge = pedge->edge;
+ *vert = pedge->vert;
+ BLI_remlink(&mesh->propagatestack, pedge);
+ BLI_addhead(&mesh->reusestack, pedge);
+ }
+ else {
+ *edge = NULL;
+ *vert = NULL;
+ }
+}
+
static void split_edge(SmoothEdge *edge, SmoothVert *vert, SmoothMesh *mesh);
static void propagate_split(SmoothEdge *edge, SmoothVert *vert,
- SmoothMesh *mesh)
+ SmoothMesh *mesh)
{
SmoothEdge *edge2;
LinkNode *visited_faces = NULL;
@@ -2316,7 +2934,7 @@ static void propagate_split(SmoothEdge *edge, SmoothVert *vert,
#endif
edge2 = find_other_sharp_edge(vert, edge, &visited_faces,
- mesh->threshold, mesh->flags);
+ mesh->threshold, mesh->flags);
if(!edge2) {
/* didn't find a sharp or loose edge, so we've hit a dead end */
@@ -2375,12 +2993,12 @@ static void split_edge(SmoothEdge *edge, SmoothVert *vert, SmoothMesh *mesh)
#endif
edge2 = find_other_sharp_edge(vert, edge, &visited_faces,
- mesh->threshold, mesh->flags);
+ mesh->threshold, mesh->flags);
if(!edge2) {
/* didn't find a sharp or loose edge, so try the other vert */
vert2 = other_vert(edge, vert);
- propagate_split(edge, vert2, mesh);
+ push_propagate_stack(edge, vert2, mesh);
} else if(!edge_is_loose(edge2)) {
/* edge2 is not loose, so it must be sharp */
SmoothEdge *copy_edge = smoothedge_copy(edge, mesh);
@@ -2400,20 +3018,20 @@ static void split_edge(SmoothEdge *edge, SmoothVert *vert, SmoothMesh *mesh)
vert2 = smoothvert_copy(vert, mesh);
/* replace vert with its copy in visited_faces (must be done after
- * edge replacement so edges have correct vertices)
- */
+ * edge replacement so edges have correct vertices)
+ */
repdata.find = vert;
repdata.replace = vert2;
BLI_linklist_apply(visited_faces, face_replace_vert, &repdata);
/* all copying and replacing is done; the mesh should be consistent.
- * now propagate the split to the vertices at either end
- */
- propagate_split(copy_edge, other_vert(copy_edge, vert2), mesh);
- propagate_split(copy_edge2, other_vert(copy_edge2, vert2), mesh);
+ * now propagate the split to the vertices at either end
+ */
+ push_propagate_stack(copy_edge, other_vert(copy_edge, vert2), mesh);
+ push_propagate_stack(copy_edge2, other_vert(copy_edge2, vert2), mesh);
if(smoothedge_has_vert(edge, vert))
- propagate_split(edge, vert, mesh);
+ push_propagate_stack(edge, vert, mesh);
} else {
/* edge2 is loose */
SmoothEdge *copy_edge = smoothedge_copy(edge, mesh);
@@ -2427,19 +3045,19 @@ static void split_edge(SmoothEdge *edge, SmoothVert *vert, SmoothMesh *mesh)
vert2 = smoothvert_copy(vert, mesh);
/* replace vert with its copy in visited_faces (must be done after
- * edge replacement so edges have correct vertices)
- */
+ * edge replacement so edges have correct vertices)
+ */
repdata.find = vert;
repdata.replace = vert2;
BLI_linklist_apply(visited_faces, face_replace_vert, &repdata);
/* copying and replacing is done; the mesh should be consistent.
- * now propagate the split to the vertex at the other end
- */
- propagate_split(copy_edge, other_vert(copy_edge, vert2), mesh);
+ * now propagate the split to the vertex at the other end
+ */
+ push_propagate_stack(copy_edge, other_vert(copy_edge, vert2), mesh);
if(smoothedge_has_vert(edge, vert))
- propagate_split(edge, vert, mesh);
+ push_propagate_stack(edge, vert, mesh);
}
BLI_linklist_free(visited_faces, NULL);
@@ -2450,7 +3068,7 @@ static void split_edge(SmoothEdge *edge, SmoothVert *vert, SmoothMesh *mesh)
}
static void tag_and_count_extra_edges(SmoothMesh *mesh, float split_angle,
- int flags, int *extra_edges)
+ int flags, int *extra_edges)
{
/* if normal1 dot normal2 < threshold, angle is greater, so split */
/* FIXME not sure if this always works */
@@ -2477,40 +3095,41 @@ static void tag_and_count_extra_edges(SmoothMesh *mesh, float split_angle,
for(node = edge->faces->next->next->next; node; node = node->next)
(*extra_edges)++;
} else if((flags & (MOD_EDGESPLIT_FROMANGLE | MOD_EDGESPLIT_FROMFLAG))
- && !edge_is_loose(edge)) {
+ && !edge_is_loose(edge)) {
/* (the edge can only be sharp if we're checking angle or flag,
- * and it has at least 2 faces) */
+ * and it has at least 2 faces) */
- /* if we're checking the sharp flag and it's set, good */
- if((flags & MOD_EDGESPLIT_FROMFLAG) && (edge->flag & ME_SHARP)) {
- /* this edge is sharp */
- sharp = 1;
+ /* if we're checking the sharp flag and it's set, good */
+ if((flags & MOD_EDGESPLIT_FROMFLAG) && (edge->flag & ME_SHARP)) {
+ /* this edge is sharp */
+ sharp = 1;
- (*extra_edges)++;
- } else if(flags & MOD_EDGESPLIT_FROMANGLE) {
- /* we know the edge has 2 faces, so check the angle */
- SmoothFace *face1 = edge->faces->link;
- SmoothFace *face2 = edge->faces->next->link;
- float edge_angle_cos = MTC_dot3Float(face1->normal,
- face2->normal);
-
- if(edge_angle_cos < threshold) {
- /* this edge is sharp */
- sharp = 1;
-
- (*extra_edges)++;
- }
- }
- }
+ (*extra_edges)++;
+ } else if(flags & MOD_EDGESPLIT_FROMANGLE) {
+ /* we know the edge has 2 faces, so check the angle */
+ SmoothFace *face1 = edge->faces->link;
+ SmoothFace *face2 = edge->faces->next->link;
+ float edge_angle_cos = MTC_dot3Float(face1->normal,
+ face2->normal);
+
+ if(edge_angle_cos < threshold) {
+ /* this edge is sharp */
+ sharp = 1;
- /* set/clear sharp flag appropriately */
- if(sharp) edge->flag |= ME_SHARP;
- else edge->flag &= ~ME_SHARP;
+ (*extra_edges)++;
+ }
+ }
+ }
+
+ /* set/clear sharp flag appropriately */
+ if(sharp) edge->flag |= ME_SHARP;
+ else edge->flag &= ~ME_SHARP;
}
}
static void split_sharp_edges(SmoothMesh *mesh, float split_angle, int flags)
{
+ SmoothVert *vert;
int i;
/* if normal1 dot normal2 < threshold, angle is greater, so split */
/* FIXME not sure if this always works */
@@ -2523,10 +3142,16 @@ static void split_sharp_edges(SmoothMesh *mesh, float split_angle, int flags)
for(i = 0; i < mesh->num_edges; i++) {
SmoothEdge *edge = &mesh->edges[i];
- if(edge_is_sharp(edge, flags, mesh->threshold))
+ if(edge_is_sharp(edge, flags, mesh->threshold)) {
split_edge(edge, edge->verts[0], mesh);
- }
+ do {
+ pop_propagate_stack(&edge, &vert, mesh);
+ if(edge && smoothedge_has_vert(edge, vert))
+ propagate_split(edge, vert, mesh);
+ } while(edge);
+ }
+ }
}
static int count_bridge_verts(SmoothMesh *mesh)
@@ -2548,19 +3173,19 @@ static int count_bridge_verts(SmoothMesh *mesh)
next_edge = face->edges[next];
/* if there are other faces sharing this vertex but not
- * these edges, the vertex will be split, so count it
- */
+ * these edges, the vertex will be split, so count it
+ */
/* vert has to have at least one face (this one), so faces != 0 */
if(!edge->faces->next && !next_edge->faces->next
- && vert->faces->next) {
+ && vert->faces->next) {
count++;
- }
+ }
}
}
/* each bridge vert will be counted once per face that uses it,
- * so count is too high, but it's ok for now
- */
+ * so count is too high, but it's ok for now
+ */
return count;
}
@@ -2583,21 +3208,21 @@ static void split_bridge_verts(SmoothMesh *mesh)
next_edge = face->edges[next];
/* if there are other faces sharing this vertex but not
- * these edges, split the vertex
- */
+ * these edges, split the vertex
+ */
/* vert has to have at least one face (this one), so faces != 0 */
if(!edge->faces->next && !next_edge->faces->next
- && vert->faces->next)
+ && vert->faces->next)
/* FIXME this needs to find all faces that share edges with
- * this one and split off together
- */
+ * this one and split off together
+ */
split_single_vert(vert, face, mesh);
}
}
}
static DerivedMesh *edgesplitModifier_do(EdgeSplitModifierData *emd,
- Object *ob, DerivedMesh *dm)
+ Object *ob, DerivedMesh *dm)
{
SmoothMesh *mesh;
DerivedMesh *result;
@@ -2640,8 +3265,8 @@ static DerivedMesh *edgesplitModifier_do(EdgeSplitModifierData *emd,
#ifdef EDGESPLIT_DEBUG_0
printf("Edgesplit: Estimated %d verts & %d edges, "
- "found %d verts & %d edges\n", max_verts, max_edges,
- mesh->num_verts, mesh->num_edges);
+ "found %d verts & %d edges\n", max_verts, max_edges,
+ mesh->num_verts, mesh->num_edges);
#endif
result = CDDM_from_smoothmesh(mesh);
@@ -2651,26 +3276,111 @@ static DerivedMesh *edgesplitModifier_do(EdgeSplitModifierData *emd,
}
static DerivedMesh *edgesplitModifier_applyModifier(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- int useRenderParams, int isFinalCalc)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
{
DerivedMesh *result;
EdgeSplitModifierData *emd = (EdgeSplitModifierData*) md;
result = edgesplitModifier_do(emd, ob, derivedData);
- CDDM_calc_normals(result);
+ if(result != derivedData)
+ CDDM_calc_normals(result);
return result;
}
static DerivedMesh *edgesplitModifier_applyModifierEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData)
{
return edgesplitModifier_applyModifier(md, ob, derivedData, 0, 1);
}
+/* Bevel */
+
+static void bevelModifier_initData(ModifierData *md)
+{
+ BevelModifierData *bmd = (BevelModifierData*) md;
+
+ bmd->value = 0.1f;
+ bmd->res = 1;
+ bmd->flags = 0;
+ bmd->val_flags = 0;
+ bmd->lim_flags = 0;
+ bmd->e_flags = 0;
+ bmd->bevel_angle = 30;
+ bmd->defgrp_name[0] = '\0';
+}
+
+static void bevelModifier_copyData(ModifierData *md, ModifierData *target)
+{
+ BevelModifierData *bmd = (BevelModifierData*) md;
+ BevelModifierData *tbmd = (BevelModifierData*) target;
+
+ tbmd->value = bmd->value;
+ tbmd->res = bmd->res;
+ tbmd->flags = bmd->flags;
+ tbmd->val_flags = bmd->val_flags;
+ tbmd->lim_flags = bmd->lim_flags;
+ tbmd->e_flags = bmd->e_flags;
+ tbmd->bevel_angle = bmd->bevel_angle;
+ strncpy(tbmd->defgrp_name, bmd->defgrp_name, 32);
+}
+
+CustomDataMask bevelModifier_requiredDataMask(ModifierData *md)
+{
+ BevelModifierData *bmd = (BevelModifierData *)md;
+ CustomDataMask dataMask = 0;
+
+ /* ask for vertexgroups if we need them */
+ if(bmd->defgrp_name[0]) dataMask |= (1 << CD_MDEFORMVERT);
+
+ return dataMask;
+}
+
+static DerivedMesh *bevelModifier_applyModifier(
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
+{
+ DerivedMesh *result;
+ BME_Mesh *bm;
+
+ /*bDeformGroup *def;*/
+ int /*i,*/ options, defgrp_index = -1;
+ BevelModifierData *bmd = (BevelModifierData*) md;
+
+ options = bmd->flags|bmd->val_flags|bmd->lim_flags|bmd->e_flags;
+
+ //~ if ((options & BME_BEVEL_VWEIGHT) && bmd->defgrp_name[0]) {
+ //~ for (i = 0, def = ob->defbase.first; def; def = def->next, i++) {
+ //~ if (!strcmp(def->name, bmd->defgrp_name)) {
+ //~ defgrp_index = i;
+ //~ break;
+ //~ }
+ //~ }
+ //~ if (defgrp_index < 0) {
+ //~ options &= ~BME_BEVEL_VWEIGHT;
+ //~ }
+ //~ }
+
+ bm = BME_derivedmesh_to_bmesh(derivedData);
+ BME_bevel(bm,bmd->value,bmd->res,options,defgrp_index,bmd->bevel_angle,NULL);
+ result = BME_bmesh_to_derivedmesh(bm,derivedData);
+ BME_free_mesh(bm);
+
+ CDDM_calc_normals(result);
+
+ return result;
+}
+
+static DerivedMesh *bevelModifier_applyModifierEM(
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData)
+{
+ return bevelModifier_applyModifier(md, ob, derivedData, 0, 1);
+}
+
/* Displace */
static void displaceModifier_initData(ModifierData *md)
@@ -2712,8 +3422,22 @@ CustomDataMask displaceModifier_requiredDataMask(ModifierData *md)
return dataMask;
}
+static int displaceModifier_dependsOnTime(ModifierData *md)
+{
+ DisplaceModifierData *dmd = (DisplaceModifierData *)md;
+
+ if(dmd->texture)
+ {
+ return BKE_texture_dependsOnTime(dmd->texture);
+ }
+ else
+ {
+ return 0;
+ }
+}
+
static void displaceModifier_foreachObjectLink(ModifierData *md, Object *ob,
- ObjectWalkFunc walk, void *userData)
+ ObjectWalkFunc walk, void *userData)
{
DisplaceModifierData *dmd = (DisplaceModifierData*) md;
@@ -2721,13 +3445,13 @@ static void displaceModifier_foreachObjectLink(ModifierData *md, Object *ob,
}
static void displaceModifier_foreachIDLink(ModifierData *md, Object *ob,
- IDWalkFunc walk, void *userData)
+ IDWalkFunc walk, void *userData)
{
DisplaceModifierData *dmd = (DisplaceModifierData*) md;
walk(userData, ob, (ID **)&dmd->texture);
- displaceModifier_foreachObjectLink(md, ob, (ObjectWalkFunc) walk, userData);
+ displaceModifier_foreachObjectLink(md, ob, (ObjectWalkFunc)walk, userData);
}
static int displaceModifier_isDisabled(ModifierData *md)
@@ -2738,8 +3462,8 @@ static int displaceModifier_isDisabled(ModifierData *md)
}
static void displaceModifier_updateDepgraph(
- ModifierData *md, DagForest *forest,
- Object *ob, DagNode *obNode)
+ ModifierData *md, DagForest *forest,
+ Object *ob, DagNode *obNode)
{
DisplaceModifierData *dmd = (DisplaceModifierData*) md;
@@ -2747,7 +3471,7 @@ static void displaceModifier_updateDepgraph(
DagNode *curNode = dag_get_node(forest, dmd->map_object);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Displace Modifier");
}
}
@@ -2761,17 +3485,17 @@ static void validate_layer_name(const CustomData *data, int type, char *name)
if(index < 0) {
/* either no layer was specified, or the layer we want has been
- * deleted, so assign the active layer to name
- */
+ * deleted, so assign the active layer to name
+ */
index = CustomData_get_active_layer_index(data, CD_MTFACE);
strcpy(name, data->layers[index].name);
}
}
static void get_texture_coords(DisplaceModifierData *dmd, Object *ob,
- DerivedMesh *dm,
- float (*co)[3], float (*texco)[3],
- int numVerts)
+ DerivedMesh *dm,
+ float (*co)[3], float (*texco)[3],
+ int numVerts)
{
int i;
int texmapping = dmd->texmapping;
@@ -2789,14 +3513,14 @@ static void get_texture_coords(DisplaceModifierData *dmd, Object *ob,
MFace *mface = dm->getFaceArray(dm);
MFace *mf;
char *done = MEM_callocN(sizeof(*done) * numVerts,
- "get_texture_coords done");
+ "get_texture_coords done");
int numFaces = dm->getNumFaces(dm);
MTFace *tf;
validate_layer_name(&dm->faceData, CD_MTFACE, dmd->uvlayer_name);
tf = CustomData_get_layer_named(&dm->faceData, CD_MTFACE,
- dmd->uvlayer_name);
+ dmd->uvlayer_name);
/* verts are given the UV from the first face that uses them */
for(i = 0, mf = mface; i < numFaces; ++i, ++mf, ++tf) {
@@ -2840,18 +3564,18 @@ static void get_texture_coords(DisplaceModifierData *dmd, Object *ob,
for(i = 0; i < numVerts; ++i, ++co, ++texco) {
switch(texmapping) {
- case MOD_DISP_MAP_LOCAL:
- VECCOPY(*texco, *co);
- break;
- case MOD_DISP_MAP_GLOBAL:
- VECCOPY(*texco, *co);
- Mat4MulVecfl(ob->obmat, *texco);
- break;
- case MOD_DISP_MAP_OBJECT:
- VECCOPY(*texco, *co);
- Mat4MulVecfl(ob->obmat, *texco);
- Mat4MulVecfl(dmd->map_object->imat, *texco);
- break;
+ case MOD_DISP_MAP_LOCAL:
+ VECCOPY(*texco, *co);
+ break;
+ case MOD_DISP_MAP_GLOBAL:
+ VECCOPY(*texco, *co);
+ Mat4MulVecfl(ob->obmat, *texco);
+ break;
+ case MOD_DISP_MAP_OBJECT:
+ VECCOPY(*texco, *co);
+ Mat4MulVecfl(ob->obmat, *texco);
+ Mat4MulVecfl(dmd->map_object->imat, *texco);
+ break;
}
}
}
@@ -2861,23 +3585,23 @@ static void get_texture_value(Tex *texture, float *tex_co, TexResult *texres)
int result_type;
result_type = multitex_ext(texture, tex_co, NULL,
- NULL, 1, texres);
+ NULL, 1, texres);
/* if the texture gave an RGB value, we assume it didn't give a valid
- * intensity, so calculate one (formula from do_material_tex).
- * if the texture didn't give an RGB value, copy the intensity across
- */
+ * intensity, so calculate one (formula from do_material_tex).
+ * if the texture didn't give an RGB value, copy the intensity across
+ */
if(result_type & TEX_RGB)
texres->tin = (0.35 * texres->tr + 0.45 * texres->tg
- + 0.2 * texres->tb);
+ + 0.2 * texres->tb);
else
texres->tr = texres->tg = texres->tb = texres->tin;
}
/* dm must be a CDDerivedMesh */
static void displaceModifier_do(
- DisplaceModifierData *dmd, Object *ob,
- DerivedMesh *dm, float (*vertexCos)[3], int numVerts)
+ DisplaceModifierData *dmd, Object *ob,
+ DerivedMesh *dm, float (*vertexCos)[3], int numVerts)
{
int i;
MVert *mvert;
@@ -2904,7 +3628,7 @@ static void displaceModifier_do(
dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
tex_co = MEM_callocN(sizeof(*tex_co) * numVerts,
- "displaceModifier_do tex_co");
+ "displaceModifier_do tex_co");
get_texture_coords(dmd, ob, dm, vertexCos, tex_co, numVerts);
for(i = 0; i < numVerts; ++i) {
@@ -2933,25 +3657,25 @@ static void displaceModifier_do(
delta *= strength;
switch(dmd->direction) {
- case MOD_DISP_DIR_X:
- vertexCos[i][0] += delta;
- break;
- case MOD_DISP_DIR_Y:
- vertexCos[i][1] += delta;
- break;
- case MOD_DISP_DIR_Z:
- vertexCos[i][2] += delta;
- break;
- case MOD_DISP_DIR_RGB_XYZ:
- vertexCos[i][0] += (texres.tr - dmd->midlevel) * strength;
- vertexCos[i][1] += (texres.tg - dmd->midlevel) * strength;
- vertexCos[i][2] += (texres.tb - dmd->midlevel) * strength;
- break;
- case MOD_DISP_DIR_NOR:
- vertexCos[i][0] += delta * mvert[i].no[0] / 32767.0f;
- vertexCos[i][1] += delta * mvert[i].no[1] / 32767.0f;
- vertexCos[i][2] += delta * mvert[i].no[2] / 32767.0f;
- break;
+ case MOD_DISP_DIR_X:
+ vertexCos[i][0] += delta;
+ break;
+ case MOD_DISP_DIR_Y:
+ vertexCos[i][1] += delta;
+ break;
+ case MOD_DISP_DIR_Z:
+ vertexCos[i][2] += delta;
+ break;
+ case MOD_DISP_DIR_RGB_XYZ:
+ vertexCos[i][0] += (texres.tr - dmd->midlevel) * strength;
+ vertexCos[i][1] += (texres.tg - dmd->midlevel) * strength;
+ vertexCos[i][2] += (texres.tb - dmd->midlevel) * strength;
+ break;
+ case MOD_DISP_DIR_NOR:
+ vertexCos[i][0] += delta * mvert[i].no[0] / 32767.0f;
+ vertexCos[i][1] += delta * mvert[i].no[1] / 32767.0f;
+ vertexCos[i][2] += delta * mvert[i].no[2] / 32767.0f;
+ break;
}
}
@@ -2959,8 +3683,8 @@ static void displaceModifier_do(
}
static void displaceModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm;
@@ -2972,14 +3696,14 @@ static void displaceModifier_deformVerts(
CDDM_calc_normals(dm);
displaceModifier_do((DisplaceModifierData *)md, ob, dm,
- vertexCos, numVerts);
+ vertexCos, numVerts);
dm->release(dm);
}
static void displaceModifier_deformVertsEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm;
@@ -2990,7 +3714,7 @@ static void displaceModifier_deformVertsEM(
CDDM_calc_normals(dm);
displaceModifier_do((DisplaceModifierData *)md, ob, dm,
- vertexCos, numVerts);
+ vertexCos, numVerts);
dm->release(dm);
}
@@ -3038,7 +3762,7 @@ CustomDataMask uvprojectModifier_requiredDataMask(ModifierData *md)
}
static void uvprojectModifier_foreachObjectLink(ModifierData *md, Object *ob,
- ObjectWalkFunc walk, void *userData)
+ ObjectWalkFunc walk, void *userData)
{
UVProjectModifierData *umd = (UVProjectModifierData*) md;
int i;
@@ -3048,18 +3772,18 @@ static void uvprojectModifier_foreachObjectLink(ModifierData *md, Object *ob,
}
static void uvprojectModifier_foreachIDLink(ModifierData *md, Object *ob,
- IDWalkFunc walk, void *userData)
+ IDWalkFunc walk, void *userData)
{
UVProjectModifierData *umd = (UVProjectModifierData*) md;
walk(userData, ob, (ID **)&umd->image);
uvprojectModifier_foreachObjectLink(md, ob, (ObjectWalkFunc)walk,
- userData);
+ userData);
}
static void uvprojectModifier_updateDepgraph(ModifierData *md,
- DagForest *forest, Object *ob, DagNode *obNode)
+ DagForest *forest, Object *ob, DagNode *obNode)
{
UVProjectModifierData *umd = (UVProjectModifierData*) md;
int i;
@@ -3069,7 +3793,7 @@ static void uvprojectModifier_updateDepgraph(ModifierData *md,
DagNode *curNode = dag_get_node(forest, umd->projectors[i]);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "UV Project Modifier");
}
}
}
@@ -3081,7 +3805,7 @@ typedef struct Projector {
} Projector;
static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
- Object *ob, DerivedMesh *dm)
+ Object *ob, DerivedMesh *dm)
{
float (*coords)[3], (*co)[3];
MTFace *tface;
@@ -3110,13 +3834,13 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
/* make sure we are not modifying the original UV layer */
tface = CustomData_duplicate_referenced_layer_named(&dm->faceData,
- CD_MTFACE,
- umd->uvlayer_name);
+ CD_MTFACE,
+ umd->uvlayer_name);
numVerts = dm->getNumVerts(dm);
coords = MEM_callocN(sizeof(*coords) * numVerts,
- "uvprojectModifier_do coords");
+ "uvprojectModifier_do coords");
dm->getVertCos(dm, coords);
/* convert coords to world space */
@@ -3127,12 +3851,12 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
for(i = 0; i < num_projectors; ++i) {
float tmpmat[4][4];
float offsetmat[4][4];
-
+ Camera *cam = NULL;
/* calculate projection matrix */
Mat4Invert(projectors[i].projmat, projectors[i].ob->obmat);
if(projectors[i].ob->type == OB_CAMERA) {
- Camera *cam = (Camera *)projectors[i].ob->data;
+ cam = (Camera *)projectors[i].ob->data;
if(cam->type == CAM_PERSP) {
float perspmat[4][4];
float xmax;
@@ -3152,7 +3876,7 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
ymin = -ymax;
i_window(xmin, xmax, ymin, ymax,
- cam->clipsta, cam->clipend, perspmat);
+ cam->clipsta, cam->clipend, perspmat);
Mat4MulMat4(tmpmat, projectors[i].projmat, perspmat);
} else if(cam->type == CAM_ORTHO) {
float orthomat[4][4];
@@ -3172,7 +3896,7 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
ymin = -ymax;
i_ortho(xmin, xmax, ymin, ymax,
- cam->clipsta, cam->clipend, orthomat);
+ cam->clipsta, cam->clipend, orthomat);
Mat4MulMat4(tmpmat, projectors[i].projmat, orthomat);
}
} else {
@@ -3182,6 +3906,20 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
Mat4One(offsetmat);
Mat4MulFloat3(offsetmat[0], 0.5);
offsetmat[3][0] = offsetmat[3][1] = offsetmat[3][2] = 0.5;
+
+ if (cam) {
+ if (umd->aspectx == umd->aspecty) {
+ offsetmat[3][0] -= cam->shiftx;
+ offsetmat[3][1] -= cam->shifty;
+ } else if (umd->aspectx < umd->aspecty) {
+ offsetmat[3][0] -=(cam->shiftx * umd->aspecty/umd->aspectx);
+ offsetmat[3][1] -= cam->shifty;
+ } else {
+ offsetmat[3][0] -= cam->shiftx;
+ offsetmat[3][1] -=(cam->shifty * umd->aspectx/umd->aspecty);
+ }
+ }
+
Mat4MulMat4(projectors[i].projmat, tmpmat, offsetmat);
/* calculate worldspace projector normal (for best projector test) */
@@ -3216,8 +3954,8 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
}
} else {
/* multiple projectors, select the closest to face normal
- * direction
- */
+ * direction
+ */
float co1[3], co2[3], co3[3], co4[3];
float face_no[3];
int j;
@@ -3237,14 +3975,14 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
}
/* find the projector which the face points at most directly
- * (projector normal with largest dot product is best)
- */
+ * (projector normal with largest dot product is best)
+ */
best_dot = MTC_dot3Float(projectors[0].normal, face_no);
best_projector = &projectors[0];
for(j = 1; j < num_projectors; ++j) {
float tmp_dot = MTC_dot3Float(projectors[j].normal,
- face_no);
+ face_no);
if(tmp_dot > best_dot) {
best_dot = tmp_dot;
best_projector = &projectors[j];
@@ -3283,8 +4021,8 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
}
static DerivedMesh *uvprojectModifier_applyModifier(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- int useRenderParams, int isFinalCalc)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
{
DerivedMesh *result;
UVProjectModifierData *umd = (UVProjectModifierData*) md;
@@ -3295,8 +4033,8 @@ static DerivedMesh *uvprojectModifier_applyModifier(
}
static DerivedMesh *uvprojectModifier_applyModifierEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData)
{
return uvprojectModifier_applyModifier(md, ob, derivedData, 0, 1);
}
@@ -3321,8 +4059,8 @@ static void decimateModifier_copyData(ModifierData *md, ModifierData *target)
//XXX
#if 0
static DerivedMesh *decimateModifier_applyModifier(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- int useRenderParams, int isFinalCalc)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
{
DecimateModifierData *dmd = (DecimateModifierData*) md;
DerivedMesh *dm = derivedData, *result = NULL;
@@ -3346,7 +4084,7 @@ static DerivedMesh *decimateModifier_applyModifier(
if(numTris<3) {
modifier_setError(md,
- "There must be more than 3 input faces (triangles).");
+ "Modifier requires more than 3 input faces (triangles).");
goto exit;
}
@@ -3436,7 +4174,7 @@ static DerivedMesh *decimateModifier_applyModifier(
MEM_freeN(lod.triangle_index_buffer);
exit:
- return result;
+ return result;
}
#endif
@@ -3488,8 +4226,8 @@ CustomDataMask smoothModifier_requiredDataMask(ModifierData *md)
}
static void smoothModifier_do(
- SmoothModifierData *smd, Object *ob, DerivedMesh *dm,
- float (*vertexCos)[3], int numVerts)
+ SmoothModifierData *smd, Object *ob, DerivedMesh *dm,
+ float (*vertexCos)[3], int numVerts)
{
MDeformVert *dvert = NULL;
MEdge *medges = NULL;
@@ -3499,10 +4237,10 @@ static void smoothModifier_do(
float *ftmp, fac, facm;
ftmp = (float*)MEM_callocN(3*sizeof(float)*numVerts,
- "smoothmodifier_f");
+ "smoothmodifier_f");
if (!ftmp) return;
uctmp = (unsigned char*)MEM_callocN(sizeof(unsigned char)*numVerts,
- "smoothmodifier_uc");
+ "smoothmodifier_uc");
if (!uctmp) {
if (ftmp) MEM_freeN(ftmp);
return;
@@ -3531,7 +4269,7 @@ static void smoothModifier_do(
dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
/* NOTICE: this can be optimized a little bit by moving the
- * if (dvert) out of the loop, if needed */
+ * if (dvert) out of the loop, if needed */
for (j = 0; j < smd->repeat; j++) {
for (i = 0; i < numDMEdges; i++) {
float fvec[3];
@@ -3627,8 +4365,8 @@ static void smoothModifier_do(
}
static void smoothModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm;
@@ -3639,14 +4377,14 @@ static void smoothModifier_deformVerts(
CDDM_calc_normals(dm);
smoothModifier_do((SmoothModifierData *)md, ob, dm,
- vertexCos, numVerts);
+ vertexCos, numVerts);
dm->release(dm);
}
static void smoothModifier_deformVertsEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm;
@@ -3657,7 +4395,7 @@ static void smoothModifier_deformVertsEM(
CDDM_calc_normals(dm);
smoothModifier_do((SmoothModifierData *)md, ob, dm,
- vertexCos, numVerts);
+ vertexCos, numVerts);
dm->release(dm);
}
@@ -3672,7 +4410,7 @@ static void castModifier_initData(ModifierData *md)
cmd->radius = 0.0f;
cmd->size = 0.0f;
cmd->flag = MOD_CAST_X | MOD_CAST_Y | MOD_CAST_Z
- | MOD_CAST_SIZE_FROM_RADIUS;
+ | MOD_CAST_SIZE_FROM_RADIUS;
cmd->type = MOD_CAST_TYPE_SPHERE;
cmd->defgrp_name[0] = '\0';
cmd->object = NULL;
@@ -3717,9 +4455,9 @@ CustomDataMask castModifier_requiredDataMask(ModifierData *md)
}
static void castModifier_foreachObjectLink(
- ModifierData *md, Object *ob,
- void (*walk)(void *userData, Object *ob, Object **obpoin),
- void *userData)
+ ModifierData *md, Object *ob,
+ void (*walk)(void *userData, Object *ob, Object **obpoin),
+ void *userData)
{
CastModifierData *cmd = (CastModifierData*) md;
@@ -3727,21 +4465,22 @@ static void castModifier_foreachObjectLink(
}
static void castModifier_updateDepgraph(
- ModifierData *md, DagForest *forest, Object *ob,
- DagNode *obNode)
+ ModifierData *md, DagForest *forest, Object *ob,
+ DagNode *obNode)
{
CastModifierData *cmd = (CastModifierData*) md;
if (cmd->object) {
DagNode *curNode = dag_get_node(forest, cmd->object);
- dag_add_relation(forest, curNode, obNode, DAG_RL_OB_DATA);
+ dag_add_relation(forest, curNode, obNode, DAG_RL_OB_DATA,
+ "Cast Modifier");
}
}
static void castModifier_sphere_do(
- CastModifierData *cmd, Object *ob, DerivedMesh *dm,
- float (*vertexCos)[3], int numVerts)
+ CastModifierData *cmd, Object *ob, DerivedMesh *dm,
+ float (*vertexCos)[3], int numVerts)
{
MDeformVert *dvert = NULL;
@@ -3766,8 +4505,8 @@ static void castModifier_sphere_do(
ctrl_ob = cmd->object;
/* spherify's center is {0, 0, 0} (the ob's own center in its local
- * space), by default, but if the user defined a control object,
- * we use its location, transformed to ob's local space */
+ * space), by default, but if the user defined a control object,
+ * we use its location, transformed to ob's local space */
if (ctrl_ob) {
if(flag & MOD_CAST_USE_OB_TRANSFORM) {
Mat4Invert(ctrl_ob->imat, ctrl_ob->obmat);
@@ -3784,11 +4523,11 @@ static void castModifier_sphere_do(
/* 1) (flag was checked in the "if (ctrl_ob)" block above) */
/* 2) cmd->radius > 0.0f: only the vertices within this radius from
- * the center of the effect should be deformed */
+ * the center of the effect should be deformed */
if (cmd->radius > FLT_EPSILON) has_radius = 1;
/* 3) if we were given a vertex group name,
- * only those vertices should be affected */
+ * only those vertices should be affected */
if (cmd->defgrp_name[0]) {
bDeformGroup *def;
@@ -3820,10 +4559,10 @@ static void castModifier_sphere_do(
}
/* ready to apply the effect, one vertex at a time;
- * tiny optimization: the code is separated (with parts repeated)
+ * tiny optimization: the code is separated (with parts repeated)
* in two possible cases:
- * with or w/o a vgroup. With lots of if's in the code below,
- * further optimizations are possible, if needed */
+ * with or w/o a vgroup. With lots of if's in the code below,
+ * further optimizations are possible, if needed */
if (dvert) { /* with a vgroup */
float fac_orig = fac;
for (i = 0; i < numVerts; i++) {
@@ -3926,8 +4665,8 @@ static void castModifier_sphere_do(
}
static void castModifier_cuboid_do(
- CastModifierData *cmd, Object *ob, DerivedMesh *dm,
- float (*vertexCos)[3], int numVerts)
+ CastModifierData *cmd, Object *ob, DerivedMesh *dm,
+ float (*vertexCos)[3], int numVerts)
{
MDeformVert *dvert = NULL;
Object *ctrl_ob = NULL;
@@ -3951,11 +4690,11 @@ static void castModifier_cuboid_do(
/* 1) (flag was checked in the "if (ctrl_ob)" block above) */
/* 2) cmd->radius > 0.0f: only the vertices within this radius from
- * the center of the effect should be deformed */
+ * the center of the effect should be deformed */
if (cmd->radius > FLT_EPSILON) has_radius = 1;
/* 3) if we were given a vertex group name,
- * only those vertices should be affected */
+ * only those vertices should be affected */
if (cmd->defgrp_name[0]) {
bDeformGroup *def;
@@ -3995,12 +4734,12 @@ static void castModifier_cuboid_do(
} else {
/* get bound box */
/* We can't use the object's bound box because other modifiers
- * may have changed the vertex data. */
+ * may have changed the vertex data. */
INIT_MINMAX(min, max);
/* Cast's center is the ob's own center in its local space,
- * by default, but if the user defined a control object, we use
- * its location, transformed to ob's local space. */
+ * by default, but if the user defined a control object, we use
+ * its location, transformed to ob's local space. */
if (ctrl_ob) {
float vec[3];
@@ -4036,10 +4775,10 @@ static void castModifier_cuboid_do(
bb[4][2] = bb[5][2] = bb[6][2] = bb[7][2] = max[2];
/* ready to apply the effect, one vertex at a time;
- * tiny optimization: the code is separated (with parts repeated)
+ * tiny optimization: the code is separated (with parts repeated)
* in two possible cases:
- * with or w/o a vgroup. With lots of if's in the code below,
- * further optimizations are possible, if needed */
+ * with or w/o a vgroup. With lots of if's in the code below,
+ * further optimizations are possible, if needed */
if (dvert) { /* with a vgroup */
float fac_orig = fac;
for (i = 0; i < numVerts; i++) {
@@ -4059,8 +4798,8 @@ static void castModifier_cuboid_do(
if (has_radius) {
if (fabs(tmp_co[0]) > cmd->radius ||
- fabs(tmp_co[1]) > cmd->radius ||
- fabs(tmp_co[2]) > cmd->radius) continue;
+ fabs(tmp_co[1]) > cmd->radius ||
+ fabs(tmp_co[2]) > cmd->radius) continue;
}
for (j = 0; j < dvert[i].totweight; ++j) {
@@ -4077,10 +4816,10 @@ static void castModifier_cuboid_do(
/* The algo used to project the vertices to their
* bounding box (bb) is pretty simple:
* for each vertex v:
- * 1) find in which octant v is in;
- * 2) find which outer "wall" of that octant is closer to v;
- * 3) calculate factor (var fbb) to project v to that wall;
- * 4) project. */
+ * 1) find in which octant v is in;
+ * 2) find which outer "wall" of that octant is closer to v;
+ * 3) calculate factor (var fbb) to project v to that wall;
+ * 4) project. */
/* find in which octant this vertex is in */
octant = 0;
@@ -4114,7 +4853,7 @@ static void castModifier_cuboid_do(
continue;
/* finally, this is the factor we wanted, to project the vertex
- * to its bounding box (bb) */
+ * to its bounding box (bb) */
fbb = apex[coord] / tmp_co[coord];
/* calculate the new vertex position */
@@ -4155,8 +4894,8 @@ static void castModifier_cuboid_do(
if (has_radius) {
if (fabs(tmp_co[0]) > cmd->radius ||
- fabs(tmp_co[1]) > cmd->radius ||
- fabs(tmp_co[2]) > cmd->radius) continue;
+ fabs(tmp_co[1]) > cmd->radius ||
+ fabs(tmp_co[2]) > cmd->radius) continue;
}
octant = 0;
@@ -4206,8 +4945,8 @@ static void castModifier_cuboid_do(
}
static void castModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm = derivedData;
CastModifierData *cmd = (CastModifierData *)md;
@@ -4225,8 +4964,8 @@ static void castModifier_deformVerts(
}
static void castModifier_deformVertsEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm = derivedData;
CastModifierData *cmd = (CastModifierData *)md;
@@ -4245,13 +4984,13 @@ static void castModifier_deformVertsEM(
/* Wave */
-static void waveModifier_initData(ModifierData *md)
+static void waveModifier_initData(ModifierData *md)
{
WaveModifierData *wmd = (WaveModifierData*) md; // whadya know, moved here from Iraq
-
+
wmd->flag |= (MOD_WAVE_X | MOD_WAVE_Y | MOD_WAVE_CYCL
- | MOD_WAVE_NORM_X | MOD_WAVE_NORM_Y | MOD_WAVE_NORM_Z);
-
+ | MOD_WAVE_NORM_X | MOD_WAVE_NORM_Y | MOD_WAVE_NORM_Z);
+
wmd->objectcenter = NULL;
wmd->texture = NULL;
wmd->map_object = NULL;
@@ -4261,6 +5000,7 @@ static void waveModifier_initData(ModifierData *md)
wmd->narrow= 1.5f;
wmd->lifetime= 0.0f;
wmd->damp= 10.0f;
+ wmd->falloff= 0.0f;
wmd->texmapping = MOD_WAV_MAP_LOCAL;
wmd->defgrp_name[0] = 0;
}
@@ -4280,6 +5020,7 @@ static void waveModifier_copyData(ModifierData *md, ModifierData *target)
twmd->starty = wmd->starty;
twmd->timeoffs = wmd->timeoffs;
twmd->width = wmd->width;
+ twmd->falloff = wmd->falloff;
twmd->objectcenter = wmd->objectcenter;
twmd->texture = wmd->texture;
twmd->map_object = wmd->map_object;
@@ -4293,8 +5034,8 @@ static int waveModifier_dependsOnTime(ModifierData *md)
}
static void waveModifier_foreachObjectLink(
- ModifierData *md, Object *ob,
- ObjectWalkFunc walk, void *userData)
+ ModifierData *md, Object *ob,
+ ObjectWalkFunc walk, void *userData)
{
WaveModifierData *wmd = (WaveModifierData*) md;
@@ -4303,7 +5044,7 @@ static void waveModifier_foreachObjectLink(
}
static void waveModifier_foreachIDLink(ModifierData *md, Object *ob,
- IDWalkFunc walk, void *userData)
+ IDWalkFunc walk, void *userData)
{
WaveModifierData *wmd = (WaveModifierData*) md;
@@ -4313,21 +5054,23 @@ static void waveModifier_foreachIDLink(ModifierData *md, Object *ob,
}
static void waveModifier_updateDepgraph(
- ModifierData *md, DagForest *forest, Object *ob,
- DagNode *obNode)
+ ModifierData *md, DagForest *forest, Object *ob,
+ DagNode *obNode)
{
WaveModifierData *wmd = (WaveModifierData*) md;
if(wmd->objectcenter) {
DagNode *curNode = dag_get_node(forest, wmd->objectcenter);
- dag_add_relation(forest, curNode, obNode, DAG_RL_OB_DATA);
+ dag_add_relation(forest, curNode, obNode, DAG_RL_OB_DATA,
+ "Wave Modifier");
}
if(wmd->map_object) {
DagNode *curNode = dag_get_node(forest, wmd->map_object);
- dag_add_relation(forest, curNode, obNode, DAG_RL_OB_DATA);
+ dag_add_relation(forest, curNode, obNode, DAG_RL_OB_DATA,
+ "Wave Modifer");
}
}
@@ -4349,9 +5092,9 @@ CustomDataMask waveModifier_requiredDataMask(ModifierData *md)
}
static void wavemod_get_texture_coords(WaveModifierData *wmd, Object *ob,
- DerivedMesh *dm,
- float (*co)[3], float (*texco)[3],
- int numVerts)
+ DerivedMesh *dm,
+ float (*co)[3], float (*texco)[3],
+ int numVerts)
{
int i;
int texmapping = wmd->texmapping;
@@ -4369,14 +5112,14 @@ static void wavemod_get_texture_coords(WaveModifierData *wmd, Object *ob,
MFace *mface = dm->getFaceArray(dm);
MFace *mf;
char *done = MEM_callocN(sizeof(*done) * numVerts,
- "get_texture_coords done");
+ "get_texture_coords done");
int numFaces = dm->getNumFaces(dm);
MTFace *tf;
validate_layer_name(&dm->faceData, CD_MTFACE, wmd->uvlayer_name);
tf = CustomData_get_layer_named(&dm->faceData, CD_MTFACE,
- wmd->uvlayer_name);
+ wmd->uvlayer_name);
/* verts are given the UV from the first face that uses them */
for(i = 0, mf = mface; i < numFaces; ++i, ++mf, ++tf) {
@@ -4420,25 +5163,25 @@ static void wavemod_get_texture_coords(WaveModifierData *wmd, Object *ob,
for(i = 0; i < numVerts; ++i, ++co, ++texco) {
switch(texmapping) {
- case MOD_WAV_MAP_LOCAL:
- VECCOPY(*texco, *co);
- break;
- case MOD_WAV_MAP_GLOBAL:
- VECCOPY(*texco, *co);
- Mat4MulVecfl(ob->obmat, *texco);
- break;
- case MOD_WAV_MAP_OBJECT:
- VECCOPY(*texco, *co);
- Mat4MulVecfl(ob->obmat, *texco);
- Mat4MulVecfl(wmd->map_object->imat, *texco);
- break;
+ case MOD_WAV_MAP_LOCAL:
+ VECCOPY(*texco, *co);
+ break;
+ case MOD_WAV_MAP_GLOBAL:
+ VECCOPY(*texco, *co);
+ Mat4MulVecfl(ob->obmat, *texco);
+ break;
+ case MOD_WAV_MAP_OBJECT:
+ VECCOPY(*texco, *co);
+ Mat4MulVecfl(ob->obmat, *texco);
+ Mat4MulVecfl(wmd->map_object->imat, *texco);
+ break;
}
}
}
static void waveModifier_do(
- WaveModifierData *md, Object *ob, DerivedMesh *dm,
- float (*vertexCos)[3], int numVerts)
+ WaveModifierData *md, Object *ob, DerivedMesh *dm,
+ float (*vertexCos)[3], int numVerts)
{
WaveModifierData *wmd = (WaveModifierData*) md;
MVert *mvert = NULL;
@@ -4446,7 +5189,7 @@ static void waveModifier_do(
int defgrp_index;
float ctime = bsystem_time(ob, (float)G.scene->r.cfra, 0.0);
float minfac =
- (float)(1.0 / exp(wmd->width * wmd->narrow * wmd->width * wmd->narrow));
+ (float)(1.0 / exp(wmd->width * wmd->narrow * wmd->width * wmd->narrow));
float lifefac = wmd->height;
float (*tex_co)[3] = NULL;
@@ -4488,16 +5231,16 @@ static void waveModifier_do(
if(x > wmd->lifetime) {
lifefac = x - wmd->lifetime;
-
+
if(lifefac > wmd->damp) lifefac = 0.0;
else lifefac =
- (float)(wmd->height * (1.0 - sqrt(lifefac / wmd->damp)));
+ (float)(wmd->height * (1.0 - sqrt(lifefac / wmd->damp)));
}
}
if(wmd->texture) {
tex_co = MEM_mallocN(sizeof(*tex_co) * numVerts,
- "waveModifier_do tex_co");
+ "waveModifier_do tex_co");
wavemod_get_texture_coords(wmd, ob, dm, vertexCos, tex_co, numVerts);
}
@@ -4509,6 +5252,8 @@ static void waveModifier_do(
float x = co[0] - wmd->startx;
float y = co[1] - wmd->starty;
float amplit= 0.0f;
+ float dist = 0.0f;
+ float falloff_fac = 0.0f;
TexResult texres;
MDeformWeight *def_weight = NULL;
@@ -4531,32 +5276,54 @@ static void waveModifier_do(
get_texture_value(wmd->texture, tex_co[i], &texres);
}
+ /*get dist*/
+ if(wmd->flag & MOD_WAVE_X) {
+ if(wmd->flag & MOD_WAVE_Y){
+ dist = (float)sqrt(x*x + y*y);
+ }
+ else{
+ dist = fabs(x);
+ }
+ }
+ else if(wmd->flag & MOD_WAVE_Y) {
+ dist = fabs(y);
+ }
+
+ falloff_fac = (1.0-(dist / wmd->falloff));
+ CLAMP(falloff_fac,0,1);
if(wmd->flag & MOD_WAVE_X) {
if(wmd->flag & MOD_WAVE_Y) amplit = (float)sqrt(x*x + y*y);
else amplit = x;
}
- else if(wmd->flag & MOD_WAVE_Y)
+ else if(wmd->flag & MOD_WAVE_Y)
amplit= y;
-
+
/* this way it makes nice circles */
amplit -= (ctime - wmd->timeoffs) * wmd->speed;
if(wmd->flag & MOD_WAVE_CYCL) {
amplit = (float)fmod(amplit - wmd->width, 2.0 * wmd->width)
- + wmd->width;
+ + wmd->width;
}
/* GAUSSIAN */
if(amplit > -wmd->width && amplit < wmd->width) {
amplit = amplit * wmd->narrow;
amplit = (float)(1.0 / exp(amplit * amplit) - minfac);
+
+ /*apply texture*/
if(wmd->texture)
amplit = amplit * texres.tin;
+ /*apply weight*/
if(def_weight)
amplit = amplit * def_weight->weight;
+ /*apply falloff*/
+ if (wmd->falloff > 0)
+ amplit = amplit * falloff_fac;
+
if(mvert) {
/* move along normals */
if(wmd->flag & MOD_WAVE_NORM_X) {
@@ -4581,8 +5348,8 @@ static void waveModifier_do(
}
static void waveModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm;
WaveModifierData *wmd = (WaveModifierData *)md;
@@ -4604,15 +5371,15 @@ static void waveModifier_deformVerts(
}
static void waveModifier_deformVertsEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm;
WaveModifierData *wmd = (WaveModifierData *)md;
if(!wmd->texture && !wmd->defgrp_name[0] && !(wmd->flag & MOD_WAVE_NORM))
dm = derivedData;
- else if(derivedData) dm = derivedData;
+ else if(derivedData) dm = CDDM_copy(derivedData);
else dm = CDDM_from_editmesh(editData, ob->data);
if(wmd->flag & MOD_WAVE_NORM) {
@@ -4662,9 +5429,9 @@ static int armatureModifier_isDisabled(ModifierData *md)
}
static void armatureModifier_foreachObjectLink(
- ModifierData *md, Object *ob,
- void (*walk)(void *userData, Object *ob, Object **obpoin),
- void *userData)
+ ModifierData *md, Object *ob,
+ void (*walk)(void *userData, Object *ob, Object **obpoin),
+ void *userData)
{
ArmatureModifierData *amd = (ArmatureModifierData*) md;
@@ -4672,8 +5439,8 @@ static void armatureModifier_foreachObjectLink(
}
static void armatureModifier_updateDepgraph(
- ModifierData *md, DagForest *forest, Object *ob,
- DagNode *obNode)
+ ModifierData *md, DagForest *forest, Object *ob,
+ DagNode *obNode)
{
ArmatureModifierData *amd = (ArmatureModifierData*) md;
@@ -4681,21 +5448,21 @@ static void armatureModifier_updateDepgraph(
DagNode *curNode = dag_get_node(forest, amd->object);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Armature Modifier");
}
}
static void armatureModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
ArmatureModifierData *amd = (ArmatureModifierData*) md;
modifier_vgroup_cache(md, vertexCos); /* if next modifier needs original vertices */
armature_deform_verts(amd->object, ob, derivedData, vertexCos, NULL,
- numVerts, amd->deformflag,
- (float(*)[3])amd->prevCos, amd->defgrp_name);
+ numVerts, amd->deformflag,
+ (float(*)[3])amd->prevCos, amd->defgrp_name);
/* free cache */
if(amd->prevCos) {
MEM_freeN(amd->prevCos);
@@ -4704,8 +5471,8 @@ static void armatureModifier_deformVerts(
}
static void armatureModifier_deformVertsEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
ArmatureModifierData *amd = (ArmatureModifierData*) md;
DerivedMesh *dm = derivedData;
@@ -4713,15 +5480,15 @@ static void armatureModifier_deformVertsEM(
if(!derivedData) dm = CDDM_from_editmesh(editData, ob->data);
armature_deform_verts(amd->object, ob, dm, vertexCos, NULL, numVerts,
- amd->deformflag, NULL, amd->defgrp_name);
+ amd->deformflag, NULL, amd->defgrp_name);
if(!derivedData) dm->release(dm);
}
static void armatureModifier_deformMatricesEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData, float (*vertexCos)[3],
- float (*defMats)[3][3], int numVerts)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData, float (*vertexCos)[3],
+ float (*defMats)[3][3], int numVerts)
{
ArmatureModifierData *amd = (ArmatureModifierData*) md;
DerivedMesh *dm = derivedData;
@@ -4729,7 +5496,7 @@ static void armatureModifier_deformMatricesEM(
if(!derivedData) dm = CDDM_from_editmesh(editData, ob->data);
armature_deform_verts(amd->object, ob, dm, vertexCos, defMats, numVerts,
- amd->deformflag, NULL, amd->defgrp_name);
+ amd->deformflag, NULL, amd->defgrp_name);
if(!derivedData) dm->release(dm);
}
@@ -4784,9 +5551,9 @@ static int hookModifier_isDisabled(ModifierData *md)
}
static void hookModifier_foreachObjectLink(
- ModifierData *md, Object *ob,
- void (*walk)(void *userData, Object *ob, Object **obpoin),
- void *userData)
+ ModifierData *md, Object *ob,
+ void (*walk)(void *userData, Object *ob, Object **obpoin),
+ void *userData)
{
HookModifierData *hmd = (HookModifierData*) md;
@@ -4794,20 +5561,21 @@ static void hookModifier_foreachObjectLink(
}
static void hookModifier_updateDepgraph(ModifierData *md, DagForest *forest,
- Object *ob, DagNode *obNode)
+ Object *ob, DagNode *obNode)
{
HookModifierData *hmd = (HookModifierData*) md;
if (hmd->object) {
DagNode *curNode = dag_get_node(forest, hmd->object);
- dag_add_relation(forest, curNode, obNode, DAG_RL_OB_DATA);
+ dag_add_relation(forest, curNode, obNode, DAG_RL_OB_DATA,
+ "Hook Modifier");
}
}
static void hookModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
HookModifierData *hmd = (HookModifierData*) md;
float vec[3], mat[4][4];
@@ -4816,7 +5584,7 @@ static void hookModifier_deformVerts(
Mat4Invert(ob->imat, ob->obmat);
Mat4MulSerie(mat, ob->imat, hmd->object->obmat, hmd->parentinv,
- NULL, NULL, NULL, NULL, NULL);
+ NULL, NULL, NULL, NULL, NULL);
/* vertex indices? */
if(hmd->indexar) {
@@ -4824,24 +5592,24 @@ static void hookModifier_deformVerts(
int index = hmd->indexar[i];
/* This should always be true and I don't generally like
- * "paranoid" style code like this, but old files can have
- * indices that are out of range because old blender did
- * not correct them on exit editmode. - zr
- */
+ * "paranoid" style code like this, but old files can have
+ * indices that are out of range because old blender did
+ * not correct them on exit editmode. - zr
+ */
if(index < numVerts) {
float *co = vertexCos[index];
float fac = hmd->force;
/* if DerivedMesh is present and has original index data,
- * use it
- */
+ * use it
+ */
if(dm && dm->getVertData(dm, 0, CD_ORIGINDEX)) {
int j;
int orig_index;
for(j = 0; j < numVerts; ++j) {
fac = hmd->force;
orig_index = *(int *)dm->getVertData(dm, j,
- CD_ORIGINDEX);
+ CD_ORIGINDEX);
if(orig_index == index) {
co = vertexCos[j];
if(hmd->falloff != 0.0) {
@@ -4885,44 +5653,44 @@ static void hookModifier_deformVerts(
if(dm)
if(dm->getVertData(dm, 0, CD_MDEFORMVERT)) {
+ use_dverts = 1;
+ maxVerts = dm->getNumVerts(dm);
+ } else use_dverts = 0;
+ else if(me->dvert) {
use_dverts = 1;
- maxVerts = dm->getNumVerts(dm);
+ maxVerts = me->totvert;
} else use_dverts = 0;
- else if(me->dvert) {
- use_dverts = 1;
- maxVerts = me->totvert;
- } else use_dverts = 0;
- if(curdef && use_dverts) {
- MDeformVert *dvert = me->dvert;
- int i, j;
+ if(curdef && use_dverts) {
+ MDeformVert *dvert = me->dvert;
+ int i, j;
- for(i = 0; i < maxVerts; i++, dvert++) {
- if(dm) dvert = dm->getVertData(dm, i, CD_MDEFORMVERT);
- for(j = 0; j < dvert->totweight; j++) {
- if(dvert->dw[j].def_nr == index) {
- float fac = hmd->force*dvert->dw[j].weight;
- float *co = vertexCos[i];
+ for(i = 0; i < maxVerts; i++, dvert++) {
+ if(dm) dvert = dm->getVertData(dm, i, CD_MDEFORMVERT);
+ for(j = 0; j < dvert->totweight; j++) {
+ if(dvert->dw[j].def_nr == index) {
+ float fac = hmd->force*dvert->dw[j].weight;
+ float *co = vertexCos[i];
- if(hmd->falloff != 0.0) {
- float len = VecLenf(co, hmd->cent);
- if(len > hmd->falloff) fac = 0.0;
- else if(len > 0.0)
- fac *= sqrt(1.0 - len / hmd->falloff);
- }
+ if(hmd->falloff != 0.0) {
+ float len = VecLenf(co, hmd->cent);
+ if(len > hmd->falloff) fac = 0.0;
+ else if(len > 0.0)
+ fac *= sqrt(1.0 - len / hmd->falloff);
+ }
- VecMat4MulVecfl(vec, mat, co);
- VecLerpf(co, co, vec, fac);
+ VecMat4MulVecfl(vec, mat, co);
+ VecLerpf(co, co, vec, fac);
+ }
}
}
}
- }
}
}
static void hookModifier_deformVertsEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm = derivedData;
@@ -4936,12 +5704,322 @@ static void hookModifier_deformVertsEM(
/* Softbody */
static void softbodyModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
sbObjectStep(ob, (float)G.scene->r.cfra, vertexCos, numVerts);
}
+static int softbodyModifier_dependsOnTime(ModifierData *md)
+{
+ return 1;
+}
+
+
+/* Cloth */
+
+static void clothModifier_initData(ModifierData *md)
+{
+ ClothModifierData *clmd = (ClothModifierData*) md;
+
+ clmd->sim_parms = MEM_callocN(sizeof(ClothSimSettings), "cloth sim parms");
+ clmd->coll_parms = MEM_callocN(sizeof(ClothCollSettings), "cloth coll parms");
+ clmd->point_cache = BKE_ptcache_add();
+
+ /* check for alloc failing */
+ if(!clmd->sim_parms || !clmd->coll_parms || !clmd->point_cache)
+ return;
+
+ cloth_init (clmd);
+}
+
+static DerivedMesh *clothModifier_applyModifier(ModifierData *md, Object *ob,
+ DerivedMesh *derivedData, int useRenderParams, int isFinalCalc)
+{
+ ClothModifierData *clmd = (ClothModifierData*) md;
+ DerivedMesh *result=NULL;
+
+ /* check for alloc failing */
+ if(!clmd->sim_parms || !clmd->coll_parms)
+ {
+ clothModifier_initData(md);
+
+ if(!clmd->sim_parms || !clmd->coll_parms)
+ return derivedData;
+ }
+
+ result = clothModifier_do(clmd, ob, derivedData, useRenderParams, isFinalCalc);
+
+ if(result)
+ {
+ CDDM_calc_normals(result);
+ return result;
+ }
+ return derivedData;
+}
+
+static void clothModifier_updateDepgraph(
+ ModifierData *md, DagForest *forest, Object *ob,
+ DagNode *obNode)
+{
+ ClothModifierData *clmd = (ClothModifierData*) md;
+
+ Base *base;
+
+ if(clmd)
+ {
+ for(base = G.scene->base.first; base; base= base->next)
+ {
+ Object *ob1= base->object;
+ if(ob1 != ob)
+ {
+ CollisionModifierData *coll_clmd = (CollisionModifierData *)modifiers_findByType(ob1, eModifierType_Collision);
+ if(coll_clmd)
+ {
+ DagNode *curNode = dag_get_node(forest, ob1);
+ dag_add_relation(forest, curNode, obNode, DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Cloth Collision");
+ }
+ }
+ }
+ }
+}
+
+CustomDataMask clothModifier_requiredDataMask(ModifierData *md)
+{
+ CustomDataMask dataMask = 0;
+
+ /* ask for vertexgroups if we need them */
+ dataMask |= (1 << CD_MDEFORMVERT);
+
+ return dataMask;
+}
+
+static void clothModifier_copyData(ModifierData *md, ModifierData *target)
+{
+ ClothModifierData *clmd = (ClothModifierData*) md;
+ ClothModifierData *tclmd = (ClothModifierData*) target;
+
+ if(tclmd->sim_parms)
+ MEM_freeN(tclmd->sim_parms);
+ if(tclmd->coll_parms)
+ MEM_freeN(tclmd->coll_parms);
+ if(tclmd->point_cache)
+ BKE_ptcache_free(tclmd->point_cache);
+
+ tclmd->sim_parms = MEM_dupallocN(clmd->sim_parms);
+ tclmd->coll_parms = MEM_dupallocN(clmd->coll_parms);
+ tclmd->point_cache = BKE_ptcache_copy(clmd->point_cache);
+ tclmd->clothObject = NULL;
+}
+
+static int clothModifier_dependsOnTime(ModifierData *md)
+{
+ return 1;
+}
+
+static void clothModifier_freeData(ModifierData *md)
+{
+ ClothModifierData *clmd = (ClothModifierData*) md;
+
+ if (clmd)
+ {
+ if(G.rt > 0)
+ printf("clothModifier_freeData\n");
+
+ cloth_free_modifier_extern (clmd);
+
+ if(clmd->sim_parms)
+ MEM_freeN(clmd->sim_parms);
+ if(clmd->coll_parms)
+ MEM_freeN(clmd->coll_parms);
+ if(clmd->point_cache)
+ BKE_ptcache_free(clmd->point_cache);
+ }
+}
+
+/* Collision */
+
+static void collisionModifier_initData(ModifierData *md)
+{
+ CollisionModifierData *collmd = (CollisionModifierData*) md;
+
+ collmd->x = NULL;
+ collmd->xnew = NULL;
+ collmd->current_x = NULL;
+ collmd->current_xnew = NULL;
+ collmd->current_v = NULL;
+ collmd->time = -1;
+ collmd->numverts = 0;
+ collmd->bvhtree = NULL;
+}
+
+static void collisionModifier_freeData(ModifierData *md)
+{
+ CollisionModifierData *collmd = (CollisionModifierData*) md;
+
+ if (collmd)
+ {
+ if(collmd->bvhtree)
+ BLI_bvhtree_free(collmd->bvhtree);
+ if(collmd->x)
+ MEM_freeN(collmd->x);
+ if(collmd->xnew)
+ MEM_freeN(collmd->xnew);
+ if(collmd->current_x)
+ MEM_freeN(collmd->current_x);
+ if(collmd->current_xnew)
+ MEM_freeN(collmd->current_xnew);
+ if(collmd->current_v)
+ MEM_freeN(collmd->current_v);
+ if(collmd->mfaces)
+ MEM_freeN(collmd->mfaces);
+
+ collmd->x = NULL;
+ collmd->xnew = NULL;
+ collmd->current_x = NULL;
+ collmd->current_xnew = NULL;
+ collmd->current_v = NULL;
+ collmd->time = -1;
+ collmd->numverts = 0;
+ collmd->bvhtree = NULL;
+ collmd->mfaces = NULL;
+ }
+}
+
+static int collisionModifier_dependsOnTime(ModifierData *md)
+{
+ return 1;
+}
+
+static void collisionModifier_deformVerts(
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
+{
+ CollisionModifierData *collmd = (CollisionModifierData*) md;
+ DerivedMesh *dm = NULL;
+ float current_time = 0;
+ unsigned int numverts = 0, i = 0;
+ MVert *tempVert = NULL;
+
+ /* if possible use/create DerivedMesh */
+ if(derivedData) dm = CDDM_copy(derivedData);
+ else if(ob->type==OB_MESH) dm = CDDM_from_mesh(ob->data, ob);
+
+ if(!ob->pd)
+ {
+ printf("collisionModifier_deformVerts: Should not happen!\n");
+ return;
+ }
+
+ if(dm)
+ {
+ CDDM_apply_vert_coords(dm, vertexCos);
+ CDDM_calc_normals(dm);
+
+ current_time = bsystem_time ( ob, ( float ) G.scene->r.cfra, 0.0 );
+
+ if(G.rt > 0)
+ printf("current_time %f, collmd->time %f\n", current_time, collmd->time);
+
+ numverts = dm->getNumVerts ( dm );
+
+ if((current_time > collmd->time)|| (BKE_ptcache_get_continue_physics()))
+ {
+ // check if mesh has changed
+ if(collmd->x && (numverts != collmd->numverts))
+ collisionModifier_freeData((ModifierData *)collmd);
+
+ if(collmd->time == -1) // first time
+ {
+ collmd->x = dm->dupVertArray(dm); // frame start position
+
+ for ( i = 0; i < numverts; i++ )
+ {
+ // we save global positions
+ Mat4MulVecfl ( ob->obmat, collmd->x[i].co );
+ }
+
+ collmd->xnew = MEM_dupallocN(collmd->x); // frame end position
+ collmd->current_x = MEM_dupallocN(collmd->x); // inter-frame
+ collmd->current_xnew = MEM_dupallocN(collmd->x); // inter-frame
+ collmd->current_v = MEM_dupallocN(collmd->x); // inter-frame
+
+ collmd->numverts = numverts;
+
+ collmd->mfaces = dm->dupFaceArray(dm);
+ collmd->numfaces = dm->getNumFaces(dm);
+
+ // create bounding box hierarchy
+ collmd->bvhtree = bvhtree_build_from_mvert(collmd->mfaces, collmd->numfaces, collmd->x, numverts, ob->pd->pdef_sboft);
+
+ collmd->time = current_time;
+ }
+ else if(numverts == collmd->numverts)
+ {
+ // put positions to old positions
+ tempVert = collmd->x;
+ collmd->x = collmd->xnew;
+ collmd->xnew = tempVert;
+
+ memcpy(collmd->xnew, dm->getVertArray(dm), numverts*sizeof(MVert));
+
+ for ( i = 0; i < numverts; i++ )
+ {
+ // we save global positions
+ Mat4MulVecfl ( ob->obmat, collmd->xnew[i].co );
+ }
+
+ memcpy(collmd->current_xnew, collmd->x, numverts*sizeof(MVert));
+ memcpy(collmd->current_x, collmd->x, numverts*sizeof(MVert));
+
+ /* check if GUI setting has changed for bvh */
+ if(collmd->bvhtree)
+ {
+ if(ob->pd->pdef_sboft != BLI_bvhtree_getepsilon(collmd->bvhtree))
+ {
+ BLI_bvhtree_free(collmd->bvhtree);
+ collmd->bvhtree = bvhtree_build_from_mvert(collmd->mfaces, collmd->numfaces, collmd->current_x, numverts, ob->pd->pdef_sboft);
+ }
+
+ }
+
+ /* happens on file load (ONLY when i decomment changes in readfile.c) */
+ if(!collmd->bvhtree)
+ {
+ collmd->bvhtree = bvhtree_build_from_mvert(collmd->mfaces, collmd->numfaces, collmd->current_x, numverts, ob->pd->pdef_sboft);
+ }
+ else
+ {
+ // recalc static bounding boxes
+ bvhtree_update_from_mvert ( collmd->bvhtree, collmd->mfaces, collmd->numfaces, collmd->current_x, collmd->current_xnew, collmd->numverts, 1 );
+ }
+
+ collmd->time = current_time;
+ }
+ else if(numverts != collmd->numverts)
+ {
+ collisionModifier_freeData((ModifierData *)collmd);
+ }
+
+ }
+ else if(current_time < collmd->time)
+ {
+ collisionModifier_freeData((ModifierData *)collmd);
+ }
+ else
+ {
+ if(numverts != collmd->numverts)
+ {
+ collisionModifier_freeData((ModifierData *)collmd);
+ }
+ }
+ }
+
+ if(dm)
+ dm->release(dm);
+}
+
+
/* Boolean */
static void booleanModifier_copyData(ModifierData *md, ModifierData *target)
@@ -4961,9 +6039,9 @@ static int booleanModifier_isDisabled(ModifierData *md)
}
static void booleanModifier_foreachObjectLink(
- ModifierData *md, Object *ob,
- void (*walk)(void *userData, Object *ob, Object **obpoin),
- void *userData)
+ ModifierData *md, Object *ob,
+ void (*walk)(void *userData, Object *ob, Object **obpoin),
+ void *userData)
{
BooleanModifierData *bmd = (BooleanModifierData*) md;
@@ -4971,8 +6049,8 @@ static void booleanModifier_foreachObjectLink(
}
static void booleanModifier_updateDepgraph(
- ModifierData *md, DagForest *forest, Object *ob,
- DagNode *obNode)
+ ModifierData *md, DagForest *forest, Object *ob,
+ DagNode *obNode)
{
BooleanModifierData *bmd = (BooleanModifierData*) md;
@@ -4980,32 +6058,32 @@ static void booleanModifier_updateDepgraph(
DagNode *curNode = dag_get_node(forest, bmd->object);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Boolean Modifier");
}
}
static DerivedMesh *booleanModifier_applyModifier(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- int useRenderParams, int isFinalCalc)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
{
// XXX doesn't handle derived data
BooleanModifierData *bmd = (BooleanModifierData*) md;
/* we do a quick sanity check */
if(((Mesh *)ob->data)->totface > 3
- && bmd->object && ((Mesh *)bmd->object->data)->totface > 3) {
+ && bmd->object && ((Mesh *)bmd->object->data)->totface > 3) {
DerivedMesh *result = NewBooleanDerivedMesh(bmd->object, ob,
- 1 + bmd->operation);
+ 1 + bmd->operation);
/* if new mesh returned, return it; otherwise there was
- * an error, so delete the modifier object */
+ * an error, so delete the modifier object */
if(result)
return result;
else
bmd->object = NULL;
- }
+ }
- return derivedData;
+ return derivedData;
}
/* Particles */
@@ -5026,7 +6104,6 @@ static void particleSystemModifier_freeData(ModifierData *md)
psmd->dm=0;
}
- psmd->psys->flag &= ~PSYS_ENABLED;
psmd->psys->flag |= PSYS_DELETE;
}
static void particleSystemModifier_copyData(ModifierData *md, ModifierData *target)
@@ -5035,6 +6112,7 @@ static void particleSystemModifier_copyData(ModifierData *md, ModifierData *targ
ParticleSystemModifierData *tpsmd= (ParticleSystemModifierData*) target;
tpsmd->dm = 0;
+ tpsmd->totdmvert = tpsmd->totdmedge = tpsmd->totdmface = 0;
//tpsmd->facepa = 0;
tpsmd->flag = psmd->flag;
/* need to keep this to recognise a bit later in copy_object */
@@ -5056,7 +6134,7 @@ CustomDataMask particleSystemModifier_requiredDataMask(ModifierData *md)
}
/* particles only need this if they are after a non deform modifier, and
- * the modifier stack will only create them in that case. */
+ * the modifier stack will only create them in that case. */
dataMask |= CD_MASK_ORIGSPACE;
dataMask |= CD_MASK_ORCO;
@@ -5088,12 +6166,13 @@ static int is_last_displist(Object *ob)
}
/* saves the current emitter state for a particle system and calculates particles */
static void particleSystemModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm = derivedData;
ParticleSystemModifierData *psmd= (ParticleSystemModifierData*) md;
ParticleSystem * psys=0;
+ Mesh *me;
int needsFree=0;
if(ob->particlesystem.first)
@@ -5101,6 +6180,14 @@ static void particleSystemModifier_deformVerts(
else
return;
+ /* multires check */
+ if(ob->type == OB_MESH) {
+ me= (Mesh*)ob->data;
+ if(me->mr && me->mr->current != 1)
+ modifier_setError(md,
+ "Particles only supported on first multires level.");
+ }
+
if(!psys_check_enabled(ob, psys))
return;
@@ -5151,6 +6238,7 @@ static void particleSystemModifier_deformVerts(
/* make new dm */
psmd->dm=CDDM_copy(dm);
+ CDDM_apply_vert_coords(psmd->dm, vertexCos);
CDDM_calc_normals(psmd->dm);
if(needsFree){
@@ -5163,8 +6251,8 @@ static void particleSystemModifier_deformVerts(
/* report change in mesh structure */
if(psmd->dm->getNumVerts(psmd->dm)!=psmd->totdmvert ||
- psmd->dm->getNumEdges(psmd->dm)!=psmd->totdmedge ||
- psmd->dm->getNumFaces(psmd->dm)!=psmd->totdmface){
+ psmd->dm->getNumEdges(psmd->dm)!=psmd->totdmedge ||
+ psmd->dm->getNumFaces(psmd->dm)!=psmd->totdmface){
/* in file read dm hasn't really changed but just wasn't saved in file */
psys->recalc |= PSYS_RECALC_HAIR;
@@ -5174,13 +6262,13 @@ static void particleSystemModifier_deformVerts(
psmd->totdmvert= psmd->dm->getNumVerts(psmd->dm);
psmd->totdmedge= psmd->dm->getNumEdges(psmd->dm);
psmd->totdmface= psmd->dm->getNumFaces(psmd->dm);
- }
+ }
- if(psys){
- particle_system_update(ob,psys);
- psmd->flag |= eParticleSystemFlag_psys_updated;
- psmd->flag &= ~eParticleSystemFlag_DM_changed;
- }
+ if(psys){
+ particle_system_update(ob,psys);
+ psmd->flag |= eParticleSystemFlag_psys_updated;
+ psmd->flag &= ~eParticleSystemFlag_DM_changed;
+ }
}
/* disabled particles in editmode for now, until support for proper derivedmesh
@@ -5206,7 +6294,7 @@ static void particleInstanceModifier_initData(ModifierData *md)
ParticleInstanceModifierData *pimd= (ParticleInstanceModifierData*) md;
pimd->flag = eParticleInstanceFlag_Parents|eParticleInstanceFlag_Unborn|
- eParticleInstanceFlag_Alive|eParticleInstanceFlag_Dead;
+ eParticleInstanceFlag_Alive|eParticleInstanceFlag_Dead;
pimd->psys = 1;
}
@@ -5225,7 +6313,7 @@ static int particleInstanceModifier_dependsOnTime(ModifierData *md)
return 0;
}
static void particleInstanceModifier_updateDepgraph(ModifierData *md, DagForest *forest,
- Object *ob, DagNode *obNode)
+ Object *ob, DagNode *obNode)
{
ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData*) md;
@@ -5233,12 +6321,13 @@ static void particleInstanceModifier_updateDepgraph(ModifierData *md, DagForest
DagNode *curNode = dag_get_node(forest, pimd->ob);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA,
+ "Particle Instance Modifier");
}
}
static void particleInstanceModifier_foreachObjectLink(ModifierData *md, Object *ob,
- ObjectWalkFunc walk, void *userData)
+ ObjectWalkFunc walk, void *userData)
{
ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData*) md;
@@ -5246,8 +6335,8 @@ static void particleInstanceModifier_foreachObjectLink(ModifierData *md, Object
}
static DerivedMesh * particleInstanceModifier_applyModifier(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- int useRenderParams, int isFinalCalc)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
{
DerivedMesh *dm = derivedData, *result;
ParticleInstanceModifierData *pimd= (ParticleInstanceModifierData*) md;
@@ -5257,7 +6346,7 @@ static DerivedMesh * particleInstanceModifier_applyModifier(
MVert *mvert, *orig_mvert;
int i,totvert, totpart=0, totface, maxvert, maxface, first_particle=0;
short track=ob->trackflag%3, trackneg;
- float max_co=0.0, min_co=0.0, temp_co[3];
+ float max_co=0.0, min_co=0.0, temp_co[3], cross[3];
trackneg=((ob->trackflag>2)?1:0);
@@ -5336,15 +6425,29 @@ static DerivedMesh * particleInstanceModifier_applyModifier(
if(trackneg)
state.time=1.0f-state.time;
psys_get_particle_on_path(pimd->ob,psys,first_particle + i/totvert,&state,1);
+
+ mv->co[0] = 0.0;
+
+ Normalize(state.vel);
+
+ if(state.vel[0] < -0.9999 || state.vel[0] > 0.9999) {
+ state.rot[0] = 1.0;
+ state.rot[1] = state.rot[2] = state.rot[3] = 0.0f;
+ }
+ else {
+ /* a cross product of state.vel and a unit vector in x-direction */
+ cross[0] = 0.0f;
+ cross[1] = -state.vel[2];
+ cross[2] = state.vel[1];
+
+ /* state.vel[0] is the only component surviving from a dot product with a vector in x-direction*/
+ VecRotToQuat(cross,saacos(state.vel[0]),state.rot);
+ }
}
else{
state.time=-1.0;
psys_get_particle_state(pimd->ob,psys,i/totvert,&state,1);
- }
-
- /*displace vertice to path location*/
- if(pimd->flag & eParticleInstanceFlag_Path)
- mv->co[0]=0.0;
+ }
QuatMulVecf(state.rot,mv->co);
VECADD(mv->co,mv->co,state.co);
@@ -5402,8 +6505,8 @@ static DerivedMesh * particleInstanceModifier_applyModifier(
return result;
}
static DerivedMesh *particleInstanceModifier_applyModifierEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData)
{
return particleInstanceModifier_applyModifier(md, ob, derivedData, 0, 1);
}
@@ -5429,6 +6532,8 @@ static void explodeModifier_copyData(ModifierData *md, ModifierData *target)
temd->facepa = 0;
temd->flag = emd->flag;
+ temd->protect = emd->protect;
+ temd->vgroup = emd->vgroup;
}
static int explodeModifier_dependsOnTime(ModifierData *md)
{
@@ -5445,25 +6550,9 @@ CustomDataMask explodeModifier_requiredDataMask(ModifierData *md)
return dataMask;
}
-/* this should really be put somewhere permanently */
-static float vert_weight(MDeformVert *dvert, int group)
-{
- MDeformWeight *dw;
- int i;
-
- if(dvert) {
- dw= dvert->dw;
- for(i= dvert->totweight; i>0; i--, dw++) {
- if(dw->def_nr == group) return dw->weight;
- if(i==1) break; /*otherwise dw will point to somewhere it shouldn't*/
- }
- }
- return 0.0;
-}
-
static void explodeModifier_createFacepa(ExplodeModifierData *emd,
- ParticleSystemModifierData *psmd,
- Object *ob, DerivedMesh *dm)
+ ParticleSystemModifierData *psmd,
+ Object *ob, DerivedMesh *dm)
{
ParticleSystem *psys=psmd->psys;
MFace *fa=0, *mface=0;
@@ -5504,7 +6593,7 @@ static void explodeModifier_createFacepa(ExplodeModifierData *emd,
for(i=0; i<totvert; i++){
val = BLI_frand();
val = (1.0f-emd->protect)*val + emd->protect*0.5f;
- if(val < vert_weight(dvert+i,emd->vgroup-1))
+ if(val < deformvert_get_weight(dvert+i,emd->vgroup-1))
vertpa[i] = -1;
}
}
@@ -5513,7 +6602,7 @@ static void explodeModifier_createFacepa(ExplodeModifierData *emd,
/* make tree of emitter locations */
tree=BLI_kdtree_new(totpart);
for(p=0,pa=psys->particles; p<totpart; p++,pa++){
- psys_particle_on_dm(ob,psmd->dm,psys->part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,0,0,0,0,0);
+ psys_particle_on_dm(psmd->dm,psys->part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,0,0,0,0,0);
BLI_kdtree_insert(tree, p, co, NULL);
}
BLI_kdtree_balance(tree);
@@ -5549,20 +6638,29 @@ static void explodeModifier_createFacepa(ExplodeModifierData *emd,
if(vertpa) MEM_freeN(vertpa);
BLI_kdtree_free(tree);
}
+
+static int edgesplit_get(EdgeHash *edgehash, int v1, int v2)
+{
+ return GET_INT_FROM_POINTER(BLI_edgehash_lookup(edgehash, v1, v2));
+}
+
static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, DerivedMesh *dm){
DerivedMesh *splitdm;
MFace *mf=0,*df1=0,*df2=0,*df3=0;
MFace *mface=CDDM_get_faces(dm);
MVert *dupve, *mv;
+ EdgeHash *edgehash;
+ EdgeHashIterator *ehi;
int totvert=dm->getNumVerts(dm);
int totface=dm->getNumFaces(dm);
- int *edgesplit = MEM_callocN(sizeof(int)*totvert*totvert,"explode_edgesplit");
- int *facesplit = MEM_callocN(sizeof(int)*totface,"explode_edgesplit");
+ int *facesplit = MEM_callocN(sizeof(int)*totface,"explode_facesplit");
int *vertpa = MEM_callocN(sizeof(int)*totvert,"explode_vertpa2");
int *facepa = emd->facepa;
int *fs, totesplit=0,totfsplit=0,totin=0,curdupvert=0,curdupface=0,curdupin=0;
- int i,j,v1,v2,v3,v4;
+ int i,j,v1,v2,v3,v4,esplit;
+
+ edgehash= BLI_edgehash_new();
/* recreate vertpa from facepa calculation */
for (i=0,mf=mface; i<totface; i++,mf++) {
@@ -5582,22 +6680,22 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
v4=vertpa[mf->v4];
if(v1!=v2){
- edgesplit[mf->v1*totvert+mf->v2]=edgesplit[mf->v2*totvert+mf->v1]=1;
+ BLI_edgehash_insert(edgehash, mf->v1, mf->v2, NULL);
(*fs)++;
}
if(v2!=v3){
- edgesplit[mf->v2*totvert+mf->v3]=edgesplit[mf->v3*totvert+mf->v2]=1;
+ BLI_edgehash_insert(edgehash, mf->v2, mf->v3, NULL);
(*fs)++;
}
if(v3!=v4){
- edgesplit[mf->v3*totvert+mf->v4]=edgesplit[mf->v4*totvert+mf->v3]=1;
+ BLI_edgehash_insert(edgehash, mf->v3, mf->v4, NULL);
(*fs)++;
}
if(v1!=v4){
- edgesplit[mf->v1*totvert+mf->v4]=edgesplit[mf->v4*totvert+mf->v1]=1;
+ BLI_edgehash_insert(edgehash, mf->v1, mf->v4, NULL);
(*fs)++;
}
@@ -5606,28 +6704,29 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
*fs=1;
else if(v1!=v2){
if(v1!=v4)
- edgesplit[mf->v2*totvert+mf->v3]=edgesplit[mf->v3*totvert+mf->v2]=1;
+ BLI_edgehash_insert(edgehash, mf->v2, mf->v3, NULL);
else
- edgesplit[mf->v3*totvert+mf->v4]=edgesplit[mf->v4*totvert+mf->v3]=1;
+ BLI_edgehash_insert(edgehash, mf->v3, mf->v4, NULL);
}
else{
if(v1!=v4)
- edgesplit[mf->v1*totvert+mf->v2]=edgesplit[mf->v2*totvert+mf->v1]=1;
+ BLI_edgehash_insert(edgehash, mf->v1, mf->v2, NULL);
else
- edgesplit[mf->v1*totvert+mf->v4]=edgesplit[mf->v4*totvert+mf->v1]=1;
+ BLI_edgehash_insert(edgehash, mf->v1, mf->v4, NULL);
}
}
}
}
/* count splits & reindex */
+ ehi= BLI_edgehashIterator_new(edgehash);
totesplit=totvert;
- for(j=0; j<totvert; j++){
- for(i=j+1; i<totvert; i++){
- if(edgesplit[j*totvert+i])
- edgesplit[j*totvert+i]=edgesplit[i*totvert+j]=totesplit++;
- }
+ for(; !BLI_edgehashIterator_isDone(ehi); BLI_edgehashIterator_step(ehi)) {
+ BLI_edgehashIterator_setValue(ehi, SET_INT_IN_POINTER(totesplit));
+ totesplit++;
}
+ BLI_edgehashIterator_free(ehi);
+
/* count new faces due to splitting */
for(i=0,fs=facesplit; i<totface; i++,fs++){
if(*fs==1)
@@ -5675,23 +6774,23 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
/* create new verts */
curdupvert=totvert;
- for(j=0; j<totvert; j++){
- for(i=j+1; i<totvert; i++){
- if(edgesplit[j*totvert+i]){
- mv=CDDM_get_vert(splitdm,j);
- dupve=CDDM_get_vert(splitdm,edgesplit[j*totvert+i]);
+ ehi= BLI_edgehashIterator_new(edgehash);
+ for(; !BLI_edgehashIterator_isDone(ehi); BLI_edgehashIterator_step(ehi)) {
+ BLI_edgehashIterator_getKey(ehi, &i, &j);
+ esplit= GET_INT_FROM_POINTER(BLI_edgehashIterator_getValue(ehi));
+ mv=CDDM_get_vert(splitdm,j);
+ dupve=CDDM_get_vert(splitdm,esplit);
- DM_copy_vert_data(splitdm,splitdm,j,edgesplit[j*totvert+i],1);
+ DM_copy_vert_data(splitdm,splitdm,j,esplit,1);
- *dupve=*mv;
+ *dupve=*mv;
- mv=CDDM_get_vert(splitdm,i);
+ mv=CDDM_get_vert(splitdm,i);
- VECADD(dupve->co,dupve->co,mv->co);
- VecMulf(dupve->co,0.5);
- }
- }
+ VECADD(dupve->co,dupve->co,mv->co);
+ VecMulf(dupve->co,0.5);
}
+ BLI_edgehashIterator_free(ehi);
/* create new faces */
curdupface=totface;
@@ -5712,14 +6811,14 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
curdupface++;
if(v1==v2){
- df1->v1=edgesplit[mf->v1*totvert+mf->v4];
- df1->v2=edgesplit[mf->v2*totvert+mf->v3];
+ df1->v1=edgesplit_get(edgehash, mf->v1, mf->v4);
+ df1->v2=edgesplit_get(edgehash, mf->v2, mf->v3);
mf->v3=df1->v2;
mf->v4=df1->v1;
}
else{
- df1->v1=edgesplit[mf->v1*totvert+mf->v2];
- df1->v4=edgesplit[mf->v3*totvert+mf->v4];
+ df1->v1=edgesplit_get(edgehash, mf->v1, mf->v2);
+ df1->v4=edgesplit_get(edgehash, mf->v3, mf->v4);
mf->v2=df1->v1;
mf->v3=df1->v4;
}
@@ -5742,8 +6841,8 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
if(v1!=v2){
if(v1!=v4){
- df1->v1=edgesplit[mf->v1*totvert+mf->v4];
- df1->v2=edgesplit[mf->v1*totvert+mf->v2];
+ df1->v1=edgesplit_get(edgehash, mf->v1, mf->v4);
+ df1->v2=edgesplit_get(edgehash, mf->v1, mf->v2);
df2->v1=df1->v3=mf->v2;
df2->v3=df1->v4=mf->v4;
df2->v2=mf->v3;
@@ -5756,8 +6855,8 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
facepa[i]=v1;
}
else{
- df1->v2=edgesplit[mf->v1*totvert+mf->v2];
- df1->v3=edgesplit[mf->v2*totvert+mf->v3];
+ df1->v2=edgesplit_get(edgehash, mf->v1, mf->v2);
+ df1->v3=edgesplit_get(edgehash, mf->v2, mf->v3);
df1->v4=mf->v3;
df2->v2=mf->v3;
df2->v3=mf->v4;
@@ -5773,8 +6872,8 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
}
else{
if(v1!=v4){
- df1->v3=edgesplit[mf->v3*totvert+mf->v4];
- df1->v4=edgesplit[mf->v1*totvert+mf->v4];
+ df1->v3=edgesplit_get(edgehash, mf->v3, mf->v4);
+ df1->v4=edgesplit_get(edgehash, mf->v1, mf->v4);
df1->v2=mf->v3;
mf->v1=df1->v4;
@@ -5786,8 +6885,8 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
facepa[i]=v4;
}
else{
- df1->v3=edgesplit[mf->v2*totvert+mf->v3];
- df1->v4=edgesplit[mf->v3*totvert+mf->v4];
+ df1->v3=edgesplit_get(edgehash, mf->v2, mf->v3);
+ df1->v4=edgesplit_get(edgehash, mf->v3, mf->v4);
df1->v1=mf->v4;
df1->v2=mf->v2;
df2->v3=mf->v4;
@@ -5823,9 +6922,9 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
curdupface++;
if(v1==v2){
- df2->v1=df1->v1=edgesplit[mf->v1*totvert+mf->v4];
- df3->v1=df1->v2=edgesplit[mf->v2*totvert+mf->v3];
- df3->v3=df2->v2=df1->v3=edgesplit[mf->v3*totvert+mf->v4];
+ df2->v1=df1->v1=edgesplit_get(edgehash, mf->v1, mf->v4);
+ df3->v1=df1->v2=edgesplit_get(edgehash, mf->v2, mf->v3);
+ df3->v3=df2->v2=df1->v3=edgesplit_get(edgehash, mf->v3, mf->v4);
df3->v2=mf->v3;
df2->v3=mf->v4;
df1->v4=df2->v4=df3->v4=0;
@@ -5838,9 +6937,9 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
facepa[curdupface-2]=v4;
}
else if(v2==v3){
- df3->v1=df2->v3=df1->v1=edgesplit[mf->v1*totvert+mf->v4];
- df2->v2=df1->v2=edgesplit[mf->v1*totvert+mf->v2];
- df3->v2=df1->v3=edgesplit[mf->v3*totvert+mf->v4];
+ df3->v1=df2->v3=df1->v1=edgesplit_get(edgehash, mf->v1, mf->v4);
+ df2->v2=df1->v2=edgesplit_get(edgehash, mf->v1, mf->v2);
+ df3->v2=df1->v3=edgesplit_get(edgehash, mf->v3, mf->v4);
df3->v3=mf->v4;
df2->v1=mf->v1;
@@ -5854,9 +6953,9 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
facepa[curdupface-2]=v1;
}
else if(v3==v4){
- df3->v2=df2->v1=df1->v1=edgesplit[mf->v1*totvert+mf->v2];
- df2->v3=df1->v2=edgesplit[mf->v2*totvert+mf->v3];
- df3->v3=df1->v3=edgesplit[mf->v1*totvert+mf->v4];
+ df3->v2=df2->v1=df1->v1=edgesplit_get(edgehash, mf->v1, mf->v2);
+ df2->v3=df1->v2=edgesplit_get(edgehash, mf->v2, mf->v3);
+ df3->v3=df1->v3=edgesplit_get(edgehash, mf->v1, mf->v4);
df3->v1=mf->v1;
df2->v2=mf->v2;
@@ -5870,9 +6969,9 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
facepa[curdupface-2]=v2;
}
else{
- df3->v1=df1->v1=edgesplit[mf->v1*totvert+mf->v2];
- df3->v3=df2->v1=df1->v2=edgesplit[mf->v2*totvert+mf->v3];
- df2->v3=df1->v3=edgesplit[mf->v3*totvert+mf->v4];
+ df3->v1=df1->v1=edgesplit_get(edgehash, mf->v1, mf->v2);
+ df3->v3=df2->v1=df1->v2=edgesplit_get(edgehash, mf->v2, mf->v3);
+ df2->v3=df1->v3=edgesplit_get(edgehash, mf->v3, mf->v4);
df3->v2=mf->v2;
df2->v2=mf->v3;
@@ -5923,11 +7022,11 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
*df3=*mf;
curdupface++;
- df1->v1=edgesplit[mf->v1*totvert+mf->v2];
- df3->v2=df1->v3=edgesplit[mf->v2*totvert+mf->v3];
+ df1->v1=edgesplit_get(edgehash, mf->v1, mf->v2);
+ df3->v2=df1->v3=edgesplit_get(edgehash, mf->v2, mf->v3);
- df2->v1=edgesplit[mf->v1*totvert+mf->v4];
- df3->v4=df2->v3=edgesplit[mf->v3*totvert+mf->v4];
+ df2->v1=edgesplit_get(edgehash, mf->v1, mf->v4);
+ df3->v4=df2->v3=edgesplit_get(edgehash, mf->v3, mf->v4);
df3->v1=df2->v2=df1->v4=curdupin;
@@ -5964,11 +7063,11 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
curdupface++;
if(v2==v3){
- df1->v1=edgesplit[mf->v1*totvert+mf->v2];
- df3->v1=df1->v2=df1->v3=edgesplit[mf->v2*totvert+mf->v3];
- df2->v1=df1->v4=edgesplit[mf->v1*totvert+mf->v4];
+ df1->v1=edgesplit_get(edgehash, mf->v1, mf->v2);
+ df3->v1=df1->v2=df1->v3=edgesplit_get(edgehash, mf->v2, mf->v3);
+ df2->v1=df1->v4=edgesplit_get(edgehash, mf->v1, mf->v4);
- df3->v3=df2->v3=edgesplit[mf->v3*totvert+mf->v4];
+ df3->v3=df2->v3=edgesplit_get(edgehash, mf->v3, mf->v4);
df3->v2=mf->v3;
df3->v4=0;
@@ -5982,11 +7081,11 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
facepa[curdupface-1]=v3;
}
else{
- df3->v1=df2->v1=df1->v2=edgesplit[mf->v1*totvert+mf->v2];
- df2->v4=df1->v3=edgesplit[mf->v3*totvert+mf->v4];
- df1->v4=edgesplit[mf->v1*totvert+mf->v4];
+ df3->v1=df2->v1=df1->v2=edgesplit_get(edgehash, mf->v1, mf->v2);
+ df2->v4=df1->v3=edgesplit_get(edgehash, mf->v3, mf->v4);
+ df1->v4=edgesplit_get(edgehash, mf->v1, mf->v4);
- df3->v3=df2->v2=edgesplit[mf->v2*totvert+mf->v3];
+ df3->v3=df2->v2=edgesplit_get(edgehash, mf->v2, mf->v3);
df3->v4=0;
@@ -6010,7 +7109,7 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
}
}
- MEM_freeN(edgesplit);
+ BLI_edgehash_free(edgehash, NULL);
MEM_freeN(facesplit);
MEM_freeN(vertpa);
@@ -6018,19 +7117,20 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
}
static DerivedMesh * explodeModifier_explodeMesh(ExplodeModifierData *emd,
- ParticleSystemModifierData *psmd, Object *ob,
- DerivedMesh *to_explode)
+ ParticleSystemModifierData *psmd, Object *ob,
+ DerivedMesh *to_explode)
{
DerivedMesh *explode, *dm=to_explode;
MFace *mf=0;
- MVert *dupvert=0;
ParticleSettings *part=psmd->psys->part;
- ParticleData *pa, *pars=psmd->psys->particles;
+ ParticleData *pa=NULL, *pars=psmd->psys->particles;
ParticleKey state;
+ EdgeHash *vertpahash;
+ EdgeHashIterator *ehi;
float *vertco=0, imat[4][4];
float loc0[3], nor[3];
float timestep, cfra;
- int *facepa=emd->facepa, *vertpa=0;
+ int *facepa=emd->facepa;
int totdup=0,totvert=0,totface=0,totpart=0;
int i, j, v, mindex=0;
@@ -6045,81 +7145,87 @@ static DerivedMesh * explodeModifier_explodeMesh(ExplodeModifierData *emd,
else
cfra=bsystem_time(ob,(float)G.scene->r.cfra,0.0);
- /* table for vertice <-> particle relations (row totpart+1 is for yet unexploded verts) */
- vertpa = MEM_callocN(sizeof(int)*(totpart+1)*totvert, "explode_vertpatab");
- for(i=0; i<(totpart+1)*totvert; i++)
- vertpa[i] = -1;
+ /* hash table for vertice <-> particle relations */
+ vertpahash= BLI_edgehash_new();
for (i=0; i<totface; i++) {
+ /* do mindex + totvert to ensure the vertex index to be the first
+ * with BLI_edgehashIterator_getKey */
if(facepa[i]==totpart || cfra <= (pars+facepa[i])->time)
- mindex = totpart*totvert;
+ mindex = totvert+totpart;
else
- mindex = facepa[i]*totvert;
+ mindex = totvert+facepa[i];
mf=CDDM_get_face(dm,i);
- /*set face vertices to exist in particle group*/
- vertpa[mindex+mf->v1] = 1;
- vertpa[mindex+mf->v2] = 1;
- vertpa[mindex+mf->v3] = 1;
+ /* set face vertices to exist in particle group */
+ BLI_edgehash_insert(vertpahash, mf->v1, mindex, NULL);
+ BLI_edgehash_insert(vertpahash, mf->v2, mindex, NULL);
+ BLI_edgehash_insert(vertpahash, mf->v3, mindex, NULL);
if(mf->v4)
- vertpa[mindex+mf->v4] = 1;
+ BLI_edgehash_insert(vertpahash, mf->v4, mindex, NULL);
}
- /*make new vertice indexes & count total vertices after duplication*/
- for(i=0; i<(totpart+1)*totvert; i++){
- if(vertpa[i] != -1)
- vertpa[i] = totdup++;
+ /* make new vertice indexes & count total vertices after duplication */
+ ehi= BLI_edgehashIterator_new(vertpahash);
+ for(; !BLI_edgehashIterator_isDone(ehi); BLI_edgehashIterator_step(ehi)) {
+ BLI_edgehashIterator_setValue(ehi, SET_INT_IN_POINTER(totdup));
+ totdup++;
}
+ BLI_edgehashIterator_free(ehi);
- /*the final duplicated vertices*/
+ /* the final duplicated vertices */
explode= CDDM_from_template(dm, totdup, 0,totface);
- dupvert= CDDM_get_verts(explode);
+ /*dupvert= CDDM_get_verts(explode);*/
/* getting back to object space */
Mat4Invert(imat,ob->obmat);
psmd->psys->lattice = psys_get_lattice(ob, psmd->psys);
- /*duplicate & displace vertices*/
- for(i=0, pa=pars; i<=totpart; i++, pa++){
- if(i!=totpart){
- psys_particle_on_emitter(ob, psmd,part->from,pa->num,-1,pa->fuv,pa->foffset,loc0,nor,0,0,0,0);
- Mat4MulVecfl(ob->obmat,loc0);
+ /* duplicate & displace vertices */
+ ehi= BLI_edgehashIterator_new(vertpahash);
+ for(; !BLI_edgehashIterator_isDone(ehi); BLI_edgehashIterator_step(ehi)) {
+ MVert source;
+ MVert *dest;
- state.time=cfra;
- psys_get_particle_state(ob,psmd->psys,i,&state,1);
- }
+ /* get particle + vertex from hash */
+ BLI_edgehashIterator_getKey(ehi, &j, &i);
+ i -= totvert;
+ v= GET_INT_FROM_POINTER(BLI_edgehashIterator_getValue(ehi));
- for(j=0; j<totvert; j++){
- v=vertpa[i*totvert+j];
- if(v != -1) {
- MVert source;
- MVert *dest;
+ dm->getVert(dm, j, &source);
+ dest = CDDM_get_vert(explode,v);
- dm->getVert(dm, j, &source);
- dest = CDDM_get_vert(explode,v);
+ DM_copy_vert_data(dm,explode,j,v,1);
+ *dest = source;
- DM_copy_vert_data(dm,explode,j,v,1);
- *dest = source;
+ if(i!=totpart) {
+ /* get particle */
+ pa= pars+i;
- if(i!=totpart){
- vertco=CDDM_get_vert(explode,v)->co;
-
- Mat4MulVecfl(ob->obmat,vertco);
+ /* get particle state */
+ psys_particle_on_emitter(psmd,part->from,pa->num,-1,pa->fuv,pa->foffset,loc0,nor,0,0,0,0);
+ Mat4MulVecfl(ob->obmat,loc0);
- VECSUB(vertco,vertco,loc0);
+ state.time=cfra;
+ psys_get_particle_state(ob,psmd->psys,i,&state,1);
- /* apply rotation, size & location */
- QuatMulVecf(state.rot,vertco);
- VecMulf(vertco,pa->size);
- VECADD(vertco,vertco,state.co);
+ vertco=CDDM_get_vert(explode,v)->co;
+
+ Mat4MulVecfl(ob->obmat,vertco);
- Mat4MulVecfl(imat,vertco);
- }
- }
+ VECSUB(vertco,vertco,loc0);
+
+ /* apply rotation, size & location */
+ QuatMulVecf(state.rot,vertco);
+ VecMulf(vertco,pa->size);
+ VECADD(vertco,vertco,state.co);
+
+ Mat4MulVecfl(imat,vertco);
}
}
+ BLI_edgehashIterator_free(ehi);
/*map new vertices to faces*/
for (i=0; i<totface; i++) {
@@ -6141,15 +7247,15 @@ static DerivedMesh * explodeModifier_explodeMesh(ExplodeModifierData *emd,
orig_v4 = source.v4;
if(facepa[i]!=totpart && cfra <= pa->time)
- mindex = totpart*totvert;
+ mindex = totvert+totpart;
else
- mindex = facepa[i]*totvert;
+ mindex = totvert+facepa[i];
- source.v1 = vertpa[mindex+source.v1];
- source.v2 = vertpa[mindex+source.v2];
- source.v3 = vertpa[mindex+source.v3];
+ source.v1 = edgesplit_get(vertpahash, source.v1, mindex);
+ source.v2 = edgesplit_get(vertpahash, source.v2, mindex);
+ source.v3 = edgesplit_get(vertpahash, source.v3, mindex);
if(source.v4)
- source.v4 = vertpa[mindex+source.v4];
+ source.v4 = edgesplit_get(vertpahash, source.v4, mindex);
DM_copy_face_data(dm,explode,i,i,1);
@@ -6158,9 +7264,10 @@ static DerivedMesh * explodeModifier_explodeMesh(ExplodeModifierData *emd,
test_index_face(mf, &explode->faceData, i, (mf->v4 ? 4 : 3));
}
+ MEM_printmemlist_stats();
/* cleanup */
- if(vertpa) MEM_freeN(vertpa);
+ BLI_edgehash_free(vertpahash, NULL);
/* finalization */
CDDM_calc_edges(explode);
@@ -6186,8 +7293,8 @@ static ParticleSystemModifierData * explodeModifier_findPrecedingParticlesystem(
return psmd;
}
static DerivedMesh * explodeModifier_applyModifier(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- int useRenderParams, int isFinalCalc)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
{
DerivedMesh *dm = derivedData;
ExplodeModifierData *emd= (ExplodeModifierData*) md;
@@ -6198,12 +7305,13 @@ static DerivedMesh * explodeModifier_applyModifier(
if(psys==0 || psys->totpart==0) return derivedData;
if(psys->part==0 || psys->particles==0) return derivedData;
+ if(psmd->dm==0) return derivedData;
/* 1. find faces to be exploded if needed */
if(emd->facepa==0
- || psmd->flag&eParticleSystemFlag_Pars
- || emd->flag&eExplodeFlag_CalcFaces
- || MEM_allocN_len(emd->facepa)/sizeof(int) != dm->getNumFaces(dm)){
+ || psmd->flag&eParticleSystemFlag_Pars
+ || emd->flag&eExplodeFlag_CalcFaces
+ || MEM_allocN_len(emd->facepa)/sizeof(int) != dm->getNumFaces(dm)){
if(psmd->flag & eParticleSystemFlag_Pars)
psmd->flag &= ~eParticleSystemFlag_Pars;
@@ -6211,24 +7319,111 @@ static DerivedMesh * explodeModifier_applyModifier(
emd->flag &= ~eExplodeFlag_CalcFaces;
explodeModifier_createFacepa(emd,psmd,ob,derivedData);
- }
+ }
+
+ /* 2. create new mesh */
+ if(emd->flag & eExplodeFlag_EdgeSplit){
+ int *facepa = emd->facepa;
+ DerivedMesh *splitdm=explodeModifier_splitEdges(emd,dm);
+ DerivedMesh *explode=explodeModifier_explodeMesh(emd,psmd,ob,splitdm);
+
+ MEM_freeN(emd->facepa);
+ emd->facepa=facepa;
+ splitdm->release(splitdm);
+ return explode;
+ }
+ else
+ return explodeModifier_explodeMesh(emd,psmd,ob,derivedData);
+ }
+ return derivedData;
+}
- /* 2. create new mesh */
- if(emd->flag & eExplodeFlag_EdgeSplit){
- int *facepa = emd->facepa;
- DerivedMesh *splitdm=explodeModifier_splitEdges(emd,dm);
- DerivedMesh *explode=explodeModifier_explodeMesh(emd,psmd,ob,splitdm);
+/* Fluidsim */
+static void fluidsimModifier_initData(ModifierData *md)
+{
+ FluidsimModifierData *fluidmd= (FluidsimModifierData*) md;
+
+ fluidsim_init(fluidmd);
+}
+static void fluidsimModifier_freeData(ModifierData *md)
+{
+ FluidsimModifierData *fluidmd= (FluidsimModifierData*) md;
+
+ fluidsim_free(fluidmd);
+}
- MEM_freeN(emd->facepa);
- emd->facepa=facepa;
- splitdm->release(splitdm);
- return explode;
- }
- else
- return explodeModifier_explodeMesh(emd,psmd,ob,derivedData);
+static void fluidsimModifier_copyData(ModifierData *md, ModifierData *target)
+{
+ FluidsimModifierData *fluidmd= (FluidsimModifierData*) md;
+ FluidsimModifierData *tfluidmd= (FluidsimModifierData*) target;
+
+ if(tfluidmd->fss)
+ MEM_freeN(tfluidmd->fss);
+
+ tfluidmd->fss = MEM_dupallocN(fluidmd->fss);
+}
+
+static DerivedMesh * fluidsimModifier_applyModifier(
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
+{
+ FluidsimModifierData *fluidmd= (FluidsimModifierData*) md;
+ DerivedMesh *result = NULL;
+
+ /* check for alloc failing */
+ if(!fluidmd->fss)
+ {
+ fluidsimModifier_initData(md);
+
+ if(!fluidmd->fss)
+ return derivedData;
+ }
+
+ result = fluidsimModifier_do(fluidmd, ob, derivedData, useRenderParams, isFinalCalc);
+
+ if(result)
+ {
+ return result;
}
+
return derivedData;
}
+
+static void fluidsimModifier_updateDepgraph(
+ ModifierData *md, DagForest *forest,
+ Object *ob, DagNode *obNode)
+{
+ FluidsimModifierData *fluidmd= (FluidsimModifierData*) md;
+ Base *base;
+
+ if(fluidmd && fluidmd->fss)
+ {
+ if(fluidmd->fss->type == OB_FLUIDSIM_DOMAIN)
+ {
+ for(base = G.scene->base.first; base; base= base->next)
+ {
+ Object *ob1= base->object;
+ if(ob1 != ob)
+ {
+ FluidsimModifierData *fluidmdtmp = (FluidsimModifierData *)modifiers_findByType(ob1, eModifierType_Fluidsim);
+
+ // only put dependancies from NON-DOMAIN fluids in here
+ if(fluidmdtmp && fluidmdtmp->fss && (fluidmdtmp->fss->type!=OB_FLUIDSIM_DOMAIN))
+ {
+ DagNode *curNode = dag_get_node(forest, ob1);
+ dag_add_relation(forest, curNode, obNode, DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Fluidsim Object");
+ }
+ }
+ }
+ }
+ }
+}
+
+static int fluidsimModifier_dependsOnTime(ModifierData *md)
+{
+ return 1;
+}
+
/* MeshDeform */
static void meshdeformModifier_initData(ModifierData *md)
@@ -6277,9 +7472,9 @@ static int meshdeformModifier_isDisabled(ModifierData *md)
}
static void meshdeformModifier_foreachObjectLink(
- ModifierData *md, Object *ob,
- void (*walk)(void *userData, Object *ob, Object **obpoin),
- void *userData)
+ ModifierData *md, Object *ob,
+ void (*walk)(void *userData, Object *ob, Object **obpoin),
+ void *userData)
{
MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
@@ -6287,8 +7482,8 @@ static void meshdeformModifier_foreachObjectLink(
}
static void meshdeformModifier_updateDepgraph(
- ModifierData *md, DagForest *forest, Object *ob,
- DagNode *obNode)
+ ModifierData *md, DagForest *forest, Object *ob,
+ DagNode *obNode)
{
MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
@@ -6296,7 +7491,8 @@ static void meshdeformModifier_updateDepgraph(
DagNode *curNode = dag_get_node(forest, mmd->object);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA|DAG_RL_OB_DATA|DAG_RL_DATA_OB|DAG_RL_OB_OB);
+ DAG_RL_DATA_DATA|DAG_RL_OB_DATA|DAG_RL_DATA_OB|DAG_RL_OB_OB,
+ "Mesh Deform Modifier");
}
}
@@ -6353,11 +7549,11 @@ static float meshdeform_dynamic_bind(MeshDeformModifierData *mmd, float (*dco)[3
}
static void meshdeformModifier_do(
- ModifierData *md, Object *ob, DerivedMesh *dm,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *dm,
+ float (*vertexCos)[3], int numVerts)
{
MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
- float imat[4][4], cagemat[4][4], icagemat[4][4], iobmat[3][3];
+ float imat[4][4], cagemat[4][4], iobmat[4][4], icagemat[3][3], cmat[4][4];
float weight, totweight, fac, co[3], *weights, (*dco)[3], (*bindcos)[3];
int a, b, totvert, totcagevert, defgrp_index;
DerivedMesh *tmpdm, *cagedm;
@@ -6380,15 +7576,24 @@ static void meshdeformModifier_do(
if(!cagedm)
return;
- /* compute matrices to go in and out of cage object space */
+ /* compute matrices to go in and out of cage object space */
Mat4Invert(imat, mmd->object->obmat);
Mat4MulMat4(cagemat, ob->obmat, imat);
- Mat4Invert(icagemat, cagemat);
- Mat3CpyMat4(iobmat, icagemat);
+ Mat4MulMat4(cmat, cagemat, mmd->bindmat);
+ Mat4Invert(iobmat, cmat);
+ Mat3CpyMat4(icagemat, iobmat);
/* bind weights if needed */
- if(!mmd->bindcos)
- //XXX harmonic_coordinates_bind(mmd, vertexCos, numVerts, cagemat);
+ if(!mmd->bindcos) {
+ static int recursive = 0;
+
+ /* progress bar redraw can make this recursive .. */
+ if(!recursive) {
+ recursive = 1;
+ //XXX harmonic_coordinates_bind(mmd, vertexCos, numVerts, cagemat);
+ recursive = 0;
+ }
+ }
/* verify we have compatible weights */
totvert= numVerts;
@@ -6482,11 +7687,11 @@ static void meshdeformModifier_do(
if(totweight > 0.0f) {
VecMulf(co, fac/totweight);
- Mat3MulVecfl(iobmat, co);
+ Mat3MulVecfl(icagemat, co);
if(G.rt != 527)
VECADD(vertexCos[b], vertexCos[b], co)
- else
- VECCOPY(vertexCos[b], co)
+ else
+ VECCOPY(vertexCos[b], co)
}
}
@@ -6496,8 +7701,8 @@ static void meshdeformModifier_do(
}
static void meshdeformModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm;
@@ -6515,8 +7720,8 @@ static void meshdeformModifier_deformVerts(
}
static void meshdeformModifier_deformVertsEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm;
@@ -6531,6 +7736,235 @@ static void meshdeformModifier_deformVertsEM(
dm->release(dm);
}
+
+/* Shrinkwrap */
+
+static void shrinkwrapModifier_initData(ModifierData *md)
+{
+ ShrinkwrapModifierData *smd = (ShrinkwrapModifierData*) md;
+ smd->shrinkType = MOD_SHRINKWRAP_NEAREST_SURFACE;
+ smd->shrinkOpts = MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR;
+ smd->keepDist = 0.0f;
+
+ smd->target = NULL;
+ smd->auxTarget = NULL;
+}
+
+static void shrinkwrapModifier_copyData(ModifierData *md, ModifierData *target)
+{
+ ShrinkwrapModifierData *smd = (ShrinkwrapModifierData*)md;
+ ShrinkwrapModifierData *tsmd = (ShrinkwrapModifierData*)target;
+
+ tsmd->target = smd->target;
+ tsmd->auxTarget = smd->auxTarget;
+
+ strcpy(tsmd->vgroup_name, smd->vgroup_name);
+
+ tsmd->keepDist = smd->keepDist;
+ tsmd->shrinkType= smd->shrinkType;
+ tsmd->shrinkOpts= smd->shrinkOpts;
+ tsmd->projAxis = smd->projAxis;
+ tsmd->subsurfLevels = smd->subsurfLevels;
+}
+
+CustomDataMask shrinkwrapModifier_requiredDataMask(ModifierData *md)
+{
+ ShrinkwrapModifierData *smd = (ShrinkwrapModifierData *)md;
+ CustomDataMask dataMask = 0;
+
+ /* ask for vertexgroups if we need them */
+ if(smd->vgroup_name[0])
+ dataMask |= (1 << CD_MDEFORMVERT);
+
+ if(smd->shrinkType == MOD_SHRINKWRAP_PROJECT
+ && smd->projAxis == MOD_SHRINKWRAP_PROJECT_OVER_NORMAL)
+ dataMask |= (1 << CD_MVERT);
+
+ return dataMask;
+}
+
+static int shrinkwrapModifier_isDisabled(ModifierData *md)
+{
+ ShrinkwrapModifierData *smd = (ShrinkwrapModifierData*) md;
+ return !smd->target;
+}
+
+
+static void shrinkwrapModifier_foreachObjectLink(ModifierData *md, Object *ob, ObjectWalkFunc walk, void *userData)
+{
+ ShrinkwrapModifierData *smd = (ShrinkwrapModifierData*) md;
+
+ walk(userData, ob, &smd->target);
+ walk(userData, ob, &smd->auxTarget);
+}
+
+static void shrinkwrapModifier_deformVerts(ModifierData *md, Object *ob, DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+{
+ DerivedMesh *dm = NULL;
+ CustomDataMask dataMask = shrinkwrapModifier_requiredDataMask(md);
+
+ /* We implement requiredDataMask but thats not really usefull since mesh_calc_modifiers pass a NULL derivedData or without the modified vertexs applied */
+ if(dataMask)
+ {
+ if(derivedData) dm = CDDM_copy(derivedData);
+ else if(ob->type==OB_MESH) dm = CDDM_from_mesh(ob->data, ob);
+ else if(ob->type==OB_LATTICE) dm = NULL;
+ else return;
+
+ if(dm != NULL && (dataMask & CD_MVERT))
+ {
+ CDDM_apply_vert_coords(dm, vertexCos);
+ CDDM_calc_normals(dm);
+ }
+ }
+
+ shrinkwrapModifier_deform((ShrinkwrapModifierData*)md, ob, dm, vertexCos, numVerts);
+
+ if(dm)
+ dm->release(dm);
+}
+
+static void shrinkwrapModifier_deformVertsEM(ModifierData *md, Object *ob, EditMesh *editData, DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+{
+ DerivedMesh *dm = NULL;
+ CustomDataMask dataMask = shrinkwrapModifier_requiredDataMask(md);
+
+ if(dataMask)
+ {
+ if(derivedData) dm = CDDM_copy(derivedData);
+ else if(ob->type==OB_MESH) dm = CDDM_from_editmesh(editData, ob->data);
+ else if(ob->type==OB_LATTICE) dm = NULL;
+ else return;
+
+ if(dm != NULL && (dataMask & CD_MVERT))
+ {
+ CDDM_apply_vert_coords(dm, vertexCos);
+ CDDM_calc_normals(dm);
+ }
+ }
+
+ shrinkwrapModifier_deform((ShrinkwrapModifierData*)md, ob, dm, vertexCos, numVerts);
+
+ if(dm)
+ dm->release(dm);
+}
+
+static void shrinkwrapModifier_updateDepgraph(ModifierData *md, DagForest *forest, Object *ob, DagNode *obNode)
+{
+ ShrinkwrapModifierData *smd = (ShrinkwrapModifierData*) md;
+
+ if (smd->target)
+ dag_add_relation(forest, dag_get_node(forest, smd->target), obNode, DAG_RL_OB_DATA | DAG_RL_DATA_DATA, "Shrinkwrap Modifier");
+
+ if (smd->auxTarget)
+ dag_add_relation(forest, dag_get_node(forest, smd->auxTarget), obNode, DAG_RL_OB_DATA | DAG_RL_DATA_DATA, "Shrinkwrap Modifier");
+}
+
+/* SimpleDeform */
+static void simpledeformModifier_initData(ModifierData *md)
+{
+ SimpleDeformModifierData *smd = (SimpleDeformModifierData*) md;
+
+ smd->mode = MOD_SIMPLEDEFORM_MODE_TWIST;
+ smd->axis = 0;
+
+ smd->origin = NULL;
+ smd->factor = 0.35f;
+ smd->limit[0] = 0.0f;
+ smd->limit[1] = 1.0f;
+}
+
+static void simpledeformModifier_copyData(ModifierData *md, ModifierData *target)
+{
+ SimpleDeformModifierData *smd = (SimpleDeformModifierData*)md;
+ SimpleDeformModifierData *tsmd = (SimpleDeformModifierData*)target;
+
+ tsmd->mode = smd->mode;
+ tsmd->axis = smd->axis;
+ tsmd->origin= smd->origin;
+ tsmd->factor= smd->factor;
+ memcpy(tsmd->limit, smd->limit, sizeof(tsmd->limit));
+}
+
+static CustomDataMask simpledeformModifier_requiredDataMask(ModifierData *md)
+{
+ SimpleDeformModifierData *smd = (SimpleDeformModifierData *)md;
+ CustomDataMask dataMask = 0;
+
+ /* ask for vertexgroups if we need them */
+ if(smd->vgroup_name[0])
+ dataMask |= (1 << CD_MDEFORMVERT);
+
+ return dataMask;
+}
+
+static void simpledeformModifier_foreachObjectLink(ModifierData *md, Object *ob, void (*walk)(void *userData, Object *ob, Object **obpoin), void *userData)
+{
+ SimpleDeformModifierData *smd = (SimpleDeformModifierData*)md;
+ walk(userData, ob, &smd->origin);
+}
+
+static void simpledeformModifier_updateDepgraph(ModifierData *md, DagForest *forest, Object *ob, DagNode *obNode)
+{
+ SimpleDeformModifierData *smd = (SimpleDeformModifierData*)md;
+
+ if (smd->origin)
+ dag_add_relation(forest, dag_get_node(forest, smd->origin), obNode, DAG_RL_OB_DATA, "SimpleDeform Modifier");
+}
+
+static void simpledeformModifier_deformVerts(ModifierData *md, Object *ob, DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+{
+ DerivedMesh *dm = NULL;
+ CustomDataMask dataMask = simpledeformModifier_requiredDataMask(md);
+
+ /* We implement requiredDataMask but thats not really usefull since mesh_calc_modifiers pass a NULL derivedData or without the modified vertexs applied */
+ if(dataMask)
+ {
+ if(derivedData) dm = CDDM_copy(derivedData);
+ else if(ob->type==OB_MESH) dm = CDDM_from_mesh(ob->data, ob);
+ else if(ob->type==OB_LATTICE) dm = NULL;
+ else return;
+
+ if(dm != NULL && (dataMask & CD_MVERT))
+ {
+ CDDM_apply_vert_coords(dm, vertexCos);
+ CDDM_calc_normals(dm);
+ }
+ }
+
+ SimpleDeformModifier_do((SimpleDeformModifierData*)md, ob, dm, vertexCos, numVerts);
+
+ if(dm)
+ dm->release(dm);
+
+}
+
+static void simpledeformModifier_deformVertsEM(ModifierData *md, Object *ob, EditMesh *editData, DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+{
+ DerivedMesh *dm = NULL;
+ CustomDataMask dataMask = simpledeformModifier_requiredDataMask(md);
+
+ /* We implement requiredDataMask but thats not really usefull since mesh_calc_modifiers pass a NULL derivedData or without the modified vertexs applied */
+ if(dataMask)
+ {
+ if(derivedData) dm = CDDM_copy(derivedData);
+ else if(ob->type==OB_MESH) dm = CDDM_from_editmesh(editData, ob->data);
+ else if(ob->type==OB_LATTICE) dm = NULL;
+ else return;
+
+ if(dm != NULL && (dataMask & CD_MVERT))
+ {
+ CDDM_apply_vert_coords(dm, vertexCos);
+ CDDM_calc_normals(dm);
+ }
+ }
+
+ SimpleDeformModifier_do((SimpleDeformModifierData*)md, ob, dm, vertexCos, numVerts);
+
+ if(dm)
+ dm->release(dm);
+}
+
/***/
static ModifierTypeInfo typeArr[NUM_MODIFIER_TYPES];
@@ -6545,15 +7979,15 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
/* Initialize and return the appropriate type info structure,
* assumes that modifier has:
- * name == typeName,
- * structName == typeName + 'ModifierData'
- */
+ * name == typeName,
+ * structName == typeName + 'ModifierData'
+ */
#define INIT_TYPE(typeName) \
(strcpy(typeArr[eModifierType_##typeName].name, #typeName), \
strcpy(typeArr[eModifierType_##typeName].structName, \
- #typeName "ModifierData"), \
+#typeName "ModifierData"), \
typeArr[eModifierType_##typeName].structSize = \
- sizeof(typeName##ModifierData), \
+ sizeof(typeName##ModifierData), \
&typeArr[eModifierType_##typeName])
mti = &typeArr[eModifierType_None];
@@ -6562,13 +7996,13 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti->structSize = sizeof(ModifierData);
mti->type = eModifierType_None;
mti->flags = eModifierTypeFlag_AcceptsMesh
- | eModifierTypeFlag_AcceptsCVs;
+ | eModifierTypeFlag_AcceptsCVs;
mti->isDisabled = noneModifier_isDisabled;
mti = INIT_TYPE(Curve);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsCVs
- | eModifierTypeFlag_SupportsEditmode;
+ | eModifierTypeFlag_SupportsEditmode;
mti->initData = curveModifier_initData;
mti->copyData = curveModifier_copyData;
mti->requiredDataMask = curveModifier_requiredDataMask;
@@ -6581,7 +8015,7 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(Lattice);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsCVs
- | eModifierTypeFlag_SupportsEditmode;
+ | eModifierTypeFlag_SupportsEditmode;
mti->copyData = latticeModifier_copyData;
mti->requiredDataMask = latticeModifier_requiredDataMask;
mti->isDisabled = latticeModifier_isDisabled;
@@ -6593,9 +8027,9 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(Subsurf);
mti->type = eModifierTypeType_Constructive;
mti->flags = eModifierTypeFlag_AcceptsMesh
- | eModifierTypeFlag_SupportsMapping
- | eModifierTypeFlag_SupportsEditmode
- | eModifierTypeFlag_EnableInEditmode;
+ | eModifierTypeFlag_SupportsMapping
+ | eModifierTypeFlag_SupportsEditmode
+ | eModifierTypeFlag_EnableInEditmode;
mti->initData = subsurfModifier_initData;
mti->copyData = subsurfModifier_copyData;
mti->freeData = subsurfModifier_freeData;
@@ -6609,13 +8043,22 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti->copyData = buildModifier_copyData;
mti->dependsOnTime = buildModifier_dependsOnTime;
mti->applyModifier = buildModifier_applyModifier;
+
+ mti = INIT_TYPE(Mask);
+ mti->type = eModifierTypeType_Nonconstructive;
+ mti->flags = eModifierTypeFlag_AcceptsMesh;
+ mti->copyData = maskModifier_copyData;
+ mti->requiredDataMask= maskModifier_requiredDataMask;
+ mti->foreachObjectLink = maskModifier_foreachObjectLink;
+ mti->updateDepgraph = maskModifier_updateDepgraph;
+ mti->applyModifier = maskModifier_applyModifier;
mti = INIT_TYPE(Array);
mti->type = eModifierTypeType_Constructive;
mti->flags = eModifierTypeFlag_AcceptsMesh
- | eModifierTypeFlag_SupportsMapping
- | eModifierTypeFlag_SupportsEditmode
- | eModifierTypeFlag_EnableInEditmode;
+ | eModifierTypeFlag_SupportsMapping
+ | eModifierTypeFlag_SupportsEditmode
+ | eModifierTypeFlag_EnableInEditmode;
mti->initData = arrayModifier_initData;
mti->copyData = arrayModifier_copyData;
mti->foreachObjectLink = arrayModifier_foreachObjectLink;
@@ -6626,9 +8069,9 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(Mirror);
mti->type = eModifierTypeType_Constructive;
mti->flags = eModifierTypeFlag_AcceptsMesh
- | eModifierTypeFlag_SupportsMapping
- | eModifierTypeFlag_SupportsEditmode
- | eModifierTypeFlag_EnableInEditmode;
+ | eModifierTypeFlag_SupportsMapping
+ | eModifierTypeFlag_SupportsEditmode
+ | eModifierTypeFlag_EnableInEditmode;
mti->initData = mirrorModifier_initData;
mti->copyData = mirrorModifier_copyData;
mti->foreachObjectLink = mirrorModifier_foreachObjectLink;
@@ -6639,20 +8082,32 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(EdgeSplit);
mti->type = eModifierTypeType_Constructive;
mti->flags = eModifierTypeFlag_AcceptsMesh
- | eModifierTypeFlag_SupportsMapping
- | eModifierTypeFlag_SupportsEditmode
- | eModifierTypeFlag_EnableInEditmode;
+ | eModifierTypeFlag_SupportsMapping
+ | eModifierTypeFlag_SupportsEditmode
+ | eModifierTypeFlag_EnableInEditmode;
mti->initData = edgesplitModifier_initData;
mti->copyData = edgesplitModifier_copyData;
mti->applyModifier = edgesplitModifier_applyModifier;
mti->applyModifierEM = edgesplitModifier_applyModifierEM;
+ mti = INIT_TYPE(Bevel);
+ mti->type = eModifierTypeType_Constructive;
+ mti->flags = eModifierTypeFlag_AcceptsMesh
+ | eModifierTypeFlag_SupportsEditmode
+ | eModifierTypeFlag_EnableInEditmode;
+ mti->initData = bevelModifier_initData;
+ mti->copyData = bevelModifier_copyData;
+ mti->requiredDataMask = bevelModifier_requiredDataMask;
+ mti->applyModifier = bevelModifier_applyModifier;
+ mti->applyModifierEM = bevelModifier_applyModifierEM;
+
mti = INIT_TYPE(Displace);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsMesh|eModifierTypeFlag_SupportsEditmode;
mti->initData = displaceModifier_initData;
mti->copyData = displaceModifier_copyData;
mti->requiredDataMask = displaceModifier_requiredDataMask;
+ mti->dependsOnTime = displaceModifier_dependsOnTime;
mti->foreachObjectLink = displaceModifier_foreachObjectLink;
mti->foreachIDLink = displaceModifier_foreachIDLink;
mti->updateDepgraph = displaceModifier_updateDepgraph;
@@ -6663,9 +8118,9 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(UVProject);
mti->type = eModifierTypeType_Nonconstructive;
mti->flags = eModifierTypeFlag_AcceptsMesh
- | eModifierTypeFlag_SupportsMapping
- | eModifierTypeFlag_SupportsEditmode
- | eModifierTypeFlag_EnableInEditmode;
+ | eModifierTypeFlag_SupportsMapping
+ | eModifierTypeFlag_SupportsEditmode
+ | eModifierTypeFlag_EnableInEditmode;
mti->initData = uvprojectModifier_initData;
mti->copyData = uvprojectModifier_copyData;
mti->requiredDataMask = uvprojectModifier_requiredDataMask;
@@ -6685,7 +8140,7 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(Smooth);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsMesh
- | eModifierTypeFlag_SupportsEditmode;
+ | eModifierTypeFlag_SupportsEditmode;
mti->initData = smoothModifier_initData;
mti->copyData = smoothModifier_copyData;
mti->requiredDataMask = smoothModifier_requiredDataMask;
@@ -6695,7 +8150,7 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(Cast);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsCVs
- | eModifierTypeFlag_SupportsEditmode;
+ | eModifierTypeFlag_SupportsEditmode;
mti->initData = castModifier_initData;
mti->copyData = castModifier_copyData;
mti->requiredDataMask = castModifier_requiredDataMask;
@@ -6707,7 +8162,7 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(Wave);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsCVs
- | eModifierTypeFlag_SupportsEditmode;
+ | eModifierTypeFlag_SupportsEditmode;
mti->initData = waveModifier_initData;
mti->copyData = waveModifier_copyData;
mti->dependsOnTime = waveModifier_dependsOnTime;
@@ -6721,7 +8176,7 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(Armature);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsCVs
- | eModifierTypeFlag_SupportsEditmode;
+ | eModifierTypeFlag_SupportsEditmode;
mti->initData = armatureModifier_initData;
mti->copyData = armatureModifier_copyData;
mti->requiredDataMask = armatureModifier_requiredDataMask;
@@ -6735,7 +8190,7 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(Hook);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsCVs
- | eModifierTypeFlag_SupportsEditmode;
+ | eModifierTypeFlag_SupportsEditmode;
mti->initData = hookModifier_initData;
mti->copyData = hookModifier_copyData;
mti->requiredDataMask = hookModifier_requiredDataMask;
@@ -6749,14 +8204,36 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(Softbody);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsCVs
- | eModifierTypeFlag_RequiresOriginalData;
+ | eModifierTypeFlag_RequiresOriginalData;
mti->deformVerts = softbodyModifier_deformVerts;
+ mti->dependsOnTime = softbodyModifier_dependsOnTime;
+
+ mti = INIT_TYPE(Cloth);
+ mti->type = eModifierTypeType_Nonconstructive;
+ mti->initData = clothModifier_initData;
+ mti->flags = eModifierTypeFlag_AcceptsMesh
+ | eModifierTypeFlag_UsesPointCache;
+ mti->dependsOnTime = clothModifier_dependsOnTime;
+ mti->freeData = clothModifier_freeData;
+ mti->requiredDataMask = clothModifier_requiredDataMask;
+ mti->copyData = clothModifier_copyData;
+ mti->applyModifier = clothModifier_applyModifier;
+ mti->updateDepgraph = clothModifier_updateDepgraph;
+
+ mti = INIT_TYPE(Collision);
+ mti->type = eModifierTypeType_OnlyDeform;
+ mti->initData = collisionModifier_initData;
+ mti->flags = eModifierTypeFlag_AcceptsMesh;
+ mti->dependsOnTime = collisionModifier_dependsOnTime;
+ mti->freeData = collisionModifier_freeData;
+ mti->deformVerts = collisionModifier_deformVerts;
+ // mti->copyData = collisionModifier_copyData;
mti = INIT_TYPE(Boolean);
mti->type = eModifierTypeType_Nonconstructive;
mti->flags = eModifierTypeFlag_AcceptsMesh
- | eModifierTypeFlag_RequiresOriginalData
- | eModifierTypeFlag_UsesPointCache;
+ | eModifierTypeFlag_RequiresOriginalData
+ | eModifierTypeFlag_UsesPointCache;
mti->copyData = booleanModifier_copyData;
mti->isDisabled = booleanModifier_isDisabled;
mti->applyModifier = booleanModifier_applyModifier;
@@ -6766,7 +8243,7 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(MeshDeform);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsCVs
- | eModifierTypeFlag_SupportsEditmode;
+ | eModifierTypeFlag_SupportsEditmode;
mti->initData = meshdeformModifier_initData;
mti->freeData = meshdeformModifier_freeData;
mti->copyData = meshdeformModifier_copyData;
@@ -6780,11 +8257,11 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(ParticleSystem);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsMesh
- | eModifierTypeFlag_SupportsMapping
- | eModifierTypeFlag_UsesPointCache;
+ | eModifierTypeFlag_SupportsMapping
+ | eModifierTypeFlag_UsesPointCache;
#if 0
- | eModifierTypeFlag_SupportsEditmode;
- |eModifierTypeFlag_EnableInEditmode;
+ | eModifierTypeFlag_SupportsEditmode;
+ |eModifierTypeFlag_EnableInEditmode;
#endif
mti->initData = particleSystemModifier_initData;
mti->freeData = particleSystemModifier_freeData;
@@ -6798,9 +8275,9 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(ParticleInstance);
mti->type = eModifierTypeType_Constructive;
mti->flags = eModifierTypeFlag_AcceptsMesh
- | eModifierTypeFlag_SupportsMapping
- | eModifierTypeFlag_SupportsEditmode
- | eModifierTypeFlag_EnableInEditmode;
+ | eModifierTypeFlag_SupportsMapping
+ | eModifierTypeFlag_SupportsEditmode
+ | eModifierTypeFlag_EnableInEditmode;
mti->initData = particleInstanceModifier_initData;
mti->copyData = particleInstanceModifier_copyData;
mti->dependsOnTime = particleInstanceModifier_dependsOnTime;
@@ -6818,6 +8295,46 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti->dependsOnTime = explodeModifier_dependsOnTime;
mti->requiredDataMask = explodeModifier_requiredDataMask;
mti->applyModifier = explodeModifier_applyModifier;
+
+ mti = INIT_TYPE(Fluidsim);
+ mti->type = eModifierTypeType_Nonconstructive
+ | eModifierTypeFlag_RequiresOriginalData;
+ mti->flags = eModifierTypeFlag_AcceptsMesh;
+ mti->initData = fluidsimModifier_initData;
+ mti->freeData = fluidsimModifier_freeData;
+ mti->copyData = fluidsimModifier_copyData;
+ mti->dependsOnTime = fluidsimModifier_dependsOnTime;
+ mti->applyModifier = fluidsimModifier_applyModifier;
+ mti->updateDepgraph = fluidsimModifier_updateDepgraph;
+
+ mti = INIT_TYPE(Shrinkwrap);
+ mti->type = eModifierTypeType_OnlyDeform;
+ mti->flags = eModifierTypeFlag_AcceptsMesh
+ | eModifierTypeFlag_AcceptsCVs
+ | eModifierTypeFlag_SupportsEditmode
+ | eModifierTypeFlag_EnableInEditmode;
+ mti->initData = shrinkwrapModifier_initData;
+ mti->copyData = shrinkwrapModifier_copyData;
+ mti->requiredDataMask = shrinkwrapModifier_requiredDataMask;
+ mti->isDisabled = shrinkwrapModifier_isDisabled;
+ mti->foreachObjectLink = shrinkwrapModifier_foreachObjectLink;
+ mti->deformVerts = shrinkwrapModifier_deformVerts;
+ mti->deformVertsEM = shrinkwrapModifier_deformVertsEM;
+ mti->updateDepgraph = shrinkwrapModifier_updateDepgraph;
+
+ mti = INIT_TYPE(SimpleDeform);
+ mti->type = eModifierTypeType_OnlyDeform;
+ mti->flags = eModifierTypeFlag_AcceptsMesh
+ | eModifierTypeFlag_AcceptsCVs
+ | eModifierTypeFlag_SupportsEditmode
+ | eModifierTypeFlag_EnableInEditmode;
+ mti->initData = simpledeformModifier_initData;
+ mti->copyData = simpledeformModifier_copyData;
+ mti->requiredDataMask = simpledeformModifier_requiredDataMask;
+ mti->deformVerts = simpledeformModifier_deformVerts;
+ mti->deformVertsEM = simpledeformModifier_deformVertsEM;
+ mti->foreachObjectLink = simpledeformModifier_foreachObjectLink;
+ mti->updateDepgraph = simpledeformModifier_updateDepgraph;
typeArrInit = 0;
#undef INIT_TYPE
@@ -6841,7 +8358,7 @@ ModifierData *modifier_new(int type)
md->type = type;
md->mode = eModifierMode_Realtime
- | eModifierMode_Render | eModifierMode_Expanded;
+ | eModifierMode_Render | eModifierMode_Expanded;
if (mti->flags & eModifierTypeFlag_EnableInEditmode)
md->mode |= eModifierMode_Editmode;
@@ -6873,7 +8390,7 @@ int modifier_supportsMapping(ModifierData *md)
ModifierTypeInfo *mti = modifierType_getInfo(md->type);
return (mti->type==eModifierTypeType_OnlyDeform ||
- (mti->flags & eModifierTypeFlag_SupportsMapping));
+ (mti->flags & eModifierTypeFlag_SupportsMapping));
}
ModifierData *modifiers_findByType(Object *ob, ModifierType type)
@@ -6905,7 +8422,7 @@ void modifiers_clearErrors(Object *ob)
}
void modifiers_foreachObjectLink(Object *ob, ObjectWalkFunc walk,
- void *userData)
+ void *userData)
{
ModifierData *md = ob->modifiers.first;
@@ -6948,9 +8465,9 @@ int modifier_couldBeCage(ModifierData *md)
ModifierTypeInfo *mti = modifierType_getInfo(md->type);
return ( (md->mode & eModifierMode_Realtime) &&
- (md->mode & eModifierMode_Editmode) &&
- (!mti->isDisabled || !mti->isDisabled(md)) &&
- modifier_supportsMapping(md));
+ (md->mode & eModifierMode_Editmode) &&
+ (!mti->isDisabled || !mti->isDisabled(md)) &&
+ modifier_supportsMapping(md));
}
void modifier_setError(ModifierData *md, char *format, ...)
@@ -6981,7 +8498,7 @@ int modifiers_getCageIndex(Object *ob, int *lastPossibleCageIndex_r)
ModifierData *md = ob->modifiers.first;
int i, cageIndex = -1;
- /* Find the last modifier acting on the cage. */
+ /* Find the last modifier acting on the cage. */
for (i=0; md; i++,md=md->next) {
ModifierTypeInfo *mti = modifierType_getInfo(md->type);
@@ -7010,6 +8527,13 @@ int modifiers_isSoftbodyEnabled(Object *ob)
return (md && md->mode & (eModifierMode_Realtime | eModifierMode_Render));
}
+int modifiers_isClothEnabled(Object *ob)
+{
+ ModifierData *md = modifiers_findByType(ob, eModifierType_Cloth);
+
+ return (md && md->mode & (eModifierMode_Realtime | eModifierMode_Render));
+}
+
int modifiers_isParticleEnabled(Object *ob)
{
ModifierData *md = modifiers_findByType(ob, eModifierType_ParticleSystem);
@@ -7033,11 +8557,11 @@ LinkNode *modifiers_calcDataMasks(ModifierData *md, CustomDataMask dataMask)
}
/* build the list of required data masks - each mask in the list must
- * include all elements of the masks that follow it
- *
- * note the list is currently in reverse order, so "masks that follow it"
- * actually means "masks that precede it" at the moment
- */
+ * include all elements of the masks that follow it
+ *
+ * note the list is currently in reverse order, so "masks that follow it"
+ * actually means "masks that precede it" at the moment
+ */
for(curr = dataMasks, prev = NULL; curr; prev = curr, curr = curr->next) {
if(prev) {
CustomDataMask prev_mask = (CustomDataMask)prev->link;
@@ -7060,8 +8584,8 @@ LinkNode *modifiers_calcDataMasks(ModifierData *md, CustomDataMask dataMask)
ModifierData *modifiers_getVirtualModifierList(Object *ob)
{
/* Kinda hacky, but should be fine since we are never
- * reentrant and avoid free hassles.
- */
+ * reentrant and avoid free hassles.
+ */
static ArmatureModifierData amd;
static CurveModifierData cmd;
static LatticeModifierData lmd;
@@ -7119,7 +8643,7 @@ Object *modifiers_isDeformedByArmature(Object *ob)
ArmatureModifierData *amd= NULL;
/* return the first selected armature, this lets us use multiple armatures
- */
+ */
for (; md; md=md->next) {
if (md->type==eModifierType_Armature) {
amd = (ArmatureModifierData*) md;
@@ -7144,7 +8668,7 @@ Object *modifiers_isDeformedByLattice(Object *ob)
LatticeModifierData *lmd= NULL;
/* return the first selected armature, this lets us use multiple armatures
- */
+ */
for (; md; md=md->next) {
if (md->type==eModifierType_Lattice) {
lmd = (LatticeModifierData*) md;
@@ -7234,3 +8758,4 @@ void modifier_freeTemporaryData(ModifierData *md)
}
+
diff --git a/source/blender/blenkernel/intern/multires-firstlevel.c b/source/blender/blenkernel/intern/multires-firstlevel.c
index b27d1c4b156..8c667a9ecf0 100644
--- a/source/blender/blenkernel/intern/multires-firstlevel.c
+++ b/source/blender/blenkernel/intern/multires-firstlevel.c
@@ -1,5 +1,5 @@
/*
- * $Id: multires-firstlevel.c 13001 2007-12-26 09:39:15Z nicholasbishop $
+ * $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -73,7 +73,7 @@ char type_ok(const int type)
}
/* Copy vdata or fdata from Mesh or EditMesh to Multires. */
-void multires_update_customdata(MultiresLevel *lvl1, CustomData *src, CustomData *dst, const int type)
+void multires_update_customdata(MultiresLevel *lvl1, EditMesh *em, CustomData *src, CustomData *dst, const int type)
{
if(src && dst && type_ok(type)) {
const int tot= (type == CD_MDEFORMVERT ? lvl1->totvert : lvl1->totface);
@@ -82,7 +82,7 @@ void multires_update_customdata(MultiresLevel *lvl1, CustomData *src, CustomData
CustomData_free(dst, tot);
if(CustomData_has_layer(src, type)) {
- if(G.obedit) {
+ if(em) {
EditVert *eve= G.editMesh->verts.first;
EditFace *efa= G.editMesh->faces.first;
CustomData_copy(src, dst, cdmask(type), CD_CALLOC, tot);
@@ -225,9 +225,9 @@ void multires_del_lower_customdata(Multires *mr, MultiresLevel *cr_lvl)
void multires_update_first_level(Mesh *me, EditMesh *em)
{
if(me && me->mr && me->mr->current == 1) {
- multires_update_customdata(me->mr->levels.first, em ? &em->vdata : &me->vdata,
+ multires_update_customdata(me->mr->levels.first, em, em ? &em->vdata : &me->vdata,
&me->mr->vdata, CD_MDEFORMVERT);
- multires_update_customdata(me->mr->levels.first, em ? &em->fdata : &me->fdata,
+ multires_update_customdata(me->mr->levels.first, em, em ? &em->fdata : &me->fdata,
&me->mr->fdata, CD_MTFACE);
multires_update_edge_flags(me, em);
}
diff --git a/source/blender/blenkernel/intern/multires.c b/source/blender/blenkernel/intern/multires.c
index a3c1d9ef19d..96e81c604fa 100644
--- a/source/blender/blenkernel/intern/multires.c
+++ b/source/blender/blenkernel/intern/multires.c
@@ -205,7 +205,7 @@ static void multires_get_edge(MultiresEdge *e, EditEdge *eed, MEdge *m, short *f
}
}
-static void multires_get_face(MultiresFace *f, EditFace *efa, MFace *m)
+static void multires_get_face(MultiresFace *f, CustomData *fdata, int findex, EditFace *efa, MFace *m)
{
if(efa) {
MFace tmp;
@@ -215,7 +215,7 @@ static void multires_get_face(MultiresFace *f, EditFace *efa, MFace *m)
tmp.v3= efa->v3->tmp.l;
tmp.v4= 0;
if(efa->v4) tmp.v4= efa->v4->tmp.l;
- //XXX test_index_face(&tmp, NULL, 0, efa->v4?4:3);
+ //XXX test_index_face(&tmp, fdata, findex, efa->v4?4:3);
for(j=0; j<4; ++j) f->v[j]= (&tmp.v1)[j];
/* Flags */
@@ -370,7 +370,7 @@ void multires_create(Object *ob, Mesh *me)
/* Load vertices and vdata (MDeformVerts) */
lvl->totvert= em ? BLI_countlist(&em->verts) : me->totvert;
me->mr->verts= MEM_callocN(sizeof(MVert)*lvl->totvert,"multires verts");
- multires_update_customdata(me->mr->levels.first, em ? &em->vdata : &me->vdata,
+ multires_update_customdata(me->mr->levels.first, em, em ? &em->vdata : &me->vdata,
&me->mr->vdata, CD_MDEFORMVERT);
if(em) eve= em->verts.first;
for(i=0; i<lvl->totvert; ++i) {
@@ -381,11 +381,11 @@ void multires_create(Object *ob, Mesh *me)
/* Load faces and fdata (MTFaces) */
lvl->totface= em ? BLI_countlist(&em->faces) : me->totface;
lvl->faces= MEM_callocN(sizeof(MultiresFace)*lvl->totface,"multires faces");
- multires_update_customdata(me->mr->levels.first, em ? &em->fdata : &me->fdata,
+ multires_update_customdata(me->mr->levels.first, em, em ? &em->fdata : &me->fdata,
&me->mr->fdata, CD_MTFACE);
if(em) efa= em->faces.first;
for(i=0; i<lvl->totface; ++i) {
- multires_get_face(&lvl->faces[i], efa, &me->mface[i]);
+ multires_get_face(&lvl->faces[i], &me->mr->fdata, i, efa, &me->mface[i]);
if(em) efa= efa->next;
}
@@ -639,6 +639,10 @@ static void multires_update_vertices(Mesh *me, EditMesh *em)
MultiApplyData data;
int i, j;
+ /* XXX added this to prevent crash, but if it works? (ton) */
+ if(me->mr->verts==NULL)
+ return;
+
/* Prepare deltas */
pr_deltas= MEM_callocN(sizeof(vec3f)*last_lvl->totvert, "multires deltas 1");
cr_deltas= MEM_callocN(sizeof(vec3f)*last_lvl->totvert, "multires deltas 2");
@@ -762,7 +766,7 @@ static void multires_update_faces(Mesh *me, EditMesh *em)
if(em) efa= em->faces.first;
for(i=0; i<cr_lvl->totface; ++i) {
MultiresFace mftmp;
- multires_get_face(&mftmp, efa, &me->mface[i]);
+ multires_get_face(&mftmp, &me->mr->fdata, i, efa, &me->mface[i]);
if(cr_lvl->faces[i].flag != mftmp.flag)
cr_flag_damaged[i]= 1;
if(cr_lvl->faces[i].mat_nr != mftmp.mat_nr)
@@ -1284,7 +1288,7 @@ void multires_edge_level_update(Object *ob, Mesh *me)
if(!G.obedit) {
MultiresLevel *cr_lvl= BLI_findlink(&me->mr->levels,me->mr->current-1);
MultiresLevel *edge_lvl= BLI_findlink(&me->mr->levels,me->mr->edgelvl-1);
- const int threshold= edge_lvl->totedge * powf(2, me->mr->current - me->mr->edgelvl);
+ const int threshold= edge_lvl->totedge * pow(2, me->mr->current - me->mr->edgelvl);
unsigned i;
for(i=0; i<cr_lvl->totedge; ++i) {
diff --git a/source/blender/blenkernel/intern/node.c b/source/blender/blenkernel/intern/node.c
index 5c9b609bbaf..8d60b1b4359 100644
--- a/source/blender/blenkernel/intern/node.c
+++ b/source/blender/blenkernel/intern/node.c
@@ -27,6 +27,10 @@
* ***** END GPL LICENSE BLOCK *****
*/
+#ifndef DISABLE_PYTHON
+#include <Python.h>
+#endif
+
#include <stdlib.h>
#include <string.h>
@@ -34,6 +38,7 @@
#include "DNA_image_types.h"
#include "DNA_node_types.h"
#include "DNA_material_types.h"
+#include "DNA_text_types.h"
#include "DNA_scene_types.h"
#include "BKE_blender.h"
@@ -44,6 +49,7 @@
#include "BKE_main.h"
#include "BKE_node.h"
#include "BKE_texture.h"
+#include "BKE_text.h"
#include "BKE_utildefines.h"
#include "BLI_arithb.h"
@@ -61,10 +67,12 @@
#include "RE_render_ext.h" /* <- ibuf_sample() */
#include "CMP_node.h"
+#include "intern/CMP_util.h" /* stupid include path... */
+
#include "SHD_node.h"
-/* not very important, but the stack solver likes to know a maximum */
-#define MAX_SOCKET 64
+#include "GPU_extensions.h"
+#include "GPU_material.h"
static ListBase empty_list = {NULL, NULL};
ListBase node_all_composit = {NULL, NULL};
@@ -72,7 +80,7 @@ ListBase node_all_shaders = {NULL, NULL};
/* ************** Type stuff ********** */
-static bNodeType *node_get_type(bNodeTree *ntree, int type, bNodeTree *ngroup)
+static bNodeType *node_get_type(bNodeTree *ntree, int type, bNodeTree *ngroup, ID *id)
{
if(type==NODE_GROUP) {
if(ngroup && GS(ngroup->id.name)==ID_NT) {
@@ -83,7 +91,7 @@ static bNodeType *node_get_type(bNodeTree *ntree, int type, bNodeTree *ngroup)
else {
bNodeType *ntype = ntree->alltypes.first;
for(; ntype; ntype= ntype->next)
- if(ntype->type==type)
+ if(ntype->type==type && id==ntype->id )
return ntype;
return NULL;
@@ -105,7 +113,27 @@ void ntreeInitTypes(bNodeTree *ntree)
for(node= ntree->nodes.first; node; node= next) {
next= node->next;
- node->typeinfo= node_get_type(ntree, node->type, (bNodeTree *)node->id);
+ if(node->type==NODE_DYNAMIC) {
+ bNodeType *stype= NULL;
+ if(node->id==NULL) { /* empty script node */
+ stype= node_get_type(ntree, node->type, NULL, NULL);
+ } else { /* not an empty script node */
+ stype= node_get_type(ntree, node->type, NULL, node->id);
+ if(!stype) {
+ stype= node_get_type(ntree, node->type, NULL, NULL);
+ /* needed info if the pynode script fails now: */
+ if (node->id) node->storage= ntree;
+ } else {
+ node->custom1= 0;
+ node->custom1= BSET(node->custom1,NODE_DYNAMIC_ADDEXIST);
+ }
+ }
+ node->typeinfo= stype;
+ node->typeinfo->initfunc(node);
+ } else {
+ node->typeinfo= node_get_type(ntree, node->type, (bNodeTree *)node->id, NULL);
+ }
+
if(node->typeinfo==NULL) {
printf("Error: Node type %s doesn't exist anymore, removed\n", node->name);
nodeFreeNode(ntree, node);
@@ -115,6 +143,18 @@ void ntreeInitTypes(bNodeTree *ntree)
ntree->init |= NTREE_TYPE_INIT;
}
+/* updates node with (modified) bNodeType.. this should be done for all trees */
+void ntreeUpdateType(bNodeTree *ntree, bNodeType *ntype)
+{
+ bNode *node;
+
+ for(node= ntree->nodes.first; node; node= node->next) {
+ if(node->typeinfo== ntype) {
+ nodeUpdateType(ntree, node, ntype);
+ }
+ }
+}
+
/* only used internal... we depend on type definitions! */
static bNodeSocket *node_add_socket_type(ListBase *lb, bNodeSocketType *stype)
{
@@ -137,7 +177,7 @@ static bNodeSocket *node_add_socket_type(ListBase *lb, bNodeSocketType *stype)
if(lb)
BLI_addtail(lb, sock);
-
+
return sock;
}
@@ -483,6 +523,28 @@ bNode *nodeMakeGroupFromSelected(bNodeTree *ntree)
BLI_addtail(&ngroup->nodes, node);
node->locx-= 0.5f*(min[0]+max[0]);
node->locy-= 0.5f*(min[1]+max[1]);
+
+ /* set selin and selout of the nodetree */
+ for(sock= node->inputs.first; sock; sock= sock->next) {
+ if(sock->flag & SOCK_SEL) {
+ ngroup->selin= sock;
+ break;
+ }
+ }
+ for(sock= node->outputs.first; sock; sock= sock->next) {
+ if(sock->flag & SOCK_SEL) {
+ ngroup->selout= sock;
+ break;
+ }
+ }
+
+ /* set socket own_index to zero since it can still have a value
+ * from being in a group before, otherwise it doesn't get a unique
+ * index in group_verify_own_indices */
+ for(sock= node->inputs.first; sock; sock= sock->next)
+ sock->own_index= 0;
+ for(sock= node->outputs.first; sock; sock= sock->next)
+ sock->own_index= 0;
}
}
@@ -499,7 +561,7 @@ bNode *nodeMakeGroupFromSelected(bNodeTree *ntree)
ntreeMakeOwnType(ngroup);
/* make group node */
- gnode= nodeAddNodeType(ntree, NODE_GROUP, ngroup);
+ gnode= nodeAddNodeType(ntree, NODE_GROUP, ngroup, NULL);
gnode->locx= 0.5f*(min[0]+max[0]);
gnode->locy= 0.5f*(min[1]+max[1]);
@@ -538,6 +600,10 @@ bNode *nodeMakeGroupFromSelected(bNodeTree *ntree)
}
}
}
+
+ /* update node levels */
+ ntreeSolveOrder(ntree);
+
return gnode;
}
@@ -653,7 +719,8 @@ void nodeGroupSocketUseFlags(bNodeTree *ngroup)
}
}
-static void find_node_with_socket(bNodeTree *ntree, bNodeSocket *sock, bNode **nodep, int *sockindex)
+/* finds a node based on given socket */
+int nodeFindNode(bNodeTree *ntree, bNodeSocket *sock, bNode **nodep, int *sockindex)
{
bNode *node;
bNodeSocket *tsock;
@@ -671,13 +738,15 @@ static void find_node_with_socket(bNodeTree *ntree, bNodeSocket *sock, bNode **n
if(tsock)
break;
}
+
if(node) {
*nodep= node;
- *sockindex= index;
- }
- else {
- *nodep= NULL;
+ if(sockindex) *sockindex= index;
+ return 1;
}
+
+ *nodep= NULL;
+ return 0;
}
/* returns 1 if its OK */
@@ -717,7 +786,7 @@ int nodeGroupUnGroup(bNodeTree *ntree, bNode *gnode)
for(link= ntree->links.first; link; link= link->next) {
if(link->tonode==gnode) {
/* link->tosock->tosock is on the node we look for */
- find_node_with_socket(ngroup, link->tosock->tosock, &nextn, &index);
+ nodeFindNode(ngroup, link->tosock->tosock, &nextn, &index);
if(nextn==NULL) printf("wrong stuff!\n");
else if(nextn->new_node==NULL) printf("wrong stuff too!\n");
else {
@@ -727,7 +796,7 @@ int nodeGroupUnGroup(bNodeTree *ntree, bNode *gnode)
}
else if(link->fromnode==gnode) {
/* link->fromsock->tosock is on the node we look for */
- find_node_with_socket(ngroup, link->fromsock->tosock, &nextn, &index);
+ nodeFindNode(ngroup, link->fromsock->tosock, &nextn, &index);
if(nextn==NULL) printf("1 wrong stuff!\n");
else if(nextn->new_node==NULL) printf("1 wrong stuff too!\n");
else {
@@ -749,30 +818,28 @@ int nodeGroupUnGroup(bNodeTree *ntree, bNode *gnode)
return 1;
}
-/* ************** Add stuff ********** */
+void nodeCopyGroup(bNode *gnode)
+{
+ bNodeSocket *sock;
+
+ gnode->id->us--;
+ gnode->id= (ID *)ntreeCopyTree((bNodeTree *)gnode->id, 0);
-bNode *nodeAddNodeType(bNodeTree *ntree, int type, bNodeTree *ngroup)
+ /* new_sock was set in nodeCopyNode */
+ for(sock=gnode->inputs.first; sock; sock=sock->next)
+ if(sock->tosock)
+ sock->tosock= sock->tosock->new_sock;
+
+ for(sock=gnode->outputs.first; sock; sock=sock->next)
+ if(sock->tosock)
+ sock->tosock= sock->tosock->new_sock;
+}
+
+/* ************** Add stuff ********** */
+void nodeAddSockets(bNode *node, bNodeType *ntype)
{
- bNode *node;
- bNodeType *ntype= node_get_type(ntree, type, ngroup);
bNodeSocketType *stype;
-
- node= MEM_callocN(sizeof(bNode), "new node");
- BLI_addtail(&ntree->nodes, node);
- node->typeinfo= ntype;
-
- if(ngroup)
- BLI_strncpy(node->name, ngroup->id.name+2, NODE_MAXSTR);
- else
- BLI_strncpy(node->name, ntype->name, NODE_MAXSTR);
- node->type= ntype->type;
- node->flag= NODE_SELECT|ntype->flag;
- node->width= ntype->width;
- node->miniwidth= 42.0f; /* small value only, allows print of first chars */
-
- if(type==NODE_GROUP)
- node->id= (ID *)ngroup;
-
+
if(ntype->inputs) {
stype= ntype->inputs;
while(stype->type != -1) {
@@ -787,34 +854,111 @@ bNode *nodeAddNodeType(bNodeTree *ntree, int type, bNodeTree *ngroup)
stype++;
}
}
-
+}
+
+
+bNode *nodeAddNodeType(bNodeTree *ntree, int type, bNodeTree *ngroup, ID *id)
+{
+ bNode *node= NULL;
+ bNodeType *ntype= NULL;
+
+ if(type>=NODE_DYNAMIC_MENU) {
+ int a=0, idx= type-NODE_DYNAMIC_MENU;
+ ntype= ntree->alltypes.first;
+ while(ntype) {
+ if(ntype->type==NODE_DYNAMIC) {
+ if(a==idx)
+ break;
+ a++;
+ }
+ ntype= ntype->next;
+ }
+ } else
+ ntype= node_get_type(ntree, type, ngroup, id);
+
+ node= MEM_callocN(sizeof(bNode), "new node");
+ BLI_addtail(&ntree->nodes, node);
+ node->typeinfo= ntype;
+ if(type>=NODE_DYNAMIC_MENU)
+ node->custom2= type; /* for node_dynamic_init */
+
+ if(ngroup)
+ BLI_strncpy(node->name, ngroup->id.name+2, NODE_MAXSTR);
+ else if(type>NODE_DYNAMIC_MENU) {
+ BLI_strncpy(node->name, ntype->id->name+2, NODE_MAXSTR);
+ }
+ else
+ BLI_strncpy(node->name, ntype->name, NODE_MAXSTR);
+ node->type= ntype->type;
+ node->flag= NODE_SELECT|ntype->flag;
+ node->width= ntype->width;
+ node->miniwidth= 42.0f; /* small value only, allows print of first chars */
+
+ if(type==NODE_GROUP)
+ node->id= (ID *)ngroup;
+
/* need init handler later? */
- /* got it-bob*/
- if(ntype->initfunc!=NULL)
- ntype->initfunc(node);
+ /* got it-bob*/
+ if(ntype->initfunc!=NULL)
+ ntype->initfunc(node);
+
+ nodeAddSockets(node, ntype);
+
+ return node;
+}
+
+void nodeMakeDynamicType(bNode *node)
+{
+ /* find SH_DYNAMIC_NODE ntype */
+ bNodeType *ntype= node_all_shaders.first;
+ while(ntype) {
+ if(ntype->type==NODE_DYNAMIC && ntype->id==NULL)
+ break;
+ ntype= ntype->next;
+ }
+
+ /* make own type struct to fill */
+ if(ntype) {
+ /*node->typeinfo= MEM_dupallocN(ntype);*/
+ bNodeType *newtype= MEM_callocN(sizeof(bNodeType), "dynamic bNodeType");
+ *newtype= *ntype;
+ newtype->name= BLI_strdup(ntype->name);
+ node->typeinfo= newtype;
+ }
+}
- return node;
+void nodeUpdateType(bNodeTree *ntree, bNode* node, bNodeType *ntype)
+{
+ verify_socket_list(ntree, &node->inputs, ntype->inputs);
+ verify_socket_list(ntree, &node->outputs, ntype->outputs);
}
/* keep socket listorder identical, for copying links */
/* ntree is the target tree */
-bNode *nodeCopyNode(struct bNodeTree *ntree, struct bNode *node)
+bNode *nodeCopyNode(struct bNodeTree *ntree, struct bNode *node, int internal)
{
bNode *nnode= MEM_callocN(sizeof(bNode), "dupli node");
- bNodeSocket *sock;
+ bNodeSocket *sock, *oldsock;
*nnode= *node;
BLI_addtail(&ntree->nodes, nnode);
BLI_duplicatelist(&nnode->inputs, &node->inputs);
- for(sock= nnode->inputs.first; sock; sock= sock->next)
- sock->own_index= 0;
+ oldsock= node->inputs.first;
+ for(sock= nnode->inputs.first; sock; sock= sock->next, oldsock= oldsock->next) {
+ oldsock->new_sock= sock;
+ if(internal)
+ sock->own_index= 0;
+ }
BLI_duplicatelist(&nnode->outputs, &node->outputs);
- for(sock= nnode->outputs.first; sock; sock= sock->next) {
- sock->own_index= 0;
+ oldsock= node->outputs.first;
+ for(sock= nnode->outputs.first; sock; sock= sock->next, oldsock= oldsock->next) {
+ if(internal)
+ sock->own_index= 0;
sock->stack_index= 0;
sock->ns.data= NULL;
+ oldsock->new_sock= sock;
}
if(nnode->id)
@@ -892,12 +1036,34 @@ bNodeTree *ntreeCopyTree(bNodeTree *ntree, int internal_select)
node->new_node= NULL;
if(internal_select==0 || (node->flag & NODE_SELECT)) {
- nnode= nodeCopyNode(newtree, node); /* sets node->new */
+ nnode= nodeCopyNode(newtree, node, internal_select); /* sets node->new */
if(internal_select) {
node->flag &= ~NODE_SELECT;
nnode->flag |= NODE_SELECT;
}
node->flag &= ~NODE_ACTIVE;
+
+ /* deselect original sockets */
+ for(sock= node->inputs.first; sock; sock= sock->next) {
+ if(sock->flag & SOCK_SEL) sock->flag&= ~SOCK_SEL;
+ }
+ for(sock= node->outputs.first; sock; sock= sock->next) {
+ if(sock->flag & SOCK_SEL) sock->flag&= ~SOCK_SEL;
+ }
+
+ /* set tree selin and selout to new sockets */
+ for(sock= nnode->inputs.first; sock; sock= sock->next) {
+ if(sock->flag & SOCK_SEL) {
+ ntree->selin= sock;
+ break;
+ }
+ }
+ for(sock= nnode->outputs.first; sock; sock= sock->next) {
+ if(sock->flag & SOCK_SEL) {
+ ntree->selout= sock;
+ break;
+ }
+ }
}
if(node==last) break;
}
@@ -941,7 +1107,7 @@ bNodeTree *ntreeCopyTree(bNodeTree *ntree, int internal_select)
/* ************** Free stuff ********** */
/* goes over entire tree */
-static void node_unlink_node(bNodeTree *ntree, bNode *node)
+void nodeUnlinkNode(bNodeTree *ntree, bNode *node)
{
bNodeLink *link, *next;
bNodeSocket *sock;
@@ -985,7 +1151,7 @@ static void composit_free_node_cache(bNode *node)
void nodeFreeNode(bNodeTree *ntree, bNode *node)
{
- node_unlink_node(ntree, node);
+ nodeUnlinkNode(ntree, node);
BLI_remlink(&ntree->nodes, node);
/* since it is called while free database, node->id is undefined */
@@ -1003,6 +1169,7 @@ void nodeFreeNode(bNodeTree *ntree, bNode *node)
if(node->typeinfo && node->typeinfo->freestoragefunc) {
node->typeinfo->freestoragefunc(node);
}
+
MEM_freeN(node);
}
@@ -1204,11 +1371,21 @@ bNode *nodeGetActiveID(bNodeTree *ntree, short idtype)
bNode *node;
if(ntree==NULL) return NULL;
+
+ /* check for group edit */
+ for(node= ntree->nodes.first; node; node= node->next)
+ if(node->flag & NODE_GROUP_EDIT)
+ break;
+
+ if(node)
+ ntree= (bNodeTree*)node->id;
+ /* now find active node with this id */
for(node= ntree->nodes.first; node; node= node->next)
if(node->id && GS(node->id->name)==idtype)
if(node->flag & NODE_ACTIVE_ID)
break;
+
return node;
}
@@ -1629,7 +1806,7 @@ static void composit_begin_exec(bNodeTree *ntree, int is_group)
if(is_group==0) {
for(sock= node->outputs.first; sock; sock= sock->next) {
- bNodeStack *ns= ntree->stack[0] + sock->stack_index;
+ bNodeStack *ns= ntree->stack + sock->stack_index;
if(sock->ns.data) {
ns->data= sock->ns.data;
@@ -1662,7 +1839,7 @@ static void composit_end_exec(bNodeTree *ntree, int is_group)
bNodeSocket *sock;
for(sock= node->outputs.first; sock; sock= sock->next) {
- ns= ntree->stack[0] + sock->stack_index;
+ ns= ntree->stack + sock->stack_index;
if(ns->data) {
sock->ns.data= ns->data;
ns->data= NULL;
@@ -1680,7 +1857,7 @@ static void composit_end_exec(bNodeTree *ntree, int is_group)
if(is_group==0) {
/* internally, group buffers are not stored */
- for(ns= ntree->stack[0], a=0; a<ntree->stacksize; a++, ns++) {
+ for(ns= ntree->stack, a=0; a<ntree->stacksize; a++, ns++) {
if(ns->data) {
printf("freed leftover buffer from stack\n");
free_compbuf(ns->data);
@@ -1721,15 +1898,47 @@ static void group_tag_used_outputs(bNode *gnode, bNodeStack *stack)
/* per tree (and per group) unique indices are created */
/* the index_ext we need to be able to map from groups to the group-node own stack */
+typedef struct bNodeThreadStack {
+ struct bNodeThreadStack *next, *prev;
+ bNodeStack *stack;
+ int used;
+} bNodeThreadStack;
+
+static bNodeThreadStack *ntreeGetThreadStack(bNodeTree *ntree, int thread)
+{
+ ListBase *lb= &ntree->threadstack[thread];
+ bNodeThreadStack *nts;
+
+ for(nts=lb->first; nts; nts=nts->next) {
+ if(!nts->used) {
+ nts->used= 1;
+ return nts;
+ }
+ }
+
+ nts= MEM_callocN(sizeof(bNodeThreadStack), "bNodeThreadStack");
+ nts->stack= MEM_dupallocN(ntree->stack);
+ nts->used= 1;
+ BLI_addtail(lb, nts);
+
+ return nts;
+}
+
+static void ntreeReleaseThreadStack(bNodeThreadStack *nts)
+{
+ nts->used= 0;
+}
+
void ntreeBeginExecTree(bNodeTree *ntree)
{
/* let's make it sure */
if(ntree->init & NTREE_EXEC_INIT)
return;
-
- /* allocate the stack pointer array */
- ntree->stack= MEM_callocN(BLENDER_MAX_THREADS*sizeof(void *), "stack array");
-
+
+ /* allocate the thread stack listbase array */
+ if(ntree->type!=NTREE_COMPOSIT)
+ ntree->threadstack= MEM_callocN(BLENDER_MAX_THREADS*sizeof(ListBase), "thread stack array");
+
/* goes recursive over all groups */
ntree->stacksize= ntree_begin_exec_tree(ntree);
@@ -1739,7 +1948,7 @@ void ntreeBeginExecTree(bNodeTree *ntree)
int a;
/* allocate the base stack */
- ns=ntree->stack[0]= MEM_callocN(ntree->stacksize*sizeof(bNodeStack), "node stack");
+ ns=ntree->stack= MEM_callocN(ntree->stacksize*sizeof(bNodeStack), "node stack");
/* tag inputs, the get_stack() gives own socket stackdata if not in use */
for(a=0; a<ntree->stacksize; a++, ns++) ns->hasinput= 1;
@@ -1749,7 +1958,7 @@ void ntreeBeginExecTree(bNodeTree *ntree)
bNodeSocket *sock;
for(sock= node->inputs.first; sock; sock= sock->next) {
if(sock->link) {
- ns= ntree->stack[0] + sock->link->fromsock->stack_index;
+ ns= ntree->stack + sock->link->fromsock->stack_index;
ns->hasoutput= 1;
ns->sockettype= sock->link->fromsock->type;
}
@@ -1757,16 +1966,11 @@ void ntreeBeginExecTree(bNodeTree *ntree)
sock->ns.sockettype= sock->type;
}
if(node->type==NODE_GROUP && node->id)
- group_tag_used_outputs(node, ntree->stack[0]);
+ group_tag_used_outputs(node, ntree->stack);
}
- /* composite does 1 node per thread, so no multiple stacks needed */
if(ntree->type==NTREE_COMPOSIT)
composit_begin_exec(ntree, 0);
- else {
- for(a=1; a<BLENDER_MAX_THREADS; a++)
- ntree->stack[a]= MEM_dupallocN(ntree->stack[0]);
- }
}
ntree->init |= NTREE_EXEC_INIT;
@@ -1776,6 +1980,7 @@ void ntreeEndExecTree(bNodeTree *ntree)
{
if(ntree->init & NTREE_EXEC_INIT) {
+ bNodeThreadStack *nts;
int a;
/* another callback candidate! */
@@ -1783,14 +1988,21 @@ void ntreeEndExecTree(bNodeTree *ntree)
composit_end_exec(ntree, 0);
if(ntree->stack) {
- for(a=0; a<BLENDER_MAX_THREADS; a++)
- if(ntree->stack[a])
- MEM_freeN(ntree->stack[a]);
-
MEM_freeN(ntree->stack);
ntree->stack= NULL;
}
+ if(ntree->threadstack) {
+ for(a=0; a<BLENDER_MAX_THREADS; a++) {
+ for(nts=ntree->threadstack[a].first; nts; nts=nts->next)
+ if (nts->stack) MEM_freeN(nts->stack);
+ BLI_freelistN(&ntree->threadstack[a]);
+ }
+
+ MEM_freeN(ntree->threadstack);
+ ntree->threadstack= NULL;
+ }
+
ntree->init &= ~NTREE_EXEC_INIT;
}
}
@@ -1819,12 +2031,20 @@ void ntreeExecTree(bNodeTree *ntree, void *callerdata, int thread)
bNodeStack *nsin[MAX_SOCKET]; /* arbitrary... watch this */
bNodeStack *nsout[MAX_SOCKET]; /* arbitrary... watch this */
bNodeStack *stack;
+ bNodeThreadStack *nts = NULL;
/* only when initialized */
if((ntree->init & NTREE_EXEC_INIT)==0)
ntreeBeginExecTree(ntree);
- stack= ntree->stack[thread];
+ /* composite does 1 node per thread, so no multiple stacks needed */
+ if(ntree->type==NTREE_COMPOSIT) {
+ stack= ntree->stack;
+ }
+ else {
+ nts= ntreeGetThreadStack(ntree, thread);
+ stack= nts->stack;
+ }
for(node= ntree->nodes.first; node; node= node->next) {
if(node->typeinfo->execfunc) {
@@ -1836,10 +2056,34 @@ void ntreeExecTree(bNodeTree *ntree, void *callerdata, int thread)
node_group_execute(stack, callerdata, node, nsin, nsout);
}
}
+
+ if(nts)
+ ntreeReleaseThreadStack(nts);
}
/* ***************************** threaded version for execute composite nodes ************* */
+/* these are nodes without input, only giving values */
+/* or nodes with only value inputs */
+static int node_only_value(bNode *node)
+{
+ bNodeSocket *sock;
+
+ if(ELEM3(node->type, CMP_NODE_TIME, CMP_NODE_VALUE, CMP_NODE_RGB))
+ return 1;
+
+ /* doing this for all node types goes wrong. memory free errors */
+ if(node->inputs.first && node->type==CMP_NODE_MAP_VALUE) {
+ int retval= 1;
+ for(sock= node->inputs.first; sock; sock= sock->next) {
+ if(sock->link)
+ retval &= node_only_value(sock->link->fromnode);
+ }
+ return retval;
+ }
+ return 0;
+}
+
/* not changing info, for thread callback */
typedef struct ThreadData {
@@ -1856,7 +2100,14 @@ static void *exec_composite_node(void *node_v)
node_get_stack(node, thd->stack, nsin, nsout);
- if(node->typeinfo->execfunc) {
+ if((node->flag & NODE_MUTED) && (!node_only_value(node))) {
+ /* viewers we execute, for feedback to user */
+ if(ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
+ node->typeinfo->execfunc(thd->rd, node, nsin, nsout);
+ else
+ node_compo_pass_on(node, nsin, nsout);
+ }
+ else if(node->typeinfo->execfunc) {
node->typeinfo->execfunc(thd->rd, node, nsin, nsout);
}
else if(node->type==NODE_GROUP && node->id) {
@@ -1867,27 +2118,6 @@ static void *exec_composite_node(void *node_v)
return 0;
}
-/* these are nodes without input, only giving values */
-/* or nodes with only value inputs */
-static int node_only_value(bNode *node)
-{
- bNodeSocket *sock;
-
- if(ELEM3(node->type, CMP_NODE_TIME, CMP_NODE_VALUE, CMP_NODE_RGB))
- return 1;
-
- /* doing this for all node types goes wrong. memory free errors */
- if(node->inputs.first && node->type==CMP_NODE_MAP_VALUE) {
- int retval= 1;
- for(sock= node->inputs.first; sock; sock= sock->next) {
- if(sock->link)
- retval &= node_only_value(sock->link->fromnode);
- }
- return retval;
- }
- return 0;
-}
-
/* return total of executable nodes, for timecursor */
/* only compositor uses it */
static int setExecutableNodes(bNodeTree *ntree, ThreadData *thd)
@@ -2010,7 +2240,7 @@ static void freeExecutableNode(bNodeTree *ntree)
for(node= ntree->nodes.first; node; node= node->next) {
if(node->exec & NODE_FREEBUFS) {
for(sock= node->outputs.first; sock; sock= sock->next) {
- bNodeStack *ns= ntree->stack[0] + sock->stack_index;
+ bNodeStack *ns= ntree->stack + sock->stack_index;
if(ns->data) {
free_compbuf(ns->data);
ns->data= NULL;
@@ -2064,7 +2294,7 @@ void ntreeCompositExecTree(bNodeTree *ntree, RenderData *rd, int do_preview)
/* setup callerdata for thread callback */
thdata.rd= rd;
- thdata.stack= ntree->stack[0];
+ thdata.stack= ntree->stack;
/* fixed seed, for example noise texture */
BLI_srandom(rd->cfra);
@@ -2128,6 +2358,117 @@ void ntreeCompositExecTree(bNodeTree *ntree, RenderData *rd, int do_preview)
ntreeEndExecTree(ntree);
}
+/* GPU material from shader nodes */
+
+static void gpu_from_node_stack(ListBase *sockets, bNodeStack **ns, GPUNodeStack *gs)
+{
+ bNodeSocket *sock;
+ int i;
+
+ for (sock=sockets->first, i=0; sock; sock=sock->next, i++) {
+ memset(&gs[i], 0, sizeof(gs[i]));
+
+ QUATCOPY(gs[i].vec, ns[i]->vec);
+ gs[i].link= ns[i]->data;
+
+ if (sock->type == SOCK_VALUE)
+ gs[i].type= GPU_FLOAT;
+ else if (sock->type == SOCK_VECTOR)
+ gs[i].type= GPU_VEC3;
+ else if (sock->type == SOCK_RGBA)
+ gs[i].type= GPU_VEC4;
+ else
+ gs[i].type= GPU_NONE;
+
+ gs[i].name = "";
+ gs[i].hasinput= ns[i]->hasinput && ns[i]->data;
+ gs[i].hasoutput= ns[i]->hasinput && ns[i]->data;
+ gs[i].sockettype= ns[i]->sockettype;
+ }
+
+ gs[i].type= GPU_NONE;
+}
+
+static void data_from_gpu_stack(ListBase *sockets, bNodeStack **ns, GPUNodeStack *gs)
+{
+ bNodeSocket *sock;
+ int i;
+
+ for (sock=sockets->first, i=0; sock; sock=sock->next, i++) {
+ ns[i]->data= gs[i].link;
+ ns[i]->hasinput= gs[i].hasinput && gs[i].link;
+ ns[i]->hasoutput= gs[i].hasoutput;
+ ns[i]->sockettype= gs[i].sockettype;
+ }
+}
+
+static void gpu_node_group_execute(bNodeStack *stack, GPUMaterial *mat, bNode *gnode, bNodeStack **in, bNodeStack **out)
+{
+ bNode *node;
+ bNodeTree *ntree= (bNodeTree *)gnode->id;
+ bNodeStack *nsin[MAX_SOCKET]; /* arbitrary... watch this */
+ bNodeStack *nsout[MAX_SOCKET]; /* arbitrary... watch this */
+ GPUNodeStack gpuin[MAX_SOCKET+1], gpuout[MAX_SOCKET+1];
+ int doit = 0;
+
+ if(ntree==NULL) return;
+
+ stack+= gnode->stack_index;
+
+ for(node= ntree->nodes.first; node; node= node->next) {
+ if(node->typeinfo->gpufunc) {
+ group_node_get_stack(node, stack, nsin, nsout, in, out);
+
+ doit = 0;
+
+ /* for groups, only execute outputs for edited group */
+ if(node->typeinfo->nclass==NODE_CLASS_OUTPUT) {
+ if(gnode->flag & NODE_GROUP_EDIT)
+ if(node->flag & NODE_DO_OUTPUT)
+ doit = 1;
+ }
+ else
+ doit = 1;
+
+ if(doit) {
+ gpu_from_node_stack(&node->inputs, nsin, gpuin);
+ gpu_from_node_stack(&node->outputs, nsout, gpuout);
+ if(node->typeinfo->gpufunc(mat, node, gpuin, gpuout))
+ data_from_gpu_stack(&node->outputs, nsout, gpuout);
+ }
+ }
+ }
+}
+
+void ntreeGPUMaterialNodes(bNodeTree *ntree, GPUMaterial *mat)
+{
+ bNode *node;
+ bNodeStack *stack;
+ bNodeStack *nsin[MAX_SOCKET]; /* arbitrary... watch this */
+ bNodeStack *nsout[MAX_SOCKET]; /* arbitrary... watch this */
+ GPUNodeStack gpuin[MAX_SOCKET+1], gpuout[MAX_SOCKET+1];
+
+ if((ntree->init & NTREE_EXEC_INIT)==0)
+ ntreeBeginExecTree(ntree);
+
+ stack= ntree->stack;
+
+ for(node= ntree->nodes.first; node; node= node->next) {
+ if(node->typeinfo->gpufunc) {
+ node_get_stack(node, stack, nsin, nsout);
+ gpu_from_node_stack(&node->inputs, nsin, gpuin);
+ gpu_from_node_stack(&node->outputs, nsout, gpuout);
+ if(node->typeinfo->gpufunc(mat, node, gpuin, gpuout))
+ data_from_gpu_stack(&node->outputs, nsout, gpuout);
+ }
+ else if(node->type==NODE_GROUP && node->id) {
+ node_get_stack(node, stack, nsin, nsout);
+ gpu_node_group_execute(stack, mat, node, nsin, nsout);
+ }
+ }
+
+ ntreeEndExecTree(ntree);
+}
/* **************** call to switch lamploop for material node ************ */
@@ -2172,6 +2513,8 @@ static void force_hidden_passes(bNode *node, int passflag)
if(!(passflag & SCE_PASS_RADIO)) sock->flag |= SOCK_UNAVAIL;
sock= BLI_findlink(&node->outputs, RRES_OUT_INDEXOB);
if(!(passflag & SCE_PASS_INDEXOB)) sock->flag |= SOCK_UNAVAIL;
+ sock= BLI_findlink(&node->outputs, RRES_OUT_MIST);
+ if(!(passflag & SCE_PASS_MIST)) sock->flag |= SOCK_UNAVAIL;
}
@@ -2281,12 +2624,12 @@ void ntreeCompositTagGenerators(bNodeTree *ntree)
/* ************* node definition init ********** */
-static bNodeType *is_nodetype_registered(ListBase *typelist, int type)
+static bNodeType *is_nodetype_registered(ListBase *typelist, int type, ID *id)
{
bNodeType *ntype= typelist->first;
for(;ntype; ntype= ntype->next )
- if(ntype->type==type)
+ if(ntype->type==type && ntype->id==id)
return ntype;
return NULL;
@@ -2295,10 +2638,10 @@ static bNodeType *is_nodetype_registered(ListBase *typelist, int type)
/* type can be from a static array, we make copy for duplicate types (like group) */
void nodeRegisterType(ListBase *typelist, const bNodeType *ntype)
{
- bNodeType *found= is_nodetype_registered(typelist, ntype->type);
+ bNodeType *found= is_nodetype_registered(typelist, ntype->type, ntype->id);
if(found==NULL) {
- bNodeType *ntypen= MEM_mallocN(sizeof(bNodeType), "node type");
+ bNodeType *ntypen= MEM_callocN(sizeof(bNodeType), "node type");
*ntypen= *ntype;
BLI_addtail(typelist, ntypen);
}
@@ -2335,6 +2678,8 @@ static void registerCompositNodes(ListBase *ntypelist)
nodeRegisterType(ntypelist, &cmp_node_filter);
nodeRegisterType(ntypelist, &cmp_node_blur);
+ nodeRegisterType(ntypelist, &cmp_node_dblur);
+ nodeRegisterType(ntypelist, &cmp_node_bilateralblur);
nodeRegisterType(ntypelist, &cmp_node_vecblur);
nodeRegisterType(ntypelist, &cmp_node_dilateerode);
nodeRegisterType(ntypelist, &cmp_node_defocus);
@@ -2352,6 +2697,7 @@ static void registerCompositNodes(ListBase *ntypelist)
nodeRegisterType(ntypelist, &cmp_node_combyuva);
nodeRegisterType(ntypelist, &cmp_node_sepycca);
nodeRegisterType(ntypelist, &cmp_node_combycca);
+ nodeRegisterType(ntypelist, &cmp_node_premulkey);
nodeRegisterType(ntypelist, &cmp_node_diff_matte);
nodeRegisterType(ntypelist, &cmp_node_chroma);
@@ -2366,7 +2712,6 @@ static void registerCompositNodes(ListBase *ntypelist)
nodeRegisterType(ntypelist, &cmp_node_crop);
nodeRegisterType(ntypelist, &cmp_node_displace);
nodeRegisterType(ntypelist, &cmp_node_mapuv);
-
nodeRegisterType(ntypelist, &cmp_node_glare);
nodeRegisterType(ntypelist, &cmp_node_tonemap);
nodeRegisterType(ntypelist, &cmp_node_lensdist);
@@ -2393,12 +2738,46 @@ static void registerShaderNodes(ListBase *ntypelist)
nodeRegisterType(ntypelist, &sh_node_value);
nodeRegisterType(ntypelist, &sh_node_rgb);
nodeRegisterType(ntypelist, &sh_node_texture);
+ nodeRegisterType(ntypelist, &node_dynamic_typeinfo);
nodeRegisterType(ntypelist, &sh_node_invert);
nodeRegisterType(ntypelist, &sh_node_seprgb);
nodeRegisterType(ntypelist, &sh_node_combrgb);
nodeRegisterType(ntypelist, &sh_node_hue_sat);
}
+static void remove_dynamic_typeinfos(ListBase *list)
+{
+ bNodeType *ntype= list->first;
+ bNodeType *next= NULL;
+ while(ntype) {
+ next= ntype->next;
+ if(ntype->type==NODE_DYNAMIC && ntype->id!=NULL) {
+ BLI_remlink(list, ntype);
+ if(ntype->inputs) {
+ bNodeSocketType *sock= ntype->inputs;
+ while(sock->type!=-1) {
+ MEM_freeN(sock->name);
+ sock++;
+ }
+ MEM_freeN(ntype->inputs);
+ }
+ if(ntype->outputs) {
+ bNodeSocketType *sock= ntype->outputs;
+ while(sock->type!=-1) {
+ MEM_freeN(sock->name);
+ sock++;
+ }
+ MEM_freeN(ntype->outputs);
+ }
+ if(ntype->name) {
+ MEM_freeN(ntype->name);
+ }
+ MEM_freeN(ntype);
+ }
+ ntype= next;
+ }
+}
+
void init_nodesystem(void)
{
registerCompositNodes(&node_all_composit);
@@ -2407,8 +2786,8 @@ void init_nodesystem(void)
void free_nodesystem(void)
{
+ /*remove_dynamic_typeinfos(&node_all_composit);*/ /* unused for now */
BLI_freelistN(&node_all_composit);
+ remove_dynamic_typeinfos(&node_all_shaders);
BLI_freelistN(&node_all_shaders);
}
-
-
diff --git a/source/blender/blenkernel/intern/object.c b/source/blender/blenkernel/intern/object.c
index e5edd2239ff..2d7a5283b0c 100644
--- a/source/blender/blenkernel/intern/object.c
+++ b/source/blender/blenkernel/intern/object.c
@@ -50,6 +50,8 @@
#include "DNA_lattice_types.h"
#include "DNA_material_types.h"
#include "DNA_mesh_types.h"
+#include "DNA_meta_types.h"
+#include "DNA_curve_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_modifier_types.h"
#include "DNA_nla_types.h"
@@ -68,6 +70,7 @@
#include "BKE_armature.h"
#include "BKE_action.h"
+#include "BKE_bullet.h"
#include "BKE_colortools.h"
#include "BKE_deform.h"
#include "BKE_DerivedMesh.h"
@@ -87,7 +90,6 @@
#include "BKE_constraint.h"
#include "BKE_curve.h"
#include "BKE_displist.h"
-#include "BKE_effect.h"
#include "BKE_group.h"
#include "BKE_icons.h"
#include "BKE_ipo.h"
@@ -99,6 +101,7 @@
#include "BKE_modifier.h"
#include "BKE_object.h"
#include "BKE_particle.h"
+#include "BKE_pointcache.h"
#include "BKE_property.h"
#include "BKE_sca.h"
#include "BKE_scene.h"
@@ -107,7 +110,11 @@
#include "LBM_fluidsim.h"
+#ifndef DISABLE_PYTHON
#include "BPY_extern.h"
+#endif
+
+#include "GPU_material.h"
/* Local function protos */
static void solve_parenting (Object *ob, Object *par, float obmat[][4], float slowmat[][4], int simul);
@@ -153,6 +160,33 @@ void update_base_layer(Object *ob)
}
}
+void object_free_particlesystems(Object *ob)
+{
+ while(ob->particlesystem.first){
+ ParticleSystem *psys = ob->particlesystem.first;
+
+ BLI_remlink(&ob->particlesystem,psys);
+
+ psys_free(ob,psys);
+ }
+}
+
+void object_free_softbody(Object *ob)
+{
+ if(ob->soft) {
+ sbFree(ob->soft);
+ ob->soft= NULL;
+ }
+}
+
+void object_free_bulletsoftbody(Object *ob)
+{
+ if(ob->bsoft) {
+ bsbFree(ob->bsoft);
+ ob->bsoft= NULL;
+ }
+}
+
void object_free_modifiers(Object *ob)
{
while (ob->modifiers.first) {
@@ -164,13 +198,10 @@ void object_free_modifiers(Object *ob)
}
/* particle modifiers were freed, so free the particlesystems as well */
- while(ob->particlesystem.first){
- ParticleSystem *psys = ob->particlesystem.first;
-
- BLI_remlink(&ob->particlesystem,psys);
+ object_free_particlesystems(ob);
- psys_free(ob,psys);
- }
+ /* same for softbody */
+ object_free_softbody(ob);
}
/* here we will collect all local displist stuff */
@@ -221,14 +252,12 @@ void free_object(Object *ob)
ob->path= 0;
if(ob->ipo) ob->ipo->id.us--;
if(ob->action) ob->action->id.us--;
+ if(ob->poselib) ob->poselib->id.us--;
if(ob->dup_group) ob->dup_group->id.us--;
if(ob->defbase.first)
BLI_freelistN(&ob->defbase);
- if(ob->pose) {
- free_pose_channels(ob->pose);
- MEM_freeN(ob->pose);
- }
- free_effects(&ob->effect);
+ if(ob->pose)
+ free_pose(ob->pose);
free_properties(&ob->prop);
object_free_modifiers(ob);
@@ -239,8 +268,10 @@ void free_object(Object *ob)
free_constraints(&ob->constraints);
free_constraint_channels(&ob->constraintChannels);
free_nlastrips(&ob->nlastrips);
-
+
+#ifndef DISABLE_PYTHON
BPY_free_scriptlink(&ob->scriptlink);
+#endif
if(ob->pd){
if(ob->pd->tex)
@@ -248,7 +279,8 @@ void free_object(Object *ob)
MEM_freeN(ob->pd);
}
if(ob->soft) sbFree(ob->soft);
- if(ob->fluidsimSettings) fluidsimSettingsFree(ob->fluidsimSettings);
+ if(ob->bsoft) bsbFree(ob->bsoft);
+ if(ob->gpulamp.first) GPU_lamp_free(ob);
}
static void unlink_object__unlinkModifierLinks(void *userData, Object *ob, Object **obpoin)
@@ -274,6 +306,7 @@ void unlink_object(Object *ob)
Camera *camera;
bConstraint *con;
bActionStrip *strip;
+ ModifierData *md;
int a;
unlink_controllers(&ob->controllers);
@@ -372,10 +405,13 @@ void unlink_object(Object *ob)
/* object is deflector or field */
if(ob->pd) {
- if(give_parteff(obt))
- obt->recalc |= OB_RECALC_DATA;
- else if(obt->soft)
+ if(obt->soft)
obt->recalc |= OB_RECALC_DATA;
+
+ /* cloth */
+ for(md=obt->modifiers.first; md; md=md->next)
+ if(md->type == eModifierType_Cloth)
+ obt->recalc |= OB_RECALC_DATA;
}
/* strips */
@@ -511,11 +547,11 @@ void unlink_object(Object *ob)
if(v3d->camera==ob) {
v3d->camera= NULL;
- if(v3d->persp>1) v3d->persp= 1;
+ if(v3d->persp==V3D_CAMOB) v3d->persp= V3D_PERSP;
}
if(v3d->localvd && v3d->localvd->camera==ob ) {
v3d->localvd->camera= NULL;
- if(v3d->localvd->persp>1) v3d->localvd->persp= 1;
+ if(v3d->localvd->persp==V3D_CAMOB) v3d->localvd->persp= V3D_PERSP;
}
}
else if(sl->spacetype==SPACE_IPO) {
@@ -602,9 +638,9 @@ Camera *copy_camera(Camera *cam)
camn= copy_libblock(cam);
id_us_plus((ID *)camn->ipo);
-
+#ifndef DISABLE_PYTHON
BPY_copy_scriptlink(&camn->scriptlink);
-
+#endif
return camn;
}
@@ -671,9 +707,11 @@ float dof_camera(Object *ob)
if (cam->dof_ob) {
/* too simple, better to return the distance on the view axis only
* return VecLenf(ob->obmat[3], cam->dof_ob->obmat[3]); */
+ float mat[4][4], obmat[4][4];
- float mat[4][4];
- Mat4Invert(ob->imat, ob->obmat);
+ Mat4CpyMat4(obmat, ob->obmat);
+ Mat4Ortho(obmat);
+ Mat4Invert(ob->imat, obmat);
Mat4MulMat4(mat, cam->dof_ob->obmat, ob->imat);
return fabs(mat[3][2]);
}
@@ -709,6 +747,22 @@ void *add_lamp(char *name)
la->preview=NULL;
la->falloff_type = LA_FALLOFF_INVLINEAR;
la->curfalloff = curvemapping_add(1, 0.0f, 1.0f, 1.0f, 0.0f);
+ la->sun_effect_type = 0;
+ la->horizon_brightness = 1.0;
+ la->spread = 1.0;
+ la->sun_brightness = 1.0;
+ la->sun_size = 1.0;
+ la->backscattered_light = 1.0;
+ la->atm_turbidity = 2.0;
+ la->atm_inscattering_factor = 1.0;
+ la->atm_extinction_factor = 1.0;
+ la->atm_distance_factor = 1.0;
+ la->sun_intensity = 1.0;
+ la->skyblendtype= MA_RAMP_ADD;
+ la->skyblendfac= 1.0f;
+ la->sky_colorspace= BLI_CS_CIE;
+ la->sky_exposure= 1.0f;
+
curvemapping_initialize(la->curfalloff);
return la;
}
@@ -733,9 +787,9 @@ Lamp *copy_lamp(Lamp *la)
id_us_plus((ID *)lan->ipo);
if (la->preview) lan->preview = BKE_previewimg_copy(la->preview);
-
+#ifndef DISABLE_PYTHON
BPY_copy_scriptlink(&la->scriptlink);
-
+#endif
return lan;
}
@@ -793,7 +847,9 @@ void make_local_lamp(Lamp *la)
void free_camera(Camera *ca)
{
+#ifndef DISABLE_PYTHON
BPY_free_scriptlink(&ca->scriptlink);
+#endif
}
void free_lamp(Lamp *la)
@@ -802,8 +858,9 @@ void free_lamp(Lamp *la)
int a;
/* scriptlinks */
-
+#ifndef DISABLE_PYTHON
BPY_free_scriptlink(&la->scriptlink);
+#endif
for(a=0; a<MAX_MTEX; a++) {
mtex= la->mtex[a];
@@ -879,10 +936,12 @@ Object *add_only_object(int type, char *name)
ob->type= type;
/* ob->transflag= OB_QUAT; */
+#if 0 /* not used yet */
QuatOne(ob->quat);
QuatOne(ob->dquat);
+#endif
- ob->col[0]= ob->col[1]= ob->col[2]= 0.0;
+ ob->col[0]= ob->col[1]= ob->col[2]= 1.0;
ob->col[3]= 1.0;
ob->loc[0]= ob->loc[1]= ob->loc[2]= 0.0;
@@ -919,8 +978,9 @@ Object *add_only_object(int type, char *name)
ob->anisotropicFriction[0] = 1.0f;
ob->anisotropicFriction[1] = 1.0f;
ob->anisotropicFriction[2] = 1.0f;
- ob->gameflag= OB_PROP;
-
+ ob->gameflag= OB_PROP|OB_COLLISION;
+ ob->margin = 0.0;
+
/* NT fluid sim defaults */
ob->fluidsimFlag = 0;
ob->fluidsimSettings = NULL;
@@ -971,11 +1031,13 @@ void base_init_from_view3d(Base *base, View3D *v3d)
if (U.flag & USER_ADD_VIEWALIGNED) {
v3d->viewquat[0]= -v3d->viewquat[0];
- if (ob->transflag & OB_QUAT) {
+
+ /* Quats arnt used yet */
+ /*if (ob->transflag & OB_QUAT) {
QUATCOPY(ob->quat, v3d->viewquat);
- } else {
+ } else {*/
QuatToEul(v3d->viewquat, ob->rot);
- }
+ /*}*/
v3d->viewquat[0]= -v3d->viewquat[0];
}
}
@@ -990,15 +1052,28 @@ SoftBody *copy_softbody(SoftBody *sb)
sbn->totspring= sbn->totpoint= 0;
sbn->bpoint= NULL;
sbn->bspring= NULL;
- sbn->ctime= 0.0f;
sbn->keys= NULL;
sbn->totkey= sbn->totpointkey= 0;
sbn->scratch= NULL;
+
+ sbn->pointcache= BKE_ptcache_copy(sb->pointcache);
+
return sbn;
}
+BulletSoftBody *copy_bulletsoftbody(BulletSoftBody *bsb)
+{
+ BulletSoftBody *bsbn;
+
+ if (bsb == NULL)
+ return NULL;
+ bsbn = MEM_dupallocN(bsb);
+ /* no pointer in this structure yet */
+ return bsbn;
+}
+
ParticleSystem *copy_particlesystem(ParticleSystem *psys)
{
ParticleSystem *psysn;
@@ -1016,23 +1091,63 @@ ParticleSystem *copy_particlesystem(ParticleSystem *psys)
pa->keys= MEM_dupallocN(pa->keys);
}
- if(psys->soft)
+ if(psys->soft) {
psysn->soft= copy_softbody(psys->soft);
+ psysn->soft->particles = psysn;
+ }
psysn->pathcache= NULL;
psysn->childcache= NULL;
psysn->edit= NULL;
psysn->effectors.first= psysn->effectors.last= 0;
+
+ psysn->pathcachebufs.first = psysn->pathcachebufs.last = NULL;
+ psysn->childcachebufs.first = psysn->childcachebufs.last = NULL;
+ psysn->reactevents.first = psysn->reactevents.last = NULL;
+ psysn->renderdata = NULL;
+
+ psysn->pointcache= BKE_ptcache_copy(psys->pointcache);
id_us_plus((ID *)psysn->part);
return psysn;
}
+void copy_object_particlesystems(Object *obn, Object *ob)
+{
+ ParticleSystemModifierData *psmd;
+ ParticleSystem *psys, *npsys;
+ ModifierData *md;
+
+ obn->particlesystem.first= obn->particlesystem.last= NULL;
+ for(psys=ob->particlesystem.first; psys; psys=psys->next) {
+ npsys= copy_particlesystem(psys);
+
+ BLI_addtail(&obn->particlesystem, npsys);
+
+ /* need to update particle modifiers too */
+ for(md=obn->modifiers.first; md; md=md->next) {
+ if(md->type==eModifierType_ParticleSystem) {
+ psmd= (ParticleSystemModifierData*)md;
+ if(psmd->psys==psys)
+ psmd->psys= npsys;
+ }
+ }
+ }
+}
+
+void copy_object_softbody(Object *obn, Object *ob)
+{
+ if(ob->soft)
+ obn->soft= copy_softbody(ob->soft);
+}
+
static void copy_object_pose(Object *obn, Object *ob)
{
bPoseChannel *chan;
+ /* note: need to clear obn->pose pointer first, so that copy_pose works (otherwise there's a crash) */
+ obn->pose= NULL;
copy_pose(&obn->pose, ob->pose, 1); /* 1 = copy constraints */
for (chan = obn->pose->chanbase.first; chan; chan=chan->next){
@@ -1045,7 +1160,10 @@ static void copy_object_pose(Object *obn, Object *ob)
ListBase targets = {NULL, NULL};
bConstraintTarget *ct;
- if(con->ipo) {
+ /* note that we can't change lib linked ipo blocks. for making
+ * proxies this still works correct however because the object
+ * is changed to object->proxy_from when evaluating the driver. */
+ if(con->ipo && !con->ipo->id.lib) {
IpoCurve *icu;
for(icu= con->ipo->curve.first; icu; icu= icu->next) {
if(icu->driver && icu->driver->ob==ob)
@@ -1072,7 +1190,6 @@ Object *copy_object(Object *ob)
{
Object *obn;
ModifierData *md;
- ParticleSystem *psys;
int a;
obn= copy_libblock(ob);
@@ -1085,7 +1202,6 @@ Object *copy_object(Object *ob)
obn->path= NULL;
obn->flag &= ~OB_FROMGROUP;
- copy_effects(&obn->effect, &ob->effect);
obn->modifiers.first = obn->modifiers.last= NULL;
for (md=ob->modifiers.first; md; md=md->next) {
@@ -1093,10 +1209,12 @@ Object *copy_object(Object *ob)
modifier_copyData(md, nmd);
BLI_addtail(&obn->modifiers, nmd);
}
-
+#ifndef DISABLE_PYTHON
BPY_copy_scriptlink(&ob->scriptlink);
-
+#endif
+ obn->prop.first = obn->prop.last = NULL;
copy_properties(&obn->prop, &ob->prop);
+
copy_sensors(&obn->sensors, &ob->sensors);
copy_controllers(&obn->controllers, &ob->controllers);
copy_actuators(&obn->actuators, &ob->actuators);
@@ -1129,32 +1247,9 @@ Object *copy_object(Object *ob)
id_us_plus(&(obn->pd->tex->id));
}
obn->soft= copy_softbody(ob->soft);
+ obn->bsoft = copy_bulletsoftbody(ob->bsoft);
- /* NT copy fluid sim setting memory */
- if(obn->fluidsimSettings) {
- obn->fluidsimSettings = fluidsimSettingsCopy(ob->fluidsimSettings);
- /* copying might fail... */
- if(obn->fluidsimSettings) {
- obn->fluidsimSettings->orgMesh = (Mesh *)obn->data;
- }
- }
-
- obn->particlesystem.first= obn->particlesystem.last= NULL;
- for(psys=ob->particlesystem.first; psys; psys=psys->next) {
- ParticleSystemModifierData *psmd;
- ParticleSystem *npsys= copy_particlesystem(psys);
-
- BLI_addtail(&obn->particlesystem, npsys);
-
- /* need to update particle modifiers too */
- for(md=obn->modifiers.first; md; md=md->next) {
- if(md->type==eModifierType_ParticleSystem) {
- psmd= (ParticleSystemModifierData*)md;
- if(psmd->psys==psys)
- psmd->psys= npsys;
- }
- }
- }
+ copy_object_particlesystems(obn, ob);
obn->derivedDeform = NULL;
obn->derivedFinal = NULL;
@@ -1163,6 +1258,7 @@ Object *copy_object(Object *ob)
obn->vnode = NULL;
#endif
+ obn->gpulamp.first = obn->gpulamp.last = NULL;
return obn;
}
@@ -1170,11 +1266,13 @@ Object *copy_object(Object *ob)
void expand_local_object(Object *ob)
{
bActionStrip *strip;
+ ParticleSystem *psys;
int a;
id_lib_extern((ID *)ob->action);
id_lib_extern((ID *)ob->ipo);
id_lib_extern((ID *)ob->data);
+ id_lib_extern((ID *)ob->dup_group);
for(a=0; a<ob->totcol; a++) {
id_lib_extern((ID *)ob->mat[a]);
@@ -1182,7 +1280,8 @@ void expand_local_object(Object *ob)
for (strip=ob->nlastrips.first; strip; strip=strip->next) {
id_lib_extern((ID *)strip->act);
}
-
+ for(psys=ob->particlesystem.first; psys; psys=psys->next)
+ id_lib_extern((ID *)psys->part);
}
void make_local_object(Object *ob)
@@ -1306,11 +1405,29 @@ void object_make_proxy(Object *ob, Object *target, Object *gob)
/* skip constraints, constraintchannels, nla? */
-
+ /* set object type and link to data */
ob->type= target->type;
ob->data= target->data;
id_us_plus((ID *)ob->data); /* ensures lib data becomes LIB_EXTERN */
+ /* copy material and index information */
+ ob->actcol= ob->totcol= 0;
+ if(ob->mat) MEM_freeN(ob->mat);
+ ob->mat = NULL;
+ if ((target->totcol) && (target->mat) && ELEM5(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL)) { //XXX OB_SUPPORT_MATERIAL
+ int i;
+ ob->colbits = target->colbits;
+
+ ob->actcol= target->actcol;
+ ob->totcol= target->totcol;
+
+ ob->mat = MEM_dupallocN(target->mat);
+ for(i=0; i<target->totcol; i++) {
+ /* dont need to run test_object_materials since we know this object is new and not used elsewhere */
+ id_us_plus((ID *)ob->mat[i]);
+ }
+ }
+
/* type conversions */
if(target->type == OB_ARMATURE) {
copy_object_pose(ob, target); /* data copy, object pointers in constraints */
@@ -1357,12 +1474,12 @@ float bsystem_time(Object *ob, float cfra, float ofs)
cfra*= G.scene->r.framelen;
if (ob) {
- if (no_speed_curve==0 && ob->ipo)
+ if (no_speed_curve==0 && ob->ipo)
cfra= calc_ipo_time(ob->ipo, cfra);
/* ofset frames */
if ((ob->ipoflag & OB_OFFS_PARENT) && (ob->partype & PARSLOW)==0)
- cfra-= ob->sf;
+ cfra-= give_timeoffset(ob);
}
cfra-= ofs;
@@ -1370,25 +1487,46 @@ float bsystem_time(Object *ob, float cfra, float ofs)
return cfra;
}
-void object_to_mat3(Object *ob, float mat[][3]) /* no parent */
+void object_scale_to_mat3(Object *ob, float mat[][3])
{
- float smat[3][3], vec[3];
- float rmat[3][3];
- float q1[4];
-
- /* size */
+ float vec[3];
if(ob->ipo) {
vec[0]= ob->size[0]+ob->dsize[0];
vec[1]= ob->size[1]+ob->dsize[1];
vec[2]= ob->size[2]+ob->dsize[2];
- SizeToMat3(vec, smat);
+ SizeToMat3(vec, mat);
}
else {
- SizeToMat3(ob->size, smat);
+ SizeToMat3(ob->size, mat);
}
+}
+
+void object_rot_to_mat3(Object *ob, float mat[][3])
+{
+ float vec[3];
+ if(ob->ipo) {
+ vec[0]= ob->rot[0]+ob->drot[0];
+ vec[1]= ob->rot[1]+ob->drot[1];
+ vec[2]= ob->rot[2]+ob->drot[2];
+ EulToMat3(vec, mat);
+ }
+ else {
+ EulToMat3(ob->rot, mat);
+ }
+}
+
+void object_to_mat3(Object *ob, float mat[][3]) /* no parent */
+{
+ float smat[3][3];
+ float rmat[3][3];
+ /*float q1[4];*/
+
+ /* size */
+ object_scale_to_mat3(ob, smat);
/* rot */
- if(ob->transflag & OB_QUAT) {
+ /* Quats arnt used yet */
+ /*if(ob->transflag & OB_QUAT) {
if(ob->ipo) {
QuatMul(q1, ob->quat, ob->dquat);
QuatToMat3(q1, rmat);
@@ -1397,17 +1535,9 @@ void object_to_mat3(Object *ob, float mat[][3]) /* no parent */
QuatToMat3(ob->quat, rmat);
}
}
- else {
- if(ob->ipo) {
- vec[0]= ob->rot[0]+ob->drot[0];
- vec[1]= ob->rot[1]+ob->drot[1];
- vec[2]= ob->rot[2]+ob->drot[2];
- EulToMat3(vec, rmat);
- }
- else {
- EulToMat3(ob->rot, rmat);
- }
- }
+ else {*/
+ object_rot_to_mat3(ob, rmat);
+ /*}*/
Mat3MulMat3(mat, rmat, smat);
}
@@ -1432,8 +1562,8 @@ int enable_cu_speed= 1;
static void ob_parcurve(Object *ob, Object *par, float mat[][4])
{
Curve *cu;
- float q[4], vec[4], dir[3], *quat, x1, ctime;
- float timeoffs= 0.0;
+ float q[4], vec[4], dir[3], quat[4], x1, ctime;
+ float timeoffs = 0.0, sf_orig = 0.0;
Mat4One(mat);
@@ -1444,7 +1574,8 @@ static void ob_parcurve(Object *ob, Object *par, float mat[][4])
/* exception, timeoffset is regarded as distance offset */
if(cu->flag & CU_OFFS_PATHDIST) {
- SWAP(float, timeoffs, ob->sf);
+ timeoffs = give_timeoffset(ob);
+ SWAP(float, sf_orig, ob->sf);
}
/* catch exceptions: feature for nla stride editing */
@@ -1461,7 +1592,7 @@ static void ob_parcurve(Object *ob, Object *par, float mat[][4])
}
}
else {
- ctime= G.scene->r.cfra - ob->sf;
+ ctime= G.scene->r.cfra - give_timeoffset(ob);
ctime /= cu->pathlen;
CLAMP(ctime, 0.0, 1.0);
@@ -1472,7 +1603,7 @@ static void ob_parcurve(Object *ob, Object *par, float mat[][4])
ctime += timeoffs/cu->path->totdist;
/* restore */
- SWAP(float, timeoffs, ob->sf);
+ SWAP(float, sf_orig, ob->sf);
}
@@ -1480,7 +1611,7 @@ static void ob_parcurve(Object *ob, Object *par, float mat[][4])
if( where_on_path(par, ctime, vec, dir) ) {
if(cu->flag & CU_FOLLOW) {
- quat= vectoquat(dir, ob->trackflag, ob->upflag);
+ vectoquat(dir, ob->trackflag, ob->upflag, quat);
/* the tilt */
Normalize(dir);
@@ -1541,7 +1672,7 @@ static void give_parvert(Object *par, int nr, float *vec)
for(eve= em->verts.first; eve; eve= eve->next) {
if(eve->keyindex==nr) {
- memcpy(vec, eve->co, 12);
+ memcpy(vec, eve->co, sizeof(float)*3);
break;
}
}
@@ -1563,9 +1694,12 @@ static void give_parvert(Object *par, int nr, float *vec)
}
}
- if(count > 0) {
+ if (count==0) {
+ /* keep as 0,0,0 */
+ } else if(count > 0) {
VecMulf(vec, 1.0f / count);
} else {
+ /* use first index if its out of range */
dm->getVertCo(dm, 0, vec);
}
}
@@ -1576,18 +1710,20 @@ static void give_parvert(Object *par, int nr, float *vec)
Curve *cu;
BPoint *bp;
BezTriple *bezt;
+ int found= 0;
cu= par->data;
nu= cu->nurb.first;
//XXX if(par==G.obedit) nu= editNurb.first;
count= 0;
- while(nu) {
+ while(nu && !found) {
if((nu->type & 7)==CU_BEZIER) {
bezt= nu->bezt;
a= nu->pntsu;
while(a--) {
if(count==nr) {
+ found= 1;
VECCOPY(vec, bezt->vec[1]);
break;
}
@@ -1600,7 +1736,8 @@ static void give_parvert(Object *par, int nr, float *vec)
a= nu->pntsu*nu->pntsv;
while(a--) {
if(count==nr) {
- memcpy(vec, bp->vec, 12);
+ found= 1;
+ memcpy(vec, bp->vec, sizeof(float)*3);
break;
}
count++;
@@ -1730,7 +1867,7 @@ void where_is_object_time(Object *ob, float ctime)
if(ob->parent) {
Object *par= ob->parent;
- if(ob->ipoflag & OB_OFFS_PARENT) ctime-= ob->sf;
+ if(ob->ipoflag & OB_OFFS_PARENT) ctime-= give_timeoffset(ob);
/* hurms, code below conflicts with depgraph... (ton) */
/* and even worse, it gives bad effects for NLA stride too (try ctime != par->ctime, with MBlur) */
@@ -1754,7 +1891,7 @@ void where_is_object_time(Object *ob, float ctime)
if(ob->partype & PARSLOW) {
// include framerate
- fac1= (1.0f/(1.0f+ fabs(ob->sf)));
+ fac1= (1.0f/(1.0f+ fabs(give_timeoffset(ob))));
if(fac1>=1.0) return;
fac2= 1.0f-fac1;
@@ -1788,10 +1925,11 @@ void where_is_object_time(Object *ob, float ctime)
constraints_clear_evalob(cob);
}
-
+#ifndef DISABLE_PYTHON
if(ob->scriptlink.totscript && !during_script()) {
if (G.f & G_DOSCRIPTLINKS) BPY_do_pyscript((ID *)ob, SCRIPT_REDRAW);
}
+#endif
/* set negative scale flag in object */
Crossf(vec, ob->obmat[0], ob->obmat[1]);
@@ -1880,13 +2018,13 @@ static void solve_parenting (Object *ob, Object *par, float obmat[][4], float sl
}
void solve_tracking (Object *ob, float targetmat[][4])
{
- float *quat;
+ float quat[4];
float vec[3];
float totmat[3][3];
float tmat[4][4];
VecSubf(vec, ob->obmat[3], targetmat[3]);
- quat= vectoquat(vec, ob->trackflag, ob->upflag);
+ vectoquat(vec, ob->trackflag, ob->upflag, quat);
QuatToMat3(quat, totmat);
if(ob->parent && (ob->transflag & OB_POWERTRACK)) {
@@ -1937,7 +2075,7 @@ for a lamp that is the child of another object */
if(ob->partype & PARSLOW) {
- fac1= (float)(1.0/(1.0+ fabs(ob->sf)));
+ fac1= (float)(1.0/(1.0+ fabs(give_timeoffset(ob))));
fac2= 1.0f-fac1;
fp1= ob->obmat[0];
fp2= slowmat[0];
@@ -1998,7 +2136,7 @@ BoundBox *unit_boundbox()
BoundBox *bb;
float min[3] = {-1,-1,-1}, max[3] = {-1,-1,-1};
- bb= MEM_mallocN(sizeof(BoundBox), "bb");
+ bb= MEM_callocN(sizeof(BoundBox), "bb");
boundbox_set_from_min_max(bb, min, max);
return bb;
@@ -2142,7 +2280,7 @@ void object_handle_update(Object *ob)
if(ob->recalc & OB_RECALC) {
if(ob->recalc & OB_RECALC_OB) {
-
+
// printf("recalcob %s\n", ob->id.name+2);
/* handle proxy copy for target */
@@ -2158,6 +2296,9 @@ void object_handle_update(Object *ob)
}
else
where_is_object(ob);
+#ifndef DISABLE_PYTHON
+ if (G.f & G_DOSCRIPTLINKS) BPY_do_pyscript((ID *)ob, SCRIPT_OBJECTUPDATE);
+#endif
}
if(ob->recalc & OB_RECALC_DATA) {
@@ -2177,6 +2318,16 @@ void object_handle_update(Object *ob)
else if(ob->type==OB_LATTICE) {
lattice_calc_modifiers(ob);
}
+ else if(ob->type==OB_CAMERA) {
+ Camera *cam = (Camera *)ob->data;
+ calc_ipo(cam->ipo, frame_to_float(G.scene->r.cfra));
+ execute_ipo(&cam->id, cam->ipo);
+ }
+ else if(ob->type==OB_LAMP) {
+ Lamp *la = (Lamp *)ob->data;
+ calc_ipo(la->ipo, frame_to_float(G.scene->r.cfra));
+ execute_ipo(&la->id, la->ipo);
+ }
else if(ob->type==OB_ARMATURE) {
/* this happens for reading old files and to match library armatures with poses */
if(ob->pose==NULL || (ob->pose->flag & POSE_RECALC))
@@ -2194,6 +2345,7 @@ void object_handle_update(Object *ob)
if(ob->particlesystem.first) {
ParticleSystem *tpsys, *psys;
+ DerivedMesh *dm;
psys= ob->particlesystem.first;
while(psys) {
@@ -2210,7 +2362,21 @@ void object_handle_update(Object *ob)
else
psys= psys->next;
}
+
+ if(G.rendering && ob->transflag & OB_DUPLIPARTS) {
+ /* this is to make sure we get render level duplis in groups:
+ * the derivedmesh must be created before init_render_mesh,
+ * since object_duplilist does dupliparticles before that */
+ dm = mesh_create_derived_render(ob, CD_MASK_BAREMESH|CD_MASK_MTFACE|CD_MASK_MCOL);
+ dm->release(dm);
+
+ for(psys=ob->particlesystem.first; psys; psys=psys->next)
+ psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated;
+ }
}
+#ifndef DISABLE_PYTHON
+ if (G.f & G_DOSCRIPTLINKS) BPY_do_pyscript((ID *)ob, SCRIPT_OBDATAUPDATE);
+#endif
}
/* the no-group proxy case, we call update */
@@ -2230,3 +2396,78 @@ void object_handle_update(Object *ob)
// printf("set proxy pointer for later group stuff %s\n", ob->id.name);
}
}
+
+float give_timeoffset(Object *ob) {
+ if ((ob->ipoflag & OB_OFFS_PARENTADD) && ob->parent) {
+ return ob->sf + give_timeoffset(ob->parent);
+ } else {
+ return ob->sf;
+ }
+}
+
+int give_obdata_texspace(Object *ob, int **texflag, float **loc, float **size, float **rot) {
+
+ if (ob->data==NULL)
+ return 0;
+
+ switch (GS(((ID *)ob->data)->name)) {
+ case ID_ME:
+ {
+ Mesh *me= ob->data;
+ if (texflag) *texflag = &me->texflag;
+ if (loc) *loc = me->loc;
+ if (size) *size = me->size;
+ if (rot) *rot = me->rot;
+ break;
+ }
+ case ID_CU:
+ {
+ Curve *cu= ob->data;
+ if (texflag) *texflag = &cu->texflag;
+ if (loc) *loc = cu->loc;
+ if (size) *size = cu->size;
+ if (rot) *rot = cu->rot;
+ break;
+ }
+ case ID_MB:
+ {
+ MetaBall *mb= ob->data;
+ if (texflag) *texflag = &mb->texflag;
+ if (loc) *loc = mb->loc;
+ if (size) *size = mb->size;
+ if (rot) *rot = mb->rot;
+ break;
+ }
+ default:
+ return 0;
+ }
+ return 1;
+}
+
+/*
+ * Test a bounding box for ray intersection
+ * assumes the ray is already local to the boundbox space
+ */
+int ray_hit_boundbox(struct BoundBox *bb, float ray_start[3], float ray_normal[3])
+{
+ static int triangle_indexes[12][3] = {{0, 1, 2}, {0, 2, 3},
+ {3, 2, 6}, {3, 6, 7},
+ {1, 2, 6}, {1, 6, 5},
+ {5, 6, 7}, {4, 5, 7},
+ {0, 3, 7}, {0, 4, 7},
+ {0, 1, 5}, {0, 4, 5}};
+ int result = 0;
+ int i;
+
+ for (i = 0; i < 12 && result == 0; i++)
+ {
+ float lambda;
+ int v1, v2, v3;
+ v1 = triangle_indexes[i][0];
+ v2 = triangle_indexes[i][1];
+ v3 = triangle_indexes[i][2];
+ result = RayIntersectsTriangle(ray_start, ray_normal, bb->vec[v1], bb->vec[v2], bb->vec[v3], &lambda, NULL);
+ }
+
+ return result;
+}
diff --git a/source/blender/blenkernel/intern/packedFile.c b/source/blender/blenkernel/intern/packedFile.c
index ab67aa00fbd..22e4e8a8309 100644
--- a/source/blender/blenkernel/intern/packedFile.c
+++ b/source/blender/blenkernel/intern/packedFile.c
@@ -184,7 +184,7 @@ PackedFile * newPackedFile(char * filename)
// convert relative filenames to absolute filenames
strcpy(name, filename);
- BLI_convertstringcode(name, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(name, G.sce);
// open the file
// and create a PackedFile structure
@@ -285,7 +285,7 @@ int writePackedFile(char * filename, PackedFile *pf, int guimode)
if (guimode); //XXX waitcursor(1);
strcpy(name, filename);
- BLI_convertstringcode(name, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(name, G.sce);
if (BLI_exists(name)) {
for (number = 1; number <= 999; number++) {
@@ -316,11 +316,11 @@ int writePackedFile(char * filename, PackedFile *pf, int guimode)
if (remove_tmp) {
if (ret_value == RET_ERROR) {
- if (BLI_rename(tempname, name) == RET_ERROR) {
+ if (BLI_rename(tempname, name) != 0) {
if(guimode); //XXX error("Error restoring tempfile. Check files: '%s' '%s'", tempname, name);
}
} else {
- if (BLI_delete(tempname, 0, 0) == RET_ERROR) {
+ if (BLI_delete(tempname, 0, 0) != 0) {
if(guimode); //XXX error("Error deleting '%s' (ignored)");
}
}
@@ -350,7 +350,7 @@ int checkPackedFile(char * filename, PackedFile * pf)
char name[FILE_MAXDIR + FILE_MAXFILE];
strcpy(name, filename);
- BLI_convertstringcode(name, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(name, G.sce);
if (stat(name, &st)) {
ret_val = PF_NOFILE;
diff --git a/source/blender/blenkernel/intern/particle.c b/source/blender/blenkernel/intern/particle.c
index be69a0daaf7..32da154321e 100644
--- a/source/blender/blenkernel/intern/particle.c
+++ b/source/blender/blenkernel/intern/particle.c
@@ -46,6 +46,7 @@
#include "DNA_object_types.h"
#include "DNA_curve_types.h"
#include "DNA_key_types.h"
+#include "DNA_ipo_types.h"
#include "BLI_arithb.h"
#include "BLI_blenlib.h"
@@ -74,6 +75,7 @@
#include "BKE_modifier.h"
#include "BKE_mesh.h"
#include "BKE_cdderivedmesh.h"
+#include "BKE_pointcache.h"
#include "RE_render_ext.h"
@@ -149,6 +151,49 @@ char *psys_menu_string(Object *ob, int for_sb)
return str;
}
+
+/* we allocate path cache memory in chunks instead of a big continguous
+ * chunk, windows' memory allocater fails to find big blocks of memory often */
+
+#define PATH_CACHE_BUF_SIZE 1024
+
+static ParticleCacheKey **psys_alloc_path_cache_buffers(ListBase *bufs, int tot, int steps)
+{
+ LinkData *buf;
+ ParticleCacheKey **cache;
+ int i, totkey, totbufkey;
+
+ tot= MAX2(tot, 1);
+ totkey = 0;
+ cache = MEM_callocN(tot*sizeof(void*), "PathCacheArray");
+
+ while(totkey < tot) {
+ totbufkey= MIN2(tot-totkey, PATH_CACHE_BUF_SIZE);
+ buf= MEM_callocN(sizeof(LinkData), "PathCacheLinkData");
+ buf->data= MEM_callocN(sizeof(ParticleCacheKey)*totbufkey*steps, "ParticleCacheKey");
+
+ for(i=0; i<totbufkey; i++)
+ cache[totkey+i] = ((ParticleCacheKey*)buf->data) + i*steps;
+
+ totkey += totbufkey;
+ BLI_addtail(bufs, buf);
+ }
+
+ return cache;
+}
+
+static void psys_free_path_cache_buffers(ParticleCacheKey **cache, ListBase *bufs)
+{
+ LinkData *buf;
+
+ if(cache)
+ MEM_freeN(cache);
+
+ for(buf= bufs->first; buf; buf=buf->next)
+ MEM_freeN(buf->data);
+ BLI_freelistN(bufs);
+}
+
/************************************************/
/* Getting stuff */
/************************************************/
@@ -199,7 +244,7 @@ Object *psys_get_lattice(Object *ob, ParticleSystem *psys)
{
Object *lattice=0;
- if(!psys_in_edit_mode(psys)==0){
+ if(psys_in_edit_mode(psys)==0){
ModifierData *md = (ModifierData*)psys_get_modifier(ob,psys);
@@ -221,14 +266,14 @@ void psys_disable_all(Object *ob)
ParticleSystem *psys=ob->particlesystem.first;
for(; psys; psys=psys->next)
- psys->flag &= ~PSYS_ENABLED;
+ psys->flag |= PSYS_DISABLED;
}
void psys_enable_all(Object *ob)
{
ParticleSystem *psys=ob->particlesystem.first;
for(; psys; psys=psys->next)
- psys->flag |= PSYS_ENABLED;
+ psys->flag &= ~PSYS_DISABLED;
}
int psys_ob_has_hair(Object *ob)
{
@@ -247,10 +292,17 @@ int psys_in_edit_mode(ParticleSystem *psys)
int psys_check_enabled(Object *ob, ParticleSystem *psys)
{
ParticleSystemModifierData *psmd;
+ Mesh *me;
- if(!(psys->flag & PSYS_ENABLED))
+ if(psys->flag & PSYS_DISABLED || psys->flag & PSYS_DELETE)
return 0;
+ if(ob->type == OB_MESH) {
+ me= (Mesh*)ob->data;
+ if(me->mr && me->mr->current != 1)
+ return 0;
+ }
+
psmd= psys_get_modifier(ob, psys);
if(psys->renderdata) {
if(!(psmd->modifier.mode & eModifierMode_Render))
@@ -267,10 +319,17 @@ int psys_check_enabled(Object *ob, ParticleSystem *psys)
/************************************************/
void psys_free_settings(ParticleSettings *part)
{
- if(part->pd)
+ if(part->pd) {
MEM_freeN(part->pd);
+ part->pd = NULL;
+ }
+ if(part->pd2) {
+ MEM_freeN(part->pd2);
+ part->pd2 = NULL;
+ }
}
-void free_hair(ParticleSystem *psys)
+
+void free_hair(ParticleSystem *psys, int softbody)
{
ParticleData *pa;
int i, totpart=psys->totpart;
@@ -282,6 +341,11 @@ void free_hair(ParticleSystem *psys)
}
psys->flag &= ~PSYS_HAIR_DONE;
+
+ if(softbody && psys->soft) {
+ sbFree(psys->soft);
+ psys->soft = NULL;
+ }
}
void free_keyed_keys(ParticleSystem *psys)
{
@@ -290,39 +354,41 @@ void free_keyed_keys(ParticleSystem *psys)
}
void free_child_path_cache(ParticleSystem *psys)
{
- if(psys->childcache){
- if(psys->childcache[0])
- MEM_freeN(psys->childcache[0]);
-
- MEM_freeN(psys->childcache);
-
- psys->childcache = NULL;
- psys->totchildcache = 0;
- }
+ psys_free_path_cache_buffers(psys->childcache, &psys->childcachebufs);
+ psys->childcache = NULL;
+ psys->totchildcache = 0;
}
void psys_free_path_cache(ParticleSystem *psys)
{
- if(psys->pathcache){
- if(psys->pathcache[0])
- MEM_freeN(psys->pathcache[0]);
-
- MEM_freeN(psys->pathcache);
+ psys_free_path_cache_buffers(psys->pathcache, &psys->pathcachebufs);
+ psys->pathcache= NULL;
+ psys->totcached= 0;
- psys->pathcache = NULL;
- psys->totcached = 0;
+ free_child_path_cache(psys);
+}
+void psys_free_children(ParticleSystem *psys)
+{
+ if(psys->child) {
+ MEM_freeN(psys->child);
+ psys->child=0;
+ psys->totchild=0;
}
+
free_child_path_cache(psys);
}
/* free everything */
void psys_free(Object *ob, ParticleSystem * psys)
-{
+{
if(psys){
+ int nr = 0;
+ ParticleSystem * tpsys;
+
if(ob->particlesystem.first == NULL && G.f & G_PARTICLEEDIT)
G.f &= ~G_PARTICLEEDIT;
psys_free_path_cache(psys);
- free_hair(psys);
+ free_hair(psys, 1);
free_keyed_keys(psys);
@@ -342,17 +408,33 @@ void psys_free(Object *ob, ParticleSystem * psys)
if(psys->effectors.first)
psys_end_effectors(psys);
+
+ // check if we are last non-visible particle system
+ for(tpsys=ob->particlesystem.first; tpsys; tpsys=tpsys->next){
+ if(tpsys->part)
+ {
+ if(ELEM(tpsys->part->draw_as,PART_DRAW_OB,PART_DRAW_GR))
+ {
+ nr++;
+ break;
+ }
+ }
+ }
+ // clear do-not-draw-flag
+ if(!nr)
+ ob->transflag &= ~OB_DUPLIPARTS;
if(psys->part){
psys->part->id.us--;
psys->part=0;
}
- if(psys->soft){
- sbFree(psys->soft);
- psys->soft = 0;
- }
+ if(psys->reactevents.first)
+ BLI_freelistN(&psys->reactevents);
+ if(psys->pointcache)
+ BKE_ptcache_free(psys->pointcache);
+
MEM_freeN(psys);
}
}
@@ -362,7 +444,7 @@ void psys_free(Object *ob, ParticleSystem * psys)
* removing the previous data. this should be solved properly once */
typedef struct ParticleRenderElem {
- int curchild, totchild;
+ int curchild, totchild, reduce;
float lambda, t, scalemin, scalemax;
} ParticleRenderElem;
@@ -379,6 +461,7 @@ typedef struct ParticleRenderData {
int winx, winy;
int dosimplify;
+ int timeoffset;
ParticleRenderElem *elems;
int *origindex;
} ParticleRenderData;
@@ -391,7 +474,7 @@ static float psys_render_viewport_falloff(double rate, float dist, float width)
static float psys_render_projected_area(ParticleSystem *psys, float *center, float area, double vprate, float *viewport)
{
ParticleRenderData *data= psys->renderdata;
- float co[3], view[3], ortho1[3], ortho2[2], w, dx, dy, radius;
+ float co[4], view[3], ortho1[3], ortho2[3], w, dx, dy, radius;
/* transform to view space */
VECCOPY(co, center);
@@ -440,13 +523,15 @@ static float psys_render_projected_area(ParticleSystem *psys, float *center, flo
return area;
}
-void psys_render_set(Object *ob, ParticleSystem *psys, float viewmat[][4], float winmat[][4], int winx, int winy)
+void psys_render_set(Object *ob, ParticleSystem *psys, float viewmat[][4], float winmat[][4], int winx, int winy, int timeoffset)
{
ParticleRenderData*data;
ParticleSystemModifierData *psmd= psys_get_modifier(ob, psys);
if(!G.rendering)
return;
+ if(psys->renderdata)
+ return;
data= MEM_callocN(sizeof(ParticleRenderData), "ParticleRenderData");
@@ -474,6 +559,8 @@ void psys_render_set(Object *ob, ParticleSystem *psys, float viewmat[][4], float
data->winx= winx;
data->winy= winy;
+ data->timeoffset= timeoffset;
+
psys->renderdata= data;
}
@@ -515,8 +602,8 @@ void psys_render_restore(Object *ob, ParticleSystem *psys)
psmd->totdmface= data->totdmface;
psmd->flag &= ~eParticleSystemFlag_psys_updated;
- if(psys->part->from==PART_FROM_FACE && psmd->dm)
- psys_calc_dmfaces(ob, psmd->dm, psys);
+ if(psmd->dm)
+ psys_calc_dmcache(ob, psmd->dm, psys);
MEM_freeN(data);
psys->renderdata= NULL;
@@ -531,7 +618,7 @@ int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot)
ParticleRenderData *data;
ParticleRenderElem *elems, *elem;
ParticleSettings *part= ctx->psys->part;
- float *facearea, (*facecenter)[3], size[3], fac, powrate;
+ float *facearea, (*facecenter)[3], size[3], fac, powrate, scaleclamp;
float co1[3], co2[3], co3[3], co4[3], lambda, arearatio, t, area, viewport;
double vprate;
int *origindex, *facetotvert;
@@ -539,7 +626,13 @@ int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot)
if(part->draw_as!=PART_DRAW_PATH || !(part->draw & PART_DRAW_REN_STRAND))
return tot;
- if(!ctx->psys->renderdata || !(part->simplify_flag & PART_SIMPLIFY_ENABLE))
+ if(!ctx->psys->renderdata)
+ return tot;
+
+ data= ctx->psys->renderdata;
+ if(data->timeoffset)
+ return 0;
+ if(!(part->simplify_flag & PART_SIMPLIFY_ENABLE))
return tot;
mvert= dm->getVertArray(dm);
@@ -556,7 +649,9 @@ int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot)
facetotvert= MEM_callocN(sizeof(int)*totorigface, "SimplifyFaceArea");
elems= MEM_callocN(sizeof(ParticleRenderElem)*totorigface, "SimplifyFaceElem");
- data= ctx->psys->renderdata;
+ if(data->elems)
+ MEM_freeN(data->elems);
+
data->dosimplify= 1;
data->elems= elems;
data->origindex= origindex;
@@ -614,19 +709,30 @@ int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot)
area = psys_render_projected_area(ctx->psys, facecenter[a], facearea[a], vprate, &viewport);
arearatio= fac*area/facearea[a];
- if(arearatio < 1.0f || viewport < 1.0f) {
+ if((arearatio < 1.0f || viewport < 1.0f) && elem->totchild) {
/* lambda is percentage of elements to keep */
lambda= (arearatio < 1.0f)? pow(arearatio, powrate): 1.0f;
lambda *= viewport;
+ lambda= MAX2(lambda, 1.0f/elem->totchild);
+
/* compute transition region */
t= part->simplify_transition;
elem->t= (lambda-t < 0.0f)? lambda: (lambda+t > 1.0f)? 1.0f-lambda: t;
+ elem->reduce= 1;
/* scale at end and beginning of the transition region */
elem->scalemax= (lambda+t < 1.0f)? 1.0f/lambda: 1.0f/(1.0f - elem->t*elem->t/t);
elem->scalemin= (lambda+t < 1.0f)? 0.0f: elem->scalemax*(1.0f-elem->t/t);
+ elem->scalemin= sqrt(elem->scalemin);
+ elem->scalemax= sqrt(elem->scalemax);
+
+ /* clamp scaling */
+ scaleclamp= MIN2(elem->totchild, 10.0f);
+ elem->scalemin= MIN2(scaleclamp, elem->scalemin);
+ elem->scalemax= MIN2(scaleclamp, elem->scalemax);
+
/* extend lambda to include transition */
lambda= lambda + elem->t;
if(lambda > 1.0f)
@@ -637,6 +743,7 @@ int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot)
elem->scalemax= 1.0f; //sqrt(lambda);
elem->scalemin= 1.0f; //sqrt(lambda);
+ elem->reduce= 0;
}
elem->lambda= lambda;
@@ -698,7 +805,7 @@ int psys_render_simplify_params(ParticleSystem *psys, ChildParticle *cpa, float
scalemin= elem->scalemin;
scalemax= elem->scalemax;
- if(lambda >= 1.0f) {
+ if(!elem->reduce) {
scale= scalemin;
alpha= 1.0f;
}
@@ -746,7 +853,7 @@ static void weighted_particle_vector(float *v1, float *v2, float *v3, float *v4,
vec[1]= weights[0]*v1[1] + weights[1]*v2[1] + weights[2]*v3[1] + weights[3]*v4[1];
vec[2]= weights[0]*v1[2] + weights[1]*v2[2] + weights[2]*v3[2] + weights[3]*v4[2];
}
-static void interpolate_particle(short type, ParticleKey keys[4], float dt, ParticleKey *result)
+static void interpolate_particle(short type, ParticleKey keys[4], float dt, ParticleKey *result, int velocity)
{
float t[4];
@@ -758,18 +865,20 @@ static void interpolate_particle(short type, ParticleKey keys[4], float dt, Part
weighted_particle_vector(keys[0].co, keys[1].co, keys[2].co, keys[3].co, t, result->co);
- //if(ve){
- // if(dt>0.999f){
- // set_four_ipo(dt+0.001f,t,ipo_type);
- // weighted_particle_vector(key0->co,key1->co,key2->co,key3->co,t,temp);
- // VECSUB(ve,temp,co);
- // }
- // else{
- // set_four_ipo(dt-0.001f,t,ipo_type);
- // weighted_particle_vector(key0->co,key1->co,key2->co,key3->co,t,temp);
- // VECSUB(ve,co,temp);
- // }
- //}
+ if(velocity){
+ float temp[3];
+
+ if(dt>0.999f){
+ set_four_ipo(dt-0.001f, t, type);
+ weighted_particle_vector(keys[0].co, keys[1].co, keys[2].co, keys[3].co, t, temp);
+ VECSUB(result->vel, result->co, temp);
+ }
+ else{
+ set_four_ipo(dt+0.001f, t, type);
+ weighted_particle_vector(keys[0].co, keys[1].co, keys[2].co, keys[3].co, t, temp);
+ VECSUB(result->vel, temp, result->co);
+ }
+ }
}
}
@@ -910,7 +1019,8 @@ void psys_interpolate_face(MVert *mvert, MFace *mface, MTFace *tface, float (*or
}
}
}
-void psys_interpolate_uvs(MTFace *tface, int quad, float *w, float *uvco){
+void psys_interpolate_uvs(MTFace *tface, int quad, float *w, float *uvco)
+{
float v10= tface->uv[0][0];
float v11= tface->uv[0][1];
float v20= tface->uv[1][0];
@@ -931,9 +1041,35 @@ void psys_interpolate_uvs(MTFace *tface, int quad, float *w, float *uvco){
uvco[1]= w[0]*v11 + w[1]*v21 + w[2]*v31;
}
}
+
+void psys_interpolate_mcol(MCol *mcol, int quad, float *w, MCol *mc)
+{
+ char *cp, *cp1, *cp2, *cp3, *cp4;
+
+ cp= (char *)mc;
+ cp1= (char *)&mcol[0];
+ cp2= (char *)&mcol[1];
+ cp3= (char *)&mcol[2];
+
+ if(quad) {
+ cp4= (char *)&mcol[3];
+
+ cp[0]= (int)(w[0]*cp1[0] + w[1]*cp2[0] + w[2]*cp3[0] + w[3]*cp4[0]);
+ cp[1]= (int)(w[0]*cp1[1] + w[1]*cp2[1] + w[2]*cp3[1] + w[3]*cp4[1]);
+ cp[2]= (int)(w[0]*cp1[2] + w[1]*cp2[2] + w[2]*cp3[2] + w[3]*cp4[2]);
+ cp[3]= (int)(w[0]*cp1[3] + w[1]*cp2[3] + w[2]*cp3[3] + w[3]*cp4[3]);
+ }
+ else {
+ cp[0]= (int)(w[0]*cp1[0] + w[1]*cp2[0] + w[2]*cp3[0]);
+ cp[1]= (int)(w[0]*cp1[1] + w[1]*cp2[1] + w[2]*cp3[1]);
+ cp[2]= (int)(w[0]*cp1[2] + w[1]*cp2[2] + w[2]*cp3[2]);
+ cp[3]= (int)(w[0]*cp1[3] + w[1]*cp2[3] + w[2]*cp3[3]);
+ }
+}
+
float psys_interpolate_value_from_verts(DerivedMesh *dm, short from, int index, float *fw, float *values)
{
- if(values==0)
+ if(values==0 || index==-1)
return 0.0;
switch(from){
@@ -979,8 +1115,8 @@ static void psys_origspace_to_w(OrigSpaceFace *osface, int quad, float *w, float
}
}
-/* find the derived mesh face for a particle, set the mf passed.
-This is slow, can be optimized but only for many lookups, return the face lookup index*/
+/* find the derived mesh face for a particle, set the mf passed. this is slow
+ * and can be optimized but only for many lookups. returns the face index. */
int psys_particle_dm_face_lookup(Object *ob, DerivedMesh *dm, int index, float *fw, struct LinkNode *node)
{
Mesh *me= (Mesh*)ob->data;
@@ -1013,7 +1149,7 @@ int psys_particle_dm_face_lookup(Object *ob, DerivedMesh *dm, int index, float *
if(node) { /* we have a linked list of faces that we use, faster! */
for(;node; node=node->next) {
- findex= (int)node->link;
+ findex= GET_INT_FROM_POINTER(node->link);
faceuv= osface[findex].uv;
quad= mface[findex].v4;
@@ -1048,131 +1184,142 @@ int psys_particle_dm_face_lookup(Object *ob, DerivedMesh *dm, int index, float *
return DMCACHE_NOTFOUND;
}
-/* interprets particle data to get a point on a mesh in object space */
-#define PARTICLE_ERROR(_nor, _vec) _vec[0]=_vec[1]=_vec[2]=0.0; if(_nor){ _nor[0]=_nor[1]=0.0; _nor[2]=1.0; }
-void psys_particle_on_dm(Object *ob, DerivedMesh *dm, int from, int index, int index_dmcache, float *fw, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor)
+static int psys_map_index_on_dm(DerivedMesh *dm, int from, int index, int index_dmcache, float *fw, float foffset, int *mapindex, float *mapfw)
{
- float (*orcodata)[3];
-
- if(index < 0){ /* 'no dm' error has happened! */
- PARTICLE_ERROR(nor, vec);
- return;
- }
- orcodata= dm->getVertDataArray(dm, CD_ORCO);
+ if(index < 0)
+ return 0;
if (dm->deformedOnly || index_dmcache == DMCACHE_ISCHILD) {
- /* this works for meshes with deform verts only - constructive modifiers wont work properly*/
- float temp1[3];
-
+ /* for meshes that are either only defined or for child particles, the
+ * index and fw do not require any mapping, so we can directly use it */
if(from == PART_FROM_VERT) {
- if(index >= dm->getNumVerts(dm)) {
- PARTICLE_ERROR(nor, vec);
- return;
- }
-
- dm->getVertCo(dm,index,vec);
- if(nor){
- dm->getVertNo(dm,index,nor);
- Normalize(nor);
- }
- if(orco)
- VECCOPY(orco, orcodata[index])
- if(ornor) {
- dm->getVertNo(dm,index,nor);
- Normalize(nor);
- }
- }
- else { /* PART_FROM_FACE / PART_FROM_VOLUME */
- MFace *mface;
- MTFace *mtface=0;
- MVert *mvert;
- int uv_index;
-
- if(index >= dm->getNumFaces(dm)) {
- PARTICLE_ERROR(nor, vec);
- return;
- }
-
- mface=dm->getFaceData(dm,index,CD_MFACE);
- mvert=dm->getVertDataArray(dm,CD_MVERT);
- uv_index=CustomData_get_active_layer_index(&dm->faceData,CD_MTFACE);
+ if(index >= dm->getNumVerts(dm))
+ return 0;
- if(uv_index>=0){
- CustomDataLayer *layer=&dm->faceData.layers[uv_index];
- mtface= &((MTFace*)layer->data)[index];
- }
+ *mapindex = index;
+ }
+ else { /* FROM_FACE/FROM_VOLUME */
+ if(index >= dm->getNumFaces(dm))
+ return 0;
- if(from==PART_FROM_VOLUME){
- psys_interpolate_face(mvert,mface,mtface,orcodata,fw,vec,temp1,utan,vtan,orco,ornor);
- if(nor)
- VECCOPY(nor,temp1);
- Normalize(temp1);
- VecMulf(temp1,-foffset);
- VECADD(vec,vec,temp1);
- }
- else
- psys_interpolate_face(mvert,mface,mtface,orcodata,fw,vec,nor,utan,vtan,orco,ornor);
+ *mapindex = index;
+ QUATCOPY(mapfw, fw);
}
} else {
- /* Need to support constructive modifiers, this is a bit more tricky
- we need a customdata layer like UV's so we can position the particle */
-
- /* Only face supported at the moment */
- if (from==PART_FROM_FACE) {
+ /* for other meshes that have been modified, we try to map the particle
+ * to their new location, which means a different index, and for faces
+ * also a new face interpolation weights */
+ if(from == PART_FROM_VERT) {
+ if (index_dmcache == DMCACHE_NOTFOUND || index_dmcache > dm->getNumVerts(dm))
+ return 0;
+
+ *mapindex = index_dmcache;
+ }
+ else { /* FROM_FACE/FROM_VOLUME */
/* find a face on the derived mesh that uses this face */
- Mesh *me= (Mesh*)ob->data;
- MVert *mvert;
MFace *mface;
- MTFace *mtface;
OrigSpaceFace *osface;
- int *origindex;
- float fw_mod[4];
- int i, totface;
-
- mvert= dm->getVertDataArray(dm,CD_MVERT);
+ int i;
+
+ i = index_dmcache;
+
+ if(i== DMCACHE_NOTFOUND || i >= dm->getNumFaces(dm))
+ return 0;
+
+ *mapindex = i;
+ /* modify the original weights to become
+ * weights for the derived mesh face */
osface= dm->getFaceDataArray(dm, CD_ORIGSPACE);
- origindex= dm->getFaceDataArray(dm, CD_ORIGINDEX);
+ mface= dm->getFaceData(dm, i, CD_MFACE);
- /* For this to work we need origindex and OrigSpace coords */
- if(origindex==NULL || osface==NULL || index>=me->totface) {
- PARTICLE_ERROR(nor, vec);
- return;
- }
-
- if (index_dmcache == DMCACHE_NOTFOUND)
- i = psys_particle_dm_face_lookup(ob, dm, index, fw, (LinkNode*)NULL);
+ if(osface == NULL)
+ mapfw[0]= mapfw[1]= mapfw[2]= mapfw[3]= 0.0f;
else
- i = index_dmcache;
+ psys_origspace_to_w(&osface[i], mface->v4, fw, mapfw);
+ }
+ }
- totface = dm->getNumFaces(dm);
+ return 1;
+}
- /* Any time this happens, and the face has not been removed,
- * its a BUG watch out for this error! */
- if (i==-1) {
- printf("Cannot find original face %i\n", index);
- PARTICLE_ERROR(nor, vec);
- return;
- }
- else if(i >= totface)
- return;
+/* interprets particle data to get a point on a mesh in object space */
+void psys_particle_on_dm(DerivedMesh *dm, int from, int index, int index_dmcache, float *fw, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor)
+{
+ float tmpnor[3], mapfw[4];
+ float (*orcodata)[3];
+ int mapindex;
- mface= dm->getFaceData(dm, i, CD_MFACE);
- mtface= dm->getFaceData(dm, i, CD_MTFACE);
- osface += i;
+ if(!psys_map_index_on_dm(dm, from, index, index_dmcache, fw, foffset, &mapindex, mapfw)) {
+ if(vec) { vec[0]=vec[1]=vec[2]=0.0; }
+ if(nor) { nor[0]=nor[1]=0.0; nor[2]=1.0; }
+ if(orco) { orco[0]=orco[1]=orco[2]=0.0; }
+ if(ornor) { ornor[0]=ornor[1]=0.0; ornor[2]=1.0; }
+ if(utan) { utan[0]=utan[1]=utan[2]=0.0; }
+ if(vtan) { vtan[0]=vtan[1]=vtan[2]=0.0; }
- /* we need to modify the original weights to become weights for
- * the derived mesh face */
- psys_origspace_to_w(osface, mface->v4, fw, fw_mod);
- psys_interpolate_face(mvert,mface,mtface,orcodata,fw_mod,vec,nor,utan,vtan,orco,ornor);
+ return;
+ }
+
+ orcodata= dm->getVertDataArray(dm, CD_ORCO);
+
+ if(from == PART_FROM_VERT) {
+ dm->getVertCo(dm,mapindex,vec);
+
+ if(nor) {
+ dm->getVertNo(dm,mapindex,nor);
+ Normalize(nor);
}
- else {
- /* TODO PARTICLE - support verts and volume */
- PARTICLE_ERROR(nor, vec);
+
+ if(orco)
+ VECCOPY(orco, orcodata[mapindex])
+
+ if(ornor) {
+ dm->getVertNo(dm,mapindex,nor);
+ Normalize(nor);
}
+
+ if(utan && vtan) {
+ utan[0]= utan[1]= utan[2]= 0.0f;
+ vtan[0]= vtan[1]= vtan[2]= 0.0f;
+ }
+ }
+ else { /* PART_FROM_FACE / PART_FROM_VOLUME */
+ MFace *mface;
+ MTFace *mtface;
+ MVert *mvert;
+
+ mface=dm->getFaceData(dm,mapindex,CD_MFACE);
+ mvert=dm->getVertDataArray(dm,CD_MVERT);
+ mtface=CustomData_get_layer(&dm->faceData,CD_MTFACE);
+
+ if(mtface)
+ mtface += mapindex;
+
+ if(from==PART_FROM_VOLUME) {
+ psys_interpolate_face(mvert,mface,mtface,orcodata,mapfw,vec,tmpnor,utan,vtan,orco,ornor);
+ if(nor)
+ VECCOPY(nor,tmpnor);
+
+ Normalize(tmpnor);
+ VecMulf(tmpnor,-foffset);
+ VECADD(vec,vec,tmpnor);
+ }
+ else
+ psys_interpolate_face(mvert,mface,mtface,orcodata,mapfw,vec,nor,utan,vtan,orco,ornor);
}
}
-#undef PARTICLE_ERROR
+
+float psys_particle_value_from_verts(DerivedMesh *dm, short from, ParticleData *pa, float *values)
+{
+ float mapfw[4];
+ int mapindex;
+
+ if(!psys_map_index_on_dm(dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, &mapindex, mapfw))
+ return 0.0f;
+
+ return psys_interpolate_value_from_verts(dm, from, mapindex, mapfw, values);
+}
ParticleSystemModifierData *psys_get_modifier(Object *ob, ParticleSystem *psys)
{
@@ -1193,7 +1340,7 @@ ParticleSystemModifierData *psys_get_modifier(Object *ob, ParticleSystem *psys)
/* Particles on a shape */
/************************************************/
/* ready for future use */
-void psys_particle_on_shape(int distr, int index, float *fuv, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor)
+static void psys_particle_on_shape(int distr, int index, float *fuv, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor)
{
/* TODO */
float zerovec[3]={0.0f,0.0f,0.0f};
@@ -1219,16 +1366,16 @@ void psys_particle_on_shape(int distr, int index, float *fuv, float *vec, float
/************************************************/
/* Particles on emitter */
/************************************************/
-void psys_particle_on_emitter(Object *ob, ParticleSystemModifierData *psmd, int from, int index, int index_dmcache, float *fuv, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor){
+void psys_particle_on_emitter(ParticleSystemModifierData *psmd, int from, int index, int index_dmcache, float *fuv, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor){
if(psmd){
- if(psmd->psys->part->distr==PART_DISTR_GRID){
+ if(psmd->psys->part->distr==PART_DISTR_GRID && psmd->psys->part->from != PART_FROM_VERT){
if(vec){
VECCOPY(vec,fuv);
}
return;
}
/* we cant use the num_dmcache */
- psys_particle_on_dm(ob, psmd->dm,from,index,index_dmcache,fuv,foffset,vec,nor,utan,vtan,orco,ornor);
+ psys_particle_on_dm(psmd->dm,from,index,index_dmcache,fuv,foffset,vec,nor,utan,vtan,orco,ornor);
}
else
psys_particle_on_shape(from,index,fuv,vec,nor,utan,vtan,orco,ornor);
@@ -1263,7 +1410,7 @@ static float vert_weight(MDeformVert *dvert, int group)
}
static void do_prekink(ParticleKey *state, ParticleKey *par, float *par_rot, float time, float freq, float shape, float amplitude, short type, short axis, float obmat[][4])
{
- float vec[3]={0.0,0.0,0.0}, q1[4]={1,0,0,0},*q2;
+ float vec[3]={0.0,0.0,0.0}, q1[4]={1,0,0,0},q2[4];
float t;
CLAMP(time,0.0,1.0);
@@ -1285,10 +1432,9 @@ static void do_prekink(ParticleKey *state, ParticleKey *par, float *par_rot, flo
case PART_KINK_CURL:
vec[axis]=1.0;
if(par_rot)
- q2=par_rot;
- else{
- q2=vectoquat(par->vel,axis,(axis+1)%3);
- }
+ QUATCOPY(q2,par_rot)
+ else
+ vectoquat(par->vel,axis,(axis+1)%3, q2);
QuatMulVecf(q2,vec);
VecMulf(vec,amplitude);
VECADD(state->co,state->co,vec);
@@ -1335,9 +1481,9 @@ static void do_prekink(ParticleKey *state, ParticleKey *par, float *par_rot, flo
float inp_y,inp_z,length;
if(par_rot)
- q2=par_rot;
+ QUATCOPY(q2,par_rot)
else
- q2=vectoquat(par->vel,axis,(axis+1)%3);
+ vectoquat(par->vel,axis,(axis+1)%3,q2);
QuatMulVecf(q2,y_vec);
QuatMulVecf(q2,z_vec);
@@ -1394,59 +1540,6 @@ static void do_prekink(ParticleKey *state, ParticleKey *par, float *par_rot, flo
}
}
break;
- //case PART_KINK_ROT:
- // vec[axis]=1.0;
-
- // QuatMulVecf(par->rot,vec);
-
- // VecMulf(vec,amplitude*(float)sin(t));
-
- // VECADD(state->co,state->co,vec);
- // break;
- }
-}
-static void do_postkink(ParticleKey *state, ParticleKey *par, float *par_rot, float time, float freq, float shape, float amplitude, short type, short axis, float obmat[][4])
-{
- static ParticleKey first;
- static float q[4];
- float vec[3]={0.0,0.0,0.0};
- float t;
-
- CLAMP(time,0.0,1.0);
-
- t=time;
-
- t*=(float)M_PI*freq;
-
- if(par==0) return;
-
- switch(type){
- case PART_KINK_ROLL:
- if(time<(0.5+shape/2.0f)){
- float *q2;
- memcpy(&first,state,sizeof(ParticleKey));
- Normalize(first.vel);
- if(par_rot)
- q2=par_rot;
- else
- q2=vectoquat(par->vel,axis,(axis+1)%3);
- QUATCOPY(q,q2);
- }
- else{
- float fac;
- shape=0.5f+shape/2.0f;
- t-=(float)M_PI*(shape*freq + 0.5f);
-
- vec[axis]=1.0;
-
- QuatMulVecf(q,vec);
-
- fac=amplitude*(1.0f+((1.0f-time)/(1.0f-shape)*(float)sin(t)));
- VECADDFAC(state->co,first.co,vec,fac);
- fac=amplitude*((1.0f-time)/(1.0f-shape)*(float)cos(t));
- VECADDFAC(state->co,state->co,first.vel,fac);
- }
- break;
}
}
static void do_clump(ParticleKey *state, ParticleKey *par, float time, float clumpfac, float clumppow, float pa_clump)
@@ -1539,7 +1632,7 @@ int do_guide(ParticleKey *state, int pa_num, float time, ListBase *lb)
VecRotToQuat(guidedir,guidevec[3]-ec->firstloc[3],rot2);
QuatMulVecf(rot2,pa_loc);
- //q=vectoquat(guidedir, pd->kink_axis, (pd->kink_axis+1)%3);
+ //vectoquat(guidedir, pd->kink_axis, (pd->kink_axis+1)%3, q);
//QuatMul(par.rot,rot2,q);
}
//else{
@@ -1553,13 +1646,11 @@ int do_guide(ParticleKey *state, int pa_num, float time, ListBase *lb)
/* TODO */
//else{
///* curve size*/
- // calc_curve_subdiv_radius(cu,cu->nurb.first,((Nurb*)cu->nurb.first)->
//}
par.co[0]=par.co[1]=par.co[2]=0.0f;
VECCOPY(key.co,pa_loc);
do_prekink(&key, &par, 0, guidetime, pd->kink_freq, pd->kink_shape, pd->kink_amp, pd->kink, pd->kink_axis, 0);
do_clump(&key, &par, guidetime, pd->clump_fac, pd->clump_pow, 1.0f);
- do_postkink(&key, &par, 0, guidetime, pd->kink_freq, pd->kink_shape, pd->kink_amp, pd->kink, pd->kink_axis, 0);
VECCOPY(pa_loc,key.co);
VECADD(pa_loc,pa_loc,guidevec);
@@ -1626,40 +1717,46 @@ static void do_rough_end(float *loc, float t, float fac, float shape, ParticleKe
VECADD(state->co,state->co,rough);
}
+static void do_path_effectors(Object *ob, ParticleSystem *psys, int i, ParticleCacheKey *ca, int k, int steps, float *rootco, float effector, float dfra, float cfra, float *length, float *vec)
+{
+ float force[3] = {0.0f,0.0f,0.0f}, vel[3] = {0.0f,0.0f,0.0f};
+ ParticleKey eff_key;
+ ParticleData *pa;
+
+ VECCOPY(eff_key.co,(ca-1)->co);
+ VECCOPY(eff_key.vel,(ca-1)->vel);
+ QUATCOPY(eff_key.rot,(ca-1)->rot);
+
+ pa= psys->particles+i;
+ do_effectors(i, pa, &eff_key, ob, psys, rootco, force, vel, dfra, cfra);
+
+ VecMulf(force, effector*pow((float)k / (float)steps, 100.0f * psys->part->eff_hair) / (float)steps);
+
+ VecAddf(force, force, vec);
+
+ Normalize(force);
+
+ if(k < steps) {
+ VecSubf(vec, (ca+1)->co, ca->co);
+ *length = VecLength(vec);
+ }
+
+ VECADDFAC(ca->co, (ca-1)->co, force, *length);
+}
static int check_path_length(int k, ParticleCacheKey *keys, ParticleCacheKey *state, float max_length, float *cur_length, float length, float *dvec)
{
if(*cur_length + length > max_length){
- //if(p<totparent){
- // if(k<=(int)cache[totpart+p]->time){
- // /* parents need to be calculated fully first so that they don't mess up their children */
- // /* we'll make a note of where we got to though so that they're easy to finish later */
- // state->time=(max_length-*cur_length)/length;
- // cache[totpart+p]->time=(float)k;
- // }
- //}
- //else{
VecMulf(dvec, (max_length - *cur_length) / length);
VECADD(state->co, (state - 1)->co, dvec);
keys->steps = k;
/* something over the maximum step value */
return k=100000;
- //}
}
else {
*cur_length+=length;
return k;
}
}
-static void finalize_path_length(ParticleCacheKey *keys)
-{
- ParticleCacheKey *state = keys;
- float dvec[3];
- state += state->steps;
-
- VECSUB(dvec, state->co, (state - 1)->co);
- VecMulf(dvec, state->steps);
- VECADD(state->co, (state - 1)->co, dvec);
-}
static void offset_child(ChildParticle *cpa, ParticleKey *par, ParticleKey *child, float flat, float radius)
{
VECCOPY(child->co,cpa->fuv);
@@ -1709,14 +1806,14 @@ void psys_find_parents(Object *ob, ParticleSystemModifierData *psmd, ParticleSys
tree=BLI_kdtree_new(totparent);
for(p=0,cpa=psys->child; p<totparent; p++,cpa++){
- psys_particle_on_emitter(ob,psmd,from,cpa->num,-1,cpa->fuv,cpa->foffset,co,0,0,0,orco,0);
+ psys_particle_on_emitter(psmd,from,cpa->num,-1,cpa->fuv,cpa->foffset,co,0,0,0,orco,0);
BLI_kdtree_insert(tree, p, orco, NULL);
}
BLI_kdtree_balance(tree);
for(; p<totchild; p++,cpa++){
- psys_particle_on_emitter(ob,psmd,from,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co,0,0,0,orco,0);
+ psys_particle_on_emitter(psmd,from,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co,0,0,0,orco,0);
cpa->parent=BLI_kdtree_find_nearest(tree, orco, NULL, NULL);
}
@@ -1817,6 +1914,8 @@ int psys_threads_init_path(ParticleThread *threads, float cfra, int editupdate)
ctx->vg_rough1 = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_ROUGH1);
ctx->vg_rough2 = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_ROUGH2);
ctx->vg_roughe = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_ROUGHE);
+ if(psys->part->flag & PART_CHILD_EFFECT)
+ ctx->vg_effector = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_EFFECTOR);
}
/* set correct ipo timing */
@@ -1838,14 +1937,15 @@ void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa,
ParticleCacheKey **cache= psys->childcache;
ParticleCacheKey **pcache= psys->pathcache;
ParticleCacheKey *state, *par = NULL, *key[4];
- ParticleData *pa;
+ ParticleData *pa=NULL;
ParticleTexture ptex;
float *cpa_fuv=0;
float co[3], orco[3], ornor[3], t, rough_t, cpa_1st[3], dvec[3];
float branch_begin, branch_end, branch_prob, branchfac, rough_rand;
float pa_rough1, pa_rough2, pa_roughe;
- float length, pa_length, pa_clump, pa_kink;
+ float length, pa_length, pa_clump, pa_kink, pa_effector;
float max_length = 1.0f, cur_length = 0.0f;
+ float eff_length, eff_vec[3];
int k, cpa_num, guided=0;
short cpa_from;
@@ -1905,7 +2005,7 @@ void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa,
cpa_fuv = cpa->fuv;
cpa_from = PART_FROM_FACE;
- psys_particle_on_emitter(ob,ctx->psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa->fuv,foffset,co,ornor,0,0,orco,0);
+ psys_particle_on_emitter(ctx->psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa->fuv,foffset,co,ornor,0,0,orco,0);
/* we need to save the actual root position of the child for positioning it accurately to the surface of the emitter */
VECCOPY(cpa_1st,co);
@@ -1931,7 +2031,7 @@ void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa,
cpa_num=pa->num;
cpa_fuv=pa->fuv;
- psys_particle_on_emitter(ob,ctx->psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa_fuv,pa->foffset,co,ornor,0,0,orco,0);
+ psys_particle_on_emitter(ctx->psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa_fuv,pa->foffset,co,ornor,0,0,orco,0);
}
keys->steps = ctx->steps;
@@ -1958,6 +2058,7 @@ void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa,
pa_rough1=ptex.rough;
pa_rough2=ptex.rough;
pa_roughe=ptex.rough;
+ pa_effector= 1.0f;
if(ctx->vg_length)
pa_length*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_length);
@@ -1971,16 +2072,17 @@ void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa,
pa_rough2*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_rough2);
if(ctx->vg_roughe)
pa_roughe*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_roughe);
+ if(ctx->vg_effector)
+ pa_effector*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_effector);
/* create the child path */
for(k=0,state=keys; k<=ctx->steps; k++,state++){
- t=(float)k/(float)ctx->steps;
-
if(ctx->between){
int w=0;
state->co[0] = state->co[1] = state->co[2] = 0.0f;
state->vel[0] = state->vel[1] = state->vel[2] = 0.0f;
+ state->rot[0] = state->rot[1] = state->rot[2] = state->rot[3] = 0.0f;
//QUATCOPY(state->rot,key[0]->rot);
@@ -2009,6 +2111,23 @@ void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa,
key[0]++;
}
+ }
+
+ /* apply effectors */
+ if(part->flag & PART_CHILD_EFFECT) {
+ for(k=0,state=keys; k<=ctx->steps; k++,state++) {
+ if(k) {
+ do_path_effectors(ob, psys, cpa->pa[0], state, k, ctx->steps, keys->co, pa_effector, 0.0f, ctx->cfra, &eff_length, eff_vec);
+ }
+ else {
+ VecSubf(eff_vec,(state+1)->co,state->co);
+ eff_length= VecLength(eff_vec);
+ }
+ }
+ }
+
+ for(k=0,state=keys; k<=ctx->steps; k++,state++){
+ t=(float)k/(float)ctx->steps;
if(ctx->totparent){
if(i>=ctx->totparent)
@@ -2023,8 +2142,9 @@ void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa,
}
/* apply different deformations to the child path */
- if(part->flag & PART_CHILD_GUIDE)
- guided = do_guide((ParticleKey*)state, i, t, &(psys->effectors)); //safe to cast, since only co and vel are used
+ if(part->flag & PART_CHILD_EFFECT)
+ /* state is safe to cast, since only co and vel are used */
+ guided = do_guide((ParticleKey*)state, cpa->parent, t, &(psys->effectors));
if(guided==0){
if(part->kink)
@@ -2032,10 +2152,6 @@ void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa,
part->kink_freq * pa_kink, part->kink_shape, part->kink_amp, part->kink, part->kink_axis, ob->obmat);
do_clump((ParticleKey*)state, (ParticleKey*)par, t, part->clumpfac, part->clumppow, pa_clump);
-
- if(part->kink)
- do_postkink((ParticleKey*)state, (ParticleKey*)par, par->rot, t,
- part->kink_freq * pa_kink, part->kink_shape, part->kink_amp, part->kink, part->kink_axis, ob->obmat);
}
if(part->flag & PART_BRANCHING && ctx->between == 0 && part->flag & PART_ANIM_BRANCHING)
@@ -2044,7 +2160,7 @@ void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa,
rough_t = t;
if(part->rough1 != 0.0 && pa_rough1 != 0.0)
- do_rough(orco, rough_t, pa_rough1*part->rough1, part->rough1_size, 0.0, (ParticleKey*)state);
+ do_rough(orco, rough_t, pa_rough1*part->rough1, part->rough1_size, 0.0, (ParticleKey*)state);
if(part->rough2 != 0.0 && pa_rough2 != 0.0)
do_rough(cpa->rand, rough_t, pa_rough2*part->rough2, part->rough2_size, part->rough2_thres, (ParticleKey*)state);
@@ -2122,13 +2238,9 @@ void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa,
get_strand_normal(ctx->ma, ornor, cur_length, state->vel);
}
}
-
- /* now let's finalise the interpolated parents that we might have left half done before */
- if(i<ctx->totparent)
- finalize_path_length(keys);
}
-void *exec_child_path_cache(void *data)
+static void *exec_child_path_cache(void *data)
{
ParticleThread *thread= (ParticleThread*)data;
ParticleThreadContext *ctx= thread->ctx;
@@ -2149,11 +2261,11 @@ void psys_cache_child_paths(Object *ob, ParticleSystem *psys, float cfra, int ed
ParticleSettings *part = psys->part;
ParticleThread *pthreads;
ParticleThreadContext *ctx;
- ParticleCacheKey **cache, *tcache;
+ ParticleCacheKey **cache;
ListBase threads;
int i, totchild, totparent, totthread;
- pthreads= psys_threads_create(ob, psys, G.scene->r.threads);
+ pthreads= psys_threads_create(ob, psys);
if(!psys_threads_init_path(pthreads, cfra, editupdate)) {
psys_threads_free(pthreads);
@@ -2170,12 +2282,7 @@ void psys_cache_child_paths(Object *ob, ParticleSystem *psys, float cfra, int ed
else {
/* clear out old and create new empty path cache */
free_child_path_cache(psys);
-
- cache = psys->childcache = MEM_callocN(totchild*sizeof(void *), "Child path cache array");
- tcache = MEM_callocN(totchild * (ctx->steps + 1) * sizeof(ParticleCacheKey), "Child path cache");
- for(i=0; i<totchild; i++)
- cache[i] = tcache + i * (ctx->steps + 1);
-
+ psys->childcache= psys_alloc_path_cache_buffers(&psys->childcachebufs, totchild, ctx->steps+1);
psys->totchildcache = totchild;
}
@@ -2204,6 +2311,7 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
ParticleCacheKey *ca, **cache=psys->pathcache;
ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys);
ParticleEditSettings *pset = &G.scene->toolsettings->particle;
+ ParticleSettings *part = psys->part;
ParticleData *pa;
ParticleKey keys[4], result, *kkey[2] = {NULL, NULL};
@@ -2218,7 +2326,7 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
Material *ma;
float birthtime = 0.0, dietime = 0.0;
- float t, time, keytime, dfra = 1.0, frs_sec = G.scene->r.frs_sec;
+ float t, time = 0.0, keytime = 0.0, dfra = 1.0, frs_sec = G.scene->r.frs_sec;
float col[3] = {0.5f, 0.5f, 0.5f};
float prev_tangent[3], hairmat[4][4];
int k,i;
@@ -2227,6 +2335,10 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
char nosel[4], sel[4];
float sel_col[3];
float nosel_col[3];
+ float length, vec[3];
+ float *vg_effector= NULL, effector=0.0f;
+ float *vg_length= NULL, pa_length=1.0f, max_length=1.0f, cur_length=0.0f;
+ float len, dvec[3];
/* we don't have anything valid to create paths from so let's quit here */
if((psys->flag & PSYS_HAIR_DONE)==0 && (psys->flag & PSYS_KEYED)==0)
@@ -2260,21 +2372,28 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
else {
/* clear out old and create new empty path cache */
psys_free_path_cache(psys);
-
- /* allocate cache array for fast access and set pointers to contiguous mem block */
- cache = psys->pathcache = MEM_callocN(MAX2(1, totpart) * sizeof(void *), "Path cache array");
- cache[0] = MEM_callocN(totpart * (steps + 1) * sizeof(ParticleCacheKey), "Path cache");
- for(i=1; i<totpart; i++)
- cache[i] = cache[0] + i * (steps + 1);
+ cache= psys_alloc_path_cache_buffers(&psys->pathcachebufs, totpart, steps+1);
+ psys->pathcache= cache;
}
- if(edit==NULL && psys->soft && psys->softflag & OB_SB_ENABLE)
+ if(edit==NULL && psys->soft && psys->softflag & OB_SB_ENABLE) {
soft = psys->soft;
+ if(!soft->bpoint)
+ soft= NULL;
+ }
psys->lattice = psys_get_lattice(ob, psys);
ma= give_current_material(ob, psys->part->omat);
if(ma && (psys->part->draw & PART_DRAW_MAT_COL))
VECCOPY(col, &ma->r)
+
+ if(psys->part->from!=PART_FROM_PARTICLE) {
+ if(!(psys->part->flag & PART_CHILD_EFFECT))
+ vg_effector = psys_cache_vgroup(psmd->dm, psys, PSYS_VG_EFFECTOR);
+
+ if(!edit && !psys->totchild)
+ vg_length = psys_cache_vgroup(psmd->dm, psys, PSYS_VG_LENGTH);
+ }
/*---first main loop: create all actual particles' paths---*/
for(i=0,pa=psys->particles; i<totpart; i++, pa++){
@@ -2287,6 +2406,12 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
if(editupdate && !(pa->flag & PARS_EDIT_RECALC)) continue;
else memset(cache[i], 0, sizeof(*cache[i])*(steps+1));
+ if(!edit && !psys->totchild) {
+ pa_length = part->length * (1.0f - part->randlength*pa->r_ave[0]);
+ if(vg_length)
+ pa_length *= psys_particle_value_from_verts(psmd->dm,part->from,pa,vg_length);
+ }
+
cache[i]->steps = steps;
if(edit)
@@ -2368,7 +2493,7 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
if(soft) {
if(hkey[1] != pa->hair + pa->totkey - 1)
- bp_to_particle(keys + 3, bp[1], hkey[1] + 1);
+ bp_to_particle(keys + 3, bp[1] + 1, hkey[1] + 1);
else
bp_to_particle(keys + 3, bp[1], hkey[1]);
}
@@ -2393,8 +2518,7 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
/* now we should have in chronologiacl order k1<=k2<=t<=k3<=k4 with keytime between [0,1]->[k2,k3] (k1 & k4 used for cardinal & bspline interpolation)*/
interpolate_particle((psys->flag & PSYS_KEYED) ? -1 /* signal for cubic interpolation */
: ((psys->part->flag & PART_HAIR_BSPLINE) ? KEY_BSPLINE : KEY_CARDINAL)
- ,keys, keytime, &result);
-
+ ,keys, keytime, &result, 0);
/* the velocity needs to be converted back from cubic interpolation */
if(psys->flag & PSYS_KEYED){
@@ -2403,38 +2527,92 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
else if(soft==NULL) { /* softbody and keyed are allready in global space */
Mat4MulVecfl(hairmat, result.co);
}
-
+
+ VECCOPY(ca->co, result.co);
+
+ /* selection coloring in edit mode */
+ if(edit){
+ if(pset->brushtype==PE_BRUSH_WEIGHT){
+ if(k==steps)
+ VecLerpf(ca->col, nosel_col, sel_col, hkey[0]->weight);
+ else
+ VecLerpf(ca->col, nosel_col, sel_col,
+ (1.0f - keytime) * hkey[0]->weight + keytime * hkey[1]->weight);
+ }
+ else{
+ if((ekey + (hkey[0] - pa->hair))->flag & PEK_SELECT){
+ if((ekey + (hkey[1] - pa->hair))->flag & PEK_SELECT){
+ VECCOPY(ca->col, sel_col);
+ }
+ else{
+ VecLerpf(ca->col, sel_col, nosel_col, keytime);
+ }
+ }
+ else{
+ if((ekey + (hkey[1] - pa->hair))->flag & PEK_SELECT){
+ VecLerpf(ca->col, nosel_col, sel_col, keytime);
+ }
+ else{
+ VECCOPY(ca->col, nosel_col);
+ }
+ }
+ }
+ }
+ else{
+ VECCOPY(ca->col, col);
+ }
+ }
+
+ /*--modify paths--*/
+
+ VecSubf(vec,(cache[i]+1)->co,cache[i]->co);
+ length = VecLength(vec);
+
+ effector= 1.0f;
+ if(vg_effector)
+ effector*= psys_particle_value_from_verts(psmd->dm,psys->part->from,pa,vg_effector);
+
+ for(k=0, ca=cache[i]; k<=steps; k++, ca++) {
+ /* apply effectors */
+ if(!(psys->part->flag & PART_CHILD_EFFECT) && edit==0 && k)
+ do_path_effectors(ob, psys, i, ca, k, steps, cache[i]->co, effector, dfra, cfra, &length, vec);
/* apply guide curves to path data */
- if(edit==0 && psys->effectors.first && (psys->part->flag & PART_CHILD_GUIDE)==0)
- do_guide(&result, i, time, &psys->effectors);
+ if(edit==0 && psys->effectors.first && (psys->part->flag & PART_CHILD_EFFECT)==0)
+ /* ca is safe to cast, since only co and vel are used */
+ do_guide((ParticleKey*)ca, i, (float)k/(float)steps, &psys->effectors);
+
+ /* apply lattice */
+ if(psys->lattice && edit==0)
+ calc_latt_deform(ca->co, 1.0f);
/* figure out rotation */
if(k) {
- float angle, tangent[3], normal[3], q[4];
+ float cosangle, angle, tangent[3], normal[3], q[4];
if(k == 1) {
- float *q2;
-
- VECSUB(tangent, result.co, (ca - 1)->co);
+ VECSUB(tangent, ca->co, (ca - 1)->co);
- q2 = vectoquat(tangent, OB_POSX, OB_POSZ);
-
- QUATCOPY((ca - 1)->rot, q2);
+ vectoquat(tangent, OB_POSX, OB_POSZ, (ca-1)->rot);
VECCOPY(prev_tangent, tangent);
Normalize(prev_tangent);
}
else {
- VECSUB(tangent, result.co, (ca - 1)->co);
+ VECSUB(tangent, ca->co, (ca - 1)->co);
Normalize(tangent);
- angle = saacos(Inpf(tangent, prev_tangent));
- if((angle > -0.000001) && (angle < 0.000001)){
+ cosangle= Inpf(tangent, prev_tangent);
+
+ /* note we do the comparison on cosangle instead of
+ * angle, since floating point accuracy makes it give
+ * different results across platforms */
+ if(cosangle > 0.999999f) {
QUATCOPY((ca - 1)->rot, (ca - 2)->rot);
}
- else{
+ else {
+ angle= saacos(cosangle);
Crossf(normal, prev_tangent, tangent);
VecRotToQuat(normal, angle, q);
QuatMul((ca - 1)->rot, q, (ca - 2)->rot);
@@ -2443,13 +2621,13 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
VECCOPY(prev_tangent, tangent);
}
- if(k == steps) {
+ if(k == steps)
QUATCOPY(ca->rot, (ca - 1)->rot);
- }
}
- VECCOPY(ca->co, result.co);
+ /* set velocity */
+
if(k){
VECSUB(ca->vel, ca->co, (ca-1)->co);
@@ -2459,40 +2637,27 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
}
- /* selection coloring in edit mode */
- if(edit){
- if(pset->brushtype==PE_BRUSH_WEIGHT){
- if(k==steps)
- VecLerpf(ca->col, nosel_col, sel_col, hkey[0]->weight);
+ if(!edit && !psys->totchild) {
+ /* check if path needs to be cut before actual end of data points */
+ if(k){
+ VECSUB(dvec,ca->co,(ca-1)->co);
+ if(part->flag&PART_ABS_LENGTH)
+ len=VecLength(dvec);
else
- VecLerpf(ca->col,nosel_col,sel_col,
- (1.0f - keytime) * hkey[0]->weight + keytime * hkey[1]->weight);
+ len=1.0f/(float)steps;
+
+ k=check_path_length(k,cache[i],ca,max_length,&cur_length,len,dvec);
}
else{
- if((ekey + (hkey[0] - pa->hair))->flag & PEK_SELECT){
- if((ekey + (hkey[1] - pa->hair))->flag & PEK_SELECT){
- VECCOPY(ca->col, sel_col);
- }
- else{
- VecLerpf(ca->col, sel_col, nosel_col, keytime);
- }
- }
- else{
- if((ekey + (hkey[1] - pa->hair))->flag & PEK_SELECT){
- VecLerpf(ca->col, nosel_col, sel_col, keytime);
- }
- else{
- VECCOPY(ca->col, nosel_col);
- }
- }
+ /* initialize length calculation */
+ if(part->flag&PART_ABS_LENGTH)
+ max_length= part->abslength*pa_length;
+ else
+ max_length= pa_length;
+
+ cur_length= 0.0f;
}
}
- else{
- VECCOPY(ca->col, col);
- }
-
- if(psys->lattice && edit==0)
- calc_latt_deform(ca->co, 1.0f);
}
}
@@ -2502,6 +2667,12 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
end_latt_deform();
psys->lattice=0;
}
+
+ if(vg_effector)
+ MEM_freeN(vg_effector);
+
+ if(vg_length)
+ MEM_freeN(vg_length);
}
/************************************************/
/* Particle Key handling */
@@ -2640,7 +2811,7 @@ void psys_mat_hair_to_object(Object *ob, DerivedMesh *dm, short from, ParticleDa
float vec[3];
psys_face_mat(0, dm, pa, hairmat, 0);
- psys_particle_on_dm(ob, dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, vec, 0, 0, 0, 0, 0);
+ psys_particle_on_dm(dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, vec, 0, 0, 0, 0, 0);
VECCOPY(hairmat[3],vec);
}
@@ -2649,62 +2820,14 @@ void psys_mat_hair_to_orco(Object *ob, DerivedMesh *dm, short from, ParticleData
float vec[3], orco[3];
psys_face_mat(ob, dm, pa, hairmat, 1);
- psys_particle_on_dm(ob, dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, vec, 0, 0, 0, orco, 0);
+ psys_particle_on_dm(dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, vec, 0, 0, 0, orco, 0);
/* see psys_face_mat for why this function is called */
transform_mesh_orco_verts(ob->data, &orco, 1, 1);
VECCOPY(hairmat[3],orco);
}
-/*
-void psys_key_to_geometry(DerivedMesh *dm, ParticleData *pa, ParticleKey *key)
-{
- float q[4], v1[3], v2[3], v3[3];
-
- dm->getVertCo(dm,pa->verts[0],v1);
- dm->getVertCo(dm,pa->verts[1],v2);
- dm->getVertCo(dm,pa->verts[2],v3);
-
- triatoquat(v1, v2, v3, q);
-
- QuatInv(q);
-
- VECSUB(key->co,key->co,v1);
-
- VECADD(key->vel,key->vel,key->co);
-
- QuatMulVecf(q, key->co);
- QuatMulVecf(q, key->vel);
-
- VECSUB(key->vel,key->vel,key->co);
-
- QuatMul(key->rot,q,key->rot);
-}
-
-void psys_key_from_geometry(DerivedMesh *dm, ParticleData *pa, ParticleKey *key)
-{
- float q[4], v1[3], v2[3], v3[3];
-
- dm->getVertCo(dm,pa->verts[0],v1);
- dm->getVertCo(dm,pa->verts[1],v2);
- dm->getVertCo(dm,pa->verts[2],v3);
-
- triatoquat(v1, v2, v3, q);
-
- VECADD(key->vel,key->vel,key->co);
-
- QuatMulVecf(q, key->co);
- QuatMulVecf(q, key->vel);
-
- VECSUB(key->vel,key->vel,key->co);
-
- VECADD(key->co,key->co,v1);
-
- QuatMul(key->rot,q,key->rot);
-}
-*/
-
-void psys_vec_rot_to_face(DerivedMesh *dm, ParticleData *pa, float *vec)//to_geometry(DerivedMesh *dm, ParticleData *pa, float *vec)
+void psys_vec_rot_to_face(DerivedMesh *dm, ParticleData *pa, float *vec)
{
float mat[4][4];
@@ -2713,36 +2836,6 @@ void psys_vec_rot_to_face(DerivedMesh *dm, ParticleData *pa, float *vec)//to_geo
Mat4Mul3Vecfl(mat, vec);
}
-/* unused */
-#if 0
-static void psys_vec_rot_from_face(DerivedMesh *dm, ParticleData *pa, float *vec)//from_geometry(DerivedMesh *dm, ParticleData *pa, float *vec)
-{
- float q[4], v1[3], v2[3], v3[3];
- /*
- dm->getVertCo(dm,pa->verts[0],v1);
- dm->getVertCo(dm,pa->verts[1],v2);
- dm->getVertCo(dm,pa->verts[2],v3);
- */
- /* replace with this */
- MFace *mface;
- int i; // = psys_particle_dm_face_lookup(dm, pa->num, pa->fuv, pa->foffset, (LinkNode*)NULL);
- i = pa->num_dmcache==DMCACHE_NOTFOUND ? pa->num : pa->num_dmcache;
- if (i==-1 || i >= dm->getNumFaces(dm)) { vec[0] = vec[1] = 0; vec[2] = 1; return; }
- mface=dm->getFaceData(dm,i,CD_MFACE);
-
- dm->getVertCo(dm,mface->v1,v1);
- dm->getVertCo(dm,mface->v2,v2);
- dm->getVertCo(dm,mface->v3,v3);
- /* done */
-
- triatoquat(v1, v2, v3, q);
-
- QuatMulVecf(q, vec);
-
- //VECADD(vec,vec,v1);
-}
-#endif
-
void psys_mat_hair_to_global(Object *ob, DerivedMesh *dm, short from, ParticleData *pa, float hairmat[][4])
{
float facemat[4][4];
@@ -2779,10 +2872,10 @@ static void default_particle_settings(ParticleSettings *part)
part->integrator= PART_INT_MIDPOINT;
part->phystype= PART_PHYS_NEWTON;
- part->hair_step= 10;
+ part->hair_step= 5;
part->keys_step= 5;
- part->draw_step= 4;
- part->ren_step= 6;
+ part->draw_step= 2;
+ part->ren_step= 3;
part->adapt_angle= 5;
part->adapt_pix= 3;
part->kink_axis= 2;
@@ -2790,7 +2883,6 @@ static void default_particle_settings(ParticleSettings *part)
part->disp=100;
part->from= PART_FROM_FACE;
part->length= 1.0;
- part->rotfac= 1.0;
part->nbetween= 4;
part->boidneighbours= 5;
@@ -2853,11 +2945,12 @@ ParticleSettings *psys_copy_settings(ParticleSettings *part)
partn= copy_libblock(part);
if(partn->pd) partn->pd= MEM_dupallocN(part->pd);
+ if(partn->pd2) partn->pd2= MEM_dupallocN(part->pd2);
return partn;
}
-void psys_make_local_settings(ParticleSettings *part)
+void make_local_particlesettings(ParticleSettings *part)
{
Object *ob;
ParticleSettings *par;
@@ -2943,7 +3036,7 @@ void psys_flush_settings(ParticleSettings *part, int event, int hair_recalc)
tpsys=BLI_findlink(&tob->particlesystem,psys->target_psys-1);
if(tpsys && tpsys->part==part){
- psys->flag |= event;
+ psys->recalc |= event;
flush++;
}
}
@@ -2953,9 +3046,86 @@ void psys_flush_settings(ParticleSettings *part, int event, int hair_recalc)
}
}
}
+
+LinkNode *psys_using_settings(ParticleSettings *part, int flush_update)
+{
+ Object *ob, *tob;
+ ParticleSystem *psys, *tpsys;
+ LinkNode *node= NULL;
+ int found;
+
+ /* update all that have same particle settings */
+ for(ob=G.main->object.first; ob; ob=ob->id.next) {
+ found= 0;
+
+ for(psys=ob->particlesystem.first; psys; psys=psys->next) {
+ if(psys->part == part) {
+ BLI_linklist_append(&node, psys);
+ found++;
+ }
+ else if(psys->part->type == PART_REACTOR){
+ tob= (psys->target_ob)? psys->target_ob: ob;
+ tpsys= BLI_findlink(&tob->particlesystem, psys->target_psys-1);
+
+ if(tpsys && tpsys->part==part) {
+ BLI_linklist_append(&node, tpsys);
+ found++;
+ }
+ }
+ }
+
+ if(flush_update && found)
+ DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
+ }
+
+ return node;
+}
+
+
/************************************************/
/* Textures */
/************************************************/
+
+static int get_particle_uv(DerivedMesh *dm, ParticleData *pa, int face_index, float *fuv, char *name, float *texco)
+{
+ MFace *mf;
+ MTFace *tf;
+ int i;
+
+ tf= CustomData_get_layer_named(&dm->faceData, CD_MTFACE, name);
+
+ if(tf == NULL)
+ tf= CustomData_get_layer(&dm->faceData, CD_MTFACE);
+
+ if(tf == NULL)
+ return 0;
+
+ if(pa) {
+ i= (pa->num_dmcache==DMCACHE_NOTFOUND)? pa->num: pa->num_dmcache;
+ if(i >= dm->getNumFaces(dm))
+ i = -1;
+ }
+ else
+ i= face_index;
+
+ if (i==-1) {
+ texco[0]= 0.0f;
+ texco[1]= 0.0f;
+ texco[2]= 0.0f;
+ }
+ else {
+ mf= dm->getFaceData(dm, i, CD_MFACE);
+
+ psys_interpolate_uvs(&tf[i], mf->v4, fuv, texco);
+
+ texco[0]= texco[0]*2.0f - 1.0f;
+ texco[1]= texco[1]*2.0f - 1.0f;
+ texco[2]= 0.0f;
+ }
+
+ return 1;
+}
+
static void get_cpa_texture(DerivedMesh *dm, Material *ma, int face_index, float *fw, float *orco, ParticleTexture *ptex, int event)
{
MTex *mtex;
@@ -2965,31 +3135,18 @@ static void get_cpa_texture(DerivedMesh *dm, Material *ma, int face_index, float
if(ma) for(m=0; m<MAX_MTEX; m++){
mtex=ma->mtex[m];
if(mtex && (ma->septex & (1<<m))==0){
+ float def=mtex->def_var;
float var=mtex->varfac;
short blend=mtex->blendtype;
short neg=mtex->pmaptoneg;
- if(mtex->texco & TEXCO_UV && fw){
- int uv_index=CustomData_get_named_layer_index(&dm->faceData,CD_MTFACE,mtex->uvname);
- if(uv_index<0){
- uv_index=CustomData_get_active_layer_index(&dm->faceData,CD_MTFACE);
- }
- if(uv_index>=0){
- CustomDataLayer *layer=&dm->faceData.layers[uv_index];
- MTFace *mtface= &((MTFace*)layer->data)[face_index];
- MFace *mf=dm->getFaceData(dm,face_index,CD_MFACE);
- psys_interpolate_uvs(mtface,mf->v4,fw,texco);
- texco[0]*=2.0;
- texco[1]*=2.0;
- texco[0]-=1.0;
- texco[1]-=1.0;
- }
- else
+ if((mtex->texco & TEXCO_UV) && fw) {
+ if(!get_particle_uv(dm, NULL, face_index, fw, mtex->uvname, texco))
VECCOPY(texco,orco);
}
- else{
+ else
VECCOPY(texco,orco);
- }
+
externtex(mtex, texco, &value, rgba, rgba+1, rgba+2, rgba+3);
if((event & mtex->pmapto) & MAP_PA_TIME){
if((setvars&MAP_PA_TIME)==0){
@@ -2999,13 +3156,13 @@ static void get_cpa_texture(DerivedMesh *dm, Material *ma, int face_index, float
ptex->time= texture_value_blend(mtex->def_var,ptex->time,value,var,blend,neg & MAP_PA_TIME);
}
if((event & mtex->pmapto) & MAP_PA_LENGTH)
- ptex->length= texture_value_blend(value,ptex->length,value,var,blend,neg & MAP_PA_LENGTH);
+ ptex->length= texture_value_blend(def,ptex->length,value,var,blend,neg & MAP_PA_LENGTH);
if((event & mtex->pmapto) & MAP_PA_CLUMP)
- ptex->clump= texture_value_blend(value,ptex->clump,value,var,blend,neg & MAP_PA_CLUMP);
+ ptex->clump= texture_value_blend(def,ptex->clump,value,var,blend,neg & MAP_PA_CLUMP);
if((event & mtex->pmapto) & MAP_PA_KINK)
- ptex->kink= texture_value_blend(value,ptex->kink,value,var,blend,neg & MAP_PA_KINK);
+ ptex->kink= texture_value_blend(def,ptex->kink,value,var,blend,neg & MAP_PA_KINK);
if((event & mtex->pmapto) & MAP_PA_ROUGH)
- ptex->rough= texture_value_blend(value,ptex->rough,value,var,blend,neg & MAP_PA_ROUGH);
+ ptex->rough= texture_value_blend(def,ptex->rough,value,var,blend,neg & MAP_PA_ROUGH);
}
}
if(event & MAP_PA_TIME) { CLAMP(ptex->time,0.0,1.0); }
@@ -3025,61 +3182,48 @@ void psys_get_texture(Object *ob, Material *ma, ParticleSystemModifierData *psmd
mtex=ma->mtex[m];
if(mtex && (ma->septex & (1<<m))==0){
float var=mtex->varfac;
+ float def=mtex->def_var;
short blend=mtex->blendtype;
short neg=mtex->pmaptoneg;
- if(mtex->texco & TEXCO_UV){
- int uv_index=CustomData_get_named_layer_index(&psmd->dm->faceData,CD_MTFACE,mtex->uvname);
- if(uv_index<0){
- uv_index=CustomData_get_active_layer_index(&psmd->dm->faceData,CD_MTFACE);
- }
- if(uv_index>=0){
- CustomDataLayer *layer=&psmd->dm->faceData.layers[uv_index];
- MTFace *mtface= &((MTFace*)layer->data)[pa->num];
- MFace *mf=psmd->dm->getFaceData(psmd->dm,pa->num,CD_MFACE);
- psys_interpolate_uvs(mtface,mf->v4,pa->fuv,texco);
- texco[0]*=2.0;
- texco[1]*=2.0;
- texco[0]-=1.0;
- texco[1]-=1.0;
+ if((mtex->texco & TEXCO_UV) && ELEM(psys->part->from, PART_FROM_FACE, PART_FROM_VOLUME)) {
+ if(!get_particle_uv(psmd->dm, pa, 0, pa->fuv, mtex->uvname, texco)) {
+ /* failed to get uv's, let's try orco's */
+ psys_particle_on_emitter(psmd,psys->part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,0,0,0,texco, 0);
}
- else
- //psys_particle_on_emitter(ob,psmd,psys->part->from,pa->num,pa->fuv,pa->foffset,texco,0,0,0);
- /* <jahka> anyways I think it will be too small a difference to notice, so psys_get_texture should only know about the original mesh structure.. no dm needed anywhere */
- /* <brecht> the code only does dm based lookup now, so passing num_dmcache anyway to avoid^
- * massive slowdown here */
- psys_particle_on_emitter(ob,psmd,psys->part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,0,0,0,texco, 0);
}
- else{
- //psys_particle_on_emitter(ob,psmd,psys->part->from,pa->num,pa->fuv,pa->offset,texco,0,0,0);
- /* ditto above */
- psys_particle_on_emitter(ob,psmd,psys->part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,0,0,0,texco, 0);
+ else {
+ psys_particle_on_emitter(psmd,psys->part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,0,0,0,texco, 0);
}
+
externtex(mtex, texco, &value, rgba, rgba+1, rgba+2, rgba+3);
if((event & mtex->pmapto) & MAP_PA_TIME){
+ /* the first time has to set the base value for time regardless of blend mode */
if((setvars&MAP_PA_TIME)==0){
- ptex->time=0.0;
- setvars|=MAP_PA_TIME;
+ ptex->time *= 1.0f - var;
+ ptex->time += var * ((neg & MAP_PA_TIME)? 1.0f - value : value);
+ setvars |= MAP_PA_TIME;
}
- ptex->time= texture_value_blend(mtex->def_var,ptex->time,value,var,blend,neg & MAP_PA_TIME);
+ else
+ ptex->time= texture_value_blend(def,ptex->time,value,var,blend,neg & MAP_PA_TIME);
}
if((event & mtex->pmapto) & MAP_PA_LIFE)
- ptex->life= texture_value_blend(mtex->def_var,ptex->life,value,var,blend,neg & MAP_PA_LIFE);
+ ptex->life= texture_value_blend(def,ptex->life,value,var,blend,neg & MAP_PA_LIFE);
if((event & mtex->pmapto) & MAP_PA_DENS)
- ptex->exist= texture_value_blend(mtex->def_var,ptex->exist,value,var,blend,neg & MAP_PA_DENS);
+ ptex->exist= texture_value_blend(def,ptex->exist,value,var,blend,neg & MAP_PA_DENS);
if((event & mtex->pmapto) & MAP_PA_SIZE)
- ptex->size= texture_value_blend(mtex->def_var,ptex->size,value,var,blend,neg & MAP_PA_SIZE);
+ ptex->size= texture_value_blend(def,ptex->size,value,var,blend,neg & MAP_PA_SIZE);
if((event & mtex->pmapto) & MAP_PA_IVEL)
- ptex->ivel= texture_value_blend(mtex->def_var,ptex->ivel,value,var,blend,neg & MAP_PA_IVEL);
+ ptex->ivel= texture_value_blend(def,ptex->ivel,value,var,blend,neg & MAP_PA_IVEL);
if((event & mtex->pmapto) & MAP_PA_PVEL)
texture_rgb_blend(ptex->pvel,rgba,ptex->pvel,value,var,blend);
if((event & mtex->pmapto) & MAP_PA_LENGTH)
- ptex->length= texture_value_blend(mtex->def_var,ptex->length,value,var,blend,neg & MAP_PA_LENGTH);
+ ptex->length= texture_value_blend(def,ptex->length,value,var,blend,neg & MAP_PA_LENGTH);
if((event & mtex->pmapto) & MAP_PA_CLUMP)
- ptex->clump= texture_value_blend(mtex->def_var,ptex->clump,value,var,blend,neg & MAP_PA_CLUMP);
+ ptex->clump= texture_value_blend(def,ptex->clump,value,var,blend,neg & MAP_PA_CLUMP);
if((event & mtex->pmapto) & MAP_PA_KINK)
- ptex->kink= texture_value_blend(mtex->def_var,ptex->kink,value,var,blend,neg & MAP_PA_CLUMP);
+ ptex->kink= texture_value_blend(def,ptex->kink,value,var,blend,neg & MAP_PA_CLUMP);
}
}
if(event & MAP_PA_TIME) { CLAMP(ptex->time,0.0,1.0); }
@@ -3116,7 +3260,7 @@ float psys_get_size(Object *ob, Material *ma, ParticleSystemModifierData *psmd,
}
if(vg_size)
- size*=psys_interpolate_value_from_verts(psmd->dm,part->from,pa->num,pa->fuv,vg_size);
+ size*=psys_particle_value_from_verts(psmd->dm,part->from,pa,vg_size);
if(part->randsize!=0.0)
size*= 1.0f - part->randsize*pa->sizemul;
@@ -3149,16 +3293,24 @@ float psys_get_child_size(ParticleSystem *psys, ChildParticle *cpa, float cfra,
float size, time;
if(part->childtype==PART_CHILD_FACES){
- if(pa_time)
- time=*pa_time;
- else
- time=psys_get_child_time(psys,cpa,cfra);
+ size=part->size;
if((part->flag&PART_ABS_TIME)==0 && part->ipo){
+ IpoCurve *icu;
+
+ if(pa_time)
+ time=*pa_time;
+ else
+ time=psys_get_child_time(psys,cpa,cfra);
+
+ /* correction for lifetime */
calc_ipo(part->ipo, 100*time);
- execute_ipo((ID *)part, part->ipo);
+
+ for(icu = part->ipo->curve.first; icu; icu=icu->next) {
+ if(icu->adrcode == PART_SIZE)
+ size = icu->curval;
+ }
}
- size=part->size;
}
else
size=psys->particles[cpa->parent].size;
@@ -3179,13 +3331,13 @@ void psys_get_particle_on_path(Object *ob, ParticleSystem *psys, int p, Particle
ParticleData *pa;
ChildParticle *cpa;
ParticleTexture ptex;
- ParticleKey tstate;
- HairKey *hkey[2];
+ ParticleKey *kkey[2] = {NULL, NULL};
+ HairKey *hkey[2] = {NULL, NULL};
ParticleKey *par=0, keys[4];
- float t, real_t, dfra, keytime;
+ float t, real_t, dfra, keytime, frs_sec = G.scene->r.frs_sec;
float co[3], orco[3];
- float imat[4][4], hairmat[4][4], cpa_1st[3];
+ float hairmat[4][4];
float pa_clump = 0.0, pa_kink = 0.0;
int totparent = 0;
int totpart = psys->totpart;
@@ -3218,19 +3370,39 @@ void psys_get_particle_on_path(Object *ob, ParticleSystem *psys, int p, Particle
return;
}
- hkey[0] = pa->hair;
- hkey[1] = pa->hair + 1;
+ if(psys->flag & PSYS_KEYED) {
+ kkey[0] = pa->keys;
+ kkey[1] = kkey[0] + 1;
+
+ real_t = kkey[0]->time + t * (kkey[0][pa->totkey-1].time - kkey[0]->time);
+ }
+ else {
+ hkey[0] = pa->hair;
+ hkey[1] = pa->hair + 1;
- real_t = hkey[0]->time + (hkey[0][pa->totkey-1].time - hkey[0]->time) * t;
+ real_t = hkey[0]->time + (hkey[0][pa->totkey-1].time - hkey[0]->time) * t;
+ }
- while(hkey[1]->time < real_t)
- hkey[1]++;
+ if(psys->flag & PSYS_KEYED) {
+ while(kkey[1]->time < real_t) {
+ kkey[1]++;
+ }
+ kkey[0] = kkey[1] - 1;
- hkey[0] = hkey[1] - 1;
+ memcpy(keys + 1, kkey[0], sizeof(ParticleKey));
+ memcpy(keys + 2, kkey[1], sizeof(ParticleKey));
+ }
+ else {
+ while(hkey[1]->time < real_t)
+ hkey[1]++;
- hair_to_particle(keys + 1, hkey[0]);
- hair_to_particle(keys + 2, hkey[1]);
+ hkey[0] = hkey[1] - 1;
+ hair_to_particle(keys + 1, hkey[0]);
+ hair_to_particle(keys + 2, hkey[1]);
+ }
+
+ if((psys->flag & PSYS_KEYED)==0) {
//if(soft){
// if(key[0] != sbel.keys)
// DB_copy_key(&k1,key[0]-1);
@@ -3255,6 +3427,7 @@ void psys_get_particle_on_path(Object *ob, ParticleSystem *psys, int p, Particle
hair_to_particle(keys + 3, hkey[1] + 1);
else
hair_to_particle(keys + 3, hkey[1]);
+ }
//}
//psys_get_particle_on_path(bsys,p,t,bkey,ckey[0]);
@@ -3264,35 +3437,48 @@ void psys_get_particle_on_path(Object *ob, ParticleSystem *psys, int p, Particle
//else{
// /* TODO: different rotations */
// float nvel[3];
- // float *q2;
// VECCOPY(nvel,state->vel);
// VecMulf(nvel,-1.0f);
- // q2=vectoquat(nvel, OB_POSX, OB_POSZ);
- // QUATCOPY(state->rot,q2);
+ // vectoquat(nvel, OB_POSX, OB_POSZ, state->rot);
//}
dfra = keys[2].time - keys[1].time;
keytime = (real_t - keys[1].time) / dfra;
- interpolate_particle((psys->part->flag & PART_HAIR_BSPLINE) ? KEY_BSPLINE : KEY_CARDINAL
- ,keys, keytime, state);
+ /* convert velocity to timestep size */
+ if(psys->flag & PSYS_KEYED){
+ VecMulf(keys[1].vel, dfra / frs_sec);
+ VecMulf(keys[2].vel, dfra / frs_sec);
+ QuatInterpol(state->rot,keys[1].rot,keys[2].rot,keytime);
+ }
- if((pa->flag & PARS_REKEY)==0) {
- psys_mat_hair_to_global(ob, psmd->dm, part->from, pa, hairmat);
- Mat4MulVecfl(hairmat, state->co);
+ interpolate_particle((psys->flag & PSYS_KEYED) ? -1 /* signal for cubic interpolation */
+ : ((psys->part->flag & PART_HAIR_BSPLINE) ? KEY_BSPLINE : KEY_CARDINAL)
+ ,keys, keytime, state, 1);
- if(psys->effectors.first && (part->flag & PART_CHILD_GUIDE)==0) {
- do_guide(state, p, state->time, &psys->effectors);
- /* TODO: proper velocity handling */
- }
+ /* the velocity needs to be converted back from cubic interpolation */
+ if(psys->flag & PSYS_KEYED){
+ VecMulf(state->vel, frs_sec / dfra);
+ }
+ else {
+ if((pa->flag & PARS_REKEY)==0) {
+ psys_mat_hair_to_global(ob, psmd->dm, part->from, pa, hairmat);
+ Mat4MulVecfl(hairmat, state->co);
+ Mat4Mul3Vecfl(hairmat, state->vel);
+
+ if(psys->effectors.first && (part->flag & PART_CHILD_GUIDE)==0) {
+ do_guide(state, p, state->time, &psys->effectors);
+ /* TODO: proper velocity handling */
+ }
- if(psys->lattice && edit==0)
- calc_latt_deform(state->co,1.0f);
+ if(psys->lattice && edit==0)
+ calc_latt_deform(state->co,1.0f);
+ }
}
}
else if(totchild){
- Mat4Invert(imat,ob->obmat);
+ //Mat4Invert(imat,ob->obmat);
cpa=psys->child+p-totpart;
@@ -3321,22 +3507,12 @@ void psys_get_particle_on_path(Object *ob, ParticleSystem *psys, int p, Particle
cpa_fuv = cpa->fuv;
cpa_from = PART_FROM_FACE;
- psys_particle_on_emitter(ob,psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa->fuv,foffset,co,0,0,0,orco,0);
+ psys_particle_on_emitter(psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa->fuv,foffset,co,0,0,0,orco,0);
/* we need to save the actual root position of the child for positioning it accurately to the surface of the emitter */
- VECCOPY(cpa_1st,co);
-
- //w=0;
- //while(w<4 && cpa->pa[w]>=0){
- // pa=psys->particles+cpa->pa[w];
- // psys_particle_on_emitter(ob,psmd,part->from,pa->num,pa->fuv,pa->foffset,vec,0,0,0);
- // cpa_1st[0] -= cpa->w[w]*vec[0];
- // cpa_1st[1] -= cpa->w[w]*vec[1];
- // cpa_1st[2] -= cpa->w[w]*vec[2];
- // w++;
- //}
+ //VECCOPY(cpa_1st,co);
- Mat4MulVecfl(ob->obmat,cpa_1st);
+ //Mat4MulVecfl(ob->obmat,cpa_1st);
pa=0;
}
@@ -3353,7 +3529,7 @@ void psys_get_particle_on_path(Object *ob, ParticleSystem *psys, int p, Particle
cpa_num=pa->num;
cpa_fuv=pa->fuv;
- psys_particle_on_emitter(ob,psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa_fuv,pa->foffset,co,0,0,0,orco,0);
+ psys_particle_on_emitter(psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa_fuv,pa->foffset,co,0,0,0,orco,0);
}
/* correct child ipo timing */
@@ -3391,7 +3567,7 @@ void psys_get_particle_on_path(Object *ob, ParticleSystem *psys, int p, Particle
w++;
}
/* apply offset for correct positioning */
- VECADD(state->co,state->co,cpa_1st);
+ //VECADD(state->co,state->co,cpa_1st);
}
else{
/* offset the child from the parent position */
@@ -3418,12 +3594,8 @@ void psys_get_particle_on_path(Object *ob, ParticleSystem *psys, int p, Particle
do_clump(state, par, t, part->clumpfac, part->clumppow, 1.0f);
- if(part->kink)
- do_postkink(state, par, par->rot, t, part->kink_freq * pa_kink, part->kink_shape,
- part->kink_amp, part->kink, part->kink_axis, ob->obmat);
-
if(part->rough1 != 0.0)
- do_rough(orco, t, part->rough1, part->rough1_size, 0.0, state);
+ do_rough(orco, t, part->rough1, part->rough1_size, 0.0, state);
if(part->rough2 != 0.0)
do_rough(cpa->rand, t, part->rough2, part->rough2_size, part->rough2_thres, state);
@@ -3431,19 +3603,18 @@ void psys_get_particle_on_path(Object *ob, ParticleSystem *psys, int p, Particle
if(part->rough_end != 0.0)
do_rough_end(cpa->rand, t, part->rough_end, part->rough_end_shape, state, par);
- if(vel){
- if(t>=0.001f){
- tstate.time=t-0.001f;
- psys_get_particle_on_path(ob,psys,p,&tstate,0);
- VECSUB(state->vel,state->co,tstate.co);
- }
- else{
- tstate.time=t+0.001f;
- psys_get_particle_on_path(ob,psys,p,&tstate,0);
- VECSUB(state->vel,tstate.co,state->co);
- }
- }
-
+ //if(vel){
+ // if(t>=0.001f){
+ // tstate.time=t-0.001f;
+ // psys_get_particle_on_path(ob,psys,p,&tstate,0);
+ // VECSUB(state->vel,state->co,tstate.co);
+ // }
+ // else{
+ // tstate.time=t+0.001f;
+ // psys_get_particle_on_path(ob,psys,p,&tstate,0);
+ // VECSUB(state->vel,tstate.co,state->co);
+ // }
+ //}
}
}
/* gets particle's state at a time, returns 1 if particle exists and can be seen and 0 if not */
@@ -3453,6 +3624,7 @@ int psys_get_particle_state(Object *ob, ParticleSystem *psys, int p, ParticleKey
float cfra;
int totpart=psys->totpart, between=0;
+ /* negative time means "use current time" */
if(state->time>0)
cfra=state->time;
else
@@ -3484,50 +3656,92 @@ int psys_get_particle_state(Object *ob, ParticleSystem *psys, int p, ParticleKey
return 0;
}
- //if(bsys->flag & (BSYS_DONE|BSYS_KEYED)){
- // if(between){
- // //ChildParticle *cpa=psys->child+p-totpart;
- // //state->time= (cfra-(part->sta+(part->end-part->sta)*cpa->rand[0]))/(part->lifetime*cpa->rand[1]);
- // }
- // else
- // state->time= (cfra-pa->time)/(pa->dietime-pa->time);//pa->lifetime;
+ if(psys->flag & PSYS_KEYED){
+ if(between){
+ ChildParticle *cpa=psys->child+p-totpart;
+ state->time= (cfra-(part->sta+(part->end-part->sta)*cpa->rand[0]))/(part->lifetime*cpa->rand[1]);
+ }
+ else
+ state->time= (cfra-pa->time)/(pa->dietime-pa->time);
- // psys_get_particle_on_path(ob,psys,p,state,1);
- // return 1;
- //}
- //else{
- //if(psys->totchild && p>=psys->totpart){
- // ChildParticle *cpa=psys->child+p-psys->totpart;
- // ParticleKey *key1, skey;
- // float t=(cfra-pa->time)/pa->lifetime, clump;
-
- // pa=psys->particles+cpa->parent;
-
- // if(pa->alive==PARS_DEAD && part->flag&PART_STICKY && pa->flag&PARS_STICKY && pa->stick_ob){
- // key1=&skey;
- // copy_particle_key(key1,&pa->state,0);
- // key_from_object(pa->stick_ob,key1);
- // }
- // else{
- // key1=&pa->state;
- // }
- //
- // offset_child(cpa, key1, state, part->childflat, part->childrad);
- //
- // CLAMP(t,0.0,1.0);
- // if(part->kink) /* TODO: part->kink_freq*pa_kink */
- // do_prekink(state,key1,t,part->kink_freq,part->kink_shape,part->kink_amp,part->kink,part->kink_axis,ob->obmat);
- //
- // /* TODO: pa_clump vgroup */
- // do_clump(state,key1,t,part->clumpfac,part->clumppow,0);
-
- // if(part->kink) /* TODO: part->kink_freq*pa_kink */
- // do_postkink(state,key1,t,part->kink_freq,part->kink_shape,part->kink_amp,part->kink,part->kink_axis,ob->obmat);
+ psys_get_particle_on_path(ob,psys,p,state,1);
+ return 1;
+ }
+ else{
+ if(between)
+ return 0; /* currently not supported */
+ else if(psys->totchild && p>=psys->totpart){
+ ChildParticle *cpa=psys->child+p-psys->totpart;
+ ParticleKey *key1, skey;
+ float t = (cfra - pa->time + pa->loop * pa->lifetime) / pa->lifetime;
+
+ pa = psys->particles + cpa->parent;
+
+ if(pa->alive==PARS_DEAD && part->flag&PART_STICKY && pa->flag&PARS_STICKY && pa->stick_ob) {
+ key1 = &skey;
+ copy_particle_key(key1,&pa->state,0);
+ key_from_object(pa->stick_ob,key1);
+ }
+ else {
+ key1=&pa->state;
+ }
+
+ offset_child(cpa, key1, state, part->childflat, part->childrad);
+
+ CLAMP(t,0.0,1.0);
+ if(part->kink) /* TODO: part->kink_freq*pa_kink */
+ do_prekink(state,key1,key1->rot,t,part->kink_freq,part->kink_shape,part->kink_amp,part->kink,part->kink_axis,ob->obmat);
+
+ /* TODO: pa_clump vgroup */
+ do_clump(state,key1,t,part->clumpfac,part->clumppow,1.0);
- //}
- //else{
+ if(psys->lattice)
+ calc_latt_deform(state->co,1.0f);
+ }
+ else{
if (pa) { /* TODO PARTICLE - should this ever be NULL? - Campbell */
- copy_particle_key(state,&pa->state,0);
+ if(pa->state.time==state->time || ELEM(part->phystype,PART_PHYS_NO,PART_PHYS_KEYED))
+ copy_particle_key(state, &pa->state, 1);
+ else if(pa->prev_state.time==state->time)
+ copy_particle_key(state, &pa->prev_state, 1);
+ else {
+ /* let's interpolate to try to be as accurate as possible */
+ if(pa->state.time + 1.0f > state->time && pa->prev_state.time - 1.0f < state->time) {
+ ParticleKey keys[4];
+ float dfra, keytime, frs_sec = G.scene->r.frs_sec;
+
+ if(pa->prev_state.time >= pa->state.time) {
+ /* prev_state is wrong so let's not use it, this can happen at frame 1 or particle birth */
+ copy_particle_key(state, &pa->state, 1);
+
+ VECADDFAC(state->co, state->co, state->vel, (state->time-pa->state.time)/frs_sec);
+ }
+ else {
+ copy_particle_key(keys+1, &pa->prev_state, 1);
+ copy_particle_key(keys+2, &pa->state, 1);
+
+ dfra = keys[2].time - keys[1].time;
+
+ keytime = (state->time - keys[1].time) / dfra;
+
+ /* convert velocity to timestep size */
+ VecMulf(keys[1].vel, dfra / frs_sec);
+ VecMulf(keys[2].vel, dfra / frs_sec);
+
+ interpolate_particle(-1, keys, keytime, state, 1);
+
+ /* convert back to real velocity */
+ VecMulf(state->vel, frs_sec / dfra);
+
+ VecLerpf(state->ave, keys[1].ave, keys[2].ave, keytime);
+ QuatInterpol(state->rot, keys[1].rot, keys[2].rot, keytime);
+ }
+ }
+ else {
+ /* extrapolating over big ranges is not accurate so let's just give something close to reasonable back */
+ copy_particle_key(state, &pa->state, 0);
+ }
+ }
if(pa->alive==PARS_DEAD && part->flag&PART_STICKY && pa->flag&PARS_STICKY && pa->stick_ob){
key_from_object(pa->stick_ob,state);
@@ -3536,9 +3750,111 @@ int psys_get_particle_state(Object *ob, ParticleSystem *psys, int p, ParticleKey
if(psys->lattice)
calc_latt_deform(state->co,1.0f);
}
- //}
+ }
return 1;
- //}
+ }
+}
+
+void psys_get_dupli_texture(Object *ob, ParticleSettings *part, ParticleSystemModifierData *psmd, ParticleData *pa, ChildParticle *cpa, float *uv, float *orco)
+{
+ MFace *mface;
+ MTFace *mtface;
+ float loc[3];
+ int num;
+
+ if(cpa) {
+ if(part->childtype == PART_CHILD_FACES) {
+ mtface= CustomData_get_layer(&psmd->dm->faceData, CD_MTFACE);
+ if(mtface) {
+ mface= psmd->dm->getFaceData(psmd->dm, cpa->num, CD_MFACE);
+ mtface += cpa->num;
+ psys_interpolate_uvs(mtface, mface->v4, cpa->fuv, uv);
+ }
+ else
+ uv[0]= uv[1]= 0.0f;
+ }
+ else
+ uv[0]= uv[1]= 0.0f;
+
+ psys_particle_on_emitter(psmd,
+ (part->childtype == PART_CHILD_FACES)? PART_FROM_FACE: PART_FROM_PARTICLE,
+ cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,loc,0,0,0,orco,0);
+ }
+ else {
+ if(part->from == PART_FROM_FACE) {
+ mtface= CustomData_get_layer(&psmd->dm->faceData, CD_MTFACE);
+ num= pa->num_dmcache;
+
+ if(num == DMCACHE_NOTFOUND)
+ if(pa->num < psmd->dm->getNumFaces(psmd->dm))
+ num= pa->num;
+
+ if(mtface && num != DMCACHE_NOTFOUND) {
+ mface= psmd->dm->getFaceData(psmd->dm, num, CD_MFACE);
+ mtface += num;
+ psys_interpolate_uvs(mtface, mface->v4, pa->fuv, uv);
+ }
+ else
+ uv[0]= uv[1]= 0.0f;
+ }
+ else
+ uv[0]= uv[1]= 0.0f;
+
+ psys_particle_on_emitter(psmd,part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,loc,0,0,0,orco,0);
+ }
+}
+
+void psys_get_dupli_path_transform(Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd, ParticleData *pa, ChildParticle *cpa, ParticleCacheKey *cache, float mat[][4], float *scale)
+{
+ float loc[3], nor[3], vec[3], side[3], len, obrotmat[4][4], qmat[4][4];
+ float xvec[3] = {-1.0, 0.0, 0.0}, q[4];
+
+ VecSubf(vec, (cache+cache->steps-1)->co, cache->co);
+ len= Normalize(vec);
+
+ if(pa)
+ psys_particle_on_emitter(psmd,psys->part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,loc,nor,0,0,0,0);
+ else
+ psys_particle_on_emitter(psmd,
+ (psys->part->childtype == PART_CHILD_FACES)? PART_FROM_FACE: PART_FROM_PARTICLE,
+ cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,loc,nor,0,0,0,0);
+
+ if(psys->part->rotmode) {
+ if(!pa)
+ pa= psys->particles+cpa->pa[0];
+
+ vectoquat(xvec, ob->trackflag, ob->upflag, q);
+ QuatToMat4(q, obrotmat);
+ obrotmat[3][3]= 1.0f;
+
+ QuatToMat4(pa->state.rot, qmat);
+ Mat4MulMat4(mat, obrotmat, qmat);
+ }
+ else {
+ /* make sure that we get a proper side vector */
+ if(fabs(Inpf(nor,vec))>0.999999) {
+ if(fabs(Inpf(nor,xvec))>0.999999) {
+ nor[0] = 0.0f;
+ nor[1] = 1.0f;
+ nor[2] = 0.0f;
+ }
+ else {
+ nor[0] = 1.0f;
+ nor[1] = 0.0f;
+ nor[2] = 0.0f;
+ }
+ }
+ Crossf(side, nor, vec);
+ Normalize(side);
+ Crossf(nor, vec, side);
+
+ Mat4One(mat);
+ VECCOPY(mat[0], vec);
+ VECCOPY(mat[1], side);
+ VECCOPY(mat[2], nor);
+ }
+
+ *scale= len;
}
diff --git a/source/blender/blenkernel/intern/particle_system.c b/source/blender/blenkernel/intern/particle_system.c
index e3b3629fb72..6d8d6c233ac 100644
--- a/source/blender/blenkernel/intern/particle_system.c
+++ b/source/blender/blenkernel/intern/particle_system.c
@@ -53,13 +53,15 @@
#include "BLI_arithb.h"
#include "BLI_blenlib.h"
#include "BLI_kdtree.h"
+#include "BLI_kdopbvh.h"
#include "BLI_linklist.h"
#include "BLI_threads.h"
#include "BKE_anim.h"
#include "BKE_cdderivedmesh.h"
+#include "BKE_collision.h"
#include "BKE_displist.h"
-
+#include "BKE_effect.h"
#include "BKE_particle.h"
#include "BKE_global.h"
#include "BKE_utildefines.h"
@@ -73,10 +75,28 @@
#include "BKE_pointcache.h"
#include "BKE_mesh.h"
#include "BKE_modifier.h"
+#include "BKE_scene.h"
+#include "PIL_time.h"
#include "RE_shader_ext.h"
+/* fluid sim particle import */
+#ifndef DISABLE_ELBEEM
+#include "DNA_object_fluidsim.h"
+#include "LBM_fluidsim.h"
+#include "elbeem.h"
+#include <zlib.h>
+#include <string.h>
+
+#ifdef WIN32
+#ifndef snprintf
+#define snprintf _snprintf
+#endif
+#endif
+
+#endif // DISABLE_ELBEEM
+
/************************************************/
/* Reacting to system events */
/************************************************/
@@ -98,13 +118,65 @@ static int get_current_display_percentage(ParticleSystem *psys)
return psys->part->disp;
}
-static void alloc_particles(Object *ob, ParticleSystem *psys, int new_totpart)
+void psys_reset(ParticleSystem *psys, int mode)
+{
+ ParticleSettings *part= psys->part;
+ ParticleData *pa;
+ int i;
+
+ if(ELEM(mode, PSYS_RESET_ALL, PSYS_RESET_DEPSGRAPH)) {
+ if(mode == PSYS_RESET_ALL || !(part->type == PART_HAIR && (psys->flag & PSYS_EDITED))) {
+ if(psys->particles) {
+ if(psys->particles->keys)
+ MEM_freeN(psys->particles->keys);
+
+ for(i=0, pa=psys->particles; i<psys->totpart; i++, pa++)
+ if(pa->hair) MEM_freeN(pa->hair);
+
+ MEM_freeN(psys->particles);
+ psys->particles= NULL;
+ }
+
+ psys->totpart= 0;
+ psys->totkeyed= 0;
+ psys->flag &= ~(PSYS_HAIR_DONE|PSYS_KEYED);
+
+ if(psys->reactevents.first)
+ BLI_freelistN(&psys->reactevents);
+ }
+ }
+ else if(mode == PSYS_RESET_CACHE_MISS) {
+ /* set all particles to be skipped */
+ ParticleData *pa = psys->particles;
+ int p=0;
+
+ for(; p<psys->totpart; p++, pa++)
+ pa->flag |= PARS_NO_DISP;
+ }
+
+ /* reset children */
+ if(psys->child) {
+ MEM_freeN(psys->child);
+ psys->child= 0;
+ }
+
+ psys->totchild= 0;
+
+ /* reset path cache */
+ psys_free_path_cache(psys);
+
+ /* reset point cache */
+ psys->pointcache->flag &= ~PTCACHE_SIMULATION_VALID;
+ psys->pointcache->simframe= 0;
+}
+
+static void realloc_particles(Object *ob, ParticleSystem *psys, int new_totpart)
{
ParticleData *newpars = 0, *pa;
int i, totpart, totsaved = 0;
if(new_totpart<0) {
- if(psys->part->distr==PART_DISTR_GRID) {
+ if(psys->part->distr==PART_DISTR_GRID && psys->part->from != PART_FROM_VERT) {
totpart= psys->part->grid_res;
totpart*=totpart*totpart;
}
@@ -122,6 +194,12 @@ static void alloc_particles(Object *ob, ParticleSystem *psys, int new_totpart)
if(totsaved)
memcpy(newpars,psys->particles,totsaved*sizeof(ParticleData));
+ if(psys->particles->keys)
+ MEM_freeN(psys->particles->keys);
+
+ for(i=0, pa=psys->particles; i<totsaved; i++, pa++)
+ if(pa->keys) pa->keys= NULL;
+
for(i=totsaved, pa=psys->particles+totsaved; i<psys->totpart; i++, pa++)
if(pa->hair) MEM_freeN(pa->hair);
@@ -138,15 +216,24 @@ static void alloc_particles(Object *ob, ParticleSystem *psys, int new_totpart)
psys->totpart=totpart;
}
-static int get_alloc_child_particles_tot(ParticleSystem *psys)
+static int get_psys_child_number(ParticleSystem *psys)
{
- int child_nbr;
+ int nbr;
if(!psys->part->childtype)
return 0;
- child_nbr= (psys->renderdata)? psys->part->ren_child_nbr: psys->part->child_nbr;
- return psys->totpart*child_nbr;
+ if(psys->renderdata) {
+ nbr= psys->part->ren_child_nbr;
+ return get_render_child_particle_number(&G.scene->r, nbr);
+ }
+ else
+ return psys->part->child_nbr;
+}
+
+static int get_psys_tot_child(ParticleSystem *psys)
+{
+ return psys->totpart*get_psys_child_number(psys);
}
static void alloc_child_particles(ParticleSystem *psys, int tot)
@@ -164,12 +251,13 @@ static void alloc_child_particles(ParticleSystem *psys, int tot)
}
}
-/* only run this if from == PART_FROM_FACE */
-void psys_calc_dmfaces(Object *ob, DerivedMesh *dm, ParticleSystem *psys)
+void psys_calc_dmcache(Object *ob, DerivedMesh *dm, ParticleSystem *psys)
{
- /* use for building derived mesh face-origin info,
- node - the allocated links - total derived mesh face count
- node_array - is the array of nodes alligned with the base mesh's faces, so each original face can reference its derived faces
+ /* use for building derived mesh mapping info:
+
+ node: the allocated links - total derived mesh element count
+ nodearray: the array of nodes aligned with the base mesh's elements, so
+ each original elements can reference its derived elements
*/
Mesh *me= (Mesh*)ob->data;
ParticleData *pa= 0;
@@ -178,57 +266,60 @@ void psys_calc_dmfaces(Object *ob, DerivedMesh *dm, ParticleSystem *psys)
/* CACHE LOCATIONS */
if(!dm->deformedOnly) {
/* Will use later to speed up subsurf/derivedmesh */
+ LinkNode *node, *nodedmelem, **nodearray;
+ int totdmelem, totelem, i, *origindex;
+
+ if(psys->part->from == PART_FROM_VERT) {
+ totdmelem= dm->getNumVerts(dm);
+ totelem= me->totvert;
+ origindex= DM_get_vert_data_layer(dm, CD_ORIGINDEX);
+ }
+ else { /* FROM_FACE/FROM_VOLUME */
+ totdmelem= dm->getNumFaces(dm);
+ totelem= me->totface;
+ origindex= DM_get_face_data_layer(dm, CD_ORIGINDEX);
+ }
- int tot_dm_face = dm->getNumFaces(dm);
- int totface = me->totface;
- int *origindex = DM_get_face_data_layer(dm, CD_ORIGINDEX);
- int i;
- LinkNode *node, *node_dm_faces, **node_array;
+ nodedmelem= MEM_callocN(sizeof(LinkNode)*totdmelem, "psys node elems");
+ nodearray= MEM_callocN(sizeof(LinkNode *)*totelem, "psys node array");
- node_dm_faces = node = MEM_callocN(sizeof(LinkNode)*tot_dm_face, "faceindicies");
- node_array = MEM_callocN(sizeof(LinkNode *)*totface, "faceindicies array");
-
- for(i=0; i < tot_dm_face; i++, origindex++, node++) {
- node->link = (void *)i; // or use the index?
+ for(i=0, node=nodedmelem; i<totdmelem; i++, origindex++, node++) {
+ node->link= SET_INT_IN_POINTER(i);
+
if(*origindex != -1) {
- if(node_array[*origindex]) {
+ if(nodearray[*origindex]) {
/* prepend */
- node->next = node_array[*origindex];
- node_array[*origindex] = node;
- } else {
- node_array[*origindex] = node;
+ node->next = nodearray[*origindex];
+ nodearray[*origindex]= node;
}
+ else
+ nodearray[*origindex]= node;
}
}
- /* cache the faces! */
-
-
+ /* cache the verts/faces! */
for(p=0,pa=psys->particles; p<psys->totpart; p++,pa++) {
- //i = pa->num;
- //if (i<totface) // should never happen
- i = psys_particle_dm_face_lookup(ob, dm, pa->num, pa->fuv, node_array[pa->num]);
- pa->num_dmcache = i;
+ if(psys->part->from == PART_FROM_VERT) {
+ if(nodearray[pa->num])
+ pa->num_dmcache= GET_INT_FROM_POINTER(nodearray[pa->num]->link);
+ }
+ else { /* FROM_FACE/FROM_VOLUME */
+ /* Note that somtimes the pa->num is over the nodearray size, this is bad, maybe there is a better place to fix this,
+ * but for now passing NULL is OK. every face will be searched for the particle so its slower - Campbell */
+ pa->num_dmcache= psys_particle_dm_face_lookup(ob, dm, pa->num, pa->fuv, pa->num < totelem ? nodearray[pa->num] : NULL);
+ }
}
- //for (i=0; i < totface; i++) {
- // i = psys_particle_dm_face_lookup(ob, dm, node_array[], fuv, (LinkNode*)NULL);
- //}
- MEM_freeN(node_array);
- MEM_freeN(node_dm_faces);
-
- } else {
- /* set the num_dmcache to an invalid value, just incase */
- /* TODO PARTICLE, make the following line unnecessary, each function should know to use the num or num_dmcache */
+ MEM_freeN(nodearray);
+ MEM_freeN(nodedmelem);
+ }
+ else {
+ /* TODO PARTICLE, make the following line unnecessary, each function
+ * should know to use the num or num_dmcache, set the num_dmcache to
+ * an invalid value, just incase */
- /*
- for(p=0,pa=psys->particles; p<psys->totpart; p++,pa++) {
- pa->num_dmcache = pa->num;
- }
- */
- for(p=0,pa=psys->particles; p<psys->totpart; p++,pa++) {
+ for(p=0,pa=psys->particles; p<psys->totpart; p++,pa++)
pa->num_dmcache = -1;
- }
}
}
@@ -388,6 +479,29 @@ static void distribute_particles_in_grid(DerivedMesh *dm, ParticleSystem *psys)
}
}
+/* modified copy from rayshade.c */
+static void hammersley_create(float *out, int n, int seed, float amount)
+{
+ RNG *rng;
+ double p, t, offs[2];
+ int k, kk;
+
+ rng = rng_new(31415926 + n + seed);
+ offs[0]= rng_getDouble(rng) + amount;
+ offs[1]= rng_getDouble(rng) + amount;
+ rng_free(rng);
+
+ for (k = 0; k < n; k++) {
+ t = 0;
+ for (p = 0.5, kk = k; kk; p *= 0.5, kk >>= 1)
+ if (kk & 1) /* kk mod 2 = 1 */
+ t += p;
+
+ out[2*k + 0]= fmod((double)k/(double)n + offs[0], 1.0);
+ out[2*k + 1]= fmod(t + offs[1], 1.0);
+ }
+}
+
/* modified copy from effect.c */
static void init_mv_jit(float *jit, int num, int seed2, float amount)
{
@@ -485,7 +599,7 @@ void psys_thread_distribute_particle(ParticleThread *thread, ParticleData *pa, C
ParticleData *tpa;
ParticleSettings *part= ctx->psys->part;
float *v1, *v2, *v3, *v4, nor[3], orco1[3], co1[3], co2[3], nor1[3], ornor1[3];
- float cur_d, min_d;
+ float cur_d, min_d, randu, randv;
int from= ctx->from;
int cfrom= ctx->cfrom;
int distr= ctx->distr;
@@ -503,7 +617,7 @@ void psys_thread_distribute_particle(ParticleThread *thread, ParticleData *pa, C
KDTreeNearest ptn[3];
int w, maxw;
- psys_particle_on_dm(ctx->ob,ctx->dm,from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co1,0,0,0,orco1,0);
+ psys_particle_on_dm(ctx->dm,from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co1,0,0,0,orco1,0);
transform_mesh_orco_verts((Mesh*)ob->data, &orco1, 1, 1);
maxw = BLI_kdtree_find_n_nearest(ctx->tree,3,orco1,NULL,ptn);
@@ -527,7 +641,9 @@ void psys_thread_distribute_particle(ParticleThread *thread, ParticleData *pa, C
//ctx->jitoff[i]=(float)fmod(ctx->jitoff[i]+ctx->maxweight/ctx->weight[i],(float)ctx->jitlevel);
break;
case PART_DISTR_RAND:
- psys_uv_to_w(rng_getFloat(thread->rng), rng_getFloat(thread->rng), mface->v4, pa->fuv);
+ randu= rng_getFloat(thread->rng);
+ randv= rng_getFloat(thread->rng);
+ psys_uv_to_w(randu, randv, mface->v4, pa->fuv);
break;
}
pa->foffset= 0.0f;
@@ -625,7 +741,9 @@ void psys_thread_distribute_particle(ParticleThread *thread, ParticleData *pa, C
// ctx->jitoff[i]=(float)fmod(ctx->jitoff[i]+ctx->maxweight/ctx->weight[i],(float)ctx->jitlevel);
// break;
// case PART_DISTR_RAND:
- psys_uv_to_w(rng_getFloat(thread->rng), rng_getFloat(thread->rng), mf->v4, cpa->fuv);
+ randu= rng_getFloat(thread->rng);
+ randv= rng_getFloat(thread->rng);
+ psys_uv_to_w(randu, randv, mf->v4, cpa->fuv);
// break;
//}
@@ -643,7 +761,7 @@ void psys_thread_distribute_particle(ParticleThread *thread, ParticleData *pa, C
do_seams= (part->flag&PART_CHILD_SEAMS && ctx->seams);
- psys_particle_on_dm(ob,dm,cfrom,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co1,nor1,0,0,orco1,ornor1);
+ psys_particle_on_dm(dm,cfrom,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co1,nor1,0,0,orco1,ornor1);
transform_mesh_orco_verts((Mesh*)ob->data, &orco1, 1, 1);
maxw = BLI_kdtree_find_n_nearest(ctx->tree,(do_seams)?10:4,orco1,ornor1,ptn);
@@ -741,7 +859,7 @@ void psys_thread_distribute_particle(ParticleThread *thread, ParticleData *pa, C
}
}
-void *exec_distribution(void *data)
+static void *exec_distribution(void *data)
{
ParticleThread *thread= (ParticleThread*)data;
ParticleSystem *psys= thread->ctx->psys;
@@ -773,6 +891,29 @@ void *exec_distribution(void *data)
return 0;
}
+/* not thread safe, but qsort doesn't take userdata argument */
+static int *COMPARE_ORIG_INDEX = NULL;
+static int compare_orig_index(const void *p1, const void *p2)
+{
+ int index1 = COMPARE_ORIG_INDEX[*(const int*)p1];
+ int index2 = COMPARE_ORIG_INDEX[*(const int*)p2];
+
+ if(index1 < index2)
+ return -1;
+ else if(index1 == index2) {
+ /* this pointer comparison appears to make qsort stable for glibc,
+ * and apparently on solaris too, makes the renders reproducable */
+ if(p1 < p2)
+ return -1;
+ else if(p1 == p2)
+ return 0;
+ else
+ return 1;
+ }
+ else
+ return 1;
+}
+
/* creates a distribution of coordinates on a DerivedMesh */
/* */
/* 1. lets check from what we are emitting */
@@ -834,14 +975,14 @@ int psys_threads_init_distribution(ParticleThread *threads, DerivedMesh *finaldm
tree=BLI_kdtree_new(totpart);
for(p=0,pa=psys->particles; p<totpart; p++,pa++){
- psys_particle_on_dm(ob,dm,part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,nor,0,0,orco,ornor);
+ psys_particle_on_dm(dm,part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,nor,0,0,orco,ornor);
transform_mesh_orco_verts((Mesh*)ob->data, &orco, 1, 1);
BLI_kdtree_insert(tree, p, orco, ornor);
}
BLI_kdtree_balance(tree);
- totpart=get_alloc_child_particles_tot(psys);
+ totpart=get_psys_tot_child(psys);
cfrom=from=PART_FROM_FACE;
if(part->flag&PART_CHILD_SEAMS){
@@ -890,9 +1031,9 @@ int psys_threads_init_distribution(ParticleThread *threads, DerivedMesh *finaldm
}
else{
/* no need to figure out distribution */
- int child_nbr= (psys->renderdata)? part->ren_child_nbr: part->child_nbr;
+ int child_nbr= get_psys_child_number(psys);
- totpart= get_alloc_child_particles_tot(psys);
+ totpart= get_psys_tot_child(psys);
alloc_child_particles(psys, totpart);
cpa=psys->child;
for(i=0; i<child_nbr; i++){
@@ -923,7 +1064,7 @@ int psys_threads_init_distribution(ParticleThread *threads, DerivedMesh *finaldm
dm= CDDM_from_mesh((Mesh*)ob->data, ob);
/* special handling of grid distribution */
- if(part->distr==PART_DISTR_GRID){
+ if(part->distr==PART_DISTR_GRID && from != PART_FROM_VERT){
distribute_particles_in_grid(dm,psys);
dm->release(dm);
return 0;
@@ -980,17 +1121,21 @@ int psys_threads_init_distribution(ParticleThread *threads, DerivedMesh *finaldm
if(tot==0){
no_distr=1;
if(children){
- fprintf(stderr,"Particle child distribution error: Nothing to emit from!\n");
- for(p=0,cpa=psys->child; p<totpart; p++,cpa++){
- cpa->fuv[0]=cpa->fuv[1]=cpa->fuv[2]=cpa->fuv[3]= 0.0;
- cpa->foffset= 0.0f;
- cpa->parent=0;
- cpa->pa[0]=cpa->pa[1]=cpa->pa[2]=cpa->pa[3]=0;
- cpa->num= -1;
+ if(G.f & G_DEBUG)
+ fprintf(stderr,"Particle child distribution error: Nothing to emit from!\n");
+ if(psys->child) {
+ for(p=0,cpa=psys->child; p<totpart; p++,cpa++){
+ cpa->fuv[0]=cpa->fuv[1]=cpa->fuv[2]=cpa->fuv[3]= 0.0;
+ cpa->foffset= 0.0f;
+ cpa->parent=0;
+ cpa->pa[0]=cpa->pa[1]=cpa->pa[2]=cpa->pa[3]=0;
+ cpa->num= -1;
+ }
}
}
else {
- fprintf(stderr,"Particle distribution error: Nothing to emit from!\n");
+ if(G.f & G_DEBUG)
+ fprintf(stderr,"Particle distribution error: Nothing to emit from!\n");
for(p=0,pa=psys->particles; p<totpart; p++,pa++){
pa->fuv[0]=pa->fuv[1]=pa->fuv[2]= pa->fuv[3]= 0.0;
pa->foffset= 0.0f;
@@ -1131,7 +1276,7 @@ int psys_threads_init_distribution(ParticleThread *threads, DerivedMesh *finaldm
double step, pos;
step= (totpart <= 1)? 0.5: 1.0/(totpart-1);
- pos= 0.0f;
+ pos= 1e-16f; /* tiny offset to avoid zero weight face */
i= 0;
for(p=0; p<totpart; p++, pos+=step) {
@@ -1139,6 +1284,8 @@ int psys_threads_init_distribution(ParticleThread *threads, DerivedMesh *finaldm
i++;
index[p]= MIN2(tot-1, i);
+
+ /* avoid zero weight face */
if(p == totpart-1 && weight[index[p]] == 0.0f)
index[p]= index[p-1];
@@ -1148,6 +1295,13 @@ int psys_threads_init_distribution(ParticleThread *threads, DerivedMesh *finaldm
MEM_freeN(sum);
+ /* for hair, sort by origindex, allows optimizations in rendering */
+ if(part->type == PART_HAIR) {
+ COMPARE_ORIG_INDEX= dm->getFaceDataArray(dm, CD_ORIGINDEX);
+ if(COMPARE_ORIG_INDEX)
+ qsort(index, totpart, sizeof(int), compare_orig_index);
+ }
+
/* weights are no longer used except for FROM_PARTICLE, which needs them zeroed for indexing */
if(from==PART_FROM_PARTICLE){
for(i=0; i<tot; i++)
@@ -1165,9 +1319,15 @@ int psys_threads_init_distribution(ParticleThread *threads, DerivedMesh *finaldm
//if(jitlevel>100) jitlevel= 100;
}
- jit= MEM_callocN(2+ jitlevel*2*sizeof(float), "jit");
+ jit= MEM_callocN((2+ jitlevel*2)*sizeof(float), "jit");
- init_mv_jit(jit, jitlevel, psys->seed, part->jitfac);
+ /* for small amounts of particles we use regular jitter since it looks
+ * a bit better, for larger amounts we switch to hammersley sequence
+ * because it is much faster */
+ if(jitlevel < 25)
+ init_mv_jit(jit, jitlevel, psys->seed, part->jitfac);
+ else
+ hammersley_create(jit, jitlevel+1, psys->seed, part->jitfac);
BLI_array_randomize(jit, 2*sizeof(float), jitlevel, psys->seed); /* for custom jit or even distribution */
}
@@ -1212,7 +1372,7 @@ static void distribute_particles_on_dm(DerivedMesh *finaldm, Object *ob, Particl
ParticleThreadContext *ctx;
int i, totthread;
- pthreads= psys_threads_create(ob, psys, G.scene->r.threads);
+ pthreads= psys_threads_create(ob, psys);
if(!psys_threads_init_distribution(pthreads, finaldm, from)) {
psys_threads_free(pthreads);
@@ -1231,8 +1391,7 @@ static void distribute_particles_on_dm(DerivedMesh *finaldm, Object *ob, Particl
else
exec_distribution(&pthreads[0]);
- if (from == PART_FROM_FACE)
- psys_calc_dmfaces(ob, finaldm, psys);
+ psys_calc_dmcache(ob, finaldm, psys);
ctx= pthreads[0].ctx;
if(ctx->dm != finaldm)
@@ -1285,11 +1444,16 @@ static void distribute_particles(Object *ob, ParticleSystem *psys, int from)
}
/* threaded child particle distribution and path caching */
-ParticleThread *psys_threads_create(struct Object *ob, struct ParticleSystem *psys, int totthread)
+ParticleThread *psys_threads_create(struct Object *ob, struct ParticleSystem *psys)
{
ParticleThread *threads;
ParticleThreadContext *ctx;
- int i;
+ int i, totthread;
+
+ if(G.scene->r.mode & R_FIXED_THREADS)
+ totthread= G.scene->r.threads;
+ else
+ totthread= BLI_system_thread_count();
threads= MEM_callocN(sizeof(ParticleThread)*totthread, "ParticleThread");
ctx= MEM_callocN(sizeof(ParticleThreadContext), "ParticleThreadContext");
@@ -1326,7 +1490,7 @@ void psys_threads_free(ParticleThread *threads)
if(ctx->vg_rough1)
MEM_freeN(ctx->vg_rough1);
if(ctx->vg_rough2)
- MEM_freeN(ctx->vg_roughe);
+ MEM_freeN(ctx->vg_rough2);
if(ctx->vg_roughe)
MEM_freeN(ctx->vg_roughe);
@@ -1376,7 +1540,7 @@ void initialize_particle(ParticleData *pa, int p, Object *ob, ParticleSystem *ps
BLI_srandom(psys->seed+p);
- if(part->from!=PART_FROM_PARTICLE){
+ if(part->from!=PART_FROM_PARTICLE && part->type!=PART_FLUID){
ma=give_current_material(ob,part->omat);
/* TODO: needs some work to make most blendtypes generally usefull */
@@ -1446,7 +1610,7 @@ void initialize_particle(ParticleData *pa, int p, Object *ob, ParticleSystem *ps
NormalQuat(pa->r_rot);
- if(part->distr!=PART_DISTR_GRID){
+ if(part->distr!=PART_DISTR_GRID && part->from != PART_FROM_VERT){
/* any unique random number will do (r_ave[0]) */
if(ptex.exist < 0.5*(1.0+pa->r_ave[0]))
pa->flag |= PARS_UNEXIST;
@@ -1468,53 +1632,54 @@ static void initialize_all_particles(Object *ob, ParticleSystem *psys, ParticleS
for(p=0, pa=psys->particles; p<totpart; p++, pa++)
initialize_particle(pa,p,ob,psys,psmd);
- /* store the derived mesh face index for each particle */
- icu=find_ipocurve(psys->part->ipo,PART_EMIT_FREQ);
- if(icu){
- float time=psys->part->sta, end=psys->part->end;
- float v1, v2, a=0.0f, t1,t2, d;
+ if(psys->part->type != PART_FLUID) {
+ icu=find_ipocurve(psys->part->ipo,PART_EMIT_FREQ);
+ if(icu){
+ float time=psys->part->sta, end=psys->part->end;
+ float v1, v2, a=0.0f, t1,t2, d;
+
+ p=0;
+ pa=psys->particles;
+
+ calc_icu(icu,time);
+ v1=icu->curval;
+ if(v1<0.0f) v1=0.0f;
+
+ calc_icu(icu,time+1.0f);
+ v2=icu->curval;
+ if(v2<0.0f) v2=0.0f;
+
+ for(p=0, pa=psys->particles; p<totpart && time<end; p++, pa++){
+ while(a+0.5f*(v1+v2) < (float)(p+1) && time<end){
+ a+=0.5f*(v1+v2);
+ v1=v2;
+ time++;
+ calc_icu(icu,time+1.0f);
+ v2=icu->curval;
+ }
+ if(time<end){
+ if(v1==v2){
+ pa->time=time+((float)(p+1)-a)/v1;
+ }
+ else{
+ d=(float)sqrt(v1*v1-2.0f*(v2-v1)*(a-(float)(p+1)));
+ t1=(-v1+d)/(v2-v1);
+ t2=(-v1-d)/(v2-v1);
- p=0;
- pa=psys->particles;
+ /* the root between 0-1 is the correct one */
+ if(t1>0.0f && t1<=1.0f)
+ pa->time=time+t1;
+ else
+ pa->time=time+t2;
+ }
+ }
- calc_icu(icu,time);
- v1=icu->curval;
- if(v1<0.0f) v1=0.0f;
-
- calc_icu(icu,time+1.0f);
- v2=icu->curval;
- if(v2<0.0f) v2=0.0f;
-
- for(p=0, pa=psys->particles; p<totpart && time<end; p++, pa++){
- while(a+0.5f*(v1+v2) < (float)(p+1) && time<end){
- a+=0.5f*(v1+v2);
- v1=v2;
- time++;
- calc_icu(icu,time+1.0f);
- v2=icu->curval;
+ pa->dietime = pa->time+pa->lifetime;
+ pa->flag &= ~PARS_UNEXIST;
}
- if(time<end){
- if(v1==v2){
- pa->time=time+((float)(p+1)-a)/v1;
- }
- else{
- d=(float)sqrt(v1*v1-2.0f*(v2-v1)*(a-(float)(p+1)));
- t1=(-v1+d)/(v2-v1);
- t2=(-v1-d)/(v2-v1);
-
- /* the root between 0-1 is the correct one */
- if(t1>0.0f && t1<=1.0f)
- pa->time=time+t1;
- else
- pa->time=time+t2;
- }
+ for(; p<totpart; p++, pa++){
+ pa->flag |= PARS_UNEXIST;
}
-
- pa->dietime = pa->time+pa->lifetime;
- pa->flag &= ~PARS_UNEXIST;
- }
- for(; p<totpart; p++, pa++){
- pa->flag |= PARS_UNEXIST;
}
}
}
@@ -1526,11 +1691,10 @@ void reset_particle(ParticleData *pa, ParticleSystem *psys, ParticleSystemModifi
ParticleTexture ptex;
ParticleKey state;
IpoCurve *icu=0;
- float fac, nor[3]={0,0,0},loc[3],tloc[3],vel[3]={0.0,0.0,0.0},rot[4],*q2=0;
+ float fac, phasefac, nor[3]={0,0,0},loc[3],tloc[3],vel[3]={0.0,0.0,0.0},rot[4],q2[4];
float r_vel[3],r_ave[3],r_rot[4],p_vel[3]={0.0,0.0,0.0};
- float x_vec[3]={1.0,0.0,0.0}, utan[3]={0.0,1.0,0.0}, vtan[3]={0.0,0.0,1.0};
-
- float q_one[4]={1.0,0.0,0.0,0.0}, q_phase[4];
+ float x_vec[3]={1.0,0.0,0.0}, utan[3]={0.0,1.0,0.0}, vtan[3]={0.0,0.0,1.0}, rot_vec[3]={0.0,0.0,0.0};
+ float q_phase[4];
part=psys->part;
ptex.ivel=1.0;
@@ -1545,11 +1709,12 @@ void reset_particle(ParticleData *pa, ParticleSystem *psys, ParticleSystemModifi
tob=ob;
tpsys=BLI_findlink(&tob->particlesystem,psys->target_psys-1);
-
- /*TODO: get precise location of particle at birth*/
- state.time=cfra;
- psys_get_particle_state(tob,tpsys,pa->num,&state,1);
+ state.time = pa->time;
+ if(pa->num == -1)
+ memset(&state, 0, sizeof(state));
+ else
+ psys_get_particle_state(tob,tpsys,pa->num,&state,1);
psys_get_from_key(&state,loc,nor,rot,0);
QuatMulVecf(rot,vtan);
@@ -1571,7 +1736,7 @@ void reset_particle(ParticleData *pa, ParticleSystem *psys, ParticleSystemModifi
where_is_object_time(ob,pa->time);
/* get birth location from object */
- psys_particle_on_emitter(ob,psmd,part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,utan,vtan,0,0);
+ psys_particle_on_emitter(psmd,part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,utan,vtan,0,0);
/* save local coordinates for later */
VECCOPY(tloc,loc);
@@ -1579,9 +1744,8 @@ void reset_particle(ParticleData *pa, ParticleSystem *psys, ParticleSystemModifi
/* get possible textural influence */
psys_get_texture(ob,give_current_material(ob,part->omat),psmd,psys,pa,&ptex,MAP_PA_IVEL);
- if(vg_vel){
- ptex.ivel*=psys_interpolate_value_from_verts(psmd->dm,part->from,pa->num,pa->fuv,vg_vel);
- }
+ if(vg_vel && pa->num != -1)
+ ptex.ivel*=psys_particle_value_from_verts(psmd->dm,part->from,pa,vg_vel);
/* particles live in global space so */
/* let's convert: */
@@ -1596,7 +1760,7 @@ void reset_particle(ParticleData *pa, ParticleSystem *psys, ParticleSystemModifi
/* -tangent */
if(part->tanfac!=0.0){
- float phase=vg_rot?2.0f*(psys_interpolate_value_from_verts(psmd->dm,part->from,pa->num,pa->fuv,vg_rot)-0.5f):0.0f;
+ float phase=vg_rot?2.0f*(psys_particle_value_from_verts(psmd->dm,part->from,pa,vg_rot)-0.5f):0.0f;
VecMulf(vtan,-(float)cos(M_PI*(part->tanphase+phase)));
fac=-(float)sin(M_PI*(part->tanphase+phase));
VECADDFAC(vtan,vtan,utan,fac);
@@ -1630,7 +1794,7 @@ void reset_particle(ParticleData *pa, ParticleSystem *psys, ParticleSystemModifi
}
/* -rotation */
- if(part->rotmode==PART_ROT_RAND){
+ if(part->randrotfac != 0.0f){
QUATCOPY(r_rot,pa->r_rot);
Mat4ToQuat(ob->obmat,rot);
QuatMul(r_rot,r_rot,rot);
@@ -1638,6 +1802,12 @@ void reset_particle(ParticleData *pa, ParticleSystem *psys, ParticleSystemModifi
}
/* conversion done so now we apply new: */
/* -velocity from: */
+
+ /* *reactions */
+ if(dtime>0.0f){
+ VECSUB(vel,pa->state.vel,pa->prev_state.vel);
+ }
+
/* *emitter velocity */
if(dtime!=0.0 && part->obfac!=0.0){
VECSUB(vel,loc,pa->state.co);
@@ -1650,7 +1820,7 @@ void reset_particle(ParticleData *pa, ParticleSystem *psys, ParticleSystemModifi
/* *emitter tangent */
if(part->tanfac!=0.0)
- VECADDFAC(vel,vel,vtan,part->tanfac*(vg_tan?psys_interpolate_value_from_verts(psmd->dm,part->from,pa->num,pa->fuv,vg_tan):1.0f));
+ VECADDFAC(vel,vel,vtan,part->tanfac*(vg_tan?psys_particle_value_from_verts(psmd->dm,part->from,pa,vg_tan):1.0f));
/* *texture */
/* TODO */
@@ -1681,34 +1851,49 @@ void reset_particle(ParticleData *pa, ParticleSystem *psys, ParticleSystemModifi
pa->state.rot[1]=pa->state.rot[2]=pa->state.rot[3]=0.0;
if(part->rotmode){
+ /* create vector into which rotation is aligned */
switch(part->rotmode){
case PART_ROT_NOR:
- VecMulf(nor,-1.0);
- q2= vectoquat(nor, OB_POSX, OB_POSZ);
- VecMulf(nor,-1.0);
+ VecCopyf(rot_vec, nor);
break;
case PART_ROT_VEL:
- VecMulf(vel,-1.0);
- q2= vectoquat(vel, OB_POSX, OB_POSZ);
- VecMulf(vel,-1.0);
+ VecCopyf(rot_vec, vel);
+ break;
+ case PART_ROT_GLOB_X:
+ case PART_ROT_GLOB_Y:
+ case PART_ROT_GLOB_Z:
+ rot_vec[part->rotmode - PART_ROT_GLOB_X] = 1.0f;
break;
- case PART_ROT_RAND:
- q2= r_rot;
+ case PART_ROT_OB_X:
+ case PART_ROT_OB_Y:
+ case PART_ROT_OB_Z:
+ VecCopyf(rot_vec, ob->obmat[part->rotmode - PART_ROT_OB_X]);
break;
}
- /* how much to rotate from rest position */
- QuatInterpol(rot,q_one,q2,part->rotfac);
+
+ /* create rotation quat */
+ VecMulf(rot_vec,-1.0);
+ vectoquat(rot_vec, OB_POSX, OB_POSZ, q2);
+
+ /* randomize rotation quat */
+ if(part->randrotfac!=0.0f)
+ QuatInterpol(rot, q2, r_rot, part->randrotfac);
+ else
+ QuatCopy(rot,q2);
- /* phase */
- VecRotToQuat(x_vec,part->phasefac*(float)M_PI,q_phase);
+ /* rotation phase */
+ phasefac = part->phasefac;
+ if(part->randphasefac != 0.0f) /* abuse r_ave[0] as a random number */
+ phasefac += part->randphasefac * pa->r_ave[0];
+ VecRotToQuat(x_vec, phasefac*(float)M_PI, q_phase);
- /* combine amount & phase */
- QuatMul(pa->state.rot,rot,q_phase);
+ /* combine base rotation & phase */
+ QuatMul(pa->state.rot, rot, q_phase);
}
/* -angular velocity */
- pa->state.ave[0]=pa->state.ave[1]=pa->state.ave[2]=0.0;
+ pa->state.ave[0] = pa->state.ave[1] = pa->state.ave[2] = 0.0;
if(part->avemode){
switch(part->avemode){
@@ -1729,15 +1914,15 @@ void reset_particle(ParticleData *pa, ParticleSystem *psys, ParticleSystemModifi
}
}
- pa->dietime=pa->time+pa->lifetime;
+ pa->dietime = pa->time + pa->lifetime;
if(pa->time >= cfra)
- pa->alive=PARS_UNBORN;
+ pa->alive = PARS_UNBORN;
- pa->state.time=cfra;
+ pa->state.time = cfra;
- pa->stick_ob=0;
- pa->flag&=~PARS_STICKY;
+ pa->stick_ob = 0;
+ pa->flag &= ~PARS_STICKY;
}
static void reset_all_particles(Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd, float dtime, float cfra, int from)
{
@@ -1807,7 +1992,8 @@ int psys_count_keyed_targets(Object *ob, ParticleSystem *psys)
BLI_freelistN(&lb);
return select;
}
-void set_keyed_keys(Object *ob, ParticleSystem *psys)
+
+static void set_keyed_keys(Object *ob, ParticleSystem *psys)
{
Object *kob = ob;
ParticleSystem *kpsys = psys;
@@ -1817,17 +2003,16 @@ void set_keyed_keys(Object *ob, ParticleSystem *psys)
float prevtime, nexttime, keyedtime;
/* no proper targets so let's clear and bail out */
- if(psys->totkeyed==0){
+ if(psys->totkeyed==0) {
free_keyed_keys(psys);
psys->flag &= ~PSYS_KEYED;
return;
}
- if(totpart && psys->particles->totkey != totkeys){
+ if(totpart && psys->particles->totkey != totkeys) {
free_keyed_keys(psys);
- psys->particles->keys = MEM_callocN(psys->totpart * totkeys * sizeof(ParticleKey),"Keyed keys");
-
+ psys->particles->keys = MEM_callocN(psys->totpart*totkeys*sizeof(ParticleKey), "Keyed keys");
psys->particles->totkey = totkeys;
for(i=1, pa=psys->particles+1; i<totpart; i++,pa++){
@@ -1839,9 +2024,10 @@ void set_keyed_keys(Object *ob, ParticleSystem *psys)
psys->flag &= ~PSYS_KEYED;
state.time=-1.0;
- for(k=0; k<totkeys; k++){
- for(i=0,pa=psys->particles; i<totpart; i++, pa++){
- psys_get_particle_state(kob, kpsys, i%kpsys->totpart, pa->keys + k, 1);
+ for(k=0; k<totkeys; k++) {
+ for(i=0,pa=psys->particles; i<totpart; i++, pa++) {
+ if(kpsys->totpart > 0)
+ psys_get_particle_state(kob, kpsys, i%kpsys->totpart, pa->keys + k, 1);
if(k==0)
pa->keys->time = pa->time;
@@ -1923,22 +2109,18 @@ static void react_to_events(ParticleSystem *psys, int pa_num)
for(re=psys->reactevents.first; re; re=re->next){
birth=0;
if(part->from==PART_FROM_PARTICLE){
- if(pa->num==re->pa_num){
+ if(pa->num==re->pa_num && pa->alive==PARS_UNBORN){
if(re->event==PART_EVENT_NEAR){
ParticleData *tpa = re->psys->particles+re->pa_num;
float pa_time=tpa->time + pa->foffset*tpa->lifetime;
- if(re->time > pa_time){
- pa->alive=PARS_ALIVE;
+ if(re->time >= pa_time){
pa->time=pa_time;
pa->dietime=pa->time+pa->lifetime;
}
}
else{
- if(pa->alive==PARS_UNBORN){
- pa->alive=PARS_ALIVE;
- pa->time=re->time;
- pa->dietime=pa->time+pa->lifetime;
- }
+ pa->time=re->time;
+ pa->dietime=pa->time+pa->lifetime;
}
}
}
@@ -1946,7 +2128,6 @@ static void react_to_events(ParticleSystem *psys, int pa_num)
dist=VecLenf(pa->state.co, re->state.co);
if(dist <= re->size){
if(pa->alive==PARS_UNBORN){
- pa->alive=PARS_ALIVE;
pa->time=re->time;
pa->dietime=pa->time+pa->lifetime;
birth=1;
@@ -1982,273 +2163,70 @@ void psys_get_reactor_target(Object *ob, ParticleSystem *psys, Object **target_o
/************************************************/
/* Point Cache */
/************************************************/
-void clear_particles_from_cache(Object *ob, ParticleSystem *psys, int cfra)
-{
- ParticleSystemModifierData *psmd = psys_get_modifier(ob,psys);
- int stack_index = modifiers_indexInObject(ob,(ModifierData*)psmd);
- BKE_ptcache_id_clear((ID *)ob, PTCACHE_CLEAR_ALL, cfra, stack_index);
-}
static void write_particles_to_cache(Object *ob, ParticleSystem *psys, int cfra)
{
- FILE *fp = NULL;
- ParticleSystemModifierData *psmd = psys_get_modifier(ob,psys);
+ PTCacheID pid;
+ PTCacheFile *pf;
ParticleData *pa;
- int stack_index = modifiers_indexInObject(ob,(ModifierData*)psmd);
- int i, totpart = psys->totpart;
+ int i, totpart= psys->totpart;
- if(totpart == 0) return;
+ if(totpart == 0)
+ return;
- fp = BKE_ptcache_id_fopen((ID *)ob, 'w', cfra, stack_index);
- if(!fp) return;
+ BKE_ptcache_id_from_particles(&pid, ob, psys);
+ pf= BKE_ptcache_file_open(&pid, PTCACHE_FILE_WRITE, cfra);
+ if(!pf)
+ return;
+ /* assuming struct consists of tightly packed floats */
for(i=0, pa=psys->particles; i<totpart; i++, pa++)
- fwrite(&pa->state, sizeof(ParticleKey), 1, fp);
+ BKE_ptcache_file_write_floats(pf, (float*)&pa->state, sizeof(ParticleKey)/sizeof(float));
- fclose(fp);
+ BKE_ptcache_file_close(pf);
}
+
static int get_particles_from_cache(Object *ob, ParticleSystem *psys, int cfra)
{
- FILE *fp = NULL;
- ParticleSystemModifierData *psmd = psys_get_modifier(ob,psys);
+ PTCacheID pid;
+ PTCacheFile *pf;
ParticleData *pa;
- int stack_index = modifiers_indexInObject(ob,(ModifierData*)psmd);
- int i, totpart = psys->totpart, ret = 1;
+ int i, totpart= psys->totpart;
- if(totpart == 0) return 0;
+ if(totpart == 0)
+ return 0;
- fp = BKE_ptcache_id_fopen((ID *)ob, 'r', cfra, stack_index);
- if(!fp)
- ret = 0;
- else {
- for(i=0, pa=psys->particles; i<totpart; i++, pa++)
- if((fread(&pa->state, sizeof(ParticleKey), 1, fp)) != 1) {
- ret = 0;
- break;
- }
-
- fclose(fp);
+ BKE_ptcache_id_from_particles(&pid, ob, psys);
+ pf= BKE_ptcache_file_open(&pid, PTCACHE_FILE_READ, cfra);
+ if(!pf)
+ return 0;
+
+ /* assuming struct consists of tightly packed floats */
+ for(i=0, pa=psys->particles; i<totpart; i++, pa++) {
+ if(cfra!=pa->state.time)
+ copy_particle_key(&pa->prev_state,&pa->state,1);
+ if(!BKE_ptcache_file_read_floats(pf, (float*)&pa->state, sizeof(ParticleKey)/sizeof(float))) {
+ BKE_ptcache_file_close(pf);
+ return 0;
+ }
}
- return ret;
+ BKE_ptcache_file_close(pf);
+
+ return 1;
}
+
/************************************************/
/* Effectors */
/************************************************/
-static float effector_falloff(PartDeflect *pd, float *eff_velocity, float *vec_to_part)
-{
- float eff_dir[3], temp[3];
- float falloff=1.0, fac, r_fac;
-
- VecCopyf(eff_dir,eff_velocity);
- Normalize(eff_dir);
-
- if(pd->flag & PFIELD_POSZ && Inpf(eff_dir,vec_to_part)<0.0f)
- falloff=0.0f;
- else switch(pd->falloff){
- case PFIELD_FALL_SPHERE:
- fac=VecLength(vec_to_part);
- if(pd->flag&PFIELD_USEMAX && fac>pd->maxdist){
- falloff=0.0f;
- break;
- }
-
- if(pd->flag & PFIELD_USEMIN){
- if(fac>pd->mindist)
- fac+=1.0f-pd->mindist;
- else
- fac=1.0f;
- }
- else if(fac<0.001)
- fac=0.001f;
-
- falloff=1.0f/(float)pow((double)fac,(double)pd->f_power);
- break;
-
- case PFIELD_FALL_TUBE:
- fac=Inpf(vec_to_part,eff_dir);
- if(pd->flag&PFIELD_USEMAX && ABS(fac)>pd->maxdist){
- falloff=0.0f;
- break;
- }
-
- VECADDFAC(temp,vec_to_part,eff_dir,-fac);
- r_fac=VecLength(temp);
- if(pd->flag&PFIELD_USEMAXR && r_fac>pd->maxrad){
- falloff=0.0f;
- break;
- }
-
- fac=ABS(fac);
-
-
- if(pd->flag & PFIELD_USEMIN){
- if(fac>pd->mindist)
- fac+=1.0f-pd->mindist;
- else
- fac=1.0f;
- }
- else if(fac<0.001)
- fac=0.001f;
-
- if(pd->flag & PFIELD_USEMINR){
- if(r_fac>pd->minrad)
- r_fac+=1.0f-pd->minrad;
- else
- r_fac=1.0f;
- }
- else if(r_fac<0.001)
- r_fac=0.001f;
-
- falloff=1.0f/((float)pow((double)fac,(double)pd->f_power)*(float)pow((double)r_fac,(double)pd->f_power_r));
-
- break;
- case PFIELD_FALL_CONE:
- fac=Inpf(vec_to_part,eff_dir);
- if(pd->flag&PFIELD_USEMAX && ABS(fac)>pd->maxdist){
- falloff=0.0f;
- break;
- }
- r_fac=saacos(fac/VecLength(vec_to_part))*180.0f/(float)M_PI;
- if(pd->flag&PFIELD_USEMAXR && r_fac>pd->maxrad){
- falloff=0.0f;
- break;
- }
-
- if(pd->flag & PFIELD_USEMIN){
- if(fac>pd->mindist)
- fac+=1.0f-pd->mindist;
- else
- fac=1.0f;
- }
- else if(fac<0.001)
- fac=0.001f;
-
- if(pd->flag & PFIELD_USEMINR){
- if(r_fac>pd->minrad)
- r_fac+=1.0f-pd->minrad;
- else
- r_fac=1.0f;
- }
- else if(r_fac<0.001)
- r_fac=0.001f;
-
- falloff=1.0f/((float)pow((double)fac,(double)pd->f_power)*(float)pow((double)r_fac,(double)pd->f_power_r));
-
- break;
-// case PFIELD_FALL_INSIDE:
- //for(i=0; i<totface; i++,mface++){
- // VECCOPY(v1,mvert[mface->v1].co);
- // VECCOPY(v2,mvert[mface->v2].co);
- // VECCOPY(v3,mvert[mface->v3].co);
-
- // if(AxialLineIntersectsTriangle(a,co1, co2, v2, v3, v1, &lambda)){
- // if(from==PART_FROM_FACE)
- // (pa+(int)(lambda*size[a])*a0mul)->flag &= ~PARS_UNEXIST;
- // else /* store number of intersections */
- // (pa+(int)(lambda*size[a])*a0mul)->loop++;
- // }
- //
- // if(mface->v4){
- // VECCOPY(v4,mvert[mface->v4].co);
-
- // if(AxialLineIntersectsTriangle(a,co1, co2, v4, v1, v3, &lambda)){
- // if(from==PART_FROM_FACE)
- // (pa+(int)(lambda*size[a])*a0mul)->flag &= ~PARS_UNEXIST;
- // else
- // (pa+(int)(lambda*size[a])*a0mul)->loop++;
- // }
- // }
- //}
-
-// break;
- }
-
- return falloff;
-}
-static void do_physical_effector(short type, float force_val, float distance, float falloff, float size, float damp,
- float *eff_velocity, float *vec_to_part, float *velocity, float *field, int planar)
-{
- float mag_vec[3]={0,0,0};
- float temp[3], temp2[3];
- float eff_vel[3];
-
- VecCopyf(eff_vel,eff_velocity);
- Normalize(eff_vel);
-
- switch(type){
- case PFIELD_WIND:
- VECCOPY(mag_vec,eff_vel);
-
- VecMulf(mag_vec,force_val*falloff);
- VecAddf(field,field,mag_vec);
- break;
-
- case PFIELD_FORCE:
- if(planar)
- Projf(mag_vec,vec_to_part,eff_vel);
- else
- VecCopyf(mag_vec,vec_to_part);
-
- VecMulf(mag_vec,force_val*falloff);
- VecAddf(field,field,mag_vec);
- break;
-
- case PFIELD_VORTEX:
- Crossf(mag_vec,eff_vel,vec_to_part);
- Normalize(mag_vec);
-
- VecMulf(mag_vec,force_val*distance*falloff);
- VecAddf(field,field,mag_vec);
-
- break;
- case PFIELD_MAGNET:
- if(planar)
- VecCopyf(temp,eff_vel);
- else
- /* magnetic field of a moving charge */
- Crossf(temp,eff_vel,vec_to_part);
-
- Crossf(temp2,velocity,temp);
- VecAddf(mag_vec,mag_vec,temp2);
-
- VecMulf(mag_vec,force_val*falloff);
- VecAddf(field,field,mag_vec);
- break;
- case PFIELD_HARMONIC:
- if(planar)
- Projf(mag_vec,vec_to_part,eff_vel);
- else
- VecCopyf(mag_vec,vec_to_part);
-
- VecMulf(mag_vec,force_val*falloff);
- VecSubf(field,field,mag_vec);
-
- VecCopyf(mag_vec,velocity);
- /* 1.9 is an experimental value to get critical damping at damp=1.0 */
- VecMulf(mag_vec,damp*1.9f*(float)sqrt(force_val));
- VecSubf(field,field,mag_vec);
- break;
- case PFIELD_NUCLEAR:
- /*pow here is root of cosine expression below*/
- //rad=(float)pow(2.0,-1.0/power)*distance/size;
- //VECCOPY(mag_vec,vec_to_part);
- //Normalize(mag_vec);
- //VecMulf(mag_vec,(float)cos(3.0*M_PI/2.0*(1.0-1.0/(pow(rad,power)+1.0)))/(rad+0.2f));
- //VECADDFAC(field,field,mag_vec,force_val);
- break;
- }
-}
static void do_texture_effector(Tex *tex, short mode, short is_2d, float nabla, short object, float *pa_co, float obmat[4][4], float force_val, float falloff, float *field)
{
TexResult result[4];
float tex_co[3], strength, mag_vec[3];
- int i;
-
- if(tex==0) return;
+ int hasrgb;
+ if(tex==NULL) return;
- for(i=0; i<4; i++)
- result[i].nor=0;
+ result[0].nor = result[1].nor = result[2].nor = result[3].nor = 0;
strength= force_val*falloff;///(float)pow((double)distance,(double)power);
@@ -2264,9 +2242,9 @@ static void do_texture_effector(Tex *tex, short mode, short is_2d, float nabla,
Mat4Mul3Vecfl(obmat,tex_co);
}
- multitex_ext(tex, tex_co, NULL,NULL, 1, result);
+ hasrgb = multitex_ext(tex, tex_co, NULL,NULL, 1, result);
- if(mode==PFIELD_TEX_RGB){
+ if(hasrgb && mode==PFIELD_TEX_RGB){
mag_vec[0]= (0.5f-result->tr)*strength;
mag_vec[1]= (0.5f-result->tg)*strength;
mag_vec[2]= (0.5f-result->tb)*strength;
@@ -2285,7 +2263,7 @@ static void do_texture_effector(Tex *tex, short mode, short is_2d, float nabla,
tex_co[2]+= nabla;
multitex_ext(tex, tex_co, NULL,NULL, 1, result+3);
- if(mode==PFIELD_TEX_GRAD){
+ if(mode==PFIELD_TEX_GRAD || !hasrgb){ /* if we dont have rgb fall back to grad */
mag_vec[0]= (result[0].tin-result[1].tin)*strength;
mag_vec[1]= (result[0].tin-result[2].tin)*strength;
mag_vec[2]= (result[0].tin-result[3].tin)*strength;
@@ -2333,7 +2311,9 @@ static void add_to_effectors(ListBase *lb, Object *ob, Object *obsrc, ParticleSy
}
}
else if(pd->forcefield)
+ {
type |= PSYS_EC_EFFECTOR;
+ }
}
if(pd && pd->deflect)
@@ -2345,6 +2325,9 @@ static void add_to_effectors(ListBase *lb, Object *ob, Object *obsrc, ParticleSy
ec->type=type;
ec->distances=0;
ec->locations=0;
+ ec->rng = rng_new(1);
+ rng_srandom(ec->rng, (unsigned int)(ceil(PIL_check_seconds_timer()))); // use better seed
+
BLI_addtail(lb, ec);
}
@@ -2358,11 +2341,14 @@ static void add_to_effectors(ListBase *lb, Object *ob, Object *obsrc, ParticleSy
for(i=0; epsys; epsys=epsys->next,i++){
type=0;
- if(epsys!=psys){
+ if(epsys!=psys || (psys->part->flag & PART_SELF_EFFECT)){
epart=epsys->part;
- if(epsys->part->pd && epsys->part->pd->forcefield)
+ if((epsys->part->pd && epsys->part->pd->forcefield)
+ || (epsys->part->pd2 && epsys->part->pd2->forcefield))
+ {
type=PSYS_EC_PARTICLE;
+ }
if(epart->type==PART_REACTOR) {
tob=epsys->target_ob;
@@ -2377,6 +2363,9 @@ static void add_to_effectors(ListBase *lb, Object *ob, Object *obsrc, ParticleSy
ec->ob= ob;
ec->type=type;
ec->psys_nbr=i;
+ ec->rng = rng_new(1);
+ rng_srandom(ec->rng, (unsigned int)(ceil(PIL_check_seconds_timer())));
+
BLI_addtail(lb, ec);
}
}
@@ -2384,34 +2373,51 @@ static void add_to_effectors(ListBase *lb, Object *ob, Object *obsrc, ParticleSy
}
}
+
+static void psys_init_effectors_recurs(Object *ob, Object *obsrc, ParticleSystem *psys, ListBase *listb, int level)
+{
+ Group *group;
+ GroupObject *go;
+ unsigned int layer= obsrc->lay;
+
+ if(level>MAX_DUPLI_RECUR) return;
+
+ if(ob->lay & layer) {
+ if(ob->pd || ob->particlesystem.first)
+ add_to_effectors(listb, ob, obsrc, psys);
+
+ if(ob->dup_group) {
+ group= ob->dup_group;
+ for(go= group->gobject.first; go; go= go->next)
+ psys_init_effectors_recurs(go->ob, obsrc, psys, listb, level+1);
+ }
+ }
+}
+
void psys_init_effectors(Object *obsrc, Group *group, ParticleSystem *psys)
{
- ListBase *listb=&psys->effectors;
+ ListBase *listb= &psys->effectors;
Base *base;
- unsigned int layer= obsrc->lay;
listb->first=listb->last=0;
if(group) {
GroupObject *go;
- for(go= group->gobject.first; go; go= go->next) {
- if( (go->ob->lay & layer) && (go->ob->pd || go->ob->particlesystem.first)) {
- add_to_effectors(listb, go->ob, obsrc, psys);
- }
- }
+ for(go= group->gobject.first; go; go= go->next)
+ psys_init_effectors_recurs(go->ob, obsrc, psys, listb, 0);
}
else {
- for(base = G.scene->base.first; base; base= base->next) {
- if( (base->lay & layer) && (base->object->pd || base->object->particlesystem.first)) {
- add_to_effectors(listb, base->object, obsrc, psys);
- }
- }
+ for(base = G.scene->base.first; base; base= base->next)
+ psys_init_effectors_recurs(base->object, obsrc, psys, listb, 0);
}
}
void psys_end_effectors(ParticleSystem *psys)
{
+ /* NOTE:
+ ec->ob is not valid in here anymore! - dg
+ */
ListBase *lb=&psys->effectors;
if(lb->first) {
ParticleEffectorCache *ec;
@@ -2430,23 +2436,28 @@ void psys_end_effectors(ParticleSystem *psys)
if(ec->tree)
BLI_kdtree_free(ec->tree);
+
+ if(ec->rng)
+ rng_free(ec->rng);
+
}
BLI_freelistN(lb);
}
}
-static void precalc_effectors(Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd)
+static void precalc_effectors(Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd, float cfra)
{
ListBase *lb=&psys->effectors;
ParticleEffectorCache *ec;
ParticleSettings *part=psys->part;
ParticleData *pa;
float vec2[3],loc[3],*co=0;
- int p,totpart,totvert;
+ int p,totpart;
for(ec= lb->first; ec; ec= ec->next) {
PartDeflect *pd= ec->ob->pd;
+ co = NULL;
if(ec->type==PSYS_EC_EFFECTOR && pd->forcefield==PFIELD_GUIDE && ec->ob->type==OB_CURVE
&& part->phystype!=PART_PHYS_BOIDS) {
@@ -2467,7 +2478,7 @@ static void precalc_effectors(Object *ob, ParticleSystem *psys, ParticleSystemMo
ec->locations=MEM_callocN(totpart*3*sizeof(float),"particle locations");
for(p=0,pa=psys->particles; p<totpart; p++, pa++){
- psys_particle_on_emitter(ob,psmd,part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,loc,0,0,0,0,0);
+ psys_particle_on_emitter(psmd,part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,loc,0,0,0,0,0);
Mat4MulVecfl(ob->obmat,loc);
ec->distances[p]=VecLenf(loc,vec);
VECSUB(loc,loc,vec);
@@ -2475,96 +2486,18 @@ static void precalc_effectors(Object *ob, ParticleSystem *psys, ParticleSystemMo
}
}
}
- else if(ec->type==PSYS_EC_DEFLECT){
- DerivedMesh *dm;
- MFace *mface=0;
- MVert *mvert=0;
- int i, totface;
- float v1[3],v2[3],v3[3],v4[4], *min, *max;
-
- if(ob==ec->ob)
- dm=psmd->dm;
- else{
- psys_disable_all(ec->ob);
-
- dm=mesh_get_derived_final(ec->ob,0);
-
- psys_enable_all(ec->ob);
- }
-
- if(dm){
- totvert=dm->getNumVerts(dm);
- totface=dm->getNumFaces(dm);
- mface=dm->getFaceDataArray(dm,CD_MFACE);
- mvert=dm->getVertDataArray(dm,CD_MVERT);
-
- /* Decide which is faster to calculate by the amount of*/
- /* matrice multiplications needed to convert spaces. */
- /* With size deflect we have to convert allways because */
- /* the object can be scaled nonuniformly (sphere->ellipsoid). */
- if(totvert<2*psys->totpart || part->flag & PART_SIZE_DEFL){
- co=ec->vert_cos=MEM_callocN(sizeof(float)*3*totvert,"Particle deflection vert cos");
- /* convert vert coordinates to global (particle) coordinates */
- for(i=0; i<totvert; i++, co+=3){
- VECCOPY(co,mvert[i].co);
- Mat4MulVecfl(ec->ob->obmat,co);
- }
- co=ec->vert_cos;
- }
- else
- ec->vert_cos=0;
-
- INIT_MINMAX(ec->ob_minmax,ec->ob_minmax+3);
-
- min=ec->face_minmax=MEM_callocN(sizeof(float)*6*totface,"Particle deflection face minmax");
- max=min+3;
-
- for(i=0; i<totface; i++,mface++,min+=6,max+=6){
- if(co){
- VECCOPY(v1,co+3*mface->v1);
- VECCOPY(v2,co+3*mface->v2);
- VECCOPY(v3,co+3*mface->v3);
- }
- else{
- VECCOPY(v1,mvert[mface->v1].co);
- VECCOPY(v2,mvert[mface->v2].co);
- VECCOPY(v3,mvert[mface->v3].co);
- }
- INIT_MINMAX(min,max);
- DO_MINMAX(v1,min,max);
- DO_MINMAX(v2,min,max);
- DO_MINMAX(v3,min,max);
-
- if(mface->v4){
- if(co){
- VECCOPY(v4,co+3*mface->v4);
- }
- else{
- VECCOPY(v4,mvert[mface->v4].co);
- }
- DO_MINMAX(v4,min,max);
- }
-
- DO_MINMAX(min,ec->ob_minmax,ec->ob_minmax+3);
- DO_MINMAX(max,ec->ob_minmax,ec->ob_minmax+3);
- }
- }
- else
- ec->face_minmax=0;
- }
else if(ec->type==PSYS_EC_PARTICLE){
+ Object *eob = ec->ob;
+ ParticleSystem *epsys = BLI_findlink(&eob->particlesystem,ec->psys_nbr);
+ ParticleSettings *epart = epsys->part;
+ ParticleData *epa;
+ int p, totepart = epsys->totpart;
+
if(psys->part->phystype==PART_PHYS_BOIDS){
- Object *eob = ec->ob;
- ParticleSystem *epsys;
- ParticleSettings *epart;
- ParticleData *epa;
ParticleKey state;
PartDeflect *pd;
- int totepart, p;
- epsys= BLI_findlink(&eob->particlesystem,ec->psys_nbr);
- epart= epsys->part;
+
pd= epart->pd;
- totepart= epsys->totpart;
if(pd->forcefield==PFIELD_FORCE && totepart){
KDTree *tree;
@@ -2578,13 +2511,19 @@ static void precalc_effectors(Object *ob, ParticleSystem *psys, ParticleSystemMo
BLI_kdtree_balance(tree);
}
}
+
+ }
+ else if(ec->type==PSYS_EC_DEFLECT) {
+ CollisionModifierData *collmd = ( CollisionModifierData * ) ( modifiers_findByType ( ec->ob, eModifierType_Collision ) );
+ if(collmd)
+ collision_move_object(collmd, 1.0, 0.0);
}
}
}
/* calculate forces that all effectors apply to a particle*/
-static void do_effectors(int pa_no, ParticleData *pa, ParticleKey *state, Object *ob, ParticleSystem *psys, float *force_field, float *vel,float framestep, float cfra)
+void do_effectors(int pa_no, ParticleData *pa, ParticleKey *state, Object *ob, ParticleSystem *psys, float *rootco, float *force_field, float *vel,float framestep, float cfra)
{
Object *eob;
ParticleSystem *epsys;
@@ -2595,35 +2534,31 @@ static void do_effectors(int pa_no, ParticleData *pa, ParticleKey *state, Object
ListBase *lb=&psys->effectors;
ParticleEffectorCache *ec;
float distance, vec_to_part[3];
- float falloff;
+ float falloff, charge = 0.0f;
int p;
/* check all effector objects for interaction */
if(lb->first){
+ if(psys->part->pd && psys->part->pd->forcefield==PFIELD_CHARGE){
+ /* Only the charge of the effected particle is used for
+ interaction, not fall-offs. If the fall-offs aren't the
+ same this will be unphysical, but for animation this
+ could be the wanted behavior. If you want physical
+ correctness the fall-off should be spherical 2.0 anyways.
+ */
+ charge = psys->part->pd->f_strength;
+ }
+ if(psys->part->pd2 && psys->part->pd2->forcefield==PFIELD_CHARGE){
+ charge += psys->part->pd2->f_strength;
+ }
for(ec = lb->first; ec; ec= ec->next){
eob= ec->ob;
if(ec->type & PSYS_EC_EFFECTOR){
pd=eob->pd;
if(psys->part->type!=PART_HAIR && psys->part->integrator)
where_is_object_time(eob,cfra);
- /* Get IPO force strength and fall off values here */
- //if (has_ipo_code(eob->ipo, OB_PD_FSTR))
- // force_val = IPO_GetFloatValue(eob->ipo, OB_PD_FSTR, cfra);
- //else
- // force_val = pd->f_strength;
-
- //if (has_ipo_code(eob->ipo, OB_PD_FFALL))
- // ffall_val = IPO_GetFloatValue(eob->ipo, OB_PD_FFALL, cfra);
- //else
- // ffall_val = pd->f_power;
-
- //if (has_ipo_code(eob->ipo, OB_PD_FMAXD))
- // maxdist = IPO_GetFloatValue(eob->ipo, OB_PD_FMAXD, cfra);
- //else
- // maxdist = pd->maxdist;
/* use center of object for distance calculus */
- //obloc= eob->obmat[3];
VecSubf(vec_to_part, state->co, eob->obmat[3]);
distance = VecLength(vec_to_part);
@@ -2631,23 +2566,27 @@ static void do_effectors(int pa_no, ParticleData *pa, ParticleKey *state, Object
if(falloff<=0.0f)
; /* don't do anything */
- else if(pd->forcefield==PFIELD_TEXTURE)
+ else if(pd->forcefield==PFIELD_TEXTURE) {
do_texture_effector(pd->tex, pd->tex_mode, pd->flag&PFIELD_TEX_2D, pd->tex_nabla,
- pd->flag & PFIELD_TEX_OBJECT, state->co, eob->obmat,
- pd->f_strength, falloff, force_field);
- else
- do_physical_effector(pd->forcefield,pd->f_strength,distance,
- falloff,pd->f_dist,pd->f_damp,eob->obmat[2],vec_to_part,
- pa->state.vel,force_field,pd->flag&PFIELD_PLANAR);
+ pd->flag & PFIELD_TEX_OBJECT, (pd->flag & PFIELD_TEX_ROOTCO) ? rootco : state->co, eob->obmat,
+ pd->f_strength, falloff, force_field);
+ } else {
+ do_physical_effector(eob, state->co, pd->forcefield,pd->f_strength,distance,
+ falloff,0.0,pd->f_damp,eob->obmat[2],vec_to_part,
+ state->vel,force_field,pd->flag&PFIELD_PLANAR,ec->rng,pd->f_noise,charge,pa->size);
+ }
}
if(ec->type & PSYS_EC_PARTICLE){
- int totepart;
+ int totepart, i;
epsys= BLI_findlink(&eob->particlesystem,ec->psys_nbr);
epart= epsys->part;
- pd= epart->pd;
+ pd=epart->pd;
totepart= epsys->totpart;
-
- if(pd->forcefield==PFIELD_HARMONIC){
+
+ if(totepart <= 0)
+ continue;
+
+ if(pd && pd->forcefield==PFIELD_HARMONIC){
/* every particle is mapped to only one harmonic effector particle */
p= pa_no%epsys->totpart;
totepart= p+1;
@@ -2659,33 +2598,29 @@ static void do_effectors(int pa_no, ParticleData *pa, ParticleKey *state, Object
epsys->lattice=psys_get_lattice(ob,psys);
for(; p<totepart; p++){
+ /* particle skips itself as effector */
+ if(epsys==psys && p == pa_no) continue;
+
epa = epsys->particles + p;
- estate.time=-1.0;
+ estate.time=cfra;
if(psys_get_particle_state(eob,epsys,p,&estate,0)){
VECSUB(vec_to_part, state->co, estate.co);
distance = VecLength(vec_to_part);
-
- //if(pd->forcefield==PFIELD_HARMONIC){
- // //if(cfra < epa->time + radius){ /* radius is fade-in in ui */
- // // eforce*=(cfra-epa->time)/radius;
- // //}
- //}
- //else{
- // /* Limit minimum distance to effector particle so that */
- // /* the force is not too big */
- // if (distance < 0.001) distance = 0.001f;
- //}
- falloff=effector_falloff(pd,estate.vel,vec_to_part);
+ for(i=0, pd = epart->pd; i<2; i++,pd = epart->pd2) {
+ if(pd==NULL || pd->forcefield==0) continue;
- if(falloff<=0.0f)
- ; /* don't do anything */
- else
- do_physical_effector(pd->forcefield,pd->f_strength,distance,
- falloff,epart->size,pd->f_damp,estate.vel,vec_to_part,
- state->vel,force_field,0);
+ falloff=effector_falloff(pd,estate.vel,vec_to_part);
+
+ if(falloff<=0.0f)
+ ; /* don't do anything */
+ else
+ do_physical_effector(eob, state->co, pd->forcefield,pd->f_strength,distance,
+ falloff,epart->size,pd->f_damp,estate.vel,vec_to_part,
+ state->vel,force_field,0, ec->rng, pd->f_noise,charge,pa->size);
+ }
}
- else if(pd->forcefield==PFIELD_HARMONIC && cfra-framestep <= epa->dietime && cfra>epa->dietime){
+ else if(pd && pd->forcefield==PFIELD_HARMONIC && cfra-framestep <= epa->dietime && cfra>epa->dietime){
/* first step after key release */
psys_get_particle_state(eob,epsys,p,&estate,1);
VECADD(vel,vel,estate.vel);
@@ -2706,7 +2641,7 @@ static void do_effectors(int pa_no, ParticleData *pa, ParticleKey *state, Object
/* Newtonian physics */
/************************************************/
/* gathers all forces that effect particles and calculates a new state for the particle */
-static void apply_particle_forces(int pa_no, ParticleData *pa, Object *ob, ParticleSystem *psys, ParticleSettings *part, float timestep, float dfra, float cfra, ParticleKey *state)
+static void apply_particle_forces(int pa_no, ParticleData *pa, Object *ob, ParticleSystem *psys, ParticleSettings *part, float timestep, float dfra, float cfra)
{
ParticleKey states[5], tkey;
float force[3],tvel[3],dx[4][3],dv[4][3];
@@ -2714,7 +2649,7 @@ static void apply_particle_forces(int pa_no, ParticleData *pa, Object *ob, Parti
int i, steps=1;
/* maintain angular velocity */
- VECCOPY(state->ave,pa->state.ave);
+ VECCOPY(pa->state.ave,pa->prev_state.ave);
if(part->flag & PART_SIZEMASS)
pa_mass*=pa->size;
@@ -2737,7 +2672,8 @@ static void apply_particle_forces(int pa_no, ParticleData *pa, Object *ob, Parti
force[0]=force[1]=force[2]=0.0;
tvel[0]=tvel[1]=tvel[2]=0.0;
/* add effectors */
- do_effectors(pa_no,pa,states+i,ob,psys,force,tvel,dfra,fra);
+ if(part->type != PART_HAIR)
+ do_effectors(pa_no,pa,states+i,ob,psys,states->co,force,tvel,dfra,fra);
/* calculate air-particle interaction */
if(part->dragfac!=0.0f){
@@ -2757,17 +2693,14 @@ static void apply_particle_forces(int pa_no, ParticleData *pa, Object *ob, Parti
/* add global acceleration (gravitation) */
VECADD(force,force,part->acc);
-
- //VecMulf(force,dtime);
/* calculate next state */
VECADD(states[i].vel,states[i].vel,tvel);
- //VecMulf(force,0.5f*dt);
switch(part->integrator){
case PART_INT_EULER:
- VECADDFAC(state->co,states->co,states->vel,dtime);
- VECADDFAC(state->vel,states->vel,force,dtime);
+ VECADDFAC(pa->state.co,states->co,states->vel,dtime);
+ VECADDFAC(pa->state.vel,states->vel,force,dtime);
break;
case PART_INT_MIDPOINT:
if(i==0){
@@ -2776,8 +2709,8 @@ static void apply_particle_forces(int pa_no, ParticleData *pa, Object *ob, Parti
fra=psys->cfra+0.5f*dfra;
}
else{
- VECADDFAC(state->co,states->co,states[1].vel,dtime);
- VECADDFAC(state->vel,states->vel,force,dtime);
+ VECADDFAC(pa->state.co,states->co,states[1].vel,dtime);
+ VECADDFAC(pa->state.vel,states->vel,force,dtime);
}
break;
case PART_INT_RK4:
@@ -2817,77 +2750,78 @@ static void apply_particle_forces(int pa_no, ParticleData *pa, Object *ob, Parti
VECCOPY(dv[3],force);
VecMulf(dv[3],dtime);
- VECADDFAC(state->co,states->co,dx[0],1.0f/6.0f);
- VECADDFAC(state->co,state->co,dx[1],1.0f/3.0f);
- VECADDFAC(state->co,state->co,dx[2],1.0f/3.0f);
- VECADDFAC(state->co,state->co,dx[3],1.0f/6.0f);
+ VECADDFAC(pa->state.co,states->co,dx[0],1.0f/6.0f);
+ VECADDFAC(pa->state.co,pa->state.co,dx[1],1.0f/3.0f);
+ VECADDFAC(pa->state.co,pa->state.co,dx[2],1.0f/3.0f);
+ VECADDFAC(pa->state.co,pa->state.co,dx[3],1.0f/6.0f);
- VECADDFAC(state->vel,states->vel,dv[0],1.0f/6.0f);
- VECADDFAC(state->vel,state->vel,dv[1],1.0f/3.0f);
- VECADDFAC(state->vel,state->vel,dv[2],1.0f/3.0f);
- VECADDFAC(state->vel,state->vel,dv[3],1.0f/6.0f);
+ VECADDFAC(pa->state.vel,states->vel,dv[0],1.0f/6.0f);
+ VECADDFAC(pa->state.vel,pa->state.vel,dv[1],1.0f/3.0f);
+ VECADDFAC(pa->state.vel,pa->state.vel,dv[2],1.0f/3.0f);
+ VECADDFAC(pa->state.vel,pa->state.vel,dv[3],1.0f/6.0f);
}
break;
}
- //VECADD(states[i+1].co,states[i+1].co,force);
}
/* damp affects final velocity */
if(part->dampfac!=0.0)
- VecMulf(state->vel,1.0f-part->dampfac);
+ VecMulf(pa->state.vel,1.0f-part->dampfac);
/* finally we do guides */
time=(cfra-pa->time)/pa->lifetime;
CLAMP(time,0.0,1.0);
- VECCOPY(tkey.co,state->co);
- VECCOPY(tkey.vel,state->vel);
- tkey.time=state->time;
- if(do_guide(&tkey,pa_no,time,&psys->effectors)){
- VECCOPY(state->co,tkey.co);
- /* guides don't produce valid velocity */
- VECSUB(state->vel,tkey.co,pa->state.co);
- VecMulf(state->vel,1.0f/dtime);
- state->time=tkey.time;
+ VECCOPY(tkey.co,pa->state.co);
+ VECCOPY(tkey.vel,pa->state.vel);
+ tkey.time=pa->state.time;
+
+ if(part->type != PART_HAIR) {
+ if(do_guide(&tkey,pa_no,time,&psys->effectors)) {
+ VECCOPY(pa->state.co,tkey.co);
+ /* guides don't produce valid velocity */
+ VECSUB(pa->state.vel,tkey.co,pa->prev_state.co);
+ VecMulf(pa->state.vel,1.0f/dtime);
+ pa->state.time=tkey.time;
+ }
}
}
-static void rotate_particle(ParticleSettings *part, ParticleData *pa, float dfra, float timestep, ParticleKey *state)
+static void rotate_particle(ParticleSettings *part, ParticleData *pa, float dfra, float timestep)
{
float rotfac, rot1[4], rot2[4]={1.0,0.0,0.0,0.0}, dtime=dfra*timestep;
if((part->flag & PART_ROT_DYN)==0){
- if(ELEM(part->avemode,PART_AVE_SPIN,PART_AVE_VEL)){
+ if(part->avemode==PART_AVE_SPIN){
float angle;
- float len1 = VecLength(pa->state.vel);
- float len2 = VecLength(state->vel);
+ float len1 = VecLength(pa->prev_state.vel);
+ float len2 = VecLength(pa->state.vel);
if(len1==0.0f || len2==0.0f)
- state->ave[0]=state->ave[1]=state->ave[2]=0.0f;
+ pa->state.ave[0]=pa->state.ave[1]=pa->state.ave[2]=0.0f;
else{
- Crossf(state->ave,pa->state.vel,state->vel);
- Normalize(state->ave);
- angle=Inpf(pa->state.vel,state->vel)/(len1*len2);
- VecMulf(state->ave,saacos(angle)/dtime);
+ Crossf(pa->state.ave,pa->prev_state.vel,pa->state.vel);
+ Normalize(pa->state.ave);
+ angle=Inpf(pa->prev_state.vel,pa->state.vel)/(len1*len2);
+ VecMulf(pa->state.ave,saacos(angle)/dtime);
}
- }
- if(part->avemode == PART_AVE_SPIN)
- VecRotToQuat(state->vel,dtime*part->avefac,rot2);
+ VecRotToQuat(pa->state.vel,dtime*part->avefac,rot2);
+ }
}
- rotfac=VecLength(state->ave);
+ rotfac=VecLength(pa->state.ave);
if(rotfac==0.0){ /* QuatOne (in VecRotToQuat) doesn't give unit quat [1,0,0,0]?? */
rot1[0]=1.0;
rot1[1]=rot1[2]=rot1[3]=0;
}
else{
- VecRotToQuat(state->ave,rotfac*dtime,rot1);
+ VecRotToQuat(pa->state.ave,rotfac*dtime,rot1);
}
- QuatMul(state->rot,rot1,pa->state.rot);
- QuatMul(state->rot,rot2,state->rot);
+ QuatMul(pa->state.rot,rot1,pa->prev_state.rot);
+ QuatMul(pa->state.rot,rot2,pa->state.rot);
/* keep rotation quat in good health */
- NormalQuat(state->rot);
+ NormalQuat(pa->state.rot);
}
/* convert from triangle barycentric weights to quad mean value weights */
@@ -2922,7 +2856,7 @@ int psys_intersect_dm(Object *ob, DerivedMesh *dm, float *vert_cos, float *co1,
dm=mesh_get_derived_final(ob,0);
if(dm==0)
- mesh_get_derived_deform(ob,0);
+ dm=mesh_get_derived_deform(ob,0);
psys_enable_all(ob);
@@ -3032,37 +2966,122 @@ int psys_intersect_dm(Object *ob, DerivedMesh *dm, float *vert_cos, float *co1,
}
return intersect;
}
+
+/* container for moving data between deflet_particle and particle_intersect_face */
+typedef struct ParticleCollision
+{
+ struct Object *ob, *ob_t; // collided and current objects
+ struct CollisionModifierData *md; // collision modifier for ob_t;
+ float nor[3]; // normal at collision point
+ float vel[3]; // velocity of collision point
+ float co1[3], co2[3]; // ray start and end points
+ float ray_len; // original length of co2-co1, needed for collision time evaluation
+ float t; // time of previous collision, needed for substracting face velocity
+}
+ParticleCollision;
+
+static void particle_intersect_face(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
+{
+ ParticleCollision *col = (ParticleCollision *) userdata;
+ MFace *face = col->md->mfaces + index;
+ MVert *x = col->md->x;
+ MVert *v = col->md->current_v;
+ float vel[3], co1[3], co2[3], uv[2], ipoint[3], temp[3], t;
+
+ float *t0, *t1, *t2, *t3;
+ t0 = x[ face->v1 ].co;
+ t1 = x[ face->v2 ].co;
+ t2 = x[ face->v3 ].co;
+ t3 = face->v4 ? x[ face->v4].co : NULL;
+
+ /* calculate average velocity of face */
+ VECCOPY(vel, v[ face->v1 ].co);
+ VECADD(vel, vel, v[ face->v2 ].co);
+ VECADD(vel, vel, v[ face->v3 ].co);
+ VecMulf(vel, 0.33334f);
+
+ /* substract face velocity, in other words convert to
+ a coordinate system where only the particle moves */
+ VECADDFAC(co1, col->co1, vel, -col->t);
+ VECSUB(co2, col->co2, vel);
+
+ do
+ {
+ if(ray->radius == 0.0f) {
+ if(LineIntersectsTriangle(co1, co2, t0, t1, t2, &t, uv)) {
+ if(t >= 0.0f && t < hit->dist/col->ray_len) {
+ hit->dist = col->ray_len * t;
+ hit->index = index;
+
+ /* calculate normal that's facing the particle */
+ CalcNormFloat(t0, t1, t2, col->nor);
+ VECSUB(temp, co2, co1);
+ if(Inpf(col->nor, temp) > 0.0f)
+ VecMulf(col->nor, -1.0f);
+
+ VECCOPY(col->vel,vel);
+
+ col->ob = col->ob_t;
+ }
+ }
+ }
+ else {
+ if(SweepingSphereIntersectsTriangleUV(co1, co2, ray->radius, t0, t1, t2, &t, ipoint)) {
+ if(t >=0.0f && t < hit->dist/col->ray_len) {
+ hit->dist = col->ray_len * t;
+ hit->index = index;
+
+ VecLerpf(temp, co1, co2, t);
+
+ VECSUB(col->nor, temp, ipoint);
+ Normalize(col->nor);
+
+ VECCOPY(col->vel,vel);
+
+ col->ob = col->ob_t;
+ }
+ }
+ }
+
+ t1 = t2;
+ t2 = t3;
+ t3 = NULL;
+
+ } while(t2);
+}
/* particle - mesh collision code */
/* in addition to basic point to surface collisions handles friction & damping,*/
/* angular momentum <-> linear momentum and swept sphere - mesh collisions */
/* 1. check for all possible deflectors for closest intersection on particle path */
/* 2. if deflection was found kill the particle or calculate new coordinates */
-static void deflect_particle(Object *pob, ParticleSystemModifierData *psmd, ParticleSystem *psys, ParticleSettings *part, ParticleData *pa, int p, float dfra, float cfra, ParticleKey *state, int *pa_die){
- Object *ob, *min_ob;
- MFace *mface;
- MVert *mvert;
- DerivedMesh *dm;
+static void deflect_particle(Object *pob, ParticleSystemModifierData *psmd, ParticleSystem *psys, ParticleSettings *part, ParticleData *pa, int p, float timestep, float dfra, float cfra){
+ Object *ob = NULL;
ListBase *lb=&psys->effectors;
ParticleEffectorCache *ec;
- ParticleKey cstate;
- float imat[4][4];
- float co1[3],co2[3],def_loc[3],def_nor[3],unit_nor[3],def_tan[3],dvec[3],def_vel[3],dave[3],dvel[3];
- float pa_minmax[6];
- float min_w[4], zerovec[3]={0.0,0.0,0.0}, ipoint[3];
- float min_d,dotprod,damp,frict,o_len,d_len,radius=-1.0f;
- int min_face=0, intersect=1, through=0;
- short deflections=0, global=0;
+ ParticleKey reaction_state;
+ ParticleCollision col;
+ BVHTreeRayHit hit;
+ float ray_dir[3], zerovec[3]={0.0,0.0,0.0};
+ float radius = ((part->flag & PART_SIZE_DEFL)?pa->size:0.0f);
+ int deflections=0, max_deflections=10;
- VECCOPY(def_loc,pa->state.co);
- VECCOPY(def_vel,pa->state.vel);
+ VECCOPY(col.co1, pa->prev_state.co);
+ VECCOPY(col.co2, pa->state.co);
+ col.t = 0.0f;
/* 10 iterations to catch multiple deflections */
- if(lb->first) while(deflections<10){
- intersect=0;
- global=0;
- min_d=20000.0;
- min_ob=NULL;
+ if(lb->first) while(deflections < max_deflections){
/* 1. */
+
+ VECSUB(ray_dir, col.co2, col.co1);
+ hit.index = -1;
+ hit.dist = col.ray_len = VecLength(ray_dir);
+
+ /* even if particle is stationary we want to check for moving colliders */
+ /* if hit.dist is zero the bvhtree_ray_cast will just ignore everything */
+ if(hit.dist == 0.0f)
+ hit.dist = col.ray_len = 0.000001f;
+
for(ec=lb->first; ec; ec=ec->next){
if(ec->type & PSYS_EC_DEFLECT){
ob= ec->ob;
@@ -3070,256 +3089,168 @@ static void deflect_particle(Object *pob, ParticleSystemModifierData *psmd, Part
if(part->type!=PART_HAIR)
where_is_object_time(ob,cfra);
- if(ob==pob){
- dm=psmd->dm;
- /* particles should not collide with emitter at birth */
- if(pa->time < cfra && pa->time >= psys->cfra)
- continue;
- }
- else
- dm=0;
-
- VECCOPY(co1,def_loc);
- VECCOPY(co2,state->co);
-
- if(ec->vert_cos==0){
- /* convert particle coordinates to object coordinates */
- Mat4Invert(imat,ob->obmat);
-
- Mat4MulVecfl(imat,co1);
- Mat4MulVecfl(imat,co2);
- }
+ /* particles should not collide with emitter at birth */
+ if(ob==pob && pa->time < cfra && pa->time >= psys->cfra)
+ continue;
- INIT_MINMAX(pa_minmax,pa_minmax+3);
- DO_MINMAX(co1,pa_minmax,pa_minmax+3);
- DO_MINMAX(co2,pa_minmax,pa_minmax+3);
- if(part->flag&PART_SIZE_DEFL){
- pa_minmax[0]-=pa->size;
- pa_minmax[1]-=pa->size;
- pa_minmax[2]-=pa->size;
- pa_minmax[3]+=pa->size;
- pa_minmax[4]+=pa->size;
- pa_minmax[5]+=pa->size;
-
- radius=pa->size;
- }
+ col.md = ( CollisionModifierData * ) ( modifiers_findByType ( ec->ob, eModifierType_Collision ) );
+ col.ob_t = ob;
- if(ec->face_minmax==0 || AabbIntersectAabb(pa_minmax,pa_minmax+3,ec->ob_minmax,ec->ob_minmax+3))
- if(psys_intersect_dm(ob,dm,ec->vert_cos,co1,co2,&min_d,&min_face,min_w,
- ec->face_minmax,pa_minmax,radius,ipoint)){
- min_ob=ob;
- if(ec->vert_cos)
- global=1;
- else
- global=0;
- }
+ if(col.md && col.md->bvhtree)
+ BLI_bvhtree_ray_cast(col.md->bvhtree, col.co1, ray_dir, radius, &hit, particle_intersect_face, &col);
}
}
/* 2. */
- if(min_ob){
- BLI_srandom((int)cfra+p);
- ob=min_ob;
-
- if(ob==pob){
- dm=psmd->dm;
- }
- else{
- psys_disable_all(ob);
-
- dm=mesh_get_derived_final(ob,0);
-
- psys_enable_all(ob);
- }
-
- mface=dm->getFaceDataArray(dm,CD_MFACE);
- mface+=min_face;
- mvert=dm->getVertDataArray(dm,CD_MVERT);
-
-
- /* permeability check */
- if(BLI_frand()<ob->pd->pdef_perm)
- through=1;
- else
- through=0;
-
- if(through==0 && (part->flag & PART_DIE_ON_COL || ob->pd->flag & PDEFLE_KILL_PART)){
- pa->dietime = cfra-(1.0f-min_d)*dfra;
- VecLerpf(def_loc,co1,co2,min_d);
-
- if(global==0)
- Mat4MulVecfl(ob->obmat,def_loc);
-
- VECCOPY(state->co,def_loc);
- VecLerpf(state->vel,pa->state.vel,state->vel,min_d);
- QuatInterpol(state->rot,pa->state.rot,state->rot,min_d);
- VecLerpf(state->ave,pa->state.ave,state->ave,min_d);
+ if(hit.index>=0) {
+ PartDeflect *pd = col.ob->pd;
+ int through = (BLI_frand() < pd->pdef_perm) ? 1 : 0;
+ float co[3]; /* point of collision */
+ float vec[3]; /* movement through collision */
+ float t = hit.dist/col.ray_len; /* time of collision between this iteration */
+ float dt = col.t + t * (1.0f - col.t); /* time of collision between frame change*/
+
+ VecLerpf(co, col.co1, col.co2, t);
+ VECSUB(vec, col.co2, col.co1);
+
+ VecMulf(col.vel, 1.0f-col.t);
+
+ /* particle dies in collision */
+ if(through == 0 && (part->flag & PART_DIE_ON_COL || pd->flag & PDEFLE_KILL_PART)) {
+ pa->alive = PARS_DYING;
+ pa->dietime = pa->state.time + (cfra - pa->state.time) * dt;
+
+ /* we have to add this for dying particles too so that reactors work correctly */
+ VECADDFAC(co, co, col.nor, (through ? -0.0001f : 0.0001f));
- *pa_die=1;
+ VECCOPY(pa->state.co, co);
+ VecLerpf(pa->state.vel, pa->prev_state.vel, pa->state.vel, dt);
+ QuatInterpol(pa->state.rot, pa->prev_state.rot, pa->state.rot, dt);
+ VecLerpf(pa->state.ave, pa->prev_state.ave, pa->state.ave, dt);
/* particle is dead so we don't need to calculate further */
- deflections=10;
+ deflections=max_deflections;
/* store for reactors */
- copy_particle_key(&cstate,state,0);
+ copy_particle_key(&reaction_state,&pa->state,0);
if(part->flag & PART_STICKY){
pa->stick_ob=ob;
pa->flag |= PARS_STICKY;
- //stick_particle_to_object(ob,pa,state);
}
}
- else{
- VecLerpf(def_loc,co1,co2,min_d);
-
- if(radius>0.0f){
- VECSUB(unit_nor,def_loc,ipoint);
- }
- else{
- /* get deflection point & normal */
- psys_interpolate_face(mvert,mface,0,0,min_w,ipoint,unit_nor,0,0,0,0);
- if(global){
- Mat4Mul3Vecfl(ob->obmat,unit_nor);
- Mat4MulVecfl(ob->obmat,ipoint);
- }
- }
-
- Normalize(unit_nor);
-
- VECSUB(dvec,co1,co2);
- /* scale to remaining length after deflection */
- VecMulf(dvec,1.0f-min_d);
+ else {
+ float nor_vec[3], tan_vec[3], tan_vel[3], vel[3];
+ float damp, frict;
+ float inp, inp_v;
+
+ /* get damping & friction factors */
+ damp = pd->pdef_damp + pd->pdef_rdamp * 2 * (BLI_frand() - 0.5f);
+ CLAMP(damp,0.0,1.0);
- /* flip normal to face particle */
- if(Inpf(unit_nor,dvec)<0.0f)
- VecMulf(unit_nor,-1.0f);
+ frict = pd->pdef_frict + pd->pdef_rfrict * 2 * (BLI_frand() - 0.5f);
+ CLAMP(frict,0.0,1.0);
- /* store for easy velocity calculation */
- o_len=VecLength(dvec);
+ /* treat normal & tangent components separately */
+ inp = Inpf(col.nor, vec);
+ inp_v = Inpf(col.nor, col.vel);
- /* project particle movement to normal & create tangent */
- dotprod=Inpf(dvec,unit_nor);
- VECCOPY(def_nor,unit_nor);
- VecMulf(def_nor,dotprod);
- VECSUB(def_tan,def_nor,dvec);
+ VECADDFAC(tan_vec, vec, col.nor, -inp);
+ VECADDFAC(tan_vel, col.vel, col.nor, -inp_v);
+ if((part->flag & PART_ROT_DYN)==0)
+ VecLerpf(tan_vec, tan_vec, tan_vel, frict);
- damp=ob->pd->pdef_damp+ob->pd->pdef_rdamp*2*(BLI_frand()-0.5f);
+ VECCOPY(nor_vec, col.nor);
+ inp *= 1.0f - damp;
- /* create location after deflection */
- VECCOPY(dvec,def_nor);
- damp=ob->pd->pdef_damp+ob->pd->pdef_rdamp*2*(BLI_frand()-0.5f);
- CLAMP(damp,0.0,1.0);
- VecMulf(dvec,1.0f-damp);
if(through)
- VecMulf(dvec,-1.0);
-
- frict=ob->pd->pdef_frict+ob->pd->pdef_rfrict*2.0f*(BLI_frand()-0.5f);
- CLAMP(frict,0.0,1.0);
- VECADDFAC(dvec,dvec,def_tan,1.0f-frict);
+ inp_v *= damp;
- /* store for easy velocity calculation */
- d_len=VecLength(dvec);
+ /* special case for object hitting the particle from behind */
+ if(through==0 && ((inp_v>0 && inp>0 && inp_v>inp) || (inp_v<0 && inp<0 && inp_v<inp)))
+ VecMulf(nor_vec, inp_v);
+ else
+ VecMulf(nor_vec, inp_v + (through ? 1.0f : -1.0f) * inp);
- /* just to be sure we don't hit the current face again */
- if(through){
- VECADDFAC(ipoint,ipoint,unit_nor,-0.0001f);
- VECADDFAC(def_loc,def_loc,unit_nor,-0.0001f);
+ /* angular <-> linear velocity - slightly more physical and looks even nicer than before */
+ if(part->flag & PART_ROT_DYN) {
+ float surface_vel[3], rot_vel[3], friction[3], dave[3], dvel[3];
- if(part->flag & PART_ROT_DYN){
- VECADDFAC(def_tan,def_tan,unit_nor,-0.0001f);
- VECADDFAC(def_nor,def_nor,unit_nor,-0.0001f);
- }
- }
- else{
- VECADDFAC(ipoint,ipoint,unit_nor,0.0001f);
- VECADDFAC(def_loc,def_loc,unit_nor,0.0001f);
+ /* apparent velocity along collision surface */
+ VECSUB(surface_vel, tan_vec, tan_vel);
- if(part->flag & PART_ROT_DYN){
- VECADDFAC(def_tan,def_tan,unit_nor,0.0001f);
- VECADDFAC(def_nor,def_nor,unit_nor,0.0001f);
- }
- }
+ /* direction of rolling friction */
+ Crossf(rot_vel, pa->state.ave, col.nor);
+ /* convert to current dt */
+ VecMulf(rot_vel, (timestep*dfra) * (1.0f - col.t));
+ VecMulf(rot_vel, pa->size);
- /* lets get back to global space */
- if(global==0){
- Mat4Mul3Vecfl(ob->obmat,dvec);
- Mat4MulVecfl(ob->obmat,ipoint);
- Mat4MulVecfl(ob->obmat,def_loc);/* def_loc remains as intersection point for next iteration */
- }
+ /* apply sliding friction */
+ VECSUB(surface_vel, surface_vel, rot_vel);
+ VECCOPY(friction, surface_vel);
- /* store for reactors */
- VECCOPY(cstate.co,ipoint);
- VecLerpf(cstate.vel,pa->state.vel,state->vel,min_d);
- QuatInterpol(cstate.rot,pa->state.rot,state->rot,min_d);
-
- /* slightly unphysical but looks nice enough */
- if(part->flag & PART_ROT_DYN){
- if(global==0){
- Mat4Mul3Vecfl(ob->obmat,def_nor);
- Mat4Mul3Vecfl(ob->obmat,def_tan);
- }
+ VecMulf(surface_vel, 1.0 - frict);
+ VecMulf(friction, frict);
- Normalize(def_tan);
- Normalize(def_nor);
- VECCOPY(unit_nor,def_nor);
+ /* sliding changes angular velocity */
+ Crossf(dave, col.nor, friction);
+ VecMulf(dave, 1.0f/MAX2(pa->size, 0.001));
- /* create normal velocity */
- VecMulf(def_nor,Inpf(pa->state.vel,def_nor));
+ /* we assume rolling friction is around 0.01 of sliding friction */
+ VecMulf(rot_vel, 1.0 - frict*0.01);
- /* create tangential velocity */
- VecMulf(def_tan,Inpf(pa->state.vel,def_tan));
-
- /* angular velocity change due to tangential velocity */
- Crossf(dave,unit_nor,def_tan);
- VecMulf(dave,1.0f/pa->size);
-
- /* linear velocity change due to angular velocity */
- VecMulf(unit_nor,pa->size); /* point of impact from particle center */
- Crossf(dvel,pa->state.ave,unit_nor);
+ /* change in angular velocity has to be added to the linear velocity too */
+ Crossf(dvel, dave, col.nor);
+ VecMulf(dvel, pa->size);
+ VECADD(rot_vel, rot_vel, dvel);
- if(through)
- VecMulf(def_nor,-1.0);
+ VECADD(surface_vel, surface_vel, rot_vel);
+ VECADD(tan_vec, surface_vel, tan_vel);
- VecMulf(def_nor,1.0f-damp);
- VECSUB(dvel,dvel,def_nor);
+ /* convert back to normal time */
+ VecMulf(dave, 1.0f/MAX2((timestep*dfra) * (1.0f - col.t), 0.00001));
- VecMulf(dvel,1.0f-frict);
- VecMulf(dave,1.0f-frict);
+ VecMulf(pa->state.ave, 1.0 - frict*0.01);
+ VECADD(pa->state.ave, pa->state.ave, dave);
}
-
- if(d_len<0.001 && VecLength(pa->state.vel)<0.001){
- /* kill speed to stop slipping */
- VECCOPY(state->vel,zerovec);
- VECCOPY(state->co,def_loc);
- if(part->flag & PART_ROT_DYN)
- VECCOPY(state->ave,zerovec);
- deflections=10;
- }
- else{
- /* apply new coordinates */
- VECADD(state->co,def_loc,dvec);
+ /* combine components together again */
+ VECADD(vec, nor_vec, tan_vec);
+
+ /* calculate velocity from collision vector */
+ VECCOPY(vel, vec);
+ VecMulf(vel, 1.0f/MAX2((timestep*dfra) * (1.0f - col.t), 0.00001));
- Normalize(dvec);
+ /* make sure we don't hit the current face again */
+ VECADDFAC(co, co, col.nor, (through ? -0.0001f : 0.0001f));
- /* we have to use original velocity because otherwise we get slipping */
- /* when forces like gravity balance out damping & friction */
- VecMulf(dvec,VecLength(pa->state.vel)*(d_len/o_len));
- VECCOPY(state->vel,dvec);
+ /* store state for reactors */
+ VECCOPY(reaction_state.co, co);
+ VecLerpf(reaction_state.vel, pa->prev_state.vel, pa->state.vel, dt);
+ QuatInterpol(reaction_state.rot, pa->prev_state.rot, pa->state.rot, dt);
- if(part->flag & PART_ROT_DYN){
- VECADD(state->vel,state->vel,dvel);
- VecMulf(state->vel,0.5);
- VECADD(state->ave,state->ave,dave);
- VecMulf(state->ave,0.5);
+ /* set coordinates for next iteration */
+ VECCOPY(col.co1, co);
+ VECADDFAC(col.co2, co, vec, 1.0f - t);
+ col.t = dt;
+
+ if(VecLength(vec) < 0.001 && VecLength(pa->state.vel) < 0.001) {
+ /* kill speed to stop slipping */
+ VECCOPY(pa->state.vel,zerovec);
+ VECCOPY(pa->state.co, co);
+ if(part->flag & PART_ROT_DYN) {
+ VECCOPY(pa->state.ave,zerovec);
}
}
+ else {
+ VECCOPY(pa->state.co, col.co2);
+ VECCOPY(pa->state.vel, vel);
+ }
}
deflections++;
- cstate.time=cfra-(1.0f-min_d)*dfra;
- //particle_react_to_collision(min_ob,pob,psys,pa,p,&cstate);
- push_reaction(pob,psys,p,PART_EVENT_COLLIDE,&cstate);
+ reaction_state.time = cfra - (1.0f - dt) * dfra;
+ push_reaction(col.ob, psys, p, PART_EVENT_COLLIDE, &reaction_state);
}
else
return;
@@ -3380,7 +3311,9 @@ static int boid_see_mesh(ListBase *lb, Object *pob, ParticleSystem *psys, float
else{
psys_disable_all(ob);
- dm=mesh_get_derived_deform(ob,0);
+ dm=mesh_get_derived_final(ob,0);
+ if(dm==0)
+ dm=mesh_get_derived_deform(ob,0);
psys_enable_all(ob);
}
@@ -3483,7 +3416,7 @@ static int add_boid_acc(BoidVecFunc *bvf, float lat_max, float tan_max, float *l
}
}
/* determines the acceleration that the boid tries to acchieve */
-static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleSystem *psys, ParticleSettings *part, KDTree *tree, float timestep, float cfra, float *acc, int *pa_die)
+static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleSystem *psys, ParticleSettings *part, KDTree *tree, float timestep, float cfra, float *acc)
{
ParticleData *pars=psys->particles;
KDTreeNearest ptn[MAX_BOIDNEIGHBOURS+1];
@@ -3514,18 +3447,18 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
switch(part->boidrule[i]){
case BOID_COLLIDE:
/* collision avoidance */
- bvf->Copyf(dvec,pa->state.vel);
+ bvf->Copyf(dvec,pa->prev_state.vel);
bvf->Mulf(dvec,5.0f);
- bvf->Addf(dvec,dvec,pa->state.co);
- if(boid_see_mesh(&psys->effectors,ob,psys,pa->state.co,dvec,ob_co,ob_nor,cfra)){
+ bvf->Addf(dvec,dvec,pa->prev_state.co);
+ if(boid_see_mesh(&psys->effectors,ob,psys,pa->prev_state.co,dvec,ob_co,ob_nor,cfra)){
float probelen = bvf->Length(dvec);
float proj;
float oblen;
Normalize(ob_nor);
- proj = bvf->Inpf(ob_nor,pa->state.vel);
+ proj = bvf->Inpf(ob_nor,pa->prev_state.vel);
- bvf->Subf(dvec,pa->state.co,ob_co);
+ bvf->Subf(dvec,pa->prev_state.co,ob_co);
oblen=bvf->Length(dvec);
bvf->Copyf(dvec,ob_nor);
@@ -3545,12 +3478,12 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
if(pd->forcefield==PFIELD_FORCE && pd->f_strength<0.0){
float distance;
- VECSUB(dvec,eob->obmat[3],pa->state.co);
+ VECSUB(dvec,eob->obmat[3],pa->prev_state.co);
distance=Normalize(dvec);
if(part->flag & PART_DIE_ON_COL && distance < pd->mindist){
- *pa_die=1;
+ pa->alive = PARS_DYING;
pa->dietime=cfra;
i=BOID_TOT_RULES;
break;
@@ -3579,17 +3512,17 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
pd= epart->pd;
totepart= epsys->totpart;
- if(pd->forcefield==PFIELD_FORCE && pd->f_strength<0.0){
- count=BLI_kdtree_find_n_nearest(ec->tree,epart->boidneighbours,pa->state.co,NULL,ptn2);
+ if(pd->forcefield==PFIELD_FORCE && pd->f_strength<0.0 && ec->tree){
+ count=BLI_kdtree_find_n_nearest(ec->tree,epart->boidneighbours,pa->prev_state.co,NULL,ptn2);
for(p=0; p<count; p++){
state.time=-1.0;
if(psys_get_particle_state(eob,epsys,ptn2[p].index,&state,0)){
- VECSUB(dvec, state.co, pa->state.co);
+ VECSUB(dvec, state.co, pa->prev_state.co);
distance = Normalize(dvec);
if(part->flag & PART_DIE_ON_COL && distance < (epsys->particles+ptn2[p].index)->size){
- *pa_die=1;
+ pa->alive = PARS_DYING;
pa->dietime=cfra;
i=BOID_TOT_RULES;
break;
@@ -3614,10 +3547,12 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
near=0;
for(n=1; n<neighbours; n++){
if(ptn[n].dist<2.0f*pa->size){
- bvf->Subf(dvec,pa->state.co,pars[ptn[n].index].state.co);
- bvf->Mulf(dvec,(2.0f*pa->size-ptn[n].dist)/ptn[n].dist);
- bvf->Addf(avoid,avoid,dvec);
- near++;
+ if(ptn[n].dist!=0.0f) {
+ bvf->Subf(dvec,pa->prev_state.co,pars[ptn[n].index].state.co);
+ bvf->Mulf(dvec,(2.0f*pa->size-ptn[n].dist)/ptn[n].dist);
+ bvf->Addf(avoid,avoid,dvec);
+ near++;
+ }
}
/* ptn[] is distance ordered so no need to check others */
else break;
@@ -3636,7 +3571,7 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
}
bvf->Mulf(center,1.0f/((float)neighbours-1.0f));
- bvf->Subf(dvec,center,pa->state.co);
+ bvf->Subf(dvec,center,pa->prev_state.co);
bvf->Mulf(dvec,part->boidfac[BOID_CENTER]*2.0f);
@@ -3645,9 +3580,9 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
break;
case BOID_AV_VEL:
/* average velocity */
- cur_vel=bvf->Length(pa->state.vel);
+ cur_vel=bvf->Length(pa->prev_state.vel);
if(cur_vel>0.0){
- bvf->Copyf(dvec,pa->state.vel);
+ bvf->Copyf(dvec,pa->prev_state.vel);
bvf->Mulf(dvec,part->boidfac[BOID_AV_VEL]*(avg_vel-cur_vel)/cur_vel);
not_finished=add_boid_acc(bvf,max_lat_acc,max_tan_acc,&lat_accu,&tan_accu,acc,dvec,0);
}
@@ -3662,7 +3597,7 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
}
bvf->Mulf(velocity,1.0f/((float)neighbours-1.0f));
- bvf->Subf(dvec,velocity,pa->state.vel);
+ bvf->Subf(dvec,velocity,pa->prev_state.vel);
bvf->Mulf(dvec,part->boidfac[BOID_VEL_MATCH]);
@@ -3680,7 +3615,7 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
if(pd->forcefield==PFIELD_FORCE && pd->f_strength>0.0){
float distance;
- VECSUB(dvec,eob->obmat[3],pa->state.co);
+ VECSUB(dvec,eob->obmat[3],pa->prev_state.co);
distance=Normalize(dvec);
@@ -3697,7 +3632,7 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
where_on_path(eob, (cfra-pa->time)/pa->lifetime, temp, dvec);
- VECSUB(dvec,temp,pa->state.co);
+ VECSUB(dvec,temp,pa->prev_state.co);
distance=Normalize(dvec);
@@ -3724,12 +3659,12 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
pd= epart->pd;
totepart= epsys->totpart;
- if(pd->forcefield==PFIELD_FORCE && pd->f_strength>0.0){
- count=BLI_kdtree_find_n_nearest(ec->tree,epart->boidneighbours,pa->state.co,NULL,ptn2);
+ if(pd->forcefield==PFIELD_FORCE && pd->f_strength>0.0 && ec->tree){
+ count=BLI_kdtree_find_n_nearest(ec->tree,epart->boidneighbours,pa->prev_state.co,NULL,ptn2);
for(p=0; p<count; p++){
state.time=-1.0;
if(psys_get_particle_state(eob,epsys,ptn2[p].index,&state,0)){
- VECSUB(dvec, state.co, pa->state.co);
+ VECSUB(dvec, state.co, pa->prev_state.co);
distance = Normalize(dvec);
@@ -3751,7 +3686,7 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
/* level flight */
if((part->flag & PART_BOIDS_2D)==0){
dvec[0]=dvec[1]=0.0;
- dvec[2]=-pa->state.vel[2];
+ dvec[2]=-pa->prev_state.vel[2];
VecMulf(dvec,part->boidfac[BOID_LEVEL]);
not_finished=add_boid_acc(bvf,max_lat_acc,max_tan_acc,&lat_accu,&tan_accu,acc,dvec,0);
@@ -3761,15 +3696,15 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
}
}
/* tries to realize the wanted acceleration */
-static void boid_body(BoidVecFunc *bvf, ParticleData *pa, ParticleSystem *psys, ParticleSettings *part, float timestep, float *acc, ParticleKey *state)
+static void boid_body(BoidVecFunc *bvf, ParticleData *pa, ParticleSystem *psys, ParticleSettings *part, float timestep, float *acc)
{
float dvec[3], bvec[3], length, max_vel=part->max_vel;
- float *q2, q[4];
+ float q2[4], q[4];
float g=9.81f, pa_mass=part->mass;
float yvec[3]={0.0,1.0,0.0}, zvec[3]={0.0,0.0,-1.0}, bank;
/* apply new velocity, location & rotation */
- copy_particle_key(state,&pa->state,0);
+ copy_particle_key(&pa->state,&pa->prev_state,0);
if(part->flag & PART_SIZEMASS)
pa_mass*=pa->size;
@@ -3781,32 +3716,49 @@ static void boid_body(BoidVecFunc *bvf, ParticleData *pa, ParticleSystem *psys,
bvf->Copyf(dvec,acc);
bvf->Mulf(dvec,timestep*timestep*0.5f);
- bvf->Copyf(bvec,state->vel);
+ bvf->Copyf(bvec,pa->state.vel);
bvf->Mulf(bvec,timestep);
bvf->Addf(dvec,dvec,bvec);
- bvf->Addf(state->co,state->co,dvec);
+ bvf->Addf(pa->state.co,pa->state.co,dvec);
- /* air speed from wind effectors */
- if(psys->effectors.first){
+ /* air speed from wind and vortex effectors */
+ if(psys->effectors.first) {
ParticleEffectorCache *ec;
- for(ec=psys->effectors.first; ec; ec=ec->next){
- if(ec->type & PSYS_EC_EFFECTOR){
+ for(ec=psys->effectors.first; ec; ec=ec->next) {
+ if(ec->type & PSYS_EC_EFFECTOR) {
Object *eob = ec->ob;
PartDeflect *pd = eob->pd;
+ float direction[3], vec_to_part[3];
+ float falloff;
+
+ if(pd->f_strength != 0.0f) {
+ VecCopyf(direction, eob->obmat[2]);
+ VecSubf(vec_to_part, pa->state.co, eob->obmat[3]);
+
+ falloff=effector_falloff(pd, direction, vec_to_part);
+
+ switch(pd->forcefield) {
+ case PFIELD_WIND:
+ if(falloff <= 0.0f)
+ ; /* don't do anything */
+ else {
+ Normalize(direction);
+ VecMulf(direction, pd->f_strength * falloff);
+ bvf->Addf(pa->state.co, pa->state.co, direction);
+ }
+ break;
+ case PFIELD_VORTEX:
+ {
+ float distance, mag_vec[3];
+ Crossf(mag_vec, direction, vec_to_part);
+ Normalize(mag_vec);
- if(pd->forcefield==PFIELD_WIND && pd->f_strength!=0.0){
- float distance, wind[3];
- VecCopyf(wind,eob->obmat[2]);
- distance=VecLenf(state->co,eob->obmat[3]);
-
- if (distance < 0.001) distance = 0.001f;
+ distance = VecLength(vec_to_part);
- if(pd->flag&PFIELD_USEMAX && distance > pd->maxdist)
- ;
- else{
- Normalize(wind);
- VecMulf(wind,pd->f_strength/(float)pow((double)distance,(double)pd->f_power));
- bvf->Addf(state->co,state->co,wind);
+ VecMulf(mag_vec, pd->f_strength * distance * falloff);
+ bvf->Addf(pa->state.co, pa->state.co, mag_vec);
+ break;
+ }
}
}
}
@@ -3814,8 +3766,8 @@ static void boid_body(BoidVecFunc *bvf, ParticleData *pa, ParticleSystem *psys,
}
- if((part->flag & PART_BOIDS_2D)==0 && pa->state.vel[0]!=0.0 && pa->state.vel[0]!=0.0 && pa->state.vel[0]!=0.0){
- Crossf(yvec,state->vel,zvec);
+ if((part->flag & PART_BOIDS_2D)==0 && pa->prev_state.vel[0]!=0.0 && pa->prev_state.vel[0]!=0.0 && pa->prev_state.vel[0]!=0.0){
+ Crossf(yvec,pa->state.vel,zvec);
Normalize(yvec);
@@ -3842,27 +3794,27 @@ static void boid_body(BoidVecFunc *bvf, ParticleData *pa, ParticleSystem *psys,
}
- VecRotToQuat(state->vel,bank,q);
+ VecRotToQuat(pa->state.vel,bank,q);
- VECCOPY(dvec,state->vel);
+ VECCOPY(dvec,pa->state.vel);
VecMulf(dvec,-1.0f);
- q2= vectoquat(dvec, OB_POSX, OB_POSZ);
+ vectoquat(dvec, OB_POSX, OB_POSZ, q2);
- QuatMul(state->rot,q,q2);
+ QuatMul(pa->state.rot,q,q2);
bvf->Mulf(acc,timestep);
- bvf->Addf(state->vel,state->vel,acc);
+ bvf->Addf(pa->state.vel,pa->state.vel,acc);
if(part->flag & PART_BOIDS_2D){
- state->vel[2]=0.0;
- state->co[2]=part->groundz;
+ pa->state.vel[2]=0.0;
+ pa->state.co[2]=part->groundz;
- if(psys->keyed_ob){
+ if(psys->keyed_ob && (psys->keyed_ob->type == OB_MESH)){
Object *zob=psys->keyed_ob;
int min_face;
float co1[3],co2[3],min_d=2.0,min_w[4],imat[4][4];
- VECCOPY(co1,state->co);
- VECCOPY(co2,state->co);
+ VECCOPY(co1,pa->state.co);
+ VECCOPY(co2,pa->state.co);
co1[2]=1000.0f;
co2[2]=-1000.0f;
@@ -3893,7 +3845,7 @@ static void boid_body(BoidVecFunc *bvf, ParticleData *pa, ParticleSystem *psys,
Normalize(nor);
- VECCOPY(state->co,loc);
+ VECCOPY(pa->state.co,loc);
zvec[2]=1.0;
@@ -3905,22 +3857,22 @@ static void boid_body(BoidVecFunc *bvf, ParticleData *pa, ParticleSystem *psys,
VecRotToQuat(loc,bank,q);
- QUATCOPY(q1,state->rot);
+ QUATCOPY(q1,pa->state.rot);
- QuatMul(state->rot,q,q1);
+ QuatMul(pa->state.rot,q,q1);
}
}
}
}
- length=bvf->Length(state->vel);
+ length=bvf->Length(pa->state.vel);
if(length > max_vel)
- bvf->Mulf(state->vel,max_vel/length);
+ bvf->Mulf(pa->state.vel,max_vel/length);
}
/************************************************/
/* Hair */
/************************************************/
-void save_hair(Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd, float cfra){
+static void save_hair(Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd, float cfra){
ParticleData *pa;
HairKey *key;
int totpart;
@@ -3972,14 +3924,13 @@ static void dynamics_step(Object *ob, ParticleSystem *psys, ParticleSystemModifi
float *vg_vel, float *vg_tan, float *vg_rot, float *vg_size)
{
ParticleData *pa;
- ParticleKey *outstate, *key;
ParticleSettings *part=psys->part;
KDTree *tree=0;
BoidVecFunc bvf;
IpoCurve *icu_esize=find_ipocurve(part->ipo,PART_EMIT_SIZE);
Material *ma=give_current_material(ob,part->omat);
float timestep;
- int p, totpart, pa_die;
+ int p, totpart;
/* current time */
float ctime, ipotime;
/* frame & time changes */
@@ -4007,7 +3958,7 @@ static void dynamics_step(Object *ob, ParticleSystem *psys, ParticleSystemModifi
vg_size=psys_cache_vgroup(psmd->dm,psys,PSYS_VG_SIZE);
for(p=0, pa=psys->particles; p<totpart; p++,pa++){
- if(pa->flag & (PARS_NO_DISP+PARS_UNEXIST)) continue;
+ if(pa->flag & PARS_UNEXIST) continue;
/* set correct ipo timing */
if((part->flag&PART_ABS_TIME)==0 && part->ipo){
@@ -4017,36 +3968,31 @@ static void dynamics_step(Object *ob, ParticleSystem *psys, ParticleSystemModifi
}
pa->size=psys_get_size(ob,ma,psmd,icu_esize,psys,part,pa,vg_size);
- if(part->type==PART_REACTOR)
- initialize_particle(pa,p,ob,psys,psmd);
-
reset_particle(pa,psys,psmd,ob,dtime,cfra,vg_vel,vg_tan,vg_rot);
- if(cfra>pa->time && part->flag & PART_LOOP && (part->flag & PART_LOOP_INSTANT)==0){
- pa->loop=(short)((cfra-pa->time)/pa->lifetime)+1;
+ if(cfra>pa->time && part->flag & PART_LOOP && part->type!=PART_HAIR){
+ pa->loop=(short)((cfra-pa->time)/pa->lifetime);
pa->alive=PARS_UNBORN;
}
else{
- pa->loop=0;
- if(cfra<=pa->time)
- pa->alive=PARS_UNBORN;
+ pa->loop = 0;
+ if(cfra <= pa->time)
+ pa->alive = PARS_UNBORN;
/* without dynamics the state is allways known so no need to kill */
- else if(ELEM(part->phystype,PART_PHYS_NO,PART_PHYS_KEYED)==0)
- pa->alive=PARS_KILLED;
+ else if(ELEM(part->phystype, PART_PHYS_NO, PART_PHYS_KEYED)){
+ if(cfra < pa->dietime)
+ pa->alive = PARS_ALIVE;
+ }
+ else
+ pa->alive = PARS_KILLED;
}
}
if(vg_size)
MEM_freeN(vg_size);
-
- //if(part->phystype==PART_PHYS_SOLID)
- // reset_to_first_fragment(psys);
}
else{
BLI_srandom(31415926 + (int)cfra + psys->seed);
-
- /* outstate is used so that particles are updated in parallel */
- outstate=MEM_callocN(totpart*sizeof(ParticleKey),"Particle Outstates");
/* update effectors */
if(psys->effectors.first)
@@ -4055,7 +4001,7 @@ static void dynamics_step(Object *ob, ParticleSystem *psys, ParticleSystemModifi
psys_init_effectors(ob,part->eff_group,psys);
if(psys->effectors.first)
- precalc_effectors(ob,psys,psmd);
+ precalc_effectors(ob,psys,psmd,cfra);
if(part->phystype==PART_PHYS_BOIDS){
/* create particle tree for fast inter-particle comparisons */
@@ -4071,10 +4017,10 @@ static void dynamics_step(Object *ob, ParticleSystem *psys, ParticleSystemModifi
}
/* main loop: calculate physics for all particles */
- for(p=0, pa=psys->particles, key=outstate; p<totpart; p++,pa++,key++){
- if(pa->flag & (PARS_NO_DISP|PARS_UNEXIST)) continue;
+ for(p=0, pa=psys->particles; p<totpart; p++,pa++){
+ if(pa->flag & PARS_UNEXIST) continue;
- copy_particle_key(key,&pa->state,1);
+ copy_particle_key(&pa->prev_state,&pa->state,1);
/* set correct ipo timing */
if((part->flag&PART_ABS_TIME)==0 && part->ipo){
@@ -4084,104 +4030,85 @@ static void dynamics_step(Object *ob, ParticleSystem *psys, ParticleSystemModifi
}
pa->size=psys_get_size(ob,ma,psmd,icu_esize,psys,part,pa,vg_size);
- pa_die=0;
+ /* reactions can change birth time so they need to be checked first */
+ if(psys->reactevents.first && ELEM(pa->alive,PARS_DEAD,PARS_KILLED)==0)
+ react_to_events(psys,p);
+
+ birthtime = pa->time + pa->loop * pa->lifetime;
+ dietime = birthtime + pa->lifetime;
- if(pa->alive==PARS_UNBORN || pa->alive==PARS_KILLED || ELEM(part->phystype,PART_PHYS_NO,PART_PHYS_KEYED)){
- /* allways reset particles to emitter before birth */
+ /* allways reset particles to emitter before birth */
+ if(pa->alive==PARS_UNBORN
+ || pa->alive==PARS_KILLED
+ || ELEM(part->phystype,PART_PHYS_NO,PART_PHYS_KEYED)
+ || birthtime >= cfra){
reset_particle(pa,psys,psmd,ob,dtime,cfra,vg_vel,vg_tan,vg_rot);
- copy_particle_key(key,&pa->state,1);
}
- if(dfra>0.0 || psys->recalc){
-
- if(psys->reactevents.first && ELEM(pa->alive,PARS_DEAD,PARS_KILLED)==0)
- react_to_events(psys,p);
+ pa_dfra = dfra;
+ pa_dtime = dtime;
- pa_dfra= dfra;
- pa_dtime= dtime;
+ if(birthtime <= cfra && birthtime >= psys->cfra){
+ /* particle is born some time between this and last step*/
+ pa->alive = PARS_ALIVE;
+ pa_dfra = cfra - birthtime;
+ pa_dtime = pa_dfra*timestep;
+ }
+ else if(dietime <= cfra && psys->cfra < dietime){
+ /* particle dies some time between this and last step */
+ pa_dfra = dietime - psys->cfra;
+ pa_dtime = pa_dfra * timestep;
+ pa->alive = PARS_DYING;
+ }
+ else if(dietime < cfra){
+ /* nothing to be done when particle is dead */
+ }
- if(pa->flag & PART_LOOP && pa->flag & PART_LOOP_INSTANT)
- birthtime=pa->dietime;
- else
- birthtime=pa->time+pa->loop*pa->lifetime;
- dietime=birthtime+pa->lifetime;
+ if(dfra>0.0 && ELEM(pa->alive,PARS_ALIVE,PARS_DYING)){
+ switch(part->phystype){
+ case PART_PHYS_NEWTON:
+ /* do global forces & effectors */
+ apply_particle_forces(p,pa,ob,psys,part,timestep,pa_dfra,cfra);
+
+ /* deflection */
+ deflect_particle(ob,psmd,psys,part,pa,p,timestep,pa_dfra,cfra);
- if(birthtime < cfra && birthtime >= psys->cfra){
- /* particle is born some time between this and last step*/
- pa->alive=PARS_ALIVE;
- pa_dfra= cfra - birthtime;
- pa_dtime= pa_dfra*timestep;
- }
- else if(dietime <= cfra && psys->cfra < dietime){
- /* particle dies some time between this and last step */
- pa_dfra= dietime - psys->cfra;
- pa_dtime= pa_dfra*timestep;
- pa_die=1;
- }
- else if(dietime < cfra){
- /* TODO: figure out if there's something to be done when particle is dead */
+ /* rotations */
+ rotate_particle(part,pa,pa_dfra,timestep);
+ break;
+ case PART_PHYS_BOIDS:
+ {
+ float acc[3];
+ boid_brain(&bvf,pa,ob,psys,part,tree,timestep,cfra,acc);
+ if(pa->alive != PARS_DYING)
+ boid_body(&bvf,pa,psys,part,timestep,acc);
+ break;
+ }
}
- copy_particle_key(key,&pa->state,1);
-
- if(dfra>0.0 && pa->alive==PARS_ALIVE){
- switch(part->phystype){
- case PART_PHYS_NEWTON:
- /* do global forces & effectors */
- apply_particle_forces(p,pa,ob,psys,part,timestep,pa_dfra,cfra,key);
-
- /* deflection */
- deflect_particle(ob,psmd,psys,part,pa,p,pa_dfra,cfra,key,&pa_die);
-
- /* rotations */
- rotate_particle(part,pa,pa_dfra,timestep,key);
+ if(pa->alive == PARS_DYING){
+ push_reaction(ob,psys,p,PART_EVENT_DEATH,&pa->state);
- break;
- case PART_PHYS_BOIDS:
- {
- float acc[3];
- boid_brain(&bvf,pa,ob,psys,part,tree,timestep,cfra,acc,&pa_die);
- if(pa_die==0)
- boid_body(&bvf,pa,psys,part,timestep,acc,key);
- break;
- }
+ if(part->flag & PART_LOOP && part->type!=PART_HAIR){
+ pa->loop++;
+ reset_particle(pa,psys,psmd,ob,0.0,cfra,vg_vel,vg_tan,vg_rot);
+ pa->alive=PARS_ALIVE;
}
+ else{
+ pa->alive=PARS_DEAD;
+ pa->state.time=pa->dietime;
- push_reaction(ob,psys,p,PART_EVENT_NEAR,key);
-
- if(pa_die){
- push_reaction(ob,psys,p,PART_EVENT_DEATH,key);
-
- if(part->flag & PART_LOOP){
- pa->loop++;
-
- if(part->flag & PART_LOOP_INSTANT){
- reset_particle(pa,psys,psmd,ob,0.0,cfra,vg_vel,vg_tan,vg_rot);
- pa->alive=PARS_ALIVE;
- copy_particle_key(key,&pa->state,1);
- }
- else
- pa->alive=PARS_UNBORN;
- }
- else{
- pa->alive=PARS_DEAD;
- key->time=pa->dietime;
-
- if(pa->flag&PARS_STICKY)
- psys_key_to_object(pa->stick_ob,key,0);
- }
+ if(pa->flag&PARS_STICKY)
+ psys_key_to_object(pa->stick_ob,&pa->state,0);
}
- else
- key->time=cfra;
}
+ else
+ pa->state.time=cfra;
+
+ push_reaction(ob,psys,p,PART_EVENT_NEAR,&pa->state);
}
}
- /* apply outstates to particles */
- for(p=0, pa=psys->particles, key=outstate; p<totpart; p++,pa++,key++)
- copy_particle_key(&pa->state,key,1);
-
- MEM_freeN(outstate);
}
if(psys->reactevents.first)
BLI_freelistN(&psys->reactevents);
@@ -4196,9 +4123,8 @@ static void psys_update_path_cache(Object *ob, ParticleSystemModifierData *psmd,
ParticleSettings *part=psys->part;
ParticleEditSettings *pset=&G.scene->toolsettings->particle;
int distr=0,alloc=0;
- int child_nbr= (psys->renderdata)? part->ren_child_nbr: part->child_nbr;
- if((psys->part->childtype && psys->totchild != psys->totpart*child_nbr) || psys->recalc&PSYS_ALLOC)
+ if((psys->part->childtype && psys->totchild != get_psys_tot_child(psys)) || psys->recalc&PSYS_ALLOC)
alloc=1;
if(alloc || psys->recalc&PSYS_DISTR || (psys->vgroup[PSYS_VG_DENSITY] && (G.f & G_WEIGHTPAINT)))
@@ -4206,9 +4132,9 @@ static void psys_update_path_cache(Object *ob, ParticleSystemModifierData *psmd,
if(distr){
if(alloc)
- alloc_particles(ob,psys,psys->totpart);
+ realloc_particles(ob,psys,psys->totpart);
- if(get_alloc_child_particles_tot(psys)) {
+ if(get_psys_tot_child(psys)) {
/* don't generate children while computing the hair keys */
if(!(psys->part->type == PART_HAIR) || (psys->flag & PSYS_HAIR_DONE)) {
distribute_particles(ob,psys,PART_FROM_CHILD);
@@ -4220,13 +4146,14 @@ static void psys_update_path_cache(Object *ob, ParticleSystemModifierData *psmd,
}
if((part->type==PART_HAIR || psys->flag&PSYS_KEYED) && (psys_in_edit_mode(psys)
- || part->draw_as==PART_DRAW_PATH || part->draw&PART_DRAW_KEYS)){
+ || (part->type==PART_HAIR || part->draw_as==PART_DRAW_PATH))){
psys_cache_paths(ob, psys, cfra, 0);
/* for render, child particle paths are computed on the fly */
if(part->childtype) {
if(((psys->totchild!=0)) || (psys_in_edit_mode(psys) && (pset->flag&PE_SHOW_CHILD)))
- psys_cache_child_paths(ob, psys, cfra, 0);
+ if(!(psys->part->type == PART_HAIR) || (psys->flag & PSYS_HAIR_DONE))
+ psys_cache_child_paths(ob, psys, cfra, 0);
}
}
else if(psys->pathcache)
@@ -4236,17 +4163,27 @@ static void psys_update_path_cache(Object *ob, ParticleSystemModifierData *psmd,
static void hair_step(Object *ob, ParticleSystemModifierData *psmd, ParticleSystem *psys, float cfra)
{
ParticleSettings *part = psys->part;
+ ParticleData *pa;
+ int p;
+ float disp = (float)get_current_display_percentage(psys)/50.0f-1.0f;
+
+ for(p=0, pa=psys->particles; p<psys->totpart; p++,pa++){
+ if(pa->r_rot[0] > disp)
+ pa->flag |= PARS_NO_DISP;
+ else
+ pa->flag &= ~PARS_NO_DISP;
+ }
if(psys->recalc & PSYS_DISTR)
/* need this for changing subsurf levels */
- psys_calc_dmfaces(ob, psmd->dm, psys);
+ psys_calc_dmcache(ob, psmd->dm, psys);
if(psys->effectors.first)
psys_end_effectors(psys);
psys_init_effectors(ob,part->eff_group,psys);
if(psys->effectors.first)
- precalc_effectors(ob,psys,psmd);
+ precalc_effectors(ob,psys,psmd,cfra);
if(psys_in_edit_mode(psys))
; //XXX PE_recalc_world_cos(ob, psys);
@@ -4255,7 +4192,7 @@ static void hair_step(Object *ob, ParticleSystemModifierData *psmd, ParticleSyst
}
/* updates cached particles' alive & other flags etc..*/
-static void cached_step(Object *ob, ParticleSystemModifierData *psmd, ParticleSystem *psys, float cfra, float *vg_size)
+static void cached_step(Object *ob, ParticleSystemModifierData *psmd, ParticleSystem *psys, float cfra)
{
ParticleSettings *part=psys->part;
ParticleData *pa;
@@ -4263,34 +4200,10 @@ static void cached_step(Object *ob, ParticleSystemModifierData *psmd, ParticleSy
IpoCurve *icu_esize=find_ipocurve(part->ipo,PART_EMIT_SIZE);
Material *ma=give_current_material(ob,part->omat);
int p;
- float ipotime=cfra, disp;
-
- /* deprecated */
- //if(psys->recalc&PSYS_DISTR){
- // /* The dm could have been changed so particle emitter element */
- // /* indices might be wrong. There's really no "nice" way to handle*/
- // /* this so we just try not to crash by correcting indices. */
- // int totnum=-1;
- // switch(part->from){
- // case PART_FROM_VERT:
- // totnum=psmd->dm->getNumVerts(psmd->dm);
- // break;
- // case PART_FROM_FACE:
- // case PART_FROM_VOLUME:
- // totnum=psmd->dm->getNumFaces(psmd->dm);
- // break;
- // }
-
- // if(totnum==0){
- // /* Now we're in real trouble, there's no emitter elements!! */
- // for(p=0, pa=psys->particles; p<psys->totpart; p++,pa++)
- // pa->num=-1;
- // }
- // else if(totnum>0){
- // for(p=0, pa=psys->particles; p<psys->totpart; p++,pa++)
- // pa->num=pa->num%totnum;
- // }
- //}
+ float ipotime=cfra, disp, birthtime, dietime, *vg_size= NULL;
+
+ if(part->from!=PART_FROM_PARTICLE)
+ vg_size= psys_cache_vgroup(psmd->dm,psys,PSYS_VG_SIZE);
if(psys->effectors.first)
psys_end_effectors(psys);
@@ -4298,7 +4211,7 @@ static void cached_step(Object *ob, ParticleSystemModifierData *psmd, ParticleSy
//if(part->flag & (PART_BAKED_GUIDES+PART_BAKED_DEATHS)){
psys_init_effectors(ob,part->eff_group,psys);
if(psys->effectors.first)
- precalc_effectors(ob,psys,psmd);
+ precalc_effectors(ob,psys,psmd,cfra);
//}
disp= (float)get_current_display_percentage(psys)/50.0f-1.0f;
@@ -4313,22 +4226,30 @@ static void cached_step(Object *ob, ParticleSystemModifierData *psmd, ParticleSy
psys->lattice=psys_get_lattice(ob,psys);
+ if(part->flag & PART_LOOP && part->type!=PART_HAIR)
+ pa->loop = (short)((cfra - pa->time) / pa->lifetime);
+ else
+ pa->loop = 0;
+
+ birthtime = pa->time + pa->loop * pa->lifetime;
+ dietime = birthtime + (1 + pa->loop) * (pa->dietime - pa->time);
+
/* update alive status and push events */
- if(pa->time>cfra)
- pa->alive=PARS_UNBORN;
- else if(pa->dietime<=cfra){
- if(pa->dietime>psys->cfra){
- state.time=pa->dietime;
+ if(pa->time > cfra)
+ pa->alive = PARS_UNBORN;
+ else if(dietime <= cfra){
+ if(dietime > psys->cfra){
+ state.time = pa->dietime;
psys_get_particle_state(ob,psys,p,&state,1);
push_reaction(ob,psys,p,PART_EVENT_DEATH,&state);
}
- pa->alive=PARS_DEAD;
+ pa->alive = PARS_DEAD;
}
else{
- pa->alive=PARS_ALIVE;
- state.time=cfra;
+ pa->alive = PARS_ALIVE;
+ state.time = cfra;
psys_get_particle_state(ob,psys,p,&state,1);
- state.time=cfra;
+ state.time = cfra;
push_reaction(ob,psys,p,PART_EVENT_NEAR,&state);
}
@@ -4342,126 +4263,324 @@ static void cached_step(Object *ob, ParticleSystemModifierData *psmd, ParticleSy
else
pa->flag &= ~PARS_NO_DISP;
}
+
+ /* make sure that children are up to date */
+ if(psys->part->childtype && psys->totchild != get_psys_tot_child(psys)) {
+ realloc_particles(ob, psys, psys->totpart);
+ distribute_particles(ob, psys, PART_FROM_CHILD);
+ }
+
+ if(vg_size)
+ MEM_freeN(vg_size);
+}
+
+void psys_changed_type(ParticleSystem *psys)
+{
+ ParticleSettings *part;
+
+ part= psys->part;
+
+ /* system type has changed so set sensible defaults and clear non applicable flags */
+ if(part->from == PART_FROM_PARTICLE) {
+ if(part->type != PART_REACTOR)
+ part->from = PART_FROM_FACE;
+ if(part->distr == PART_DISTR_GRID && part->from != PART_FROM_VERT)
+ part->distr = PART_DISTR_JIT;
+ }
+
+ if(psys->part->phystype != PART_PHYS_KEYED)
+ psys->flag &= ~PSYS_KEYED;
+
+ if(part->type == PART_HAIR) {
+ part->draw_as = PART_DRAW_PATH;
+ part->rotfrom = PART_ROT_IINCR;
+ }
+ else {
+ free_hair(psys, 1);
+
+ if(part->draw_as == PART_DRAW_PATH)
+ if(psys->part->phystype != PART_PHYS_KEYED)
+ part->draw_as = PART_DRAW_DOT;
+ }
+
+ psys->softflag= 0;
+
+ psys_reset(psys, PSYS_RESET_ALL);
}
+
+static void particles_fluid_step(Object *ob, ParticleSystem *psys, int cfra)
+{
+ if(psys->particles){
+ MEM_freeN(psys->particles);
+ psys->particles = 0;
+ psys->totpart = 0;
+ }
+
+ /* fluid sim particle import handling, actual loading of particles from file */
+ #ifndef DISABLE_ELBEEM
+ {
+ FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
+
+ if( fluidmd && fluidmd->fss) {
+ FluidsimSettings *fss= fluidmd->fss;
+ ParticleSettings *part = psys->part;
+ ParticleData *pa=0;
+ char *suffix = "fluidsurface_particles_####";
+ char *suffix2 = ".gz";
+ char filename[256];
+ char debugStrBuffer[256];
+ int curFrame = G.scene->r.cfra -1; // warning - sync with derived mesh fsmesh loading
+ int p, j, numFileParts, totpart;
+ int readMask, activeParts = 0, fileParts = 0;
+ gzFile gzf;
+
+ if(ob==G.obedit) // off...
+ return;
+
+ // ok, start loading
+ strcpy(filename, fss->surfdataPath);
+ strcat(filename, suffix);
+ BLI_convertstringcode(filename, G.sce);
+ BLI_convertstringframe(filename, curFrame); // fixed #frame-no
+ strcat(filename, suffix2);
+
+ gzf = gzopen(filename, "rb");
+ if (!gzf) {
+ snprintf(debugStrBuffer,256,"readFsPartData::error - Unable to open file for reading '%s' \n", filename);
+ //elbeemDebugOut(debugStrBuffer);
+ return;
+ }
+
+ gzread(gzf, &totpart, sizeof(totpart));
+ numFileParts = totpart;
+ totpart = (G.rendering)?totpart:(part->disp*totpart)/100;
+
+ part->totpart= totpart;
+ part->sta=part->end = 1.0f;
+ part->lifetime = G.scene->r.efra + 1;
+
+ /* initialize particles */
+ realloc_particles(ob, psys, part->totpart);
+ initialize_all_particles(ob, psys, 0);
+
+ // set up reading mask
+ readMask = fss->typeFlags;
+
+ for(p=0, pa=psys->particles; p<totpart; p++, pa++) {
+ int ptype=0;
+
+ gzread(gzf, &ptype, sizeof( ptype ));
+ if(ptype&readMask) {
+ activeParts++;
+
+ gzread(gzf, &(pa->size), sizeof( float ));
+
+ pa->size /= 10.0f;
+
+ for(j=0; j<3; j++) {
+ float wrf;
+ gzread(gzf, &wrf, sizeof( wrf ));
+ pa->state.co[j] = wrf;
+ //fprintf(stderr,"Rj%d ",j);
+ }
+ for(j=0; j<3; j++) {
+ float wrf;
+ gzread(gzf, &wrf, sizeof( wrf ));
+ pa->state.vel[j] = wrf;
+ }
+
+ pa->state.ave[0] = pa->state.ave[1] = pa->state.ave[2] = 0.0f;
+ pa->state.rot[0] = 1.0;
+ pa->state.rot[1] = pa->state.rot[2] = pa->state.rot[3] = 0.0;
+
+ pa->alive = PARS_ALIVE;
+ //if(a<25) fprintf(stderr,"FSPARTICLE debug set %s , a%d = %f,%f,%f , life=%f \n", filename, a, pa->co[0],pa->co[1],pa->co[2], pa->lifetime );
+ } else {
+ // skip...
+ for(j=0; j<2*3+1; j++) {
+ float wrf; gzread(gzf, &wrf, sizeof( wrf ));
+ }
+ }
+ fileParts++;
+ }
+ gzclose( gzf );
+
+ totpart = psys->totpart = activeParts;
+ snprintf(debugStrBuffer,256,"readFsPartData::done - particles:%d, active:%d, file:%d, mask:%d \n", psys->totpart,activeParts,fileParts,readMask);
+ elbeemDebugOut(debugStrBuffer);
+ } // fluid sim particles done
+ }
+ #endif // DISABLE_ELBEEM
+}
+
/* Calculates the next state for all particles of the system */
/* In particles code most fra-ending are frames, time-ending are fra*timestep (seconds)*/
static void system_step(Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd, float cfra)
{
ParticleSettings *part;
ParticleData *pa;
- int totpart,oldtotpart=0,p;
- float disp, *vg_vel=0, *vg_tan=0, *vg_rot=0, *vg_size=0;
- int init=0,distr=0,alloc=0;
- int child_nbr;
+ PointCache *cache;
+ PTCacheID pid;
+ int totpart, oldtotpart, totchild, oldtotchild, p;
+ float disp, *vg_vel= 0, *vg_tan= 0, *vg_rot= 0, *vg_size= 0;
+ int init= 0, distr= 0, alloc= 0, usecache= 0, only_children_changed= 0;
+ int framenr, framedelta, startframe, endframe;
- /*----start validity checks----*/
+ part= psys->part;
+ cache= psys->pointcache;
- part=psys->part;
+ framenr= (int)CFRA;
+ framedelta= framenr - cache->simframe;
- if(part->flag&PART_ABS_TIME && part->ipo){
+ BKE_ptcache_id_from_particles(&pid, ob, psys);
+ BKE_ptcache_id_time(&pid, 0.0f, &startframe, &endframe, NULL);
+
+ /* update ipo's */
+ if((part->flag & PART_ABS_TIME) && part->ipo) {
calc_ipo(part->ipo, cfra);
execute_ipo((ID *)part, part->ipo);
}
- if(part->from!=PART_FROM_PARTICLE)
- vg_size=psys_cache_vgroup(psmd->dm,psys,PSYS_VG_SIZE);
+ /* hair if it's already done is handled separate */
+ if(part->type == PART_HAIR && (psys->flag & PSYS_HAIR_DONE)) {
+ hair_step(ob, psmd, psys, cfra);
+ psys->cfra = cfra;
+ psys->recalc = 0;
+ return;
+ }
+ /* fluid is also handled separate */
+ else if(part->type == PART_FLUID) {
+ particles_fluid_step(ob, psys, framenr);
+ psys->cfra = cfra;
+ psys->recalc = 0;
+ return;
+ }
- if(part->type == PART_HAIR) {
- if(psys->flag & PSYS_HAIR_DONE) {
- hair_step(ob, psmd, psys, cfra);
+ /* cache shouldn't be used for hair or "none" or "keyed" physics */
+ if(part->type == PART_HAIR || ELEM(part->phystype, PART_PHYS_NO, PART_PHYS_KEYED))
+ usecache= 0;
+ else if(BKE_ptcache_get_continue_physics())
+ usecache= 0;
+ else
+ usecache= 1;
+
+ if(usecache) {
+ /* frame clamping */
+ if(framenr < startframe) {
+ psys_reset(psys, PSYS_RESET_CACHE_MISS);
psys->cfra = cfra;
psys->recalc = 0;
return;
}
- }
- else {
- if(psys->recalc)
- clear_particles_from_cache(ob,psys,(int)cfra);
- else if(get_particles_from_cache(ob, psys, (int)cfra)){
- cached_step(ob,psmd,psys,cfra,vg_size);
- psys->cfra=cfra;
- psys->recalc = 0;
- return;
+ else if(framenr > endframe) {
+ framenr= endframe;
}
}
- /* if still here react to events */
+ /* verify if we need to reallocate */
+ oldtotpart = psys->totpart;
+ oldtotchild = psys->totchild;
- if(psys->recalc&PSYS_TYPE) {
- /* system type has changed so set sensible defaults and clear non applicable flags */
- if(part->from == PART_FROM_PARTICLE) {
- if(part->type != PART_REACTOR)
- part->from = PART_FROM_FACE;
- if(part->distr == PART_DISTR_GRID)
- part->distr = PART_DISTR_JIT;
- }
-
- if(psys->part->phystype != PART_PHYS_KEYED)
- psys->flag &= ~PSYS_KEYED;
-
- if(part->type == PART_HAIR) {
- part->draw_as = PART_DRAW_PATH;
- part->rotfrom = PART_ROT_IINCR;
- }
- else
- free_hair(psys);
-
- psys->recalc &= ~PSYS_TYPE;
- alloc = 1;
-
- /* this is a bad level call, but currently type change
- * can happen after redraw, so force redraw from here */
-// XXX allqueue(REDRAWBUTSOBJECT, 0);
- }
- else
- oldtotpart = psys->totpart;
-
- if(part->distr == PART_DISTR_GRID)
- totpart = part->grid_res * part->grid_res * part->grid_res;
+ if(part->distr == PART_DISTR_GRID && part->from != PART_FROM_VERT)
+ totpart = part->grid_res*part->grid_res*part->grid_res;
else
totpart = psys->part->totpart;
+ totchild = get_psys_tot_child(psys);
- child_nbr= (psys->renderdata)? part->ren_child_nbr: part->child_nbr;
- if(oldtotpart != totpart || psys->recalc&PSYS_ALLOC || (psys->part->childtype && psys->totchild != psys->totpart*child_nbr))
+ if(oldtotpart != totpart || (psys->part->childtype && oldtotchild != totchild)) {
+ only_children_changed = (oldtotpart == totpart);
+ realloc_particles(ob, psys, totpart);
alloc = 1;
+ distr= 1;
+ init= 1;
+ }
- /* bad context? XXX */
- if(alloc || psys->recalc&PSYS_DISTR || (psys->vgroup[PSYS_VG_DENSITY] && (G.f & G_WEIGHTPAINT) && ob==(G.scene->basact?G.scene->basact->object:NULL)))
- distr = 1;
-
- if(distr || psys->recalc&PSYS_INIT)
- init = 1;
+ if(psys->recalc & PSYS_DISTR) {
+ distr= 1;
+ init= 1;
+ }
if(init) {
if(distr) {
if(alloc)
- alloc_particles(ob, psys, totpart);
+ realloc_particles(ob, psys, totpart);
distribute_particles(ob, psys, part->from);
- if(get_alloc_child_particles_tot(psys))
+ if((psys->part->type == PART_HAIR) && !(psys->flag & PSYS_HAIR_DONE))
+ /* don't generate children while growing hair - waste of time */
+ psys_free_children(psys);
+ else if(get_psys_tot_child(psys))
distribute_particles(ob, psys, PART_FROM_CHILD);
}
- initialize_all_particles(ob, psys, psmd);
- if(alloc)
- reset_all_particles(ob, psys, psmd, 0.0, cfra, oldtotpart);
+ if(only_children_changed==0) {
+ initialize_all_particles(ob, psys, psmd);
+
+ if(alloc)
+ reset_all_particles(ob, psys, psmd, 0.0, cfra, oldtotpart);
+ }
/* flag for possible explode modifiers after this system */
psmd->flag |= eParticleSystemFlag_Pars;
}
+ /* try to read from the cache */
+ if(usecache) {
+ if(get_particles_from_cache(ob, psys, framenr)) {
+ if(part->phystype==PART_PHYS_KEYED && psys->flag&PSYS_FIRST_KEYED) {
+ psys_count_keyed_targets(ob,psys);
+ set_keyed_keys(ob, psys);
+ }
+
+ cached_step(ob,psmd,psys,cfra);
+ psys->cfra=cfra;
+ psys->recalc = 0;
+
+ if(part->phystype==PART_PHYS_KEYED && psys->flag&PSYS_FIRST_KEYED) {
+ psys_update_path_cache(ob,psmd,psys,framenr);
+ }
+
+ cache->simframe= framenr;
+ cache->flag |= PTCACHE_SIMULATION_VALID;
+
+ return;
+ }
+ else if(ob->id.lib || (cache->flag & PTCACHE_BAKED)) {
+ psys_reset(psys, PSYS_RESET_CACHE_MISS);
+ psys->cfra=cfra;
+ psys->recalc = 0;
+ return;
+ }
+
+ if(framenr != startframe && framedelta != 1) {
+ psys_reset(psys, PSYS_RESET_CACHE_MISS);
+ psys->cfra = cfra;
+ psys->recalc = 0;
+ return;
+ }
+ }
+ else {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ }
+
+ /* if on second frame, write cache for first frame */
+ if(usecache && framenr == startframe+1)
+ write_particles_to_cache(ob, psys, startframe);
if(part->phystype==PART_PHYS_KEYED && psys->flag&PSYS_FIRST_KEYED)
psys_count_keyed_targets(ob,psys);
- if(part->from!=PART_FROM_PARTICLE){
- vg_vel=psys_cache_vgroup(psmd->dm,psys,PSYS_VG_VEL);
- vg_tan=psys_cache_vgroup(psmd->dm,psys,PSYS_VG_TAN);
- vg_rot=psys_cache_vgroup(psmd->dm,psys,PSYS_VG_ROT);
+ /* initialize vertex groups */
+ if(part->from!=PART_FROM_PARTICLE) {
+ vg_vel= psys_cache_vgroup(psmd->dm,psys,PSYS_VG_VEL);
+ vg_tan= psys_cache_vgroup(psmd->dm,psys,PSYS_VG_TAN);
+ vg_rot= psys_cache_vgroup(psmd->dm,psys,PSYS_VG_ROT);
+ vg_size= psys_cache_vgroup(psmd->dm,psys,PSYS_VG_SIZE);
}
- /* set particles to be not calculated */
+ /* set particles to be not calculated TODO: can't work with pointcache */
disp= (float)get_current_display_percentage(psys)/50.0f-1.0f;
for(p=0, pa=psys->particles; p<totpart; p++,pa++){
@@ -4471,15 +4590,30 @@ static void system_step(Object *ob, ParticleSystem *psys, ParticleSystemModifier
pa->flag &= ~PARS_NO_DISP;
}
- /* ok now we're all set so let's go */
- if(psys->totpart)
- dynamics_step(ob,psys,psmd,cfra,vg_vel,vg_tan,vg_rot,vg_size);
+ if(psys->totpart) {
+ int dframe, totframesback = 0;
+
+ /* handle negative frame start at the first frame by doing
+ * all the steps before the first frame */
+ if(framenr == startframe && part->sta < startframe)
+ totframesback = (startframe - (int)part->sta);
+
+ for(dframe=-totframesback; dframe<=0; dframe++) {
+ /* ok now we're all set so let's go */
+ dynamics_step(ob,psys,psmd,cfra+dframe,vg_vel,vg_tan,vg_rot,vg_size);
+ psys->cfra = cfra+dframe;
+ }
+ }
+
+ cache->simframe= framenr;
+ cache->flag |= PTCACHE_SIMULATION_VALID;
psys->recalc = 0;
- psys->cfra=cfra;
+ psys->cfra = cfra;
- if(part->type!=PART_HAIR)
- write_particles_to_cache(ob, psys, cfra);
+ /* only write cache starting from second frame */
+ if(usecache && framenr != startframe)
+ write_particles_to_cache(ob, psys, framenr);
/* for keyed particles the path is allways known so it can be drawn */
if(part->phystype==PART_PHYS_KEYED && psys->flag&PSYS_FIRST_KEYED){
@@ -4489,8 +4623,11 @@ static void system_step(Object *ob, ParticleSystem *psys, ParticleSystemModifier
else if(psys->pathcache)
psys_free_path_cache(psys);
- if(vg_vel)
- MEM_freeN(vg_vel);
+ /* cleanup */
+ if(vg_vel) MEM_freeN(vg_vel);
+ if(vg_tan) MEM_freeN(vg_tan);
+ if(vg_rot) MEM_freeN(vg_rot);
+ if(vg_size) MEM_freeN(vg_size);
if(psys->lattice){
end_latt_deform();
@@ -4498,105 +4635,97 @@ static void system_step(Object *ob, ParticleSystem *psys, ParticleSystemModifier
}
}
-void psys_to_softbody(Object *ob, ParticleSystem *psys, int force_recalc)
+static void psys_to_softbody(Object *ob, ParticleSystem *psys)
{
SoftBody *sb;
short softflag;
- if((psys->softflag&OB_SB_ENABLE)==0) return;
-
- if(psys->recalc || force_recalc)
- psys->softflag|=OB_SB_REDO;
+ if(!(psys->softflag & OB_SB_ENABLE))
+ return;
/* let's replace the object's own softbody with the particle softbody */
/* a temporary solution before cloth simulation is implemented, jahka */
/* save these */
- sb=ob->soft;
- softflag=ob->softflag;
+ sb= ob->soft;
+ softflag= ob->softflag;
/* swich to new ones */
- ob->soft=psys->soft;
- ob->softflag=psys->softflag;
+ ob->soft= psys->soft;
+ ob->softflag= psys->softflag;
/* do softbody */
sbObjectStep(ob, (float)G.scene->r.cfra, NULL, psys_count_keys(psys));
/* return things back to normal */
- psys->soft=ob->soft;
- psys->softflag=ob->softflag;
+ psys->soft= ob->soft;
+ psys->softflag= ob->softflag;
- ob->soft=sb;
- ob->softflag=softflag;
+ ob->soft= sb;
+ ob->softflag= softflag;
}
+
static int hair_needs_recalc(ParticleSystem *psys)
{
- if((psys->flag & PSYS_EDITED)==0 && (
- (psys->flag & PSYS_HAIR_DONE)==0
- || psys->recalc & PSYS_RECALC_HAIR)
- ) {
+ if((psys->flag & PSYS_EDITED)==0 &&
+ ((psys->flag & PSYS_HAIR_DONE)==0 || psys->recalc & PSYS_RECALC_HAIR)) {
psys->recalc &= ~PSYS_RECALC_HAIR;
return 1;
}
return 0;
}
-/* main particle update call, checks that things are ok on the large scale before actual particle calculations */
-void particle_system_update(Object *ob, ParticleSystem *psys){
- ParticleSystemModifierData *psmd=0;
+/* main particle update call, checks that things are ok on the large scale before actual particle calculations */
+void particle_system_update(Object *ob, ParticleSystem *psys)
+{
+ ParticleSystemModifierData *psmd;
float cfra;
if(!psys_check_enabled(ob, psys))
return;
- cfra=bsystem_time(ob,(float)G.scene->r.cfra,0.0);
+ cfra= bsystem_time(ob, (float)G.scene->r.cfra, 0.0f);
psmd= psys_get_modifier(ob, psys);
/* system was already updated from modifier stack */
- if(psmd->flag&eParticleSystemFlag_psys_updated) {
+ if(psmd->flag & eParticleSystemFlag_psys_updated) {
psmd->flag &= ~eParticleSystemFlag_psys_updated;
/* make sure it really was updated to cfra */
- if(psys->cfra==cfra)
+ if(psys->cfra == cfra)
return;
}
if(!psmd->dm)
return;
- /* baked path softbody */
- if(psys->part->type==PART_HAIR && psys->soft)
- psys_to_softbody(ob, psys, 0);
-
- /* not needed, this is all handled in hair_step */
- ///* is the mesh changing under the edited particles? */
- //if((psys->flag & PSYS_EDITED) && psys->part->type==PART_HAIR && psys->recalc & PSYS_RECALC_HAIR) {
- // /* Just update the particles on the mesh */
- // psys_update_edithair_dmfaces(ob, psmd->dm, psys);
- //}
-
- if(psys->part->type==PART_HAIR && hair_needs_recalc(psys)){
+ /* (re-)create hair */
+ if(psys->part->type==PART_HAIR && hair_needs_recalc(psys)) {
float hcfra=0.0f;
int i;
- free_hair(psys);
+
+ free_hair(psys, 0);
/* first step is negative so particles get killed and reset */
- psys->cfra=1.0f;
+ psys->cfra= 1.0f;
for(i=0; i<=psys->part->hair_step; i++){
hcfra=100.0f*(float)i/(float)psys->part->hair_step;
- system_step(ob,psys,psmd,hcfra);
- save_hair(ob,psys,psmd,hcfra);
+ system_step(ob, psys, psmd, hcfra);
+ save_hair(ob, psys, psmd, hcfra);
}
psys->flag |= PSYS_HAIR_DONE;
-
- if(psys->softflag&OB_SB_ENABLE)
- psys_to_softbody(ob,psys,1);
}
- system_step(ob,psys,psmd,cfra);
+ /* handle softbody hair */
+ if(psys->part->type==PART_HAIR && psys->soft)
+ psys_to_softbody(ob, psys);
+
+ /* the main particle system step */
+ system_step(ob, psys, psmd, cfra);
- Mat4Invert(psys->imat, ob->obmat); /* used for duplicators */
+ /* save matrix for duplicators */
+ Mat4Invert(psys->imat, ob->obmat);
}
diff --git a/source/blender/blenkernel/intern/pointcache.c b/source/blender/blenkernel/intern/pointcache.c
index 6da13cf4021..596ac882d24 100644
--- a/source/blender/blenkernel/intern/pointcache.c
+++ b/source/blender/blenkernel/intern/pointcache.c
@@ -24,22 +24,37 @@
* ***** END GPL LICENSE BLOCK *****
*/
-
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
-#include "BKE_pointcache.h"
+#include "MEM_guardedalloc.h"
-#include "BKE_utildefines.h"
-#include "BKE_global.h"
-#include "BKE_library.h"
+#include "DNA_ID.h"
+#include "DNA_cloth_types.h"
+#include "DNA_modifier_types.h"
+#include "DNA_object_types.h"
+#include "DNA_object_force.h"
+#include "DNA_particle_types.h"
+#include "DNA_scene_types.h"
#include "BLI_blenlib.h"
+
+#include "BKE_cloth.h"
+#include "BKE_depsgraph.h"
+#include "BKE_global.h"
+#include "BKE_library.h"
+#include "BKE_main.h"
+#include "BKE_modifier.h"
+#include "BKE_object.h"
+#include "BKE_particle.h"
+#include "BKE_pointcache.h"
+#include "BKE_softbody.h"
#include "BKE_utildefines.h"
+
/* needed for directory lookup */
#ifndef WIN32
#include <dirent.h>
@@ -47,30 +62,150 @@
#include "BLI_winstuff.h"
#endif
+/* untitled blend's need getpid for a unique name */
+#ifdef WIN32
+#include <process.h>
+#else
+#include <unistd.h>
+#endif
+
+#ifdef _WIN32
+#ifndef snprintf
+#define snprintf _snprintf
+#endif
+#endif
+
+/* Creating ID's */
+
+void BKE_ptcache_id_from_softbody(PTCacheID *pid, Object *ob, SoftBody *sb)
+{
+ ParticleSystemModifierData *psmd;
+ ModifierData *md;
+ int a;
+
+ memset(pid, 0, sizeof(PTCacheID));
+
+ pid->ob= ob;
+ pid->data= sb;
+ pid->type= PTCACHE_TYPE_SOFTBODY;
+ pid->cache= sb->pointcache;
+
+ if(sb->particles) {
+ psmd= psys_get_modifier(ob, sb->particles);
+ pid->stack_index= modifiers_indexInObject(ob, (ModifierData*)psmd);
+ }
+ else {
+ for(a=0, md=ob->modifiers.first; md; md=md->next, a++) {
+ if(md->type == eModifierType_Softbody) {
+ pid->stack_index = a;
+ break;
+ }
+ }
+ }
+}
+
+void BKE_ptcache_id_from_particles(PTCacheID *pid, Object *ob, ParticleSystem *psys)
+{
+ ParticleSystemModifierData *psmd= psys_get_modifier(ob, psys);
+
+ memset(pid, 0, sizeof(PTCacheID));
+
+ pid->ob= ob;
+ pid->data= psys;
+ pid->type= PTCACHE_TYPE_PARTICLES;
+ pid->stack_index= modifiers_indexInObject(ob, (ModifierData *)psmd);
+ pid->cache= psys->pointcache;
+}
+
+void BKE_ptcache_id_from_cloth(PTCacheID *pid, Object *ob, ClothModifierData *clmd)
+{
+ memset(pid, 0, sizeof(PTCacheID));
+
+ pid->ob= ob;
+ pid->data= clmd;
+ pid->type= PTCACHE_TYPE_CLOTH;
+ pid->stack_index= modifiers_indexInObject(ob, (ModifierData *)clmd);
+ pid->cache= clmd->point_cache;
+}
+
+void BKE_ptcache_ids_from_object(ListBase *lb, Object *ob)
+{
+ PTCacheID *pid;
+ ParticleSystem *psys;
+ ModifierData *md;
+
+ lb->first= lb->last= NULL;
+
+ if(ob->soft) {
+ pid= MEM_callocN(sizeof(PTCacheID), "PTCacheID");
+ BKE_ptcache_id_from_softbody(pid, ob, ob->soft);
+ BLI_addtail(lb, pid);
+ }
+
+ for(psys=ob->particlesystem.first; psys; psys=psys->next) {
+ pid= MEM_callocN(sizeof(PTCacheID), "PTCacheID");
+ BKE_ptcache_id_from_particles(pid, ob, psys);
+ BLI_addtail(lb, pid);
+
+ if(psys->soft) {
+ pid= MEM_callocN(sizeof(PTCacheID), "PTCacheID");
+ BKE_ptcache_id_from_softbody(pid, ob, psys->soft);
+ BLI_addtail(lb, pid);
+ }
+ }
+
+ for(md=ob->modifiers.first; md; md=md->next) {
+ if(md->type == eModifierType_Cloth) {
+ pid= MEM_callocN(sizeof(PTCacheID), "PTCacheID");
+ BKE_ptcache_id_from_cloth(pid, ob, (ClothModifierData*)md);
+ BLI_addtail(lb, pid);
+ }
+ }
+}
+
/* Takes an Object ID and returns a unique name
- id: object id
- cfra: frame for the cache, can be negative
- stack_index: index in the modifier stack. we can have cache for more then one stack_index
*/
-static int ptcache_path(char *filename)
+#define MAX_PTCACHE_PATH FILE_MAX
+#define MAX_PTCACHE_FILE ((FILE_MAXDIR+FILE_MAXFILE)*2)
+
+static int ptcache_path(PTCacheID *pid, char *filename)
{
- char dir[FILE_MAX], file[FILE_MAX]; /* we dont want the dir, only the file */
+ Library *lib;
int i;
+
+ lib= (pid)? pid->ob->id.lib: NULL;
+
+ if (G.relbase_valid || lib) {
+ char file[MAX_PTCACHE_PATH]; /* we dont want the dir, only the file */
+ char *blendfilename;
+
+ blendfilename= (lib)? lib->filename: G.sce;
+
+ BLI_split_dirfile_basic(blendfilename, NULL, file);
+ i = strlen(file);
+
+ /* remove .blend */
+ if (i > 6)
+ file[i-6] = '\0';
+
+ snprintf(filename, MAX_PTCACHE_PATH, "//"PTCACHE_PATH"%s", file); /* add blend file name to pointcache dir */
+ BLI_convertstringcode(filename, blendfilename);
+ BLI_add_slash(filename);
+ return strlen(filename);
+ }
- BLI_split_dirfile(G.sce, dir, file);
- i = strlen(file);
-
- /* remove .blend */
- if (i > 6)
- file[i-6] = '\0';
-
- sprintf(filename, PTCACHE_PATH"%s/", file); /* add blend file name to pointcache dir */
- BLI_convertstringcode(filename, G.sce, 0);
+ /* use the temp path. this is weak but better then not using point cache at all */
+ /* btempdir is assumed to exist and ALWAYS has a trailing slash */
+ snprintf(filename, MAX_PTCACHE_PATH, "%s"PTCACHE_PATH"%d", btempdir, abs(getpid()));
+ BLI_add_slash(filename);
return strlen(filename);
}
-int BKE_ptcache_id_filename(struct ID *id, char *filename, int cfra, int stack_index, short do_path, short do_ext)
+static int BKE_ptcache_id_filename(PTCacheID *pid, char *filename, int cfra, short do_path, short do_ext)
{
int len=0;
char *idname;
@@ -78,23 +213,23 @@ int BKE_ptcache_id_filename(struct ID *id, char *filename, int cfra, int stack_i
filename[0] = '\0';
newname = filename;
- if (!G.relbase_valid) return 0; /* save blend fiel before using pointcache */
+ /*if (!G.relbase_valid) return 0; *//* save blend file before using pointcache */
/* start with temp dir */
if (do_path) {
- len = ptcache_path(filename);
+ len = ptcache_path(pid, filename);
newname += len;
}
- idname = (id->name+2);
+ idname = (pid->ob->id.name+2);
/* convert chars to hex so they are always a valid filename */
while('\0' != *idname) {
- sprintf(newname, "%02X", (char)(*idname++));
+ snprintf(newname, MAX_PTCACHE_FILE, "%02X", (char)(*idname++));
newname+=2;
len += 2;
}
if (do_ext) {
- sprintf(newname, "_%06d_%02d"PTCACHE_EXT, cfra, stack_index); /* always 6 chars */
+ snprintf(newname, MAX_PTCACHE_FILE, "_%06d_%02d"PTCACHE_EXT, cfra, pid->stack_index); /* always 6 chars */
len += 16;
}
@@ -102,65 +237,98 @@ int BKE_ptcache_id_filename(struct ID *id, char *filename, int cfra, int stack_i
}
/* youll need to close yourself after! */
-FILE *BKE_ptcache_id_fopen(struct ID *id, char mode, int cfra, int stack_index)
+PTCacheFile *BKE_ptcache_file_open(PTCacheID *pid, int mode, int cfra)
{
- /* mode is same as fopen's modes */
+ PTCacheFile *pf;
FILE *fp = NULL;
char filename[(FILE_MAXDIR+FILE_MAXFILE)*2];
- if (!G.relbase_valid) return NULL; /* save blend fiel before using pointcache */
+ /* don't allow writing for linked objects */
+ if(pid->ob->id.lib && mode == PTCACHE_FILE_WRITE)
+ return NULL;
+
+ /*if (!G.relbase_valid) return NULL; *//* save blend file before using pointcache */
- BKE_ptcache_id_filename(id, filename, cfra, stack_index, 1, 1);
+ BKE_ptcache_id_filename(pid, filename, cfra, 1, 1);
- if (mode=='r') {
+ if (mode==PTCACHE_FILE_READ) {
if (!BLI_exists(filename)) {
return NULL;
}
fp = fopen(filename, "rb");
- } else if (mode=='w') {
+ } else if (mode==PTCACHE_FILE_WRITE) {
BLI_make_existing_file(filename); /* will create the dir if needs be, same as //textures is created */
fp = fopen(filename, "wb");
}
- if (!fp) {
+ if (!fp)
return NULL;
- }
+
+ pf= MEM_mallocN(sizeof(PTCacheFile), "PTCacheFile");
+ pf->fp= fp;
- return fp;
+ return pf;
+}
+
+void BKE_ptcache_file_close(PTCacheFile *pf)
+{
+ fclose(pf->fp);
+ MEM_freeN(pf);
+}
+
+int BKE_ptcache_file_read_floats(PTCacheFile *pf, float *f, int tot)
+{
+ return (fread(f, sizeof(float), tot, pf->fp) == tot);
+}
+
+int BKE_ptcache_file_write_floats(PTCacheFile *pf, float *f, int tot)
+{
+ return (fwrite(f, sizeof(float), tot, pf->fp) == tot);
}
/* youll need to close yourself after!
- * mode,
+ * mode - PTCACHE_CLEAR_ALL,
*/
-void BKE_ptcache_id_clear(struct ID *id, char mode, int cfra, int stack_index)
+void BKE_ptcache_id_clear(PTCacheID *pid, int mode, int cfra)
{
int len; /* store the length of the string */
/* mode is same as fopen's modes */
DIR *dir;
struct dirent *de;
- char path[FILE_MAX];
- char filename[(FILE_MAXDIR+FILE_MAXFILE)*2];
- char path_full[(FILE_MAXDIR+FILE_MAXFILE)*2];
-
- if (!G.relbase_valid) return; /* save blend fiel before using pointcache */
+ char path[MAX_PTCACHE_PATH];
+ char filename[MAX_PTCACHE_FILE];
+ char path_full[MAX_PTCACHE_FILE];
+ char ext[MAX_PTCACHE_PATH];
+
+ if(!pid->cache)
+ return;
+
+ /* don't allow clearing for linked objects */
+ if(pid->ob->id.lib)
+ return;
+
+ /*if (!G.relbase_valid) return; *//* save blend file before using pointcache */
/* clear all files in the temp dir with the prefix of the ID and the ".bphys" suffix */
switch (mode) {
case PTCACHE_CLEAR_ALL:
case PTCACHE_CLEAR_BEFORE:
case PTCACHE_CLEAR_AFTER:
- ptcache_path(path);
- len = BKE_ptcache_id_filename(id, filename, cfra, stack_index, 0, 0); /* no path */
+ ptcache_path(pid, path);
+
+ len = BKE_ptcache_id_filename(pid, filename, cfra, 0, 0); /* no path */
dir = opendir(path);
if (dir==NULL)
return;
+
+ snprintf(ext, sizeof(ext), "_%02d"PTCACHE_EXT, pid->stack_index);
while ((de = readdir(dir)) != NULL) {
- if (strstr(de->d_name, PTCACHE_EXT)) { /* do we have the right extension?*/
+ if (strstr(de->d_name, ext)) { /* do we have the right extension?*/
if (strncmp(filename, de->d_name, len ) == 0) { /* do we have the right prefix */
if (mode == PTCACHE_CLEAR_ALL) {
BLI_join_dirfile(path_full, path, de->d_name);
@@ -169,8 +337,9 @@ void BKE_ptcache_id_clear(struct ID *id, char mode, int cfra, int stack_index)
/* read the number of the file */
int frame, len2 = strlen(de->d_name);
char num[7];
+
if (len2 > 15) { /* could crash if trying to copy a string out of this range*/
- strncpy(num, de->d_name + (strlen(de->d_name) - 15), 6);
+ BLI_strncpy(num, de->d_name + (strlen(de->d_name) - 15), sizeof(num));
frame = atoi(num);
if((mode==PTCACHE_CLEAR_BEFORE && frame < cfra) ||
@@ -188,18 +357,248 @@ void BKE_ptcache_id_clear(struct ID *id, char mode, int cfra, int stack_index)
break;
case PTCACHE_CLEAR_FRAME:
- len = BKE_ptcache_id_filename(id, filename, cfra, stack_index, 1, 1); /* no path */
+ len = BKE_ptcache_id_filename(pid, filename, cfra, 1, 1); /* no path */
BLI_delete(filename, 0, 0);
break;
}
- return;
}
-int BKE_ptcache_id_exist(struct ID *id, int cfra, int stack_index)
+int BKE_ptcache_id_exist(PTCacheID *pid, int cfra)
{
- char filename[(FILE_MAXDIR+FILE_MAXFILE)*2];
+ char filename[MAX_PTCACHE_FILE];
+
+ if(!pid->cache)
+ return 0;
- BKE_ptcache_id_filename(id, filename, cfra, stack_index, 1, 1);
+ BKE_ptcache_id_filename(pid, filename, cfra, 1, 1);
return BLI_exists(filename);
}
+
+void BKE_ptcache_id_time(PTCacheID *pid, float cfra, int *startframe, int *endframe, float *timescale)
+{
+ Object *ob;
+ PointCache *cache;
+ float offset, time, nexttime;
+
+ /* time handling for point cache:
+ * - simulation time is scaled by result of bsystem_time
+ * - for offsetting time only time offset is taken into account, since
+ * that's always the same and can't be animated. a timeoffset which
+ * varies over time is not simpe to support.
+ * - field and motion blur offsets are currently ignored, proper solution
+ * is probably to interpolate results from two frames for that ..
+ */
+
+ ob= pid->ob;
+ cache= pid->cache;
+
+ if(timescale) {
+ time= bsystem_time(ob, cfra, 0.0f);
+ nexttime= bsystem_time(ob, cfra+1.0f, 0.0f);
+
+ *timescale= MAX2(nexttime - time, 0.0f);
+ }
+
+ if(startframe && endframe) {
+ *startframe= cache->startframe;
+ *endframe= cache->endframe;
+
+ if ((ob->ipoflag & OB_OFFS_PARENT) && (ob->partype & PARSLOW)==0) {
+ offset= give_timeoffset(ob);
+
+ *startframe += (int)(offset+0.5f);
+ *endframe += (int)(offset+0.5f);
+ }
+ }
+}
+
+int BKE_ptcache_id_reset(PTCacheID *pid, int mode)
+{
+ PointCache *cache;
+ int reset, clear;
+
+ if(!pid->cache)
+ return 0;
+
+ cache= pid->cache;
+ reset= 0;
+ clear= 0;
+
+ if(mode == PTCACHE_RESET_DEPSGRAPH) {
+ if(!(cache->flag & PTCACHE_BAKED) && !BKE_ptcache_get_continue_physics()) {
+ reset= 1;
+ clear= 1;
+ }
+ else
+ cache->flag |= PTCACHE_OUTDATED;
+ }
+ else if(mode == PTCACHE_RESET_BAKED) {
+ if(!BKE_ptcache_get_continue_physics()) {
+ reset= 1;
+ clear= 1;
+ }
+ else
+ cache->flag |= PTCACHE_OUTDATED;
+ }
+ else if(mode == PTCACHE_RESET_OUTDATED) {
+ reset = 1;
+
+ if(cache->flag & PTCACHE_OUTDATED)
+ if(!(cache->flag & PTCACHE_BAKED))
+ clear= 1;
+ }
+
+ if(reset) {
+ cache->flag &= ~(PTCACHE_OUTDATED|PTCACHE_SIMULATION_VALID);
+ cache->simframe= 0;
+
+ if(pid->type == PTCACHE_TYPE_CLOTH)
+ cloth_free_modifier(pid->ob, pid->data);
+ else if(pid->type == PTCACHE_TYPE_SOFTBODY)
+ sbFreeSimulation(pid->data);
+ else if(pid->type == PTCACHE_TYPE_PARTICLES)
+ psys_reset(pid->data, PSYS_RESET_DEPSGRAPH);
+ }
+ if(clear)
+ BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0);
+
+ return (reset || clear);
+}
+
+int BKE_ptcache_object_reset(Object *ob, int mode)
+{
+ PTCacheID pid;
+ ParticleSystem *psys;
+ ModifierData *md;
+ int reset, skip;
+
+ reset= 0;
+ skip= 0;
+
+ if(ob->soft) {
+ BKE_ptcache_id_from_softbody(&pid, ob, ob->soft);
+ reset |= BKE_ptcache_id_reset(&pid, mode);
+ }
+
+ for(psys=ob->particlesystem.first; psys; psys=psys->next) {
+ /* Baked softbody hair has to be checked first, because we don't want to reset */
+ /* particles or softbody in that case -jahka */
+ if(psys->soft) {
+ BKE_ptcache_id_from_softbody(&pid, ob, psys->soft);
+ if(mode == PSYS_RESET_ALL || !(psys->part->type == PART_HAIR && (pid.cache->flag & PTCACHE_BAKED)))
+ reset |= BKE_ptcache_id_reset(&pid, mode);
+ else
+ skip = 1;
+ }
+
+ if(skip == 0) {
+ BKE_ptcache_id_from_particles(&pid, ob, psys);
+ reset |= BKE_ptcache_id_reset(&pid, mode);
+ }
+ }
+
+ for(md=ob->modifiers.first; md; md=md->next) {
+ if(md->type == eModifierType_Cloth) {
+ BKE_ptcache_id_from_cloth(&pid, ob, (ClothModifierData*)md);
+ reset |= BKE_ptcache_id_reset(&pid, mode);
+ }
+ }
+
+ return reset;
+}
+
+/* Use this when quitting blender, with unsaved files */
+void BKE_ptcache_remove(void)
+{
+ char path[MAX_PTCACHE_PATH];
+ char path_full[MAX_PTCACHE_PATH];
+ int rmdir = 1;
+
+ ptcache_path(NULL, path);
+
+ if (BLI_exist(path)) {
+ /* The pointcache dir exists? - remove all pointcache */
+
+ DIR *dir;
+ struct dirent *de;
+
+ dir = opendir(path);
+ if (dir==NULL)
+ return;
+
+ while ((de = readdir(dir)) != NULL) {
+ if( strcmp(de->d_name, ".")==0 || strcmp(de->d_name, "..")==0) {
+ /* do nothing */
+ } else if (strstr(de->d_name, PTCACHE_EXT)) { /* do we have the right extension?*/
+ BLI_join_dirfile(path_full, path, de->d_name);
+ BLI_delete(path_full, 0, 0);
+ } else {
+ rmdir = 0; /* unknown file, dont remove the dir */
+ }
+ }
+
+ closedir(dir);
+ } else {
+ rmdir = 0; /* path dosnt exist */
+ }
+
+ if (rmdir) {
+ BLI_delete(path, 1, 0);
+ }
+}
+
+/* Continuous Interaction */
+
+static int CONTINUE_PHYSICS = 0;
+
+void BKE_ptcache_set_continue_physics(int enable)
+{
+ Object *ob;
+
+ if(CONTINUE_PHYSICS != enable) {
+ CONTINUE_PHYSICS = enable;
+
+ if(CONTINUE_PHYSICS == 0) {
+ for(ob=G.main->object.first; ob; ob=ob->id.next)
+ if(BKE_ptcache_object_reset(ob, PTCACHE_RESET_OUTDATED))
+ DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
+ }
+ }
+}
+
+int BKE_ptcache_get_continue_physics()
+{
+ return CONTINUE_PHYSICS;
+}
+
+/* Point Cache */
+
+PointCache *BKE_ptcache_add()
+{
+ PointCache *cache;
+
+ cache= MEM_callocN(sizeof(PointCache), "PointCache");
+ cache->startframe= 1;
+ cache->endframe= 250;
+
+ return cache;
+}
+
+void BKE_ptcache_free(PointCache *cache)
+{
+ MEM_freeN(cache);
+}
+
+PointCache *BKE_ptcache_copy(PointCache *cache)
+{
+ PointCache *ncache;
+
+ ncache= MEM_dupallocN(cache);
+
+ ncache->flag= 0;
+ ncache->simframe= 0;
+
+ return ncache;
+}
+
diff --git a/source/blender/blenkernel/intern/property.c b/source/blender/blenkernel/intern/property.c
index b86efb97fc5..509cd8cf750 100644
--- a/source/blender/blenkernel/intern/property.c
+++ b/source/blender/blenkernel/intern/property.c
@@ -81,8 +81,7 @@ bProperty *copy_property(bProperty *prop)
void copy_properties(ListBase *lbn, ListBase *lbo)
{
bProperty *prop, *propn;
-
- lbn->first= lbn->last= 0;
+ free_properties( lbn ); /* incase we are copying to an object with props */
prop= lbo->first;
while(prop) {
propn= copy_property(prop);
@@ -137,7 +136,7 @@ bProperty *new_property(int type)
return prop;
}
-bProperty *get_property(Object *ob, char *name)
+bProperty *get_ob_property(Object *ob, char *name)
{
bProperty *prop;
@@ -149,6 +148,17 @@ bProperty *get_property(Object *ob, char *name)
return NULL;
}
+void set_ob_property(Object *ob, bProperty *propc)
+{
+ bProperty *prop;
+ prop= get_ob_property(ob, propc->name);
+ if(prop) {
+ free_property(prop);
+ BLI_remlink(&ob->prop, prop);
+ }
+ BLI_addtail(&ob->prop, copy_property(propc));
+}
+
/* negative: prop is smaller
* positive: prop is larger
*/
diff --git a/source/blender/blenkernel/intern/sca.c b/source/blender/blenkernel/intern/sca.c
index 81da2fcbd96..e8c6c5c199f 100644
--- a/source/blender/blenkernel/intern/sca.c
+++ b/source/blender/blenkernel/intern/sca.c
@@ -150,6 +150,12 @@ void init_sensor(bSensor *sens)
case SENS_PROPERTY:
sens->data= MEM_callocN(sizeof(bPropertySensor), "propsens");
break;
+ case SENS_ACTUATOR:
+ sens->data= MEM_callocN(sizeof(bActuatorSensor), "actsens");
+ break;
+ case SENS_DELAY:
+ sens->data= MEM_callocN(sizeof(bDelaySensor), "delaysens");
+ break;
case SENS_MOUSE:
ms=sens->data= MEM_callocN(sizeof(bMouseSensor), "mousesens");
//XXX ms->type= LEFTMOUSE;
@@ -411,6 +417,7 @@ void init_actuator(bActuator *act)
switch(act->type) {
#ifdef __NLA
case ACT_ACTION:
+ case ACT_SHAPEACTION:
act->data= MEM_callocN(sizeof(bActionActuator), "actionact");
break;
#endif
@@ -458,6 +465,15 @@ void init_actuator(bActuator *act)
case ACT_VISIBILITY:
act->data= MEM_callocN(sizeof(bVisibilityActuator), "visibility act");
break;
+ case ACT_2DFILTER:
+ act->data = MEM_callocN(sizeof( bTwoDFilterActuator ), "2d filter act");
+ break;
+ case ACT_PARENT:
+ act->data = MEM_callocN(sizeof( bParentActuator ), "parent act");
+ break;
+ case ACT_STATE:
+ act->data = MEM_callocN(sizeof( bStateActuator ), "state act");
+ break;
default:
; /* this is very severe... I cannot make any memory for this */
/* logic brick... */
diff --git a/source/blender/blenkernel/intern/scene.c b/source/blender/blenkernel/intern/scene.c
index ebb2a80314f..096c04b7bd3 100644
--- a/source/blender/blenkernel/intern/scene.c
+++ b/source/blender/blenkernel/intern/scene.c
@@ -61,11 +61,13 @@
#include "BKE_anim.h"
#include "BKE_armature.h"
#include "BKE_colortools.h"
+#include "BKE_colortools.h"
#include "BKE_constraint.h"
#include "BKE_depsgraph.h"
#include "BKE_global.h"
#include "BKE_group.h"
#include "BKE_ipo.h"
+#include "BKE_idprop.h"
#include "BKE_image.h"
#include "BKE_key.h"
#include "BKE_library.h"
@@ -78,8 +80,12 @@
#include "BKE_utildefines.h"
//XXX #include "BIF_previewrender.h"
+//XXX #include "BIF_editseq.h"
+#ifndef DISABLE_PYTHON
#include "BPY_extern.h"
+#endif
+
#include "BLI_arithb.h"
#include "BLI_blenlib.h"
@@ -136,7 +142,10 @@ void free_scene(Scene *sce)
if(sce->radio) MEM_freeN(sce->radio);
sce->radio= 0;
+#ifndef DISABLE_PYTHON
BPY_free_scriptlink(&sce->scriptlink);
+#endif
+
if (sce->r.avicodecdata) {
free_avicodecdata(sce->r.avicodecdata);
MEM_freeN(sce->r.avicodecdata);
@@ -147,8 +156,14 @@ void free_scene(Scene *sce)
MEM_freeN(sce->r.qtcodecdata);
sce->r.qtcodecdata = NULL;
}
+ if (sce->r.ffcodecdata.properties) {
+ IDP_FreeProperty(sce->r.ffcodecdata.properties);
+ MEM_freeN(sce->r.ffcodecdata.properties);
+ sce->r.ffcodecdata.properties = NULL;
+ }
BLI_freelistN(&sce->markers);
+ BLI_freelistN(&sce->transform_spaces);
BLI_freelistN(&sce->r.layers);
if(sce->toolsettings){
@@ -179,6 +194,7 @@ Scene *add_scene(char *name)
sce->lay= 1;
sce->selectmode= SCE_SELECT_VERTEX;
sce->editbutsize= 0.1;
+ sce->autokey_mode= U.autokey_mode;
sce->r.mode= R_GAMMA;
sce->r.cfra= 1;
@@ -215,6 +231,15 @@ Scene *add_scene(char *name)
sce->r.stereomode = 1; // no stereo
+ sce->r.simplify_subsurf= 6;
+ sce->r.simplify_particles= 1.0f;
+ sce->r.simplify_shadowsamples= 16;
+ sce->r.simplify_aosss= 1.0f;
+
+ sce->r.cineonblack= 95;
+ sce->r.cineonwhite= 685;
+ sce->r.cineongamma= 1.7f;
+
sce->toolsettings = MEM_callocN(sizeof(struct ToolSettings),"Tool Settings Struct");
sce->toolsettings->cornertype=1;
sce->toolsettings->degr = 90;
@@ -234,6 +259,21 @@ Scene *add_scene(char *name)
sce->toolsettings->select_thresh= 0.01f;
sce->toolsettings->jointrilimit = 0.8f;
+ sce->toolsettings->skgen_resolution = 100;
+ sce->toolsettings->skgen_threshold_internal = 0.01f;
+ sce->toolsettings->skgen_threshold_external = 0.01f;
+ sce->toolsettings->skgen_angle_limit = 45.0f;
+ sce->toolsettings->skgen_length_ratio = 1.3f;
+ sce->toolsettings->skgen_length_limit = 1.5f;
+ sce->toolsettings->skgen_correlation_limit = 0.98f;
+ sce->toolsettings->skgen_symmetry_limit = 0.1f;
+ sce->toolsettings->skgen_postpro = SKGEN_SMOOTH;
+ sce->toolsettings->skgen_postpro_passes = 1;
+ sce->toolsettings->skgen_options = SKGEN_FILTER_INTERNAL|SKGEN_FILTER_EXTERNAL|SKGEN_FILTER_SMART|SKGEN_HARMONIC|SKGEN_SUB_CORRELATION|SKGEN_STICK_TO_EMBEDDING;
+ sce->toolsettings->skgen_subdivisions[0] = SKGEN_SUB_CORRELATION;
+ sce->toolsettings->skgen_subdivisions[1] = SKGEN_SUB_LENGTH;
+ sce->toolsettings->skgen_subdivisions[2] = SKGEN_SUB_ANGLE;
+
pset= &sce->toolsettings->particle;
pset->flag= PE_KEEP_LENGTHS|PE_LOCK_FIRST|PE_DEFLECT_EMITTER;
pset->emitterdist= 0.25f;
@@ -252,13 +292,12 @@ Scene *add_scene(char *name)
strcpy(sce->r.backbuf, "//backbuf");
strcpy(sce->r.pic, U.renderdir);
- strcpy(sce->r.ftype, "//ftype");
BLI_init_rctf(&sce->r.safety, 0.1f, 0.9f, 0.1f, 0.9f);
sce->r.osa= 8;
sculptdata_init(sce);
-
+
/* note; in header_info.c the scene copy happens..., if you add more to renderdata it has to be checked there */
scene_add_render_layer(sce);
@@ -285,6 +324,9 @@ void set_scene_bg(Scene *sce)
GroupObject *go;
int flag;
+ // Note: this here is defined in editseq.c (BIF_editseq.h), NOT in blenkernel!
+ //XXX clear_last_seq();
+
G.scene= sce;
/* check for cyclic sets, for reading old files but also for definite security (py?) */
@@ -330,7 +372,7 @@ void set_scene_bg(Scene *sce)
/* no full animation update, this to enable render code to work (render code calls own animation updates) */
/* do we need FRAMECHANGED in set_scene? */
-// if (G.f & G_DOSCRIPTLINKS) BPY_do_all_scripts(SCRIPT_FRAMECHANGED);
+// if (G.f & G_DOSCRIPTLINKS) BPY_do_all_scripts(SCRIPT_FRAMECHANGED, 0);
}
/* called from creator.c */
@@ -413,6 +455,9 @@ int next_object(int val, Base **base, Object **ob)
duplilist= object_duplilist(G.scene, (*base)->object);
dupob= duplilist->first;
+
+ if(!dupob)
+ free_object_duplilist(duplilist);
}
}
}
@@ -494,27 +539,23 @@ void scene_select_base(Scene *sce, Base *selbase)
int scene_check_setscene(Scene *sce)
{
Scene *scene;
+ int a, totscene;
if(sce->set==NULL) return 1;
- /* LIB_DOIT is the free flag to tag library data */
+ totscene= 0;
for(scene= G.main->scene.first; scene; scene= scene->id.next)
- scene->id.flag &= ~LIB_DOIT;
-
- scene= sce;
- while(scene->set) {
- scene->id.flag |= LIB_DOIT;
- /* when set has flag set, we got a cycle */
- if(scene->set->id.flag & LIB_DOIT)
- break;
- scene= scene->set;
- }
-
- if(scene->set) {
- /* the tested scene gets zero'ed, that's typically current scene */
- sce->set= NULL;
- return 0;
+ totscene++;
+
+ for(a=0, scene=sce; scene->set; scene=scene->set, a++) {
+ /* more iterations than scenes means we have a cycle */
+ if(a > totscene) {
+ /* the tested scene gets zero'ed, that's typically current scene */
+ sce->set= NULL;
+ return 0;
+ }
}
+
return 1;
}
@@ -550,9 +591,9 @@ void scene_update_for_newframe(Scene *sce, unsigned int lay)
/* object ipos are calculated in where_is_object */
do_all_data_ipos();
-
- if (G.f & G_DOSCRIPTLINKS) BPY_do_all_scripts(SCRIPT_FRAMECHANGED);
-
+#ifndef DISABLE_PYTHON
+ if (G.f & G_DOSCRIPTLINKS) BPY_do_all_scripts(SCRIPT_FRAMECHANGED, 0);
+#endif
/* sets first, we allow per definition current scene to have dependencies on sets */
for(sce= sce->set; sce; sce= sce->set)
scene_update(sce, lay);
@@ -587,8 +628,10 @@ void sculptdata_init(Scene *sce)
sd= &sce->sculptdata;
- if(sd->cumap)
+ if(sd->cumap) {
curvemapping_free(sd->cumap);
+ sd->cumap = NULL;
+ }
memset(sd, 0, sizeof(SculptData));
@@ -600,9 +643,9 @@ void sculptdata_init(Scene *sce)
sd->grabbrush.strength = sd->layerbrush.strength =
sd->flattenbrush.strength = 25;
sd->drawbrush.dir = sd->pinchbrush.dir = sd->inflatebrush.dir = sd->layerbrush.dir= 1;
- sd->drawbrush.airbrush = sd->smoothbrush.airbrush =
- sd->pinchbrush.airbrush = sd->inflatebrush.airbrush =
- sd->layerbrush.airbrush = sd->flattenbrush.airbrush = 0;
+ sd->drawbrush.flag = sd->smoothbrush.flag =
+ sd->pinchbrush.flag = sd->inflatebrush.flag =
+ sd->layerbrush.flag = sd->flattenbrush.flag = 0;
sd->drawbrush.view= 0;
sd->brush_type= DRAW_BRUSH;
sd->texact= -1;
@@ -656,13 +699,8 @@ void sculptsession_free(Scene *sce)
if(ss->mats)
MEM_freeN(ss->mats);
- if(ss->propset) {
- if(ss->propset->texdata)
- MEM_freeN(ss->propset->texdata);
- if(ss->propset->num)
- MEM_freeN(ss->propset->num);
- MEM_freeN(ss->propset);
- }
+ if(ss->radialcontrol)
+ MEM_freeN(ss->radialcontrol);
sculpt_vertexusers_free(ss);
if(ss->texcache)
@@ -702,3 +740,38 @@ void sculpt_reset_curve(SculptData *sd)
curvemapping_changed(sd->cumap, 0);
}
+
+/* render simplification */
+
+int get_render_subsurf_level(RenderData *r, int lvl)
+{
+ if(G.rt == 1 && (r->mode & R_SIMPLIFY))
+ return MIN2(r->simplify_subsurf, lvl);
+ else
+ return lvl;
+}
+
+int get_render_child_particle_number(RenderData *r, int num)
+{
+ if(G.rt == 1 && (r->mode & R_SIMPLIFY))
+ return (int)(r->simplify_particles*num);
+ else
+ return num;
+}
+
+int get_render_shadow_samples(RenderData *r, int samples)
+{
+ if(G.rt == 1 && (r->mode & R_SIMPLIFY) && samples > 0)
+ return MIN2(r->simplify_shadowsamples, samples);
+ else
+ return samples;
+}
+
+float get_render_aosss_error(RenderData *r, float error)
+{
+ if(G.rt == 1 && (r->mode & R_SIMPLIFY))
+ return ((1.0f-r->simplify_aosss)*10.0f + 1.0f)*error;
+ else
+ return error;
+}
+
diff --git a/source/blender/blenkernel/intern/screen.c b/source/blender/blenkernel/intern/screen.c
index 926a62e9f69..bf2ed2c658e 100644
--- a/source/blender/blenkernel/intern/screen.c
+++ b/source/blender/blenkernel/intern/screen.c
@@ -20,7 +20,9 @@
* The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
* All rights reserved.
*
- * Contributor(s): Blender Foundation 2002-2008
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
*
* ***** END GPL LICENSE BLOCK *****
*/
diff --git a/source/blender/blenkernel/intern/script.c b/source/blender/blenkernel/intern/script.c
index ab7ae0e09fe..e34b1d0a1dd 100644
--- a/source/blender/blenkernel/intern/script.c
+++ b/source/blender/blenkernel/intern/script.c
@@ -32,18 +32,21 @@
*/
#include "BKE_script.h"
-//XXX #include "BPI_script.h"
+#include "DNA_space_types.h"
#include "MEM_guardedalloc.h"
-
+/*
#include "BLI_blenlib.h"
#include "BKE_utildefines.h"
#include "BKE_library.h"
#include "BKE_global.h"
#include "BKE_main.h"
+#ifndef DISABLE_PYTHON
#include "BPY_extern.h" // Blender Python library
+#endif
+*/
/* XXX this function and so also the file should not be needed anymore,
* since we have to force clearing all Python related data before freeing
@@ -54,13 +57,8 @@
void free_script (Script *script)
{
if (!script) return;
-
- if (script->py_globaldict || script->py_button ||
- script->py_event || script->py_draw)
- {
- BPY_clear_script(script);
- }
-
- return;
+#ifndef DISABLE_PYTHON
+ BPY_clear_script(script);
+#endif
}
#endif
diff --git a/source/blender/blenkernel/intern/shrinkwrap.c b/source/blender/blenkernel/intern/shrinkwrap.c
new file mode 100644
index 00000000000..ab98fb1f007
--- /dev/null
+++ b/source/blender/blenkernel/intern/shrinkwrap.c
@@ -0,0 +1,599 @@
+/**
+ * shrinkwrap.c
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): André Pinto
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#include <string.h>
+#include <float.h>
+#include <math.h>
+#include <memory.h>
+#include <stdio.h>
+#include <time.h>
+#include <assert.h>
+
+#include "DNA_object_types.h"
+#include "DNA_modifier_types.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_mesh_types.h"
+
+#include "BKE_shrinkwrap.h"
+#include "BKE_DerivedMesh.h"
+#include "BKE_lattice.h"
+#include "BKE_utildefines.h"
+#include "BKE_deform.h"
+#include "BKE_cdderivedmesh.h"
+#include "BKE_displist.h"
+#include "BKE_global.h"
+#include "BKE_subsurf.h"
+
+#include "BLI_arithb.h"
+#include "BLI_kdtree.h"
+#include "BLI_kdopbvh.h"
+
+#include "RE_raytrace.h"
+#include "MEM_guardedalloc.h"
+
+
+/* Util macros */
+#define TO_STR(a) #a
+#define JOIN(a,b) a##b
+
+#define OUT_OF_MEMORY() ((void)printf("Shrinkwrap: Out of memory\n"))
+
+/* Benchmark macros */
+#if !defined(_WIN32) && 0
+
+#include <sys/time.h>
+
+#define BENCH(a) \
+ do { \
+ double _t1, _t2; \
+ struct timeval _tstart, _tend; \
+ clock_t _clock_init = clock(); \
+ gettimeofday ( &_tstart, NULL); \
+ (a); \
+ gettimeofday ( &_tend, NULL); \
+ _t1 = ( double ) _tstart.tv_sec + ( double ) _tstart.tv_usec/ ( 1000*1000 ); \
+ _t2 = ( double ) _tend.tv_sec + ( double ) _tend.tv_usec/ ( 1000*1000 ); \
+ printf("%s: %fs (real) %fs (cpu)\n", #a, _t2-_t1, (float)(clock()-_clock_init)/CLOCKS_PER_SEC);\
+ } while(0)
+
+#else
+
+#define BENCH(a) (a)
+
+#endif
+
+typedef void ( *Shrinkwrap_ForeachVertexCallback) (DerivedMesh *target, float *co, float *normal);
+
+/* get derived mesh */
+//TODO is anyfunction that does this? returning the derivedFinal witouth we caring if its in edit mode or not?
+DerivedMesh *object_get_derived_final(Object *ob, CustomDataMask dataMask)
+{
+ if (ob==G.obedit)
+ {
+ DerivedMesh *final = NULL;
+ editmesh_get_derived_cage_and_final(&final, dataMask);
+ return final;
+ }
+ else
+ return mesh_get_derived_final(ob, dataMask);
+}
+
+/* Space transform */
+void space_transform_from_matrixs(SpaceTransform *data, float local[4][4], float target[4][4])
+{
+ float itarget[4][4];
+ Mat4Invert(itarget, target);
+ Mat4MulSerie(data->local2target, itarget, local, 0, 0, 0, 0, 0, 0);
+ Mat4Invert(data->target2local, data->local2target);
+}
+
+void space_transform_apply(const SpaceTransform *data, float *co)
+{
+ VecMat4MulVecfl(co, ((SpaceTransform*)data)->local2target, co);
+}
+
+void space_transform_invert(const SpaceTransform *data, float *co)
+{
+ VecMat4MulVecfl(co, ((SpaceTransform*)data)->target2local, co);
+}
+
+void space_transform_apply_normal(const SpaceTransform *data, float *no)
+{
+ Mat4Mul3Vecfl( ((SpaceTransform*)data)->local2target, no);
+ Normalize(no); // TODO: could we just determine de scale value from the matrix?
+}
+
+void space_transform_invert_normal(const SpaceTransform *data, float *no)
+{
+ Mat4Mul3Vecfl(((SpaceTransform*)data)->target2local, no);
+ Normalize(no); // TODO: could we just determine de scale value from the matrix?
+}
+
+/*
+ * Returns the squared distance between two given points
+ */
+static float squared_dist(const float *a, const float *b)
+{
+ float tmp[3];
+ VECSUB(tmp, a, b);
+ return INPR(tmp, tmp);
+}
+
+/* Main shrinkwrap function */
+void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, Object *ob, DerivedMesh *dm, float (*vertexCos)[3], int numVerts)
+{
+
+ ShrinkwrapCalcData calc = NULL_ShrinkwrapCalcData;
+
+ //remove loop dependencies on derived meshs (TODO should this be done elsewhere?)
+ if(smd->target == ob) smd->target = NULL;
+ if(smd->auxTarget == ob) smd->auxTarget = NULL;
+
+
+ //Configure Shrinkwrap calc data
+ calc.smd = smd;
+ calc.ob = ob;
+ calc.original = dm;
+ calc.numVerts = numVerts;
+ calc.vertexCos = vertexCos;
+
+ //DeformVertex
+ calc.vgroup = get_named_vertexgroup_num(calc.ob, calc.smd->vgroup_name);
+ if(calc.original)
+ {
+ calc.dvert = calc.original->getVertDataArray(calc.original, CD_MDEFORMVERT);
+ }
+ else if(calc.ob->type == OB_LATTICE)
+ {
+ calc.dvert = lattice_get_deform_verts(calc.ob);
+ }
+
+
+ if(smd->target)
+ {
+ //TODO currently we need a copy in case object_get_derived_final returns an emDM that does not defines getVertArray or getFace array
+ calc.target = CDDM_copy( object_get_derived_final(smd->target, CD_MASK_BAREMESH) );
+
+ //TODO there might be several "bugs" on non-uniform scales matrixs.. because it will no longer be nearest surface, not sphere projection
+ //because space has been deformed
+ space_transform_setup(&calc.local2target, ob, smd->target);
+
+ calc.keepDist = smd->keepDist; //TODO: smd->keepDist is in global units.. must change to local
+ }
+
+
+ //Projecting target defined - lets work!
+ if(calc.target)
+ {
+ switch(smd->shrinkType)
+ {
+ case MOD_SHRINKWRAP_NEAREST_SURFACE:
+ BENCH(shrinkwrap_calc_nearest_surface_point(&calc));
+ break;
+
+ case MOD_SHRINKWRAP_PROJECT:
+ BENCH(shrinkwrap_calc_normal_projection(&calc));
+ break;
+
+ case MOD_SHRINKWRAP_NEAREST_VERTEX:
+ BENCH(shrinkwrap_calc_nearest_vertex(&calc));
+ break;
+ }
+ }
+
+ //free memory
+ if(calc.target)
+ calc.target->release( calc.target );
+}
+
+/*
+ * Shrinkwrap to the nearest vertex
+ *
+ * it builds a kdtree of vertexs we can attach to and then
+ * for each vertex performs a nearest vertex search on the tree
+ */
+void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc)
+{
+ int i;
+
+ BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
+ BVHTreeNearest nearest = NULL_BVHTreeNearest;
+
+
+ BENCH(bvhtree_from_mesh_verts(&treeData, calc->target, 0.0, 2, 6));
+ if(treeData.tree == NULL)
+ {
+ OUT_OF_MEMORY();
+ return;
+ }
+
+ //Setup nearest
+ nearest.index = -1;
+ nearest.dist = FLT_MAX;
+
+#pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(treeData,calc) schedule(static)
+ for(i = 0; i<calc->numVerts; ++i)
+ {
+ float *co = calc->vertexCos[i];
+ float tmp_co[3];
+ float weight = vertexgroup_get_vertex_weight(calc->dvert, i, calc->vgroup);
+ if(weight == 0.0f) continue;
+
+ VECCOPY(tmp_co, co);
+ space_transform_apply(&calc->local2target, tmp_co); //Convert the coordinates to the tree coordinates
+
+ //Use local proximity heuristics (to reduce the nearest search)
+ //
+ //If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
+ //so we can initiate the "nearest.dist" with the expected value to that last hit.
+ //This will lead in prunning of the search tree.
+ if(nearest.index != -1)
+ nearest.dist = squared_dist(tmp_co, nearest.co);
+ else
+ nearest.dist = FLT_MAX;
+
+ BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);
+
+
+ //Found the nearest vertex
+ if(nearest.index != -1)
+ {
+ //Adjusting the vertex weight, so that after interpolating it keeps a certain distance from the nearest position
+ float dist = sasqrt(nearest.dist);
+ if(dist > FLT_EPSILON) weight *= (dist - calc->keepDist)/dist;
+
+ //Convert the coordinates back to mesh coordinates
+ VECCOPY(tmp_co, nearest.co);
+ space_transform_invert(&calc->local2target, tmp_co);
+
+ VecLerpf(co, co, tmp_co, weight); //linear interpolation
+ }
+ }
+
+ free_bvhtree_from_mesh(&treeData);
+}
+
+/*
+ * This function raycast a single vertex and updates the hit if the "hit" is considered valid.
+ * Returns TRUE if "hit" was updated.
+ * Opts control whether an hit is valid or not
+ * Supported options are:
+ * MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE (front faces hits are ignored)
+ * MOD_SHRINKWRAP_CULL_TARGET_BACKFACE (back faces hits are ignored)
+ */
+int normal_projection_project_vertex(char options, const float *vert, const float *dir, const SpaceTransform *transf, BVHTree *tree, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata)
+{
+ float tmp_co[3], tmp_no[3];
+ const float *co, *no;
+ BVHTreeRayHit hit_tmp;
+
+ //Copy from hit (we need to convert hit rays from one space coordinates to the other
+ memcpy( &hit_tmp, hit, sizeof(hit_tmp) );
+
+ //Apply space transform (TODO readjust dist)
+ if(transf)
+ {
+ VECCOPY( tmp_co, vert );
+ space_transform_apply( transf, tmp_co );
+ co = tmp_co;
+
+ VECCOPY( tmp_no, dir );
+ space_transform_apply_normal( transf, tmp_no );
+ no = tmp_no;
+
+ hit_tmp.dist *= Mat4ToScalef( ((SpaceTransform*)transf)->local2target );
+ }
+ else
+ {
+ co = vert;
+ no = dir;
+ }
+
+ hit_tmp.index = -1;
+
+ BLI_bvhtree_ray_cast(tree, co, no, 0.0f, &hit_tmp, callback, userdata);
+
+ if(hit_tmp.index != -1)
+ {
+ float dot = INPR( dir, hit_tmp.no);
+
+ if(((options & MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE) && dot <= 0.0f)
+ || ((options & MOD_SHRINKWRAP_CULL_TARGET_BACKFACE) && dot >= 0.0f))
+ return FALSE; //Ignore hit
+
+
+ //Inverting space transform (TODO make coeherent with the initial dist readjust)
+ if(transf)
+ {
+ space_transform_invert( transf, hit_tmp.co );
+ space_transform_invert_normal( transf, hit_tmp.no );
+
+ hit_tmp.dist = VecLenf( (float*)vert, hit_tmp.co );
+ }
+
+ memcpy(hit, &hit_tmp, sizeof(hit_tmp) );
+ return TRUE;
+ }
+ return FALSE;
+}
+
+
+void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc)
+{
+ int i;
+
+ //Options about projection direction
+ const char use_normal = calc->smd->shrinkOpts;
+ float proj_axis[3] = {0.0f, 0.0f, 0.0f};
+ MVert *vert = NULL; //Needed in case of vertex normal
+ DerivedMesh* ss_mesh = NULL;
+
+ //Raycast and tree stuff
+ BVHTreeRayHit hit;
+ BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh; //target
+
+ //auxiliar target
+ DerivedMesh * aux_mesh = NULL;
+ BVHTreeFromMesh auxData= NULL_BVHTreeFromMesh;
+ SpaceTransform local2aux;
+
+do
+{
+
+ //Prepare data to retrieve the direction in which we should project each vertex
+ if(calc->smd->projAxis == MOD_SHRINKWRAP_PROJECT_OVER_NORMAL)
+ {
+ //No Mvert information: jump to "free memory and return" part
+ if(calc->original == NULL) break;
+
+ if(calc->smd->subsurfLevels)
+ {
+ SubsurfModifierData smd;
+ memset(&smd, 0, sizeof(smd));
+ smd.subdivType = ME_CC_SUBSURF; //catmull clark
+ smd.levels = calc->smd->subsurfLevels; //levels
+
+ ss_mesh = subsurf_make_derived_from_derived(calc->original, &smd, FALSE, NULL, 0, 0);
+
+ if(ss_mesh)
+ {
+ vert = ss_mesh->getVertDataArray(ss_mesh, CD_MVERT);
+ if(vert)
+ {
+ //TRICKY: this code assumes subsurface will have the transformed original vertices
+ //in their original order at the end of the vert array.
+ vert = vert
+ + ss_mesh->getNumVerts(ss_mesh)
+ - calc->original->getNumVerts(calc->original);
+ }
+ }
+
+ //To make sure we are not letting any memory behind
+ assert(smd.emCache == NULL);
+ assert(smd.mCache == NULL);
+ }
+ else
+ vert = calc->original->getVertDataArray(calc->original, CD_MVERT);
+
+ //Not able to get vert information: jump to "free memory and return" part
+ if(vert == NULL) break;
+ }
+ else
+ {
+ //The code supports any axis that is a combination of X,Y,Z.. altought currently UI only allows to set the 3 diferent axis
+ if(calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_X_AXIS) proj_axis[0] = 1.0f;
+ if(calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Y_AXIS) proj_axis[1] = 1.0f;
+ if(calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Z_AXIS) proj_axis[2] = 1.0f;
+
+ Normalize(proj_axis);
+
+ //Invalid projection direction: jump to "free memory and return" part
+ if(INPR(proj_axis, proj_axis) < FLT_EPSILON) break;
+ }
+
+ //If the user doesn't allows to project in any direction of projection axis... then theres nothing todo.
+ if((use_normal & (MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR | MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR)) == 0)
+ break; //jump to "free memory and return" part
+
+
+ //Build target tree
+ BENCH(bvhtree_from_mesh_faces(&treeData, calc->target, calc->keepDist, 4, 6));
+ if(treeData.tree == NULL)
+ break; //jump to "free memory and return" part
+
+
+ //Build auxiliar target
+ if(calc->smd->auxTarget)
+ {
+ space_transform_setup( &local2aux, calc->ob, calc->smd->auxTarget);
+
+ aux_mesh = CDDM_copy( object_get_derived_final(calc->smd->auxTarget, CD_MASK_BAREMESH) ); //TODO currently we need a copy in case object_get_derived_final returns an emDM that does not defines getVertArray or getFace array
+ if(aux_mesh)
+ BENCH(bvhtree_from_mesh_faces(&auxData, aux_mesh, 0.0, 4, 6));
+ else
+ printf("Auxiliar target finalDerived mesh is null\n");
+ }
+
+
+ //Now, everything is ready to project the vertexs!
+#pragma omp parallel for private(i,hit) schedule(static)
+ for(i = 0; i<calc->numVerts; ++i)
+ {
+ float *co = calc->vertexCos[i];
+ float tmp_co[3], tmp_no[3];
+ float lim = 10000.0f; //TODO: we should use FLT_MAX here, but sweepsphere code isnt prepared for that
+ float weight = vertexgroup_get_vertex_weight(calc->dvert, i, calc->vgroup);
+
+ if(weight == 0.0f) continue;
+
+ if(ss_mesh)
+ {
+ VECCOPY(tmp_co, vert[i].co);
+ }
+ else
+ {
+ VECCOPY(tmp_co, co);
+ }
+
+
+ if(vert)
+ NormalShortToFloat(tmp_no, vert[i].no);
+ else
+ VECCOPY( tmp_no, proj_axis );
+
+
+ hit.index = -1;
+ hit.dist = lim;
+
+
+ //Project over positive direction of axis
+ if(use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR)
+ {
+
+ if(auxData.tree)
+ normal_projection_project_vertex(0, tmp_co, tmp_no, &local2aux, auxData.tree, &hit, auxData.raycast_callback, &auxData);
+
+ normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, tmp_no, &calc->local2target, treeData.tree, &hit, treeData.raycast_callback, &treeData);
+ }
+
+ //Project over negative direction of axis
+ if(use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR)
+ {
+ float inv_no[3] = { -tmp_no[0], -tmp_no[1], -tmp_no[2] };
+
+
+ if(auxData.tree)
+ normal_projection_project_vertex(0, tmp_co, inv_no, &local2aux, auxData.tree, &hit, auxData.raycast_callback, &auxData);
+
+ normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, inv_no, &calc->local2target, treeData.tree, &hit, treeData.raycast_callback, &treeData);
+ }
+
+
+ if(hit.index != -1)
+ {
+ VecLerpf(co, co, hit.co, weight);
+ }
+ }
+
+
+//Simple do{} while(0) structure to allow to easily jump to the "free memory and return" part
+} while(0);
+
+ //free data structures
+
+ free_bvhtree_from_mesh(&treeData);
+ free_bvhtree_from_mesh(&auxData);
+
+ if(aux_mesh)
+ aux_mesh->release(aux_mesh);
+
+ if(ss_mesh)
+ ss_mesh->release(ss_mesh);
+}
+
+/*
+ * Shrinkwrap moving vertexs to the nearest surface point on the target
+ *
+ * it builds a BVHTree from the target mesh and then performs a
+ * NN matchs for each vertex
+ */
+void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc)
+{
+ int i;
+
+ BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
+ BVHTreeNearest nearest = NULL_BVHTreeNearest;
+
+
+
+ //Create a bvh-tree of the given target
+ BENCH(bvhtree_from_mesh_faces( &treeData, calc->target, 0.0, 2, 6));
+ if(treeData.tree == NULL)
+ {
+ OUT_OF_MEMORY();
+ return;
+ }
+
+ //Setup nearest
+ nearest.index = -1;
+ nearest.dist = FLT_MAX;
+
+
+ //Find the nearest vertex
+#pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(calc,treeData) schedule(static)
+ for(i = 0; i<calc->numVerts; ++i)
+ {
+ float *co = calc->vertexCos[i];
+ float tmp_co[3];
+ float weight = vertexgroup_get_vertex_weight(calc->dvert, i, calc->vgroup);
+ if(weight == 0.0f) continue;
+
+ //Convert the vertex to tree coordinates
+ VECCOPY(tmp_co, co);
+ space_transform_apply(&calc->local2target, tmp_co);
+
+ //Use local proximity heuristics (to reduce the nearest search)
+ //
+ //If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
+ //so we can initiate the "nearest.dist" with the expected value to that last hit.
+ //This will lead in prunning of the search tree.
+ if(nearest.index != -1)
+ nearest.dist = squared_dist(tmp_co, nearest.co);
+ else
+ nearest.dist = FLT_MAX;
+
+ BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);
+
+ //Found the nearest vertex
+ if(nearest.index != -1)
+ {
+ if(calc->smd->shrinkOpts & MOD_SHRINKWRAP_KEEP_ABOVE_SURFACE)
+ {
+ //Make the vertex stay on the front side of the face
+ VECADDFAC(tmp_co, nearest.co, nearest.no, calc->keepDist);
+ }
+ else
+ {
+ //Adjusting the vertex weight, so that after interpolating it keeps a certain distance from the nearest position
+ float dist = sasqrt( nearest.dist );
+ if(dist > FLT_EPSILON)
+ VecLerpf(tmp_co, tmp_co, nearest.co, (dist - calc->keepDist)/dist); //linear interpolation
+ else
+ VECCOPY( tmp_co, nearest.co );
+ }
+
+ //Convert the coordinates back to mesh coordinates
+ space_transform_invert(&calc->local2target, tmp_co);
+ VecLerpf(co, co, tmp_co, weight); //linear interpolation
+ }
+ }
+
+
+ free_bvhtree_from_mesh(&treeData);
+}
+
diff --git a/source/blender/blenkernel/intern/simple_deform.c b/source/blender/blenkernel/intern/simple_deform.c
new file mode 100644
index 00000000000..2978a6f7f01
--- /dev/null
+++ b/source/blender/blenkernel/intern/simple_deform.c
@@ -0,0 +1,256 @@
+/**
+ * deform_simple.c
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): André Pinto
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#include "DNA_object_types.h"
+#include "DNA_modifier_types.h"
+#include "DNA_meshdata_types.h"
+
+#include "BKE_simple_deform.h"
+#include "BKE_DerivedMesh.h"
+#include "BKE_lattice.h"
+#include "BKE_deform.h"
+#include "BKE_utildefines.h"
+#include "BLI_arithb.h"
+#include "BKE_shrinkwrap.h"
+
+#include <string.h>
+#include <math.h>
+
+
+//Clamps/Limits the given coordinate to: limits[0] <= co[axis] <= limits[1]
+//The ammount of clamp is saved on dcut
+static void axis_limit(int axis, const float limits[2], float co[3], float dcut[3])
+{
+ float val = co[axis];
+ if(limits[0] > val) val = limits[0];
+ if(limits[1] < val) val = limits[1];
+
+ dcut[axis] = co[axis] - val;
+ co[axis] = val;
+}
+
+static void simpleDeform_taper(const float factor, const float dcut[3], float *co)
+{
+ float x = co[0], y = co[1], z = co[2];
+ float scale = z*factor;
+
+ co[0] = x + x*scale;
+ co[1] = y + y*scale;
+ co[2] = z;
+
+ if(dcut)
+ {
+ co[0] += dcut[0];
+ co[1] += dcut[1];
+ co[2] += dcut[2];
+ }
+}
+
+static void simpleDeform_stretch(const float factor, const float dcut[3], float *co)
+{
+ float x = co[0], y = co[1], z = co[2];
+ float scale;
+
+ scale = (z*z*factor-factor + 1.0);
+
+ co[0] = x*scale;
+ co[1] = y*scale;
+ co[2] = z*(1.0+factor);
+
+
+ if(dcut)
+ {
+ co[0] += dcut[0];
+ co[1] += dcut[1];
+ co[2] += dcut[2];
+ }
+}
+
+static void simpleDeform_twist(const float factor, const float *dcut, float *co)
+{
+ float x = co[0], y = co[1], z = co[2];
+ float theta, sint, cost;
+
+ theta = z*factor;
+ sint = sin(theta);
+ cost = cos(theta);
+
+ co[0] = x*cost - y*sint;
+ co[1] = x*sint + y*cost;
+ co[2] = z;
+
+ if(dcut)
+ {
+ co[0] += dcut[0];
+ co[1] += dcut[1];
+ co[2] += dcut[2];
+ }
+}
+
+static void simpleDeform_bend(const float factor, const float dcut[3], float *co)
+{
+ float x = co[0], y = co[1], z = co[2];
+ float theta, sint, cost;
+
+ theta = x*factor;
+ sint = sin(theta);
+ cost = cos(theta);
+
+ if(fabs(factor) > 1e-7f)
+ {
+ co[0] = -(y-1.0f/factor)*sint;
+ co[1] = (y-1.0f/factor)*cost + 1.0f/factor;
+ co[2] = z;
+ }
+
+
+ if(dcut)
+ {
+ co[0] += cost*dcut[0];
+ co[1] += sint*dcut[0];
+ co[2] += dcut[2];
+ }
+
+}
+
+
+/* simple deform modifier */
+void SimpleDeformModifier_do(SimpleDeformModifierData *smd, struct Object *ob, struct DerivedMesh *dm, float (*vertexCos)[3], int numVerts)
+{
+ static const float lock_axis[2] = {0.0f, 0.0f};
+
+ int i;
+ int limit_axis = 0;
+ float smd_limit[2], smd_factor;
+ SpaceTransform *transf = NULL, tmp_transf;
+ void (*simpleDeform_callback)(const float factor, const float dcut[3], float *co) = NULL; //Mode callback
+ int vgroup = get_named_vertexgroup_num(ob, smd->vgroup_name);
+ MDeformVert *dvert = NULL;
+
+ //Safe-check
+ if(smd->origin == ob) smd->origin = NULL; //No self references
+
+ if(smd->limit[0] < 0.0) smd->limit[0] = 0.0f;
+ if(smd->limit[0] > 1.0) smd->limit[0] = 1.0f;
+
+ smd->limit[0] = MIN2(smd->limit[0], smd->limit[1]); //Upper limit >= than lower limit
+
+ //Calculate matrixs do convert between coordinate spaces
+ if(smd->origin)
+ {
+ transf = &tmp_transf;
+
+ if(smd->originOpts & MOD_SIMPLEDEFORM_ORIGIN_LOCAL)
+ {
+ space_transform_from_matrixs(transf, ob->obmat, smd->origin->obmat);
+ }
+ else
+ {
+ Mat4CpyMat4(transf->local2target, smd->origin->obmat);
+ Mat4Invert(transf->target2local, transf->local2target);
+ }
+ }
+
+ //Setup vars
+ limit_axis = (smd->mode == MOD_SIMPLEDEFORM_MODE_BEND) ? 0 : 2; //Bend limits on X.. all other modes limit on Z
+
+ //Update limits if needed
+ {
+ float lower = FLT_MAX;
+ float upper = -FLT_MAX;
+
+ for(i=0; i<numVerts; i++)
+ {
+ float tmp[3];
+ VECCOPY(tmp, vertexCos[i]);
+
+ if(transf) space_transform_apply(transf, tmp);
+
+ lower = MIN2(lower, tmp[limit_axis]);
+ upper = MAX2(upper, tmp[limit_axis]);
+ }
+
+
+ //SMD values are normalized to the BV, calculate the absolut values
+ smd_limit[1] = lower + (upper-lower)*smd->limit[1];
+ smd_limit[0] = lower + (upper-lower)*smd->limit[0];
+
+ smd_factor = smd->factor / MAX2(FLT_EPSILON, smd_limit[1]-smd_limit[0]);
+ }
+
+
+ if(dm)
+ {
+ dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
+ }
+ else if(ob->type == OB_LATTICE)
+ {
+ dvert = lattice_get_deform_verts(ob);
+ }
+
+
+
+ switch(smd->mode)
+ {
+ case MOD_SIMPLEDEFORM_MODE_TWIST: simpleDeform_callback = simpleDeform_twist; break;
+ case MOD_SIMPLEDEFORM_MODE_BEND: simpleDeform_callback = simpleDeform_bend; break;
+ case MOD_SIMPLEDEFORM_MODE_TAPER: simpleDeform_callback = simpleDeform_taper; break;
+ case MOD_SIMPLEDEFORM_MODE_STRETCH: simpleDeform_callback = simpleDeform_stretch; break;
+ default:
+ return; //No simpledeform mode?
+ }
+
+ for(i=0; i<numVerts; i++)
+ {
+ float weight = vertexgroup_get_vertex_weight(dvert, i, vgroup);
+
+ if(weight != 0.0f)
+ {
+ float co[3], dcut[3] = {0.0f, 0.0f, 0.0f};
+
+ if(transf) space_transform_apply(transf, vertexCos[i]);
+
+ VECCOPY(co, vertexCos[i]);
+
+ //Apply axis limits
+ if(smd->mode != MOD_SIMPLEDEFORM_MODE_BEND) //Bend mode shoulnt have any lock axis
+ {
+ if(smd->axis & MOD_SIMPLEDEFORM_LOCK_AXIS_X) axis_limit(0, lock_axis, co, dcut);
+ if(smd->axis & MOD_SIMPLEDEFORM_LOCK_AXIS_Y) axis_limit(1, lock_axis, co, dcut);
+ }
+ axis_limit(limit_axis, smd_limit, co, dcut);
+
+ simpleDeform_callback(smd_factor, dcut, co); //Apply deform
+ VecLerpf(vertexCos[i], vertexCos[i], co, weight); //Use vertex weight has coef of linear interpolation
+
+ if(transf) space_transform_invert(transf, vertexCos[i]);
+ }
+ }
+}
+
+
diff --git a/source/blender/blenkernel/intern/softbody.c b/source/blender/blenkernel/intern/softbody.c
index ac56d876df7..1ae547ba7b8 100644
--- a/source/blender/blenkernel/intern/softbody.c
+++ b/source/blender/blenkernel/intern/softbody.c
@@ -69,6 +69,8 @@ variables on the UI for now
#include "BLI_blenlib.h"
#include "BLI_arithb.h"
#include "BLI_ghash.h"
+#include "BLI_threads.h"
+
#include "BKE_curve.h"
#include "BKE_effect.h"
#include "BKE_global.h"
@@ -84,6 +86,7 @@ variables on the UI for now
//XXX #include "BIF_editdeform.h"
//XXX #include "BIF_graphics.h"
#include "PIL_time.h"
+// #include "ONL_opennl.h" remove linking to ONL for now
/* callbacks for errors and interrupts and some goo */
static int (*SB_localInterruptCallBack)(void) = NULL;
@@ -94,7 +97,7 @@ static int (*SB_localInterruptCallBack)(void) = NULL;
typedef struct BodySpring {
int v1, v2;
- float len, strength, cf;
+ float len, strength, cf,load;
float ext_force[3]; /* edges colliding and sailing */
short order;
short flag;
@@ -102,7 +105,7 @@ typedef struct BodySpring {
typedef struct BodyFace {
int v1, v2, v3 ,v4;
- float ext_force[3]; /* edges colliding and sailing */
+ float ext_force[3]; /* faces colliding */
short flag;
} BodyFace;
@@ -117,6 +120,25 @@ typedef struct SBScratch {
float aabbmin[3],aabbmax[3];
}SBScratch;
+typedef struct SB_thread_context{
+ Object *ob;
+ float forcetime;
+ float timenow;
+ int ifirst;
+ int ilast;
+ ListBase *do_effector;
+ int do_deflector;
+ float fieldfactor;
+ float windfactor;
+ int nr;
+ int tot;
+}SB_thread_context;
+
+#define NLF_BUILD 1
+#define NLF_SOLVE 2
+
+#define MID_PRESERVE 1
+
#define SOFTGOALSNAP 0.999f
/* if bp-> goal is above make it a *forced follow original* and skip all ODE stuff for this bp
removes *unnecessary* stiffnes from ODE system
@@ -126,7 +148,9 @@ typedef struct SBScratch {
#define BSF_INTERSECT 1 /* edge intersects collider face */
#define SBF_DOFUZZY 1 /* edge intersects collider face */
-#define BFF_INTERSECT 1 /* edge intersects collider face */
+
+#define BFF_INTERSECT 1 /* collider edge intrudes face */
+#define BFF_CLOSEVERT 2 /* collider vertex repulses face */
float SoftHeunTol = 1.0f; /* humm .. this should be calculated from sb parameters and sizes */
@@ -212,7 +236,7 @@ typedef struct ccd_Mesh {
-ccd_Mesh *ccd_mesh_make(Object *ob, DerivedMesh *dm)
+static ccd_Mesh *ccd_mesh_make(Object *ob, DerivedMesh *dm)
{
ccd_Mesh *pccd_M = NULL;
ccdf_minmax *mima =NULL;
@@ -309,7 +333,7 @@ ccd_Mesh *ccd_mesh_make(Object *ob, DerivedMesh *dm)
}
return pccd_M;
}
-void ccd_mesh_update(Object *ob,ccd_Mesh *pccd_M, DerivedMesh *dm)
+static void ccd_mesh_update(Object *ob,ccd_Mesh *pccd_M, DerivedMesh *dm)
{
ccdf_minmax *mima =NULL;
MFace *mface=NULL;
@@ -448,7 +472,7 @@ void ccd_mesh_update(Object *ob,ccd_Mesh *pccd_M, DerivedMesh *dm)
return ;
}
-void ccd_mesh_free(ccd_Mesh *ccdm)
+static void ccd_mesh_free(ccd_Mesh *ccdm)
{
if(ccdm && (ccdm->savety == CCD_SAVETY )){ /*make sure we're not nuking objects we don't know*/
MEM_freeN(ccdm->mface);
@@ -460,7 +484,7 @@ void ccd_mesh_free(ccd_Mesh *ccdm)
}
}
-void ccd_build_deflector_hache(Object *vertexowner,GHash *hash)
+static void ccd_build_deflector_hache(Object *vertexowner,GHash *hash)
{
Base *base;
Object *ob;
@@ -512,7 +536,7 @@ void ccd_build_deflector_hache(Object *vertexowner,GHash *hash)
} /* while (base) */
}
-void ccd_update_deflector_hache(Object *vertexowner,GHash *hash)
+static void ccd_update_deflector_hache(Object *vertexowner,GHash *hash)
{
Base *base;
Object *ob;
@@ -582,6 +606,7 @@ static void add_mesh_quad_diag_springs(Object *ob)
if (ob->soft){
int nofquads;
+ float s_shear = ob->soft->shearstiff*ob->soft->shearstiff;
nofquads = count_mesh_quads(me);
if (nofquads) {
@@ -602,12 +627,12 @@ static void add_mesh_quad_diag_springs(Object *ob)
if(mface->v4) {
bs->v1= mface->v1;
bs->v2= mface->v3;
- bs->strength= 1.0;
+ bs->strength= s_shear;
bs->order =2;
bs++;
bs->v1= mface->v2;
bs->v2= mface->v4;
- bs->strength= 1.0;
+ bs->strength= s_shear;
bs->order =2;
bs++;
@@ -689,6 +714,7 @@ static void add_2nd_order_springs(Object *ob,float stiffness)
{
int counter = 0;
BodySpring *bs_new;
+ stiffness *=stiffness;
add_2nd_order_roller(ob,stiffness,&counter,0); /* counting */
if (counter) {
@@ -803,50 +829,6 @@ static void calculate_collision_balls(Object *ob)
}
-char set_octant_flags(float *ce, float *pos, float ball)
-{
- float x,y,z;
- char res = 0;
- int a;
-
- for (a=0;a<7;a++){
- switch(a){
- case 0: x=pos[0]; y=pos[1]; z=pos[2]; break;
- case 1: x=pos[0]+ball; y=pos[1]; z=pos[2]; break;
- case 2: x=pos[0]-ball; y=pos[1]; z=pos[2]; break;
- case 3: x=pos[0]; y=pos[1]+ball; z=pos[2]; break;
- case 4: x=pos[0]; y=pos[1]-ball; z=pos[2]; break;
- case 5: x=pos[0]; y=pos[1]; z=pos[2]+ball; break;
- case 6: x=pos[0]; y=pos[1]; z=pos[2]-ball; break;
- }
-
- x=pos[0]; y=pos[1]; z=pos[2];
-
- if (x > ce[0]){
- if (y > ce[1]){
- if (z > ce[2]) res|= 1;
- else res|= 2;
- }
- else{
- if (z > ce[2]) res|= 4;
- else res|= 8;
- }
- }
-
- else{
- if (y > ce[1]){
- if (z > ce[2]) res|= 16;
- else res|= 32;
- }
- else{
- if (z > ce[2]) res|= 64;
- else res|= 128;
- }
- }
- }
- return res;
-}
-
/* creates new softbody if didn't exist yet, makes new points and springs arrays */
static void renew_softbody(Object *ob, int totpoint, int totspring)
{
@@ -881,6 +863,8 @@ static void renew_softbody(Object *ob, int totpoint, int totspring)
bp->nofsprings= 0;
bp->springs= NULL;
bp->choke = 0.0f;
+ bp->choke2 = 0.0f;
+ bp->frozen = 1.0f;
bp->colball = 0.0f;
bp->flag = 0;
@@ -985,6 +969,7 @@ static void Vec3PlusStVec(float *v, float s, float *v1)
}
/* +++ dependancy information functions*/
+
static int are_there_deflectors(unsigned int layer)
{
Base *base;
@@ -1002,40 +987,11 @@ static int query_external_colliders(Object *me)
{
return(are_there_deflectors(me->lay));
}
-
-#if 0
-static int query_external_forces(Object *me)
-{
-/* silly but true: we need to create effector cache to see if anything is in it */
- ListBase *ec = pdInitEffectors(me,NULL);
- int result = 0;
- if (ec){
- result = 1;
- pdEndEffectors(ec); /* sorry ec, yes i'm an idiot, but i needed to know if you were there */
- }
- return result;
-}
-
-/*
-any of that external objects may have an IPO or something alike ..
-so unless we can ask them if they are moving we have to assume they do
-*/
-static int query_external_time(Object *me)
-{
- if (query_external_colliders(me)) return 1;
- if (query_external_forces(me)) return 1;
- return 0;
-}
-static int query_internal_time(Object *me)
-{
- if (me->softflag & OB_SB_GOAL) return 1;
- return 0;
-}
-#endif
/* --- dependancy information functions*/
+
/* +++ the aabb "force" section*/
-int sb_detect_aabb_collisionCached( float force[3], unsigned int par_layer,struct Object *vertexowner,float time)
+static int sb_detect_aabb_collisionCached( float force[3], unsigned int par_layer,struct Object *vertexowner,float time)
{
Object *ob;
SoftBody *sb=vertexowner->soft;
@@ -1099,15 +1055,112 @@ int sb_detect_aabb_collisionCached( float force[3], unsigned int par_layer,struc
/* +++ the face external section*/
+static int sb_detect_face_pointCached(float face_v1[3],float face_v2[3],float face_v3[3],float *damp,
+ float force[3], unsigned int par_layer,struct Object *vertexowner,float time)
+ {
+ Object *ob;
+ GHash *hash;
+ GHashIterator *ihash;
+ float nv1[3], edge1[3], edge2[3], d_nvect[3], aabbmin[3],aabbmax[3];
+ float facedist,outerfacethickness,tune = 10.f;
+ int a, deflected=0;
+
+ aabbmin[0] = MIN3(face_v1[0],face_v2[0],face_v3[0]);
+ aabbmin[1] = MIN3(face_v1[1],face_v2[1],face_v3[1]);
+ aabbmin[2] = MIN3(face_v1[2],face_v2[2],face_v3[2]);
+ aabbmax[0] = MAX3(face_v1[0],face_v2[0],face_v3[0]);
+ aabbmax[1] = MAX3(face_v1[1],face_v2[1],face_v3[1]);
+ aabbmax[2] = MAX3(face_v1[2],face_v2[2],face_v3[2]);
+
+ /* calculate face normal once again SIGH */
+ VECSUB(edge1, face_v1, face_v2);
+ VECSUB(edge2, face_v3, face_v2);
+ Crossf(d_nvect, edge2, edge1);
+ Normalize(d_nvect);
+
-int sb_detect_face_collisionCached(float face_v1[3],float face_v2[3],float face_v3[3],float *damp,
+ hash = vertexowner->soft->scratch->colliderhash;
+ ihash = BLI_ghashIterator_new(hash);
+ while (!BLI_ghashIterator_isDone(ihash) ) {
+
+ ccd_Mesh *ccdm = BLI_ghashIterator_getValue (ihash);
+ ob = BLI_ghashIterator_getKey (ihash);
+ /* only with deflecting set */
+ if(ob->pd && ob->pd->deflect) {
+ MVert *mvert= NULL;
+ MVert *mprevvert= NULL;
+ if(ccdm){
+ mvert= ccdm->mvert;
+ a = ccdm->totvert;
+ mprevvert= ccdm->mprevvert;
+ outerfacethickness =ob->pd->pdef_sboft;
+ if ((aabbmax[0] < ccdm->bbmin[0]) ||
+ (aabbmax[1] < ccdm->bbmin[1]) ||
+ (aabbmax[2] < ccdm->bbmin[2]) ||
+ (aabbmin[0] > ccdm->bbmax[0]) ||
+ (aabbmin[1] > ccdm->bbmax[1]) ||
+ (aabbmin[2] > ccdm->bbmax[2]) ) {
+ /* boxes dont intersect */
+ BLI_ghashIterator_step(ihash);
+ continue;
+ }
+
+ }
+ else{
+ /*aye that should be cached*/
+ printf("missing cache error \n");
+ BLI_ghashIterator_step(ihash);
+ continue;
+ }
+
+
+ /* use mesh*/
+ if (mvert) {
+ while(a){
+ VECCOPY(nv1,mvert[a-1].co);
+ if(mprevvert){
+ VecMulf(nv1,time);
+ Vec3PlusStVec(nv1,(1.0f-time),mprevvert[a-1].co);
+ }
+ /* origin to face_v2*/
+ VECSUB(nv1, nv1, face_v2);
+ facedist = Inpf(nv1,d_nvect);
+ if (ABS(facedist)<outerfacethickness){
+ if (point_in_tri_prism(nv1, face_v1,face_v2,face_v3) ){
+ float df;
+ if (facedist > 0){
+ df = (outerfacethickness-facedist)/outerfacethickness;
+ }
+ else {
+ df = (outerfacethickness+facedist)/outerfacethickness;
+ }
+
+ *damp=df*tune*ob->pd->pdef_sbdamp;
+
+ df = 0.01f*exp(- 100.0f*df);
+ Vec3PlusStVec(force,-df,d_nvect);
+ deflected = 3;
+ }
+ }
+ a--;
+ }/* while(a)*/
+ } /* if (mvert) */
+ } /* if(ob->pd && ob->pd->deflect) */
+ BLI_ghashIterator_step(ihash);
+ } /* while () */
+ BLI_ghashIterator_free(ihash);
+ return deflected;
+}
+
+
+static int sb_detect_face_collisionCached(float face_v1[3],float face_v2[3],float face_v3[3],float *damp,
float force[3], unsigned int par_layer,struct Object *vertexowner,float time)
{
Object *ob;
GHash *hash;
GHashIterator *ihash;
float nv1[3], nv2[3], nv3[3], nv4[3], edge1[3], edge2[3], d_nvect[3], aabbmin[3],aabbmax[3];
- float t;
+ float t,tune = 10.0f;
int a, deflected=0;
aabbmin[0] = MIN3(face_v1[0],face_v2[0],face_v3[0]);
@@ -1206,8 +1259,8 @@ int sb_detect_face_collisionCached(float face_v1[3],float face_v2[3],float face_
LineIntersectsTriangle(nv1, nv2, face_v1, face_v2, face_v3, &t, NULL) ||
LineIntersectsTriangle(nv2, nv3, face_v1, face_v2, face_v3, &t, NULL) ||
LineIntersectsTriangle(nv3, nv1, face_v1, face_v2, face_v3, &t, NULL) ){
- Vec3PlusStVec(force,-1.0f,d_nvect);
- *damp=ob->pd->pdef_sbdamp;
+ Vec3PlusStVec(force,-0.5f,d_nvect);
+ *damp=tune*ob->pd->pdef_sbdamp;
deflected = 2;
}
if (mface->v4){ /* quad */
@@ -1217,11 +1270,12 @@ int sb_detect_face_collisionCached(float face_v1[3],float face_v2[3],float face_
Crossf(d_nvect, edge2, edge1);
Normalize(d_nvect);
if (
- LineIntersectsTriangle(nv1, nv3, face_v1, face_v2, face_v3, &t, NULL) ||
+ /* LineIntersectsTriangle(nv1, nv3, face_v1, face_v2, face_v3, &t, NULL) ||
+ we did that edge allready */
LineIntersectsTriangle(nv3, nv4, face_v1, face_v2, face_v3, &t, NULL) ||
LineIntersectsTriangle(nv4, nv1, face_v1, face_v2, face_v3, &t, NULL) ){
- Vec3PlusStVec(force,-1.0f,d_nvect);
- *damp=ob->pd->pdef_sbdamp;
+ Vec3PlusStVec(force,-0.5f,d_nvect);
+ *damp=tune*ob->pd->pdef_sbdamp;
deflected = 2;
}
}
@@ -1237,12 +1291,12 @@ int sb_detect_face_collisionCached(float face_v1[3],float face_v2[3],float face_
-void scan_for_ext_face_forces(Object *ob,float timenow)
+static void scan_for_ext_face_forces(Object *ob,float timenow)
{
SoftBody *sb = ob->soft;
BodyFace *bf;
int a;
- float damp;
+ float damp=0.0f,choke=1.0f;
float tune = -10.0f;
float feedback[3];
@@ -1252,43 +1306,71 @@ void scan_for_ext_face_forces(Object *ob,float timenow)
bf = sb->scratch->bodyface;
for(a=0; a<sb->scratch->totface; a++, bf++) {
bf->ext_force[0]=bf->ext_force[1]=bf->ext_force[2]=0.0f;
+/*+++edges intruding*/
+ bf->flag &= ~BFF_INTERSECT;
feedback[0]=feedback[1]=feedback[2]=0.0f;
- bf->flag &= ~BFF_INTERSECT;
-
if (sb_detect_face_collisionCached(sb->bpoint[bf->v1].pos,sb->bpoint[bf->v2].pos, sb->bpoint[bf->v3].pos,
&damp, feedback, ob->lay ,ob , timenow)){
- Vec3PlusStVec(bf->ext_force,tune,feedback);
+ Vec3PlusStVec(sb->bpoint[bf->v1].force,tune,feedback);
+ Vec3PlusStVec(sb->bpoint[bf->v2].force,tune,feedback);
+ Vec3PlusStVec(sb->bpoint[bf->v3].force,tune,feedback);
+// Vec3PlusStVec(bf->ext_force,tune,feedback);
bf->flag |= BFF_INTERSECT;
+ choke = MIN2(MAX2(damp,choke),1.0f);
}
feedback[0]=feedback[1]=feedback[2]=0.0f;
if ((bf->v4) && (sb_detect_face_collisionCached(sb->bpoint[bf->v1].pos,sb->bpoint[bf->v3].pos, sb->bpoint[bf->v4].pos,
&damp, feedback, ob->lay ,ob , timenow))){
- Vec3PlusStVec(bf->ext_force,tune,feedback);
- bf->flag |= BFF_INTERSECT;
+ Vec3PlusStVec(sb->bpoint[bf->v1].force,tune,feedback);
+ Vec3PlusStVec(sb->bpoint[bf->v3].force,tune,feedback);
+ Vec3PlusStVec(sb->bpoint[bf->v4].force,tune,feedback);
+// Vec3PlusStVec(bf->ext_force,tune,feedback);
+ bf->flag |= BFF_INTERSECT;
+ choke = MIN2(MAX2(damp,choke),1.0f);
}
- }
+/*---edges intruding*/
+
+/*+++ close vertices*/
+ if (( bf->flag & BFF_INTERSECT)==0){
+ bf->flag &= ~BFF_CLOSEVERT;
+ tune = -1.0f;
+ feedback[0]=feedback[1]=feedback[2]=0.0f;
+ if (sb_detect_face_pointCached(sb->bpoint[bf->v1].pos,sb->bpoint[bf->v2].pos, sb->bpoint[bf->v3].pos,
+ &damp, feedback, ob->lay ,ob , timenow)){
+ Vec3PlusStVec(sb->bpoint[bf->v1].force,tune,feedback);
+ Vec3PlusStVec(sb->bpoint[bf->v2].force,tune,feedback);
+ Vec3PlusStVec(sb->bpoint[bf->v3].force,tune,feedback);
+// Vec3PlusStVec(bf->ext_force,tune,feedback);
+ bf->flag |= BFF_CLOSEVERT;
+ choke = MIN2(MAX2(damp,choke),1.0f);
+ }
-
-
+ feedback[0]=feedback[1]=feedback[2]=0.0f;
+ if ((bf->v4) && (sb_detect_face_pointCached(sb->bpoint[bf->v1].pos,sb->bpoint[bf->v3].pos, sb->bpoint[bf->v4].pos,
+ &damp, feedback, ob->lay ,ob , timenow))){
+ Vec3PlusStVec(sb->bpoint[bf->v1].force,tune,feedback);
+ Vec3PlusStVec(sb->bpoint[bf->v3].force,tune,feedback);
+ Vec3PlusStVec(sb->bpoint[bf->v4].force,tune,feedback);
+// Vec3PlusStVec(bf->ext_force,tune,feedback);
+ bf->flag |= BFF_CLOSEVERT;
+ choke = MIN2(MAX2(damp,choke),1.0f);
+ }
+ }
+/*--- close vertices*/
+ }
bf = sb->scratch->bodyface;
for(a=0; a<sb->scratch->totface; a++, bf++) {
- if ( bf->flag & BFF_INTERSECT)
+ if (( bf->flag & BFF_INTERSECT) || ( bf->flag & BFF_CLOSEVERT))
{
- VECADD(sb->bpoint[bf->v1].force,sb->bpoint[bf->v1].force,bf->ext_force);
- VECADD(sb->bpoint[bf->v2].force,sb->bpoint[bf->v2].force,bf->ext_force);
- VECADD(sb->bpoint[bf->v3].force,sb->bpoint[bf->v3].force,bf->ext_force);
+ sb->bpoint[bf->v1].choke2=MAX2(sb->bpoint[bf->v1].choke2,choke);
+ sb->bpoint[bf->v2].choke2=MAX2(sb->bpoint[bf->v2].choke2,choke);
+ sb->bpoint[bf->v3].choke2=MAX2(sb->bpoint[bf->v3].choke2,choke);
if (bf->v4){
- VECADD(sb->bpoint[bf->v4].force,sb->bpoint[bf->v4].force,bf->ext_force);
+ sb->bpoint[bf->v2].choke2=MAX2(sb->bpoint[bf->v2].choke2,choke);
}
-
- }
-
+ }
}
-
-
-
-
}
}
@@ -1297,7 +1379,7 @@ void scan_for_ext_face_forces(Object *ob,float timenow)
/* +++ the spring external section*/
-int sb_detect_edge_collisionCached(float edge_v1[3],float edge_v2[3],float *damp,
+static int sb_detect_edge_collisionCached(float edge_v1[3],float edge_v2[3],float *damp,
float force[3], unsigned int par_layer,struct Object *vertexowner,float time)
{
Object *ob;
@@ -1447,17 +1529,16 @@ int sb_detect_edge_collisionCached(float edge_v1[3],float edge_v2[3],float *damp
}
-void scan_for_ext_spring_forces(Object *ob,float timenow)
+
+static void _scan_for_ext_spring_forces(Object *ob,float timenow,int ifirst,int ilast, struct ListBase *do_effector)
{
SoftBody *sb = ob->soft;
- ListBase *do_effector;
int a;
float damp;
float feedback[3];
- do_effector= pdInitEffectors(ob,NULL);
if (sb && sb->totspring){
- for(a=0; a<sb->totspring; a++) {
+ for(a=ifirst; a<ilast; a++) {
BodySpring *bs = &sb->bspring[a];
bs->ext_force[0]=bs->ext_force[1]=bs->ext_force[2]=0.0f;
feedback[0]=feedback[1]=feedback[2]=0.0f;
@@ -1498,25 +1579,110 @@ void scan_for_ext_spring_forces(Object *ob,float timenow)
}
f = Normalize(vel);
f = -0.0001f*f*f*sb->aeroedge;
- /* todo add a nice angle dependant function */
- /* look up one at bergman scheafer */
+ /* (todo) add a nice angle dependant function done for now BUT */
+ /* still there could be some nice drag/lift function, but who needs it */
VECSUB(sp, sb->bpoint[bs->v1].pos , sb->bpoint[bs->v2].pos);
Projf(pr,vel,sp);
VECSUB(vel,vel,pr);
Normalize(vel);
- Vec3PlusStVec(bs->ext_force,f,vel);
+ if (ob->softflag & OB_SB_AERO_ANGLE){
+ Normalize(sp);
+ Vec3PlusStVec(bs->ext_force,f*(1.0f-ABS(Inpf(vel,sp))),vel);
+ }
+ else{
+ Vec3PlusStVec(bs->ext_force,f,vel); // to keep compatible with 2.45 release files
+ }
}
/* --- springs seeing wind */
}
}
}
- if(do_effector)
- pdEndEffectors(do_effector);
}
+
+
+static void scan_for_ext_spring_forces(Object *ob,float timenow)
+{
+ SoftBody *sb = ob->soft;
+ ListBase *do_effector= NULL;
+ do_effector= pdInitEffectors(ob,NULL);
+ if (sb){
+ _scan_for_ext_spring_forces(ob,timenow,0,sb->totspring,do_effector);
+ }
+ if(do_effector)
+ pdEndEffectors(do_effector);
+}
+
+static void *exec_scan_for_ext_spring_forces(void *data)
+{
+ SB_thread_context *pctx = (SB_thread_context*)data;
+ _scan_for_ext_spring_forces(pctx->ob,pctx->timenow,pctx->ifirst,pctx->ilast,pctx->do_effector);
+ return 0;
+}
+
+static void sb_sfesf_threads_run(struct Object *ob, float timenow,int totsprings,int *ptr_to_break_func())
+{
+ ListBase *do_effector = NULL;
+ ListBase threads;
+ SB_thread_context *sb_threads;
+ int i, totthread,left,dec;
+ int lowsprings =100; /* wild guess .. may increase with better thread management 'above' or even be UI option sb->spawn_cf_threads_nopts */
+
+ do_effector= pdInitEffectors(ob,NULL);
+
+ /* figure the number of threads while preventing pretty pointless threading overhead */
+ if(G.scene->r.mode & R_FIXED_THREADS)
+ totthread= G.scene->r.threads;
+ else
+ totthread= BLI_system_thread_count();
+ /* what if we got zillions of CPUs running but less to spread*/
+ while ((totsprings/totthread < lowsprings) && (totthread > 1)) {
+ totthread--;
+ }
+
+ sb_threads= MEM_callocN(sizeof(SB_thread_context)*totthread, "SBSpringsThread");
+ memset(sb_threads, 0, sizeof(SB_thread_context)*totthread);
+ left = totsprings;
+ dec = totsprings/totthread +1;
+ for(i=0; i<totthread; i++) {
+ sb_threads[i].ob = ob;
+ sb_threads[i].forcetime = 0.0; // not used here
+ sb_threads[i].timenow = timenow;
+ sb_threads[i].ilast = left;
+ left = left - dec;
+ if (left >0){
+ sb_threads[i].ifirst = left;
+ }
+ else
+ sb_threads[i].ifirst = 0;
+ sb_threads[i].do_effector = do_effector;
+ sb_threads[i].do_deflector = 0;// not used here
+ sb_threads[i].fieldfactor = 0.0f;// not used here
+ sb_threads[i].windfactor = 0.0f;// not used here
+ sb_threads[i].nr= i;
+ sb_threads[i].tot= totthread;
+ }
+ if(totthread > 1) {
+ BLI_init_threads(&threads, exec_scan_for_ext_spring_forces, totthread);
+
+ for(i=0; i<totthread; i++)
+ BLI_insert_thread(&threads, &sb_threads[i]);
+
+ BLI_end_threads(&threads);
+ }
+ else
+ exec_scan_for_ext_spring_forces(&sb_threads[0]);
+ /* clean up */
+ MEM_freeN(sb_threads);
+
+ if(do_effector)
+ pdEndEffectors(do_effector);
+}
+
+
/* --- the spring external section*/
-int choose_winner(float*w, float* pos,float*a,float*b,float*c,float*ca,float*cb,float*cc)
+static int choose_winner(float*w, float* pos,float*a,float*b,float*c,float*ca,float*cb,float*cc)
{
float mindist,cp;
int winner =1;
@@ -1543,7 +1709,7 @@ int choose_winner(float*w, float* pos,float*a,float*b,float*c,float*ca,float*cb,
-int sb_detect_vertex_collisionCached(float opco[3], float facenormal[3], float *damp,
+static int sb_detect_vertex_collisionCached(float opco[3], float facenormal[3], float *damp,
float force[3], unsigned int par_layer,struct Object *vertexowner,
float time,float vel[3], float *intrusion)
{
@@ -1833,253 +1999,6 @@ int sb_detect_vertex_collisionCached(float opco[3], float facenormal[3], float *
return deflected;
}
-/* not complete yet ..
- try to find a pos resolving all inside collisions
-*/
-#if 0 //mute it for now
-int sb_detect_vertex_collisionCachedEx(float opco[3], float facenormal[3], float *damp,
- float force[3], unsigned int par_layer,struct Object *vertexowner,
- float time,float vel[3], float *intrusion)
-{
- Object *ob;
- GHash *hash;
- GHashIterator *ihash;
- float nv1[3], nv2[3], nv3[3], nv4[3], edge1[3], edge2[3],d_nvect[3], dv1[3],ve[3],avel[3],
- vv1[3], vv2[3], vv3[3], vv4[3],
- facedist,n_mag,force_mag_norm,minx,miny,minz,maxx,maxy,maxz,
- innerfacethickness,outerfacethickness,
- closestinside,
- ee = 5.0f, ff = 0.1f, fa;
- int a, deflected=0, cavel=0;
-/* init */
- *intrusion = 0.0f;
- hash = vertexowner->soft->scratch->colliderhash;
- ihash = BLI_ghashIterator_new(hash);
-/* go */
- while (!BLI_ghashIterator_isDone(ihash) ) {
-
- ccd_Mesh *ccdm = BLI_ghashIterator_getValue (ihash);
- ob = BLI_ghashIterator_getKey (ihash);
- /* only with deflecting set */
- if(ob->pd && ob->pd->deflect) {
- MFace *mface= NULL;
- MVert *mvert= NULL;
- MVert *mprevvert= NULL;
- ccdf_minmax *mima= NULL;
-
- if(ccdm){
- mface= ccdm->mface;
- mvert= ccdm->mvert;
- mprevvert= ccdm->mprevvert;
- mima= ccdm->mima;
- a = ccdm->totface;
-
- minx =ccdm->bbmin[0];
- miny =ccdm->bbmin[1];
- minz =ccdm->bbmin[2];
-
- maxx =ccdm->bbmax[0];
- maxy =ccdm->bbmax[1];
- maxz =ccdm->bbmax[2];
-
- if ((opco[0] < minx) ||
- (opco[1] < miny) ||
- (opco[2] < minz) ||
- (opco[0] > maxx) ||
- (opco[1] > maxy) ||
- (opco[2] > maxz) ) {
- /* outside the padded boundbox --> collision object is too far away */
- BLI_ghashIterator_step(ihash);
- continue;
- }
- }
- else{
- /*aye that should be cached*/
- printf("missing cache error \n");
- BLI_ghashIterator_step(ihash);
- continue;
- }
-
- /* do object level stuff */
- /* need to have user control for that since it depends on model scale */
- innerfacethickness =-ob->pd->pdef_sbift;
- outerfacethickness =ob->pd->pdef_sboft;
- closestinside = innerfacethickness;
- fa = (ff*outerfacethickness-outerfacethickness);
- fa *= fa;
- fa = 1.0f/fa;
- avel[0]=avel[1]=avel[2]=0.0f;
- /* use mesh*/
- while (a--) {
- if (
- (opco[0] < mima->minx) ||
- (opco[0] > mima->maxx) ||
- (opco[1] < mima->miny) ||
- (opco[1] > mima->maxy) ||
- (opco[2] < mima->minz) ||
- (opco[2] > mima->maxz)
- ) {
- mface++;
- mima++;
- continue;
- }
-
- if (mvert){
-
- VECCOPY(nv1,mvert[mface->v1].co);
- VECCOPY(nv2,mvert[mface->v2].co);
- VECCOPY(nv3,mvert[mface->v3].co);
- if (mface->v4){
- VECCOPY(nv4,mvert[mface->v4].co);
- }
-
- if (mprevvert){
- /* grab the average speed of the collider vertices
- before we spoil nvX
- humm could be done once a SB steps but then we' need to store that too
- since the AABB reduced propabitlty to get here drasticallly
- it might be a nice tradeof CPU <--> memory
- */
- VECSUB(vv1,nv1,mprevvert[mface->v1].co);
- VECSUB(vv2,nv2,mprevvert[mface->v2].co);
- VECSUB(vv3,nv3,mprevvert[mface->v3].co);
- if (mface->v4){
- VECSUB(vv4,nv4,mprevvert[mface->v4].co);
- }
-
- VecMulf(nv1,time);
- Vec3PlusStVec(nv1,(1.0f-time),mprevvert[mface->v1].co);
-
- VecMulf(nv2,time);
- Vec3PlusStVec(nv2,(1.0f-time),mprevvert[mface->v2].co);
-
- VecMulf(nv3,time);
- Vec3PlusStVec(nv3,(1.0f-time),mprevvert[mface->v3].co);
-
- if (mface->v4){
- VecMulf(nv4,time);
- Vec3PlusStVec(nv4,(1.0f-time),mprevvert[mface->v4].co);
- }
- }
- }
-
- /* switch origin to be nv2*/
- VECSUB(edge1, nv1, nv2);
- VECSUB(edge2, nv3, nv2);
- VECSUB(dv1,opco,nv2); /* abuse dv1 to have vertex in question at *origin* of triangle */
-
- Crossf(d_nvect, edge2, edge1);
- n_mag = Normalize(d_nvect);
- facedist = Inpf(dv1,d_nvect);
-
- if ((facedist > closestinside) && (facedist < outerfacethickness)){
-// if ((facedist > innerfacethickness) && (facedist < outerfacethickness)){
- if (point_in_tri_prism(opco, nv1, nv2, nv3) ){
- force_mag_norm =(float)exp(-ee*facedist);
- if (facedist > outerfacethickness*ff)
- force_mag_norm =(float)force_mag_norm*fa*(facedist - outerfacethickness)*(facedist - outerfacethickness);
- *damp=ob->pd->pdef_sbdamp;
-
- if (facedist > 0.0f){
- *damp *= (1.0f - facedist/outerfacethickness);
- Vec3PlusStVec(force,force_mag_norm,d_nvect);
- if (deflected < 2){
- deflected = 1;
- if ((mprevvert) && (*damp > 0.0f)){
- choose_winner(ve,opco,nv1,nv2,nv3,vv1,vv2,vv3);
- VECADD(avel,avel,ve);
- cavel ++;
- }
- }
-
- }
- else{
- Vec3PlusStVec(force,force_mag_norm,d_nvect);
- VECCOPY(facenormal,d_nvect);
- if ((mprevvert) && (*damp > 0.0f)){
- choose_winner(avel,opco,nv1,nv2,nv3,vv1,vv2,vv3);
- cavel = 1;
- deflected = 2;
- closestinside = facedist;
- }
- }
- *intrusion = facedist;
- }
- }
- if (mface->v4){ /* quad */
- /* switch origin to be nv4 */
- VECSUB(edge1, nv3, nv4);
- VECSUB(edge2, nv1, nv4);
- VECSUB(dv1,opco,nv4); /* abuse dv1 to have vertex in question at *origin* of triangle */
-
- Crossf(d_nvect, edge2, edge1);
- n_mag = Normalize(d_nvect);
- facedist = Inpf(dv1,d_nvect);
-
- if ((facedist > innerfacethickness) && (facedist < outerfacethickness)){
- if (point_in_tri_prism(opco, nv1, nv3, nv4) ){
- force_mag_norm =(float)exp(-ee*facedist);
- if (facedist > outerfacethickness*ff)
- force_mag_norm =(float)force_mag_norm*fa*(facedist - outerfacethickness)*(facedist - outerfacethickness);
- Vec3PlusStVec(force,force_mag_norm,d_nvect);
- *damp=ob->pd->pdef_sbdamp;
-
- if (facedist > 0.0f){
- *damp *= (1.0f - facedist/outerfacethickness);
- Vec3PlusStVec(force,force_mag_norm,d_nvect);
- if (deflected < 2){
- deflected = 1;
- if ((mprevvert) && (*damp > 0.0f)){
- choose_winner(ve,opco,nv1,nv3,nv4,vv1,vv3,vv4);
- VECADD(avel,avel,ve);
- cavel ++;
- }
- }
-
- }
- else{
- Vec3PlusStVec(force,force_mag_norm,d_nvect);
- VECCOPY(facenormal,d_nvect);
- if ((mprevvert) && (*damp > 0.0f)){
- choose_winner(avel,opco,nv1,nv3,nv4,vv1,vv3,vv4);
- cavel = 1;
- deflected = 2;
- closestinside = facedist;
- }
- }
-
-
-
- *intrusion = facedist;
- }
-
- }
- }
- mface++;
- mima++;
- }/* while a */
- } /* if(ob->pd && ob->pd->deflect) */
- BLI_ghashIterator_step(ihash);
- } /* while () */
- BLI_ghashIterator_free(ihash);
- if (cavel) VecMulf(avel,1.0f/(float)cavel);
- VECCOPY(vel,avel);
-
- /* we did stay "outside" but have some close to contact forces
- just to be complete fake a face normal
- */
- if (deflected ==1){
- VECCOPY(facenormal,force);
- Normalize(facenormal);
- }
- else{
- facenormal[0] = facenormal[1] = facenormal[2] = 0.0f;
- }
- return deflected;
-}
-#endif
-
-
/* sandbox to plug in various deflection algos */
static int sb_deflect_face(Object *ob,float *actpos,float *facenormal,float *force,float *cf,float time,float *vel,float *intrusion)
@@ -2092,102 +2011,191 @@ static int sb_deflect_face(Object *ob,float *actpos,float *facenormal,float *for
return(deflected);
}
+/* hiding this for now .. but the jacobian may pop up on other tasks .. so i'd like to keep it
+static void dfdx_spring(int ia, int ic, int op, float dir[3],float L,float len,float factor)
+{
+ float m,delta_ij;
+ int i ,j;
+ if (L < len){
+ for(i=0;i<3;i++)
+ for(j=0;j<3;j++){
+ delta_ij = (i==j ? (1.0f): (0.0f));
+ m=factor*(dir[i]*dir[j] + (1-L/len)*(delta_ij - dir[i]*dir[j]));
+ nlMatrixAdd(ia+i,op+ic+j,m);
+ }
+ }
+ else{
+ for(i=0;i<3;i++)
+ for(j=0;j<3;j++){
+ m=factor*dir[i]*dir[j];
+ nlMatrixAdd(ia+i,op+ic+j,m);
+ }
+ }
+}
+
+
+static void dfdx_goal(int ia, int ic, int op, float factor)
+{
+ int i;
+ for(i=0;i<3;i++) nlMatrixAdd(ia+i,op+ic+i,factor);
+}
-static void softbody_calc_forces(Object *ob, float forcetime, float timenow)
+static void dfdv_goal(int ia, int ic,float factor)
+{
+ int i;
+ for(i=0;i<3;i++) nlMatrixAdd(ia+i,ic+i,factor);
+}
+*/
+static void sb_spring_force(Object *ob,int bpi,BodySpring *bs,float iks,float forcetime,int nl_flags)
{
-/* rule we never alter free variables :bp->vec bp->pos in here !
- * this will ruin adaptive stepsize AKA heun! (BM)
- */
+ SoftBody *sb= ob->soft; /* is supposed to be there */
+ BodyPoint *bp1,*bp2;
+
+ float dir[3],dvel[3];
+ float distance,forcefactor,kd,absvel,projvel;
+ int ia,ic;
+ /* prepare depending on which side of the spring we are on */
+ if (bpi == bs->v1){
+ bp1 = &sb->bpoint[bs->v1];
+ bp2 = &sb->bpoint[bs->v2];
+ ia =3*bs->v1;
+ ic =3*bs->v2;
+ }
+ else if (bpi == bs->v2){
+ bp1 = &sb->bpoint[bs->v2];
+ bp2 = &sb->bpoint[bs->v1];
+ ia =3*bs->v2;
+ ic =3*bs->v1;
+ }
+ else{
+ /* TODO make this debug option */
+ /**/
+ printf("bodypoint <bpi> is not attached to spring <*bs> --> sb_spring_force()\n");
+ return;
+ }
+
+ /* do bp1 <--> bp2 elastic */
+ VecSubf(dir,bp1->pos,bp2->pos);
+ distance = Normalize(dir);
+ if (bs->len < distance)
+ iks = 1.0f/(1.0f-sb->inspring)-1.0f ;/* inner spring constants function */
+ else
+ iks = 1.0f/(1.0f-sb->inpush)-1.0f ;/* inner spring constants function */
+
+ if(bs->len > 0.0f) /* check for degenerated springs */
+ forcefactor = iks/bs->len;
+ else
+ forcefactor = iks;
+ forcefactor *= bs->strength;
+ Vec3PlusStVec(bp1->force,(bs->len - distance)*forcefactor,dir);
+
+ /* do bp1 <--> bp2 viscous */
+ VecSubf(dvel,bp1->vec,bp2->vec);
+ kd = sb->infrict * sb_fric_force_scale(ob);
+ absvel = Normalize(dvel);
+ projvel = Inpf(dir,dvel);
+ kd *= absvel * projvel;
+ Vec3PlusStVec(bp1->force,-kd,dir);
+
+ /* do jacobian stuff if needed */
+ if(nl_flags & NLF_BUILD){
+ //int op =3*sb->totpoint;
+ //float mvel = -forcetime*kd;
+ //float mpos = -forcetime*forcefactor;
+ /* depending on my pos */
+ // dfdx_spring(ia,ia,op,dir,bs->len,distance,-mpos);
+ /* depending on my vel */
+ // dfdv_goal(ia,ia,mvel); // well that ignores geometie
+ if(bp2->goal < SOFTGOALSNAP){ /* ommit this bp when it snaps */
+ /* depending on other pos */
+ // dfdx_spring(ia,ic,op,dir,bs->len,distance,mpos);
+ /* depending on other vel */
+ // dfdv_goal(ia,ia,-mvel); // well that ignores geometie
+ }
+ }
+}
+
+
+/* since this is definitely the most CPU consuming task here .. try to spread it */
+/* core function _softbody_calc_forces_slice_in_a_thread */
+/* result is int to be able to flag user break */
+static int _softbody_calc_forces_slice_in_a_thread(Object *ob, float forcetime, float timenow,int ifirst,int ilast,int *ptr_to_break_func(),ListBase *do_effector,int do_deflector,float fieldfactor, float windfactor)
+{
+ float iks;
+ int bb,do_selfcollision,do_springcollision,do_aero;
+ int number_of_points_here = ilast - ifirst;
SoftBody *sb= ob->soft; /* is supposed to be there */
BodyPoint *bp;
- BodyPoint *bproot;
- BodySpring *bs;
- ListBase *do_effector;
- float iks, ks, kd, gravity, actspringlen, forcefactor, sd[3];
- float fieldfactor = 1000.0f, windfactor = 250.0f;
- float tune = sb->ballstiff;
- int a, b, do_deflector,do_selfcollision,do_springcollision,do_aero;
-
-
- gravity = sb->grav * sb_grav_force_scale(ob);
-
+ /* intitialize */
+ if (sb) {
/* check conditions for various options */
- do_deflector= query_external_colliders(ob);
- do_effector= pdInitEffectors(ob,NULL);
+ /* +++ could be done on object level to squeeze out the last bits of it */
do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF));
do_springcollision=do_deflector && (ob->softflag & OB_SB_EDGES) &&(ob->softflag & OB_SB_EDGECOLL);
do_aero=((sb->aeroedge)&& (ob->softflag & OB_SB_EDGES));
-
- iks = 1.0f/(1.0f-sb->inspring)-1.0f ;/* inner spring constants function */
- bproot= sb->bpoint; /* need this for proper spring addressing */
-
-
-
- if (do_springcollision || do_aero) scan_for_ext_spring_forces(ob,timenow);
- if (do_deflector) {
- float defforce[3];
- do_deflector = sb_detect_aabb_collisionCached(defforce,ob->lay,ob,timenow);
+ /* --- could be done on object level to squeeze out the last bits of it */
+ }
+ else {
+ printf("Error expected a SB here \n");
+ return (999);
}
- if (do_selfcollision ){
- float ce[3];
- VecMidf(ce,sb->scratch->aabbmax,sb->scratch->aabbmin);
- for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
- bp->octantflag = set_octant_flags(ce,bp->pos,bp->colball);
- }
+/* debugerin */
+ if (sb->totpoint < ifirst) {
+ printf("Aye 998");
+ return (998);
}
+/* debugerin */
- for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+
+ bp = &sb->bpoint[ifirst];
+ for(bb=number_of_points_here; bb>0; bb--, bp++) {
/* clear forces accumulator */
bp->force[0]= bp->force[1]= bp->force[2]= 0.0;
-
/* naive ball self collision */
/* needs to be done if goal snaps or not */
if(do_selfcollision){
int attached;
BodyPoint *obp;
+ BodySpring *bs;
int c,b;
float velcenter[3],dvel[3],def[3];
float distance;
float compare;
+ float bstune = sb->ballstiff;
- for(c=sb->totpoint, obp= sb->bpoint; c>=a; c--, obp++) {
-
- if ((bp->octantflag & obp->octantflag) == 0) continue;
-
+ for(c=sb->totpoint, obp= sb->bpoint; c>=ifirst+bb; c--, obp++) {
compare = (obp->colball + bp->colball);
VecSubf(def, bp->pos, obp->pos);
-
/* rather check the AABBoxes before ever calulating the real distance */
/* mathematically it is completly nuts, but performace is pretty much (3) times faster */
if ((ABS(def[0]) > compare) || (ABS(def[1]) > compare) || (ABS(def[2]) > compare)) continue;
-
distance = Normalize(def);
if (distance < compare ){
/* exclude body points attached with a spring */
attached = 0;
for(b=obp->nofsprings;b>0;b--){
bs = sb->bspring + obp->springs[b-1];
- if (( sb->totpoint-a == bs->v2) || ( sb->totpoint-a == bs->v1)){
+ if (( ilast-bb == bs->v2) || ( ilast-bb == bs->v1)){
attached=1;
continue;}
}
if (!attached){
- float f = tune/(distance) + tune/(compare*compare)*distance - 2.0f*tune/compare ;
+ float f = bstune/(distance) + bstune/(compare*compare)*distance - 2.0f*bstune/compare ;
VecMidf(velcenter, bp->vec, obp->vec);
VecSubf(dvel,velcenter,bp->vec);
VecMulf(dvel,sb->nodemass);
- Vec3PlusStVec(bp->force,sb->balldamp,dvel);
Vec3PlusStVec(bp->force,f*(1.0f-sb->balldamp),def);
+ Vec3PlusStVec(bp->force,sb->balldamp,dvel);
+
/* exploit force(a,b) == -force(b,a) part2/2 */
VecSubf(dvel,velcenter,obp->vec);
VecMulf(dvel,sb->nodemass);
Vec3PlusStVec(obp->force,sb->balldamp,dvel);
Vec3PlusStVec(obp->force,-f*(1.0f-sb->balldamp),def);
-
}
}
}
@@ -2197,24 +2205,26 @@ static void softbody_calc_forces(Object *ob, float forcetime, float timenow)
if(bp->goal < SOFTGOALSNAP){ /* ommit this bp when it snaps */
float auxvect[3];
float velgoal[3];
- float absvel =0, projvel= 0;
-
+
/* do goal stuff */
if(ob->softflag & OB_SB_GOAL) {
/* true elastic goal */
- VecSubf(auxvect,bp->origT,bp->pos);
+ float ks,kd;
+ VecSubf(auxvect,bp->pos,bp->origT);
ks = 1.0f/(1.0f- bp->goal*sb->goalspring)-1.0f ;
- bp->force[0]+= ks*(auxvect[0]);
- bp->force[1]+= ks*(auxvect[1]);
- bp->force[2]+= ks*(auxvect[2]);
+ bp->force[0]+= -ks*(auxvect[0]);
+ bp->force[1]+= -ks*(auxvect[1]);
+ bp->force[2]+= -ks*(auxvect[2]);
+
/* calulate damping forces generated by goals*/
VecSubf(velgoal,bp->origS, bp->origE);
kd = sb->goalfrict * sb_fric_force_scale(ob) ;
+ VecAddf(auxvect,velgoal,bp->vec);
if (forcetime > 0.0 ) { /* make sure friction does not become rocket motor on time reversal */
- bp->force[0]-= kd * (velgoal[0] + bp->vec[0]);
- bp->force[1]-= kd * (velgoal[1] + bp->vec[1]);
- bp->force[2]-= kd * (velgoal[2] + bp->vec[2]);
+ bp->force[0]-= kd * (auxvect[0]);
+ bp->force[1]-= kd * (auxvect[1]);
+ bp->force[2]-= kd * (auxvect[2]);
}
else {
bp->force[0]-= kd * (velgoal[0] - bp->vec[0]);
@@ -2224,13 +2234,15 @@ static void softbody_calc_forces(Object *ob, float forcetime, float timenow)
}
/* done goal stuff */
-
/* gravitation */
+ if (sb){
+ float gravity = sb->grav * sb_grav_force_scale(ob);
bp->force[2]-= gravity*sb->nodemass; /* individual mass of node here */
-
+ }
/* particle field & vortex */
if(do_effector) {
+ float kd;
float force[3]= {0.0f, 0.0f, 0.0f};
float speed[3]= {0.0f, 0.0f, 0.0f};
float eval_sb_fric_force_scale = sb_fric_force_scale(ob); /* just for calling function once */
@@ -2251,7 +2263,7 @@ static void softbody_calc_forces(Object *ob, float forcetime, float timenow)
}
else {
/* BP friction in media (not) moving*/
- kd= sb->mediafrict* sb_fric_force_scale(ob);
+ float kd = sb->mediafrict* sb_fric_force_scale(ob);
/* assume it to be proportional to actual velocity */
bp->force[0]-= bp->vec[0]*kd;
bp->force[1]-= bp->vec[1]*kd;
@@ -2260,40 +2272,34 @@ static void softbody_calc_forces(Object *ob, float forcetime, float timenow)
}
/* +++cached collision targets */
bp->choke = 0.0f;
+ bp->choke2 = 0.0f;
bp->flag &= ~SBF_DOFUZZY;
if(do_deflector) {
float cfforce[3],defforce[3] ={0.0f,0.0f,0.0f}, vel[3] = {0.0f,0.0f,0.0f}, facenormal[3], cf = 1.0f,intrusion;
- kd = 1.0f;
+ float kd = 1.0f;
if (sb_deflect_face(ob,bp->pos,facenormal,defforce,&cf,timenow,vel,&intrusion)){
- if (intrusion < 0.0f){
- /*bjornmose: uugh.. what an evil hack
- violation of the 'don't touch bp->pos in here' rule
- but works nice, like this-->
- we predict the solution beeing out of the collider
- in heun step No1 and leave the heun step No2 adapt to it
- so we kind of introduced a implicit solver for this case
- */
- Vec3PlusStVec(bp->pos,-intrusion,facenormal);
-
- sb->scratch->flag |= SBF_DOFUZZY;
- bp->flag |= SBF_DOFUZZY;
- bp->choke = sb->choke*0.01f;
- }
- else{
+ if (intrusion < 0.0f){
+ sb->scratch->flag |= SBF_DOFUZZY;
+ bp->flag |= SBF_DOFUZZY;
+ bp->choke = sb->choke*0.01f;
+ }
+
VECSUB(cfforce,bp->vec,vel);
Vec3PlusStVec(bp->force,-cf*50.0f,cfforce);
- }
-
- Vec3PlusStVec(bp->force,kd,defforce);
+
+ Vec3PlusStVec(bp->force,kd,defforce);
}
}
/* ---cached collision targets */
/* +++springs */
+ iks = 1.0f/(1.0f-sb->inspring)-1.0f ;/* inner spring constants function */
if(ob->softflag & OB_SB_EDGES) {
if (sb->bspring){ /* spring list exists at all ? */
+ int b;
+ BodySpring *bs;
for(b=bp->nofsprings;b>0;b--){
bs = sb->bspring + bp->springs[b-1];
if (do_springcollision || do_aero){
@@ -2302,67 +2308,532 @@ static void softbody_calc_forces(Object *ob, float forcetime, float timenow)
bp->choke = bs->cf;
}
-
- if (( (sb->totpoint-a) == bs->v1) ){
- actspringlen= VecLenf( (bproot+bs->v2)->pos, bp->pos);
- VecSubf(sd,(bproot+bs->v2)->pos, bp->pos);
- Normalize(sd);
-
- /* friction stuff V1 */
- VecSubf(velgoal,bp->vec,(bproot+bs->v2)->vec);
- kd = sb->infrict * sb_fric_force_scale(ob);
- absvel = Normalize(velgoal);
- projvel = ABS(Inpf(sd,velgoal));
- kd *= absvel * projvel;
- Vec3PlusStVec(bp->force,-kd,velgoal);
-
- if(bs->len > 0.0f) /* check for degenerated springs */
- forcefactor = (bs->len - actspringlen)/bs->len * iks;
- else
- forcefactor = actspringlen * iks;
- forcefactor *= bs->strength;
-
- Vec3PlusStVec(bp->force,-forcefactor,sd);
-
- }
-
- if (( (sb->totpoint-a) == bs->v2) ){
- actspringlen= VecLenf( (bproot+bs->v1)->pos, bp->pos);
- VecSubf(sd,bp->pos,(bproot+bs->v1)->pos);
- Normalize(sd);
-
- /* friction stuff V2 */
- VecSubf(velgoal,bp->vec,(bproot+bs->v1)->vec);
- kd = sb->infrict * sb_fric_force_scale(ob);
- absvel = Normalize(velgoal);
- projvel = ABS(Inpf(sd,velgoal));
- kd *= absvel * projvel;
- Vec3PlusStVec(bp->force,-kd,velgoal);
-
- if(bs->len > 0.0)
- forcefactor = (bs->len - actspringlen)/bs->len * iks;
- else
- forcefactor = actspringlen * iks;
- forcefactor *= bs->strength;
- Vec3PlusStVec(bp->force,+forcefactor,sd);
- }
+ // sb_spring_force(Object *ob,int bpi,BodySpring *bs,float iks,float forcetime,int nl_flags)
+ sb_spring_force(ob,ilast-bb,bs,iks,forcetime,0);
}/* loop springs */
}/* existing spring list */
}/*any edges*/
/* ---springs */
}/*omit on snap */
}/*loop all bp's*/
+return 0; /*done fine*/
+}
+
+static void *exec_softbody_calc_forces(void *data)
+{
+ SB_thread_context *pctx = (SB_thread_context*)data;
+ _softbody_calc_forces_slice_in_a_thread(pctx->ob,pctx->forcetime,pctx->timenow,pctx->ifirst,pctx->ilast,NULL,pctx->do_effector,pctx->do_deflector,pctx->fieldfactor,pctx->windfactor);
+ return 0;
+}
+
+static void sb_cf_threads_run(struct Object *ob, float forcetime, float timenow,int totpoint,int *ptr_to_break_func(),struct ListBase *do_effector,int do_deflector,float fieldfactor, float windfactor)
+{
+ ListBase threads;
+ SB_thread_context *sb_threads;
+ int i, totthread,left,dec;
+ int lowpoints =100; /* wild guess .. may increase with better thread management 'above' or even be UI option sb->spawn_cf_threads_nopts */
+
+ /* figure the number of threads while preventing pretty pointless threading overhead */
+ if(G.scene->r.mode & R_FIXED_THREADS)
+ totthread= G.scene->r.threads;
+ else
+ totthread= BLI_system_thread_count();
+ /* what if we got zillions of CPUs running but less to spread*/
+ while ((totpoint/totthread < lowpoints) && (totthread > 1)) {
+ totthread--;
+ }
+
+ /* printf("sb_cf_threads_run spawning %d threads \n",totthread); */
+
+ sb_threads= MEM_callocN(sizeof(SB_thread_context)*totthread, "SBThread");
+ memset(sb_threads, 0, sizeof(SB_thread_context)*totthread);
+ left = totpoint;
+ dec = totpoint/totthread +1;
+ for(i=0; i<totthread; i++) {
+ sb_threads[i].ob = ob;
+ sb_threads[i].forcetime = forcetime;
+ sb_threads[i].timenow = timenow;
+ sb_threads[i].ilast = left;
+ left = left - dec;
+ if (left >0){
+ sb_threads[i].ifirst = left;
+ }
+ else
+ sb_threads[i].ifirst = 0;
+ sb_threads[i].do_effector = do_effector;
+ sb_threads[i].do_deflector = do_deflector;
+ sb_threads[i].fieldfactor = fieldfactor;
+ sb_threads[i].windfactor = windfactor;
+ sb_threads[i].nr= i;
+ sb_threads[i].tot= totthread;
+ }
+
+
+ if(totthread > 1) {
+ BLI_init_threads(&threads, exec_softbody_calc_forces, totthread);
+
+ for(i=0; i<totthread; i++)
+ BLI_insert_thread(&threads, &sb_threads[i]);
+
+ BLI_end_threads(&threads);
+ }
+ else
+ exec_softbody_calc_forces(&sb_threads[0]);
+ /* clean up */
+ MEM_freeN(sb_threads);
+}
+static void softbody_calc_forcesEx(Object *ob, float forcetime, float timenow, int nl_flags)
+{
+/* rule we never alter free variables :bp->vec bp->pos in here !
+ * this will ruin adaptive stepsize AKA heun! (BM)
+ */
+ SoftBody *sb= ob->soft; /* is supposed to be there */
+ BodyPoint *bproot;
+ ListBase *do_effector;
+ float iks, gravity;
+ float fieldfactor = 1000.0f, windfactor = 250.0f;
+ int do_deflector,do_selfcollision,do_springcollision,do_aero;
+
+ gravity = sb->grav * sb_grav_force_scale(ob);
+
+ /* check conditions for various options */
+ do_deflector= query_external_colliders(ob);
+ do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF));
+ do_springcollision=do_deflector && (ob->softflag & OB_SB_EDGES) &&(ob->softflag & OB_SB_EDGECOLL);
+ do_aero=((sb->aeroedge)&& (ob->softflag & OB_SB_EDGES));
+
+ iks = 1.0f/(1.0f-sb->inspring)-1.0f ;/* inner spring constants function */
+ bproot= sb->bpoint; /* need this for proper spring addressing */
+
+ if (do_springcollision || do_aero)
+ sb_sfesf_threads_run(ob,timenow,sb->totspring,NULL);
+
+ /* after spring scan because it uses Effoctors too */
+ do_effector= pdInitEffectors(ob,NULL);
+
+ if (do_deflector) {
+ float defforce[3];
+ do_deflector = sb_detect_aabb_collisionCached(defforce,ob->lay,ob,timenow);
+ }
+
+ sb_cf_threads_run(ob,forcetime,timenow,sb->totpoint,NULL,do_effector,do_deflector,fieldfactor,windfactor);
/* finally add forces caused by face collision */
- if (ob->softflag & OB_SB_FACECOLL) scan_for_ext_face_forces(ob,timenow);
- /* cleanup */
+ if (ob->softflag & OB_SB_FACECOLL) scan_for_ext_face_forces(ob,timenow);
+
+ /* finish matrix and solve */
if(do_effector) pdEndEffectors(do_effector);
}
-static void softbody_apply_forces(Object *ob, float forcetime, int mode, float *err)
+
+static void softbody_calc_forces(Object *ob, float forcetime, float timenow, int nl_flags)
+{
+ /* redirection to the new threaded Version */
+ if (!(G.rt & 0x10)){ // 16
+ softbody_calc_forcesEx(ob, forcetime, timenow, nl_flags);
+ return;
+ }
+ else{
+ /* so the following will die */
+ /* |||||||||||||||||||||||||| */
+ /* VVVVVVVVVVVVVVVVVVVVVVVVVV */
+ /*backward compatibility note:
+ fixing bug [17428] which forces adaptive step size to tiny steps
+ in some situations
+ .. keeping G.rt==17 0x11 option for old files 'needing' the bug*/
+
+ /* rule we never alter free variables :bp->vec bp->pos in here !
+ * this will ruin adaptive stepsize AKA heun! (BM)
+ */
+ SoftBody *sb= ob->soft; /* is supposed to be there */
+ BodyPoint *bp;
+ BodyPoint *bproot;
+ BodySpring *bs;
+ ListBase *do_effector;
+ float iks, ks, kd, gravity;
+ float fieldfactor = 1000.0f, windfactor = 250.0f;
+ float tune = sb->ballstiff;
+ int a, b, do_deflector,do_selfcollision,do_springcollision,do_aero;
+
+
+ /* jacobian
+ NLboolean success;
+
+ if(nl_flags){
+ nlBegin(NL_SYSTEM);
+ nlBegin(NL_MATRIX);
+ }
+ */
+
+
+ gravity = sb->grav * sb_grav_force_scale(ob);
+
+ /* check conditions for various options */
+ do_deflector= query_external_colliders(ob);
+ do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF));
+ do_springcollision=do_deflector && (ob->softflag & OB_SB_EDGES) &&(ob->softflag & OB_SB_EDGECOLL);
+ do_aero=((sb->aeroedge)&& (ob->softflag & OB_SB_EDGES));
+
+ iks = 1.0f/(1.0f-sb->inspring)-1.0f ;/* inner spring constants function */
+ bproot= sb->bpoint; /* need this for proper spring addressing */
+
+ if (do_springcollision || do_aero) scan_for_ext_spring_forces(ob,timenow);
+ /* after spring scan because it uses Effoctors too */
+ do_effector= pdInitEffectors(ob,NULL);
+
+ if (do_deflector) {
+ float defforce[3];
+ do_deflector = sb_detect_aabb_collisionCached(defforce,ob->lay,ob,timenow);
+ }
+
+ for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+ /* clear forces accumulator */
+ bp->force[0]= bp->force[1]= bp->force[2]= 0.0;
+ if(nl_flags & NLF_BUILD){
+ //int ia =3*(sb->totpoint-a);
+ //int op =3*sb->totpoint;
+ /* dF/dV = v */
+ /* jacobioan
+ nlMatrixAdd(op+ia,ia,-forcetime);
+ nlMatrixAdd(op+ia+1,ia+1,-forcetime);
+ nlMatrixAdd(op+ia+2,ia+2,-forcetime);
+
+ nlMatrixAdd(ia,ia,1);
+ nlMatrixAdd(ia+1,ia+1,1);
+ nlMatrixAdd(ia+2,ia+2,1);
+
+ nlMatrixAdd(op+ia,op+ia,1);
+ nlMatrixAdd(op+ia+1,op+ia+1,1);
+ nlMatrixAdd(op+ia+2,op+ia+2,1);
+ */
+
+
+ }
+
+ /* naive ball self collision */
+ /* needs to be done if goal snaps or not */
+ if(do_selfcollision){
+ int attached;
+ BodyPoint *obp;
+ int c,b;
+ float velcenter[3],dvel[3],def[3];
+ float distance;
+ float compare;
+
+ for(c=sb->totpoint, obp= sb->bpoint; c>=a; c--, obp++) {
+
+ //if ((bp->octantflag & obp->octantflag) == 0) continue;
+
+ compare = (obp->colball + bp->colball);
+ VecSubf(def, bp->pos, obp->pos);
+
+ /* rather check the AABBoxes before ever calulating the real distance */
+ /* mathematically it is completly nuts, but performace is pretty much (3) times faster */
+ if ((ABS(def[0]) > compare) || (ABS(def[1]) > compare) || (ABS(def[2]) > compare)) continue;
+
+ distance = Normalize(def);
+ if (distance < compare ){
+ /* exclude body points attached with a spring */
+ attached = 0;
+ for(b=obp->nofsprings;b>0;b--){
+ bs = sb->bspring + obp->springs[b-1];
+ if (( sb->totpoint-a == bs->v2) || ( sb->totpoint-a == bs->v1)){
+ attached=1;
+ continue;}
+ }
+ if (!attached){
+ float f = tune/(distance) + tune/(compare*compare)*distance - 2.0f*tune/compare ;
+
+ VecMidf(velcenter, bp->vec, obp->vec);
+ VecSubf(dvel,velcenter,bp->vec);
+ VecMulf(dvel,sb->nodemass);
+
+ Vec3PlusStVec(bp->force,f*(1.0f-sb->balldamp),def);
+ Vec3PlusStVec(bp->force,sb->balldamp,dvel);
+
+ if(nl_flags & NLF_BUILD){
+ //int ia =3*(sb->totpoint-a);
+ //int ic =3*(sb->totpoint-c);
+ //int op =3*sb->totpoint;
+ //float mvel = forcetime*sb->nodemass*sb->balldamp;
+ //float mpos = forcetime*tune*(1.0f-sb->balldamp);
+ /*some quick and dirty entries to the jacobian*/
+ //dfdx_goal(ia,ia,op,mpos);
+ //dfdv_goal(ia,ia,mvel);
+ /* exploit force(a,b) == -force(b,a) part1/2 */
+ //dfdx_goal(ic,ic,op,mpos);
+ //dfdv_goal(ic,ic,mvel);
+
+
+ /*TODO sit down an X-out the true jacobian entries*/
+ /*well does not make to much sense because the eigenvalues
+ of the jacobian go negative; and negative eigenvalues
+ on a complex iterative system z(n+1)=A * z(n)
+ give imaginary roots in the charcateristic polynom
+ --> solutions that to z(t)=u(t)* exp ( i omega t) --> oscilations we don't want here
+ where u(t) is a unknown amplitude function (worst case rising fast)
+ */
+ }
+
+ /* exploit force(a,b) == -force(b,a) part2/2 */
+ VecSubf(dvel,velcenter,obp->vec);
+ VecMulf(dvel,sb->nodemass);
+
+ Vec3PlusStVec(obp->force,sb->balldamp,dvel);
+ Vec3PlusStVec(obp->force,-f*(1.0f-sb->balldamp),def);
+
+
+ }
+ }
+ }
+ }
+ /* naive ball self collision done */
+
+ if(bp->goal < SOFTGOALSNAP){ /* ommit this bp when it snaps */
+ float auxvect[3];
+ float velgoal[3];
+
+ /* do goal stuff */
+ if(ob->softflag & OB_SB_GOAL) {
+ /* true elastic goal */
+ VecSubf(auxvect,bp->pos,bp->origT);
+ ks = 1.0f/(1.0f- bp->goal*sb->goalspring)-1.0f ;
+ bp->force[0]+= -ks*(auxvect[0]);
+ bp->force[1]+= -ks*(auxvect[1]);
+ bp->force[2]+= -ks*(auxvect[2]);
+
+ if(nl_flags & NLF_BUILD){
+ //int ia =3*(sb->totpoint-a);
+ //int op =3*(sb->totpoint);
+ /* depending on my pos */
+ //dfdx_goal(ia,ia,op,ks*forcetime);
+ }
+
+
+ /* calulate damping forces generated by goals*/
+ VecSubf(velgoal,bp->origS, bp->origE);
+ kd = sb->goalfrict * sb_fric_force_scale(ob) ;
+ VecAddf(auxvect,velgoal,bp->vec);
+
+ if (forcetime > 0.0 ) { /* make sure friction does not become rocket motor on time reversal */
+ bp->force[0]-= kd * (auxvect[0]);
+ bp->force[1]-= kd * (auxvect[1]);
+ bp->force[2]-= kd * (auxvect[2]);
+ if(nl_flags & NLF_BUILD){
+ //int ia =3*(sb->totpoint-a);
+ Normalize(auxvect);
+ /* depending on my vel */
+ //dfdv_goal(ia,ia,kd*forcetime);
+ }
+
+ }
+ else {
+ bp->force[0]-= kd * (velgoal[0] - bp->vec[0]);
+ bp->force[1]-= kd * (velgoal[1] - bp->vec[1]);
+ bp->force[2]-= kd * (velgoal[2] - bp->vec[2]);
+ }
+ }
+ /* done goal stuff */
+
+
+ /* gravitation */
+ bp->force[2]-= gravity*sb->nodemass; /* individual mass of node here */
+ //bp->force[1]-= gravity*sb->nodemass; /* individual mass of node here */
+
+
+ /* particle field & vortex */
+ if(do_effector) {
+ float force[3]= {0.0f, 0.0f, 0.0f};
+ float speed[3]= {0.0f, 0.0f, 0.0f};
+ float eval_sb_fric_force_scale = sb_fric_force_scale(ob); /* just for calling function once */
+
+ pdDoEffectors(do_effector, bp->pos, force, speed, (float)G.scene->r.cfra, 0.0f, PE_WIND_AS_SPEED);
+
+ /* apply forcefield*/
+ VecMulf(force,fieldfactor* eval_sb_fric_force_scale);
+ VECADD(bp->force, bp->force, force);
+
+ /* BP friction in moving media */
+ kd= sb->mediafrict* eval_sb_fric_force_scale;
+ bp->force[0] -= kd * (bp->vec[0] + windfactor*speed[0]/eval_sb_fric_force_scale);
+ bp->force[1] -= kd * (bp->vec[1] + windfactor*speed[1]/eval_sb_fric_force_scale);
+ bp->force[2] -= kd * (bp->vec[2] + windfactor*speed[2]/eval_sb_fric_force_scale);
+ /* now we'll have nice centrifugal effect for vortex */
+
+ }
+ else {
+ /* BP friction in media (not) moving*/
+ kd= sb->mediafrict* sb_fric_force_scale(ob);
+ /* assume it to be proportional to actual velocity */
+ bp->force[0]-= bp->vec[0]*kd;
+ bp->force[1]-= bp->vec[1]*kd;
+ bp->force[2]-= bp->vec[2]*kd;
+ /* friction in media done */
+ if(nl_flags & NLF_BUILD){
+ //int ia =3*(sb->totpoint-a);
+ /* da/dv = */
+
+ // nlMatrixAdd(ia,ia,forcetime*kd);
+ // nlMatrixAdd(ia+1,ia+1,forcetime*kd);
+ // nlMatrixAdd(ia+2,ia+2,forcetime*kd);
+ }
+
+ }
+ /* +++cached collision targets */
+ bp->choke = 0.0f;
+ bp->choke2 = 0.0f;
+ bp->flag &= ~SBF_DOFUZZY;
+ if(do_deflector) {
+ float cfforce[3],defforce[3] ={0.0f,0.0f,0.0f}, vel[3] = {0.0f,0.0f,0.0f}, facenormal[3], cf = 1.0f,intrusion;
+ kd = 1.0f;
+
+ if (sb_deflect_face(ob,bp->pos,facenormal,defforce,&cf,timenow,vel,&intrusion)){
+ if ((!nl_flags)&&(intrusion < 0.0f)){
+ if(G.rt & 0x01){ // 17 we did check for bit 0x10 before
+ /*fixing bug [17428] this forces adaptive step size to tiny steps
+ in some situations .. keeping G.rt==17 option for old files 'needing' the bug
+ */
+ /*bjornmose: uugh.. what an evil hack
+ violation of the 'don't touch bp->pos in here' rule
+ but works nice, like this-->
+ we predict the solution beeing out of the collider
+ in heun step No1 and leave the heun step No2 adapt to it
+ so we kind of introduced a implicit solver for this case
+ */
+ Vec3PlusStVec(bp->pos,-intrusion,facenormal);
+ }
+ else{
+
+ VECSUB(cfforce,bp->vec,vel);
+ Vec3PlusStVec(bp->force,-cf*50.0f,cfforce);
+ }
+
+
+ sb->scratch->flag |= SBF_DOFUZZY;
+ bp->flag |= SBF_DOFUZZY;
+ bp->choke = sb->choke*0.01f;
+ }
+ else{
+ VECSUB(cfforce,bp->vec,vel);
+ Vec3PlusStVec(bp->force,-cf*50.0f,cfforce);
+ }
+ Vec3PlusStVec(bp->force,kd,defforce);
+ if (nl_flags & NLF_BUILD){
+ // int ia =3*(sb->totpoint-a);
+ // int op =3*sb->totpoint;
+ //dfdx_goal(ia,ia,op,mpos); // don't do unless you know
+ //dfdv_goal(ia,ia,-cf);
+
+ }
+
+ }
+
+ }
+ /* ---cached collision targets */
+
+ /* +++springs */
+ if(ob->softflag & OB_SB_EDGES) {
+ if (sb->bspring){ /* spring list exists at all ? */
+ for(b=bp->nofsprings;b>0;b--){
+ bs = sb->bspring + bp->springs[b-1];
+ if (do_springcollision || do_aero){
+ VecAddf(bp->force,bp->force,bs->ext_force);
+ if (bs->flag & BSF_INTERSECT)
+ bp->choke = bs->cf;
+
+ }
+ // sb_spring_force(Object *ob,int bpi,BodySpring *bs,float iks,float forcetime,int nl_flags)
+ // rather remove nl_falgs from code .. will make things a lot cleaner
+ sb_spring_force(ob,sb->totpoint-a,bs,iks,forcetime,0);
+ }/* loop springs */
+ }/* existing spring list */
+ }/*any edges*/
+ /* ---springs */
+ }/*omit on snap */
+ }/*loop all bp's*/
+
+
+ /* finally add forces caused by face collision */
+ if (ob->softflag & OB_SB_FACECOLL) scan_for_ext_face_forces(ob,timenow);
+
+ /* finish matrix and solve */
+#if (0) // remove onl linking for now .. still i am not sure .. the jacobian can be usefull .. so keep that BM
+ if(nl_flags & NLF_SOLVE){
+ //double sct,sst=PIL_check_seconds_timer();
+ for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+ int iv =3*(sb->totpoint-a);
+ int ip =3*(2*sb->totpoint-a);
+ int n;
+ for (n=0;n<3;n++) {nlRightHandSideSet(0, iv+n, bp->force[0+n]);}
+ for (n=0;n<3;n++) {nlRightHandSideSet(0, ip+n, bp->vec[0+n]);}
+ }
+ nlEnd(NL_MATRIX);
+ nlEnd(NL_SYSTEM);
+
+ if ((G.rt == 32) && (nl_flags & NLF_BUILD))
+ {
+ printf("####MEE#####\n");
+ nlPrintMatrix();
+ }
+
+ success= nlSolveAdvanced(NULL, 1);
+
+ // nlPrintMatrix(); /* for debug purpose .. anyhow cropping B vector looks like working */
+ if(success){
+ float f;
+ int index =0;
+ /* for debug purpose .. anyhow cropping B vector looks like working */
+ if (G.rt ==32)
+ for(a=2*sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+ f=nlGetVariable(0,index);
+ printf("(%f ",f);index++;
+ f=nlGetVariable(0,index);
+ printf("%f ",f);index++;
+ f=nlGetVariable(0,index);
+ printf("%f)",f);index++;
+ }
+
+ index =0;
+ for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+ f=nlGetVariable(0,index);
+ bp->impdv[0] = f; index++;
+ f=nlGetVariable(0,index);
+ bp->impdv[1] = f; index++;
+ f=nlGetVariable(0,index);
+ bp->impdv[2] = f; index++;
+ }
+ /*
+ for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+ f=nlGetVariable(0,index);
+ bp->impdx[0] = f; index++;
+ f=nlGetVariable(0,index);
+ bp->impdx[1] = f; index++;
+ f=nlGetVariable(0,index);
+ bp->impdx[2] = f; index++;
+ }
+ */
+ }
+ else{
+ printf("Matrix inversion failed \n");
+ for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+ VECCOPY(bp->impdv,bp->force);
+ }
+
+ }
+
+ //sct=PIL_check_seconds_timer();
+ //if (sct-sst > 0.01f) printf(" implicit solver time %f %s \r",sct-sst,ob->id.name);
+ }
+ /* cleanup */
+#endif
+ if(do_effector) pdEndEffectors(do_effector);
+ }
+}
+
+static void softbody_apply_forces(Object *ob, float forcetime, int mode, float *err, int mid_flags)
{
/* time evolution */
/* actually does an explicit euler step mode == 0 */
@@ -2370,7 +2841,7 @@ static void softbody_apply_forces(Object *ob, float forcetime, int mode, float *
SoftBody *sb= ob->soft; /* is supposed to be there */
BodyPoint *bp;
float dx[3],dv[3],aabbmin[3],aabbmax[3],cm[3]={0.0f,0.0f,0.0f};
- float timeovermass;
+ float timeovermass/*,freezeloc=0.00001f,freezeforce=0.00000000001f*/;
float maxerrpos= 0.0f,maxerrvel = 0.0f;
int a,fuzzy=0;
@@ -2385,14 +2856,14 @@ static void softbody_apply_forces(Object *ob, float forcetime, int mode, float *
for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
if(bp->goal < SOFTGOALSNAP){
+ /* this makes t~ = t */
+ if(mid_flags & MID_PRESERVE) VECCOPY(dx,bp->vec);
/* so here is (v)' = a(cceleration) = sum(F_springs)/m + gravitation + some friction forces + more forces*/
/* the ( ... )' operator denotes derivate respective time */
/* the euler step for velocity then becomes */
/* v(t + dt) = v(t) + a(t) * dt */
- bp->force[0]*= timeovermass; /* individual mass of node here */
- bp->force[1]*= timeovermass;
- bp->force[2]*= timeovermass;
+ VecMulf(bp->force,timeovermass);/* individual mass of node here */
/* some nasty if's to have heun in here too */
VECCOPY(dv,bp->force);
@@ -2413,14 +2884,24 @@ static void softbody_apply_forces(Object *ob, float forcetime, int mode, float *
}
else {VECADD(bp->vec, bp->vec, bp->force);}
+ /* this makes t~ = t+dt */
+ if(!(mid_flags & MID_PRESERVE)) VECCOPY(dx,bp->vec);
+
/* so here is (x)'= v(elocity) */
/* the euler step for location then becomes */
- /* x(t + dt) = x(t) + v(t) * dt */
-
- VECCOPY(dx,bp->vec);
- dx[0]*=forcetime;
- dx[1]*=forcetime;
- dx[2]*=forcetime;
+ /* x(t + dt) = x(t) + v(t~) * dt */
+ VecMulf(dx,forcetime);
+
+ /* the freezer coming sooner or later */
+ /*
+ if ((Inpf(dx,dx)<freezeloc )&&(Inpf(bp->force,bp->force)<freezeforce )){
+ bp->frozen /=2;
+ }
+ else{
+ bp->frozen =MIN2(bp->frozen*1.05f,1.0f);
+ }
+ VecMulf(dx,bp->frozen);
+ */
/* again some nasty if's to have heun in here too */
if (mode ==1){
VECCOPY(bp->prevpos,bp->pos);
@@ -2430,7 +2911,7 @@ static void softbody_apply_forces(Object *ob, float forcetime, int mode, float *
if (mode ==2){
bp->pos[0] = bp->prevpos[0] + 0.5f * ( dx[0] + bp->prevdx[0]);
bp->pos[1] = bp->prevpos[1] + 0.5f * ( dx[1] + bp->prevdx[1]);
- bp->pos[2] = bp->prevpos[2] + 0.5f* ( dx[2] + bp->prevdx[2]);
+ bp->pos[2] = bp->prevpos[2] + 0.5f * ( dx[2] + bp->prevdx[2]);
maxerrpos = MAX2(maxerrpos,ABS(dx[0] - bp->prevdx[0]));
maxerrpos = MAX2(maxerrpos,ABS(dx[1] - bp->prevdx[1]));
maxerrpos = MAX2(maxerrpos,ABS(dx[2] - bp->prevdx[2]));
@@ -2439,10 +2920,11 @@ static void softbody_apply_forces(Object *ob, float forcetime, int mode, float *
the collider object signals to get out by pushing hard. on the other hand
we don't want to end up in deep space so we add some <viscosity>
to balance that out */
+ if (bp->choke2 > 0.0f){
+ VecMulf(bp->vec,(1.0f - bp->choke2));
+ }
if (bp->choke > 0.0f){
- bp->vec[0] = bp->vec[0]*(1.0f - bp->choke);
- bp->vec[1] = bp->vec[1]*(1.0f - bp->choke);
- bp->vec[2] = bp->vec[2]*(1.0f - bp->choke);
+ VecMulf(bp->vec,(1.0f - bp->choke));
}
}
@@ -2489,6 +2971,81 @@ static void softbody_restore_prev_step(Object *ob)
}
}
+#if 0
+static void softbody_store_step(Object *ob)
+{
+ SoftBody *sb= ob->soft; /* is supposed to be there*/
+ BodyPoint *bp;
+ int a;
+
+ for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+ VECCOPY(bp->prevvec,bp->vec);
+ VECCOPY(bp->prevpos,bp->pos);
+ }
+}
+
+
+/* used by predictors and correctors */
+static void softbody_store_state(Object *ob,float *ppos,float *pvel)
+{
+ SoftBody *sb= ob->soft; /* is supposed to be there*/
+ BodyPoint *bp;
+ int a;
+ float *pp=ppos,*pv=pvel;
+
+ for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+
+ VECCOPY(pv, bp->vec);
+ pv+=3;
+
+ VECCOPY(pp, bp->pos);
+ pp+=3;
+ }
+}
+
+/* used by predictors and correctors */
+static void softbody_retrieve_state(Object *ob,float *ppos,float *pvel)
+{
+ SoftBody *sb= ob->soft; /* is supposed to be there*/
+ BodyPoint *bp;
+ int a;
+ float *pp=ppos,*pv=pvel;
+
+ for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+
+ VECCOPY(bp->vec,pv);
+ pv+=3;
+
+ VECCOPY(bp->pos,pp);
+ pp+=3;
+ }
+}
+
+/* used by predictors and correctors */
+static void softbody_swap_state(Object *ob,float *ppos,float *pvel)
+{
+ SoftBody *sb= ob->soft; /* is supposed to be there*/
+ BodyPoint *bp;
+ int a;
+ float *pp=ppos,*pv=pvel;
+ float temp[3];
+
+ for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+
+ VECCOPY(temp, bp->vec);
+ VECCOPY(bp->vec,pv);
+ VECCOPY(pv,temp);
+ pv+=3;
+
+ VECCOPY(temp, bp->pos);
+ VECCOPY(bp->pos,pp);
+ VECCOPY(pp,temp);
+ pp+=3;
+ }
+}
+#endif
+
+
/* care for bodypoints taken out of the 'ordinary' solver step
** because they are screwed to goal by bolts
** they just need to move along with the goal in time
@@ -2509,6 +3066,30 @@ static void softbody_apply_goalsnap(Object *ob)
}
}
+
+static void apply_spring_memory(Object *ob)
+{
+ SoftBody *sb = ob->soft;
+ BodySpring *bs;
+ BodyPoint *bp1, *bp2;
+ int a;
+ float b,l,r;
+
+ b = sb->plastic;
+ if (sb && sb->totspring){
+ for(a=0; a<sb->totspring; a++) {
+ bs = &sb->bspring[a];
+ bp1 =&sb->bpoint[bs->v1];
+ bp2 =&sb->bpoint[bs->v2];
+ l = VecLenf(bp1->pos,bp2->pos);
+ r = bs->len/l;
+ if (( r > 1.05f) || (r < 0.95)){
+ bs->len = ((100.0f - b) * bs->len + b*l)/100.0f;
+ }
+ }
+ }
+}
+
/* expects full initialized softbody */
static void interpolate_exciter(Object *ob, int timescale, int time)
{
@@ -2597,9 +3178,9 @@ static void springs_from_mesh(Object *ob)
}
/* recalculate spring length for meshes here */
- /* special hidden feature! shrink to fit */
- if (G.rt > 500){
- scale = (G.rt - 500) / 100.0f;
+ /* public version shrink to fit */
+ if (sb->springpreload != 0 ){
+ scale = sb->springpreload / 100.0f;
}
for(a=0; a<sb->totspring; a++) {
BodySpring *bs = &sb->bspring[a];
@@ -2712,7 +3293,7 @@ static void mesh_faces_to_scratch(Object *ob)
helper function to get proper spring length
when object is rescaled
*/
-float globallen(float *v1,float *v2,Object *ob)
+static float globallen(float *v1,float *v2,Object *ob)
{
float p1[3],p2[3];
VECCOPY(p1,v1);
@@ -3002,9 +3583,12 @@ static void particles_to_softbody(Object *ob)
/* renew ends with ob->soft with points and edges, also checks & makes ob->soft */
renew_softbody(ob, totpoint, totedge);
- psys->particles->bpi = 0;
- for(a=1, pa=psys->particles+1; a<psys->totpart; a++, pa++)
- pa->bpi = (pa-1)->bpi + pa->totkey;
+ /* find first BodyPoint index for each particle */
+ if(psys->totpart > 0) {
+ psys->particles->bpi = 0;
+ for(a=1, pa=psys->particles+1; a<psys->totpart; a++, pa++)
+ pa->bpi = (pa-1)->bpi + (pa-1)->totkey;
+ }
/* we always make body points */
sb= ob->soft;
@@ -3066,97 +3650,68 @@ static void softbody_to_object(Object *ob, float (*vertexCos)[3], int numVerts,
}
}
-void softbody_clear_cache(Object *ob, float framenr)
-{
- SoftBody *sb = ob->soft;
- ModifierData *md = ob->modifiers.first;
- int stack_index = -1;
- int a;
-
- if(sb==NULL) return;
-
- if(sb->particles)
- stack_index = modifiers_indexInObject(ob,(ModifierData*)psys_get_modifier(ob,sb->particles));
- else {
- for(a=0; md; md=md->next, a++) {
- if(md->type == eModifierType_Softbody) {
- stack_index = a;
- break;
- }
- }
- }
-
- BKE_ptcache_id_clear((ID *)ob, PTCACHE_CLEAR_ALL, framenr, stack_index);
-}
-static void softbody_write_cache(Object *ob, float framenr)
+void sbWriteCache(Object *ob, int framenr)
{
- FILE *fp = NULL;
- SoftBody *sb = ob->soft;
+ SoftBody *sb= ob->soft;
BodyPoint *bp;
- ModifierData *md = ob->modifiers.first;
- int stack_index = -1;
+ PTCacheID pid;
+ PTCacheFile *pf;
int a;
- if(sb->totpoint == 0) return;
-
- if(sb->particles)
- stack_index = modifiers_indexInObject(ob,(ModifierData*)psys_get_modifier(ob,sb->particles));
- else {
- for(a=0; md; md=md->next, a++) {
- if(md->type == eModifierType_Softbody) {
- stack_index = a;
- break;
- }
- }
- }
+ if(sb->totpoint == 0)
+ return;
- fp = BKE_ptcache_id_fopen((ID *)ob, 'w', framenr, stack_index);
- if(!fp) return;
+ BKE_ptcache_id_from_softbody(&pid, ob, sb);
+ pf= BKE_ptcache_file_open(&pid, PTCACHE_FILE_WRITE, framenr);
+ if(!pf)
+ return;
+
+ for(a=0, bp=sb->bpoint; a<sb->totpoint; a++, bp++)
+ BKE_ptcache_file_write_floats(pf, bp->pos, 3);
for(a=0, bp=sb->bpoint; a<sb->totpoint; a++, bp++)
- fwrite(&bp->pos, sizeof(float), 3, fp);
-
- fclose(fp);
+ BKE_ptcache_file_write_floats(pf, bp->vec, 3);
+
+ BKE_ptcache_file_close(pf);
}
+
static int softbody_read_cache(Object *ob, float framenr)
{
- FILE *fp = NULL;
- SoftBody *sb = ob->soft;
+ SoftBody *sb= ob->soft;
BodyPoint *bp;
- ModifierData *md = ob->modifiers.first;
- int stack_index = -1;
- int a, ret = 1;
+ PTCacheID pid;
+ PTCacheFile *pf;
+ int a;
- if(sb->totpoint == 0) return 0;
+ if(sb->totpoint == 0)
+ return 0;
+
+ BKE_ptcache_id_from_softbody(&pid, ob, sb);
+ pf= BKE_ptcache_file_open(&pid, PTCACHE_FILE_READ, framenr);
+ if(!pf)
+ return 0;
- if(sb->particles)
- stack_index = modifiers_indexInObject(ob,(ModifierData*)psys_get_modifier(ob,sb->particles));
- else {
- for(a=0; md; md=md->next, a++) {
- if(md->type == eModifierType_Softbody) {
- stack_index = a;
- break;
- }
+ for(a=0, bp=sb->bpoint; a<sb->totpoint; a++, bp++) {
+ if(!BKE_ptcache_file_read_floats(pf, bp->pos, 3)) {
+ BKE_ptcache_file_close(pf);
+ return 0;
}
}
- fp = BKE_ptcache_id_fopen((ID *)ob, 'r', framenr, stack_index);
- if(!fp)
- ret = 0;
- else {
- for(a=0, bp=sb->bpoint; a<sb->totpoint; a++, bp++)
- if(fread(&bp->pos, sizeof(float), 3, fp) != 3) {
- ret = 0;
- break;
- }
-
- fclose(fp);
+ for(a=0, bp=sb->bpoint; a<sb->totpoint; a++, bp++) {
+ if(!BKE_ptcache_file_read_floats(pf, bp->vec, 3)) {
+ BKE_ptcache_file_close(pf);
+ return 0;
+ }
}
- return ret;
+ BKE_ptcache_file_close(pf);
+
+ return 1;
}
+
/* +++ ************ maintaining scratch *************** */
-void sb_new_scratch(SoftBody *sb)
+static void sb_new_scratch(SoftBody *sb)
{
if (!sb) return;
sb->scratch = MEM_callocN(sizeof(SBScratch), "SBScratch");
@@ -3192,6 +3747,8 @@ SoftBody *sbNew(void)
sb->inspring= 0.5f;
sb->infrict= 0.5f;
+ /*todo backward file compat should copy inspring to inpush while reading old files*/
+ sb->inpush = 0.5f;
sb->interval= 10;
sb->sfra= G.scene->r.sfra;
@@ -3204,9 +3761,16 @@ SoftBody *sbNew(void)
sb->minloops = 10;
+ sb->maxloops = 300;
sb->choke = 3;
sb_new_scratch(sb);
+ /*todo backward file compat should set sb->shearstiff = 1.0f while reading old files*/
+ sb->shearstiff = 1.0f;
+ sb->solverflags |= SBSO_OLDERR;
+
+ sb->pointcache = BKE_ptcache_add();
+
return sb;
}
@@ -3214,14 +3778,19 @@ SoftBody *sbNew(void)
void sbFree(SoftBody *sb)
{
free_softbody_intern(sb);
+ BKE_ptcache_free(sb->pointcache);
MEM_freeN(sb);
}
+void sbFreeSimulation(SoftBody *sb)
+{
+ free_softbody_intern(sb);
+}
/* makes totally fresh start situation */
void sbObjectToSoftbody(Object *ob)
{
- ob->softflag |= OB_SB_REDO;
+ //ob->softflag |= OB_SB_REDO;
free_softbody_intern(ob->soft);
}
@@ -3245,306 +3814,408 @@ void sbSetInterruptCallBack(int (*f)(void))
SB_localInterruptCallBack = f;
}
-
-/* simulates one step. framenr is in frames */
-void sbObjectStep(Object *ob, float framenr, float (*vertexCos)[3], int numVerts)
+static void softbody_update_positions(Object *ob, SoftBody *sb, float (*vertexCos)[3], int numVerts)
{
- ParticleSystemModifierData *psmd=0;
- ParticleData *pa=0;
- SoftBody *sb;
+ ParticleSystemModifierData *psmd= NULL;
+ ParticleData *pa= NULL;
HairKey *key= NULL;
BodyPoint *bp;
+ float hairmat[4][4];
int a;
- float dtime,ctime,forcetime,err;
+
+ /* update the vertex locations */
+ if(sb->particles && sb->particles->totpart>0) {
+ psmd= psys_get_modifier(ob,sb->particles);
+
+ pa= sb->particles->particles;
+ key= pa->hair;
+
+ psys_mat_hair_to_global(ob, psmd->dm, sb->particles->part->from, pa, hairmat);
+ }
+
+ for(a=0,bp=sb->bpoint; a<numVerts; a++, bp++) {
+ /* store where goals are now */
+ VECCOPY(bp->origS, bp->origE);
+ /* copy the position of the goals at desired end time */
+ if(sb->particles) {
+ if(key == pa->hair + pa->totkey) {
+ pa++;
+ key = pa->hair;
+
+ psys_mat_hair_to_global(ob, psmd->dm, sb->particles->part->from, pa, hairmat);
+ }
+ VECCOPY(bp->origE, key->co);
+ Mat4MulVecfl(hairmat,bp->origE);
+
+ key++;
+ }
+ else{
+ VECCOPY(bp->origE, vertexCos[a]);
+ /* vertexCos came from local world, go global */
+ Mat4MulVecfl(ob->obmat, bp->origE);
+ }
+ /* just to be save give bp->origT a defined value
+ will be calulated in interpolate_exciter()*/
+ VECCOPY(bp->origT, bp->origE);
+ }
+}
+
+static void softbody_reset(Object *ob, SoftBody *sb, float (*vertexCos)[3], int numVerts)
+{
+ ParticleSystemModifierData *psmd= NULL;
+ HairKey *key= NULL;
+ ParticleData *pa= NULL;
+ BodyPoint *bp;
float hairmat[4][4];
+ int a;
- /* This part only sets goals and springs, based on original mesh/curve/lattice data.
- Copying coordinates happens in next chunk by setting softbody flag OB_SB_RESET */
- /* remake softbody if: */
- if( (ob->softflag & OB_SB_REDO) || /* signal after weightpainting */
- (ob->soft==NULL) || /* just to be nice we allow full init */
- (ob->soft->bpoint==NULL) || /* after reading new file, or acceptable as signal to refresh */
- (numVerts!=ob->soft->totpoint) || /* should never happen, just to be safe */
- ((ob->softflag & OB_SB_EDGES) && !ob->soft->bspring && object_has_edges(ob))) /* happens when in UI edges was set */
- {
- if(ob->soft && ob->soft->bpoint) /* don't clear on file load */
- softbody_clear_cache(ob, framenr);
+ if(sb->particles && sb->particles->totpart>0) {
+ psmd= psys_get_modifier(ob, sb->particles);
+ pa= sb->particles->particles;
+ key= pa->hair;
- if(ob->soft->particles){
- particles_to_softbody(ob);
+ psys_mat_hair_to_global(ob, psmd->dm, sb->particles->part->from, pa, hairmat);
+ }
+
+ for(a=0,bp=sb->bpoint; a<numVerts; a++, bp++) {
+ if(sb->particles) {
+ if(key == pa->hair + pa->totkey) {
+ pa++;
+ key = pa->hair;
+
+ psys_mat_hair_to_global(ob, psmd->dm, sb->particles->part->from, pa, hairmat);
+ }
+ VECCOPY(bp->pos, key->co);
+ Mat4MulVecfl(hairmat, bp->pos);
+ key++;
+ }
+ else {
+ VECCOPY(bp->pos, vertexCos[a]);
+ Mat4MulVecfl(ob->obmat, bp->pos); /* yep, sofbody is global coords*/
}
- else switch(ob->type) {
+ VECCOPY(bp->origS, bp->pos);
+ VECCOPY(bp->origE, bp->pos);
+ VECCOPY(bp->origT, bp->pos);
+ bp->vec[0]= bp->vec[1]= bp->vec[2]= 0.0f;
+
+ /* the bp->prev*'s are for rolling back from a canceled try to propagate in time
+ adaptive step size algo in a nutshell:
+ 1. set sheduled time step to new dtime
+ 2. try to advance the sheduled time step, beeing optimistic execute it
+ 3. check for success
+ 3.a we 're fine continue, may be we can increase sheduled time again ?? if so, do so!
+ 3.b we did exceed error limit --> roll back, shorten the sheduled time and try again at 2.
+ 4. check if we did reach dtime
+ 4.a nope we need to do some more at 2.
+ 4.b yup we're done
+ */
+
+ VECCOPY(bp->prevpos, bp->pos);
+ VECCOPY(bp->prevvec, bp->vec);
+ VECCOPY(bp->prevdx, bp->vec);
+ VECCOPY(bp->prevdv, bp->vec);
+ }
+
+ /* make a nice clean scratch struc */
+ free_scratch(sb); /* clear if any */
+ sb_new_scratch(sb); /* make a new */
+ sb->scratch->needstobuildcollider=1;
+
+ if((sb->particles)==0) {
+ /* copy some info to scratch */
+ switch(ob->type) {
case OB_MESH:
- mesh_to_softbody(ob);
+ if (ob->softflag & OB_SB_FACECOLL) mesh_faces_to_scratch(ob);
break;
case OB_LATTICE:
- lattice_to_softbody(ob);
break;
case OB_CURVE:
case OB_SURF:
- curve_surf_to_softbody(ob);
break;
default:
- renew_softbody(ob, numVerts, 0);
break;
}
+ }
+}
+
+static void softbody_step(Object *ob, SoftBody *sb, float dtime)
+{
+ /* the simulator */
+ float forcetime;
+ double sct,sst=PIL_check_seconds_timer();
+ ccd_update_deflector_hache(ob,sb->scratch->colliderhash);
- /* still need to update to correct vertex locations, happens on next step */
- ob->softflag |= OB_SB_RESET;
- ob->softflag &= ~OB_SB_REDO;
+ if(sb->scratch->needstobuildcollider){
+ if (query_external_colliders(ob)){
+ ccd_build_deflector_hache(ob,sb->scratch->colliderhash);
+ }
+ sb->scratch->needstobuildcollider=0;
}
- sb= ob->soft;
+ if (sb->solver_ID < 2) {
+ /* special case of 2nd order Runge-Kutta type AKA Heun */
+ int mid_flags=0;
+ float err = 0;
+ float forcetimemax = 1.0f;
+ float forcetimemin = 0.001f;
+ float timedone =0.0; /* how far did we get without violating error condition */
+ /* loops = counter for emergency brake
+ * we don't want to lock up the system if physics fail
+ */
+ int loops =0 ;
+
+ SoftHeunTol = sb->rklimit; /* humm .. this should be calculated from sb parameters and sizes */
+ if (sb->minloops > 0) forcetimemax = 1.0f / sb->minloops;
+
+ if (sb->maxloops > 0) forcetimemin = 1.0f / sb->maxloops;
- /* still no points? go away */
- if(sb->totpoint==0) return;
+ if(sb->solver_ID>0) mid_flags |= MID_PRESERVE;
+
+ //forcetime = dtime; /* hope for integrating in one step */
+ forcetime =forcetimemax; /* hope for integrating in one step */
+ while ( (ABS(timedone) < ABS(dtime)) && (loops < 2000) )
+ {
+ /* set goals in time */
+ interpolate_exciter(ob,200,(int)(200.0*(timedone/dtime)));
+
+ sb->scratch->flag &= ~SBF_DOFUZZY;
+ /* do predictive euler step */
+ softbody_calc_forces(ob, forcetime,timedone/dtime,0);
- if(sb->particles){
- psmd=psys_get_modifier(ob,sb->particles);
- pa=sb->particles->particles;
- }
+ softbody_apply_forces(ob, forcetime, 1, NULL,mid_flags);
- /* checking time: */
+ /* crop new slope values to do averaged slope step */
+ softbody_calc_forces(ob, forcetime,timedone/dtime,0);
- ctime= bsystem_time(ob, framenr, 0.0);
+ softbody_apply_forces(ob, forcetime, 2, &err,mid_flags);
+ softbody_apply_goalsnap(ob);
+
+ if (err > SoftHeunTol) { /* error needs to be scaled to some quantity */
+
+ if (forcetime > forcetimemin){
+ forcetime = MAX2(forcetime / 2.0f,forcetimemin);
+ softbody_restore_prev_step(ob);
+ //printf("down,");
+ }
+ else {
+ timedone += forcetime;
+ }
+ }
+ else {
+ float newtime = forcetime * 1.1f; /* hope for 1.1 times better conditions in next step */
+
+ if (sb->scratch->flag & SBF_DOFUZZY){
+ //if (err > SoftHeunTol/(2.0f*sb->fuzzyness)) { /* stay with this stepsize unless err really small */
+ newtime = forcetime;
+ //}
+ }
+ else {
+ if (err > SoftHeunTol/2.0f) { /* stay with this stepsize unless err really small */
+ newtime = forcetime;
+ }
+ }
+ timedone += forcetime;
+ newtime=MIN2(forcetimemax,MAX2(newtime,forcetimemin));
+ //if (newtime > forcetime) printf("up,");
+ if (forcetime > 0.0)
+ forcetime = MIN2(dtime - timedone,newtime);
+ else
+ forcetime = MAX2(dtime - timedone,newtime);
+ }
+ loops++;
+ if(sb->solverflags & SBSO_MONITOR ){
+ sct=PIL_check_seconds_timer();
+ if (sct-sst > 0.5f) printf("%3.0f%% \r",100.0f*timedone);
+ }
+ /* ask for user break */
+ if (SB_localInterruptCallBack && SB_localInterruptCallBack()) break;
- if (ob->softflag&OB_SB_RESET) {
- dtime = 0.0;
- } else {
- dtime= ctime - sb->ctime;
+ }
+ /* move snapped to final position */
+ interpolate_exciter(ob, 2, 2);
+ softbody_apply_goalsnap(ob);
+
+ // if(G.f & G_DEBUG){
+ if(sb->solverflags & SBSO_MONITOR ){
+ if (loops > HEUNWARNLIMIT) /* monitor high loop counts */
+ printf("\r needed %d steps/frame",loops);
+ }
+
}
+ else if (sb->solver_ID == 2)
+ {/* do semi "fake" implicit euler */
+ //removed
+ }/*SOLVER SELECT*/
+ else if (sb->solver_ID == 4)
+ {
+ /* do semi "fake" implicit euler */
+ }/*SOLVER SELECT*/
+ else if (sb->solver_ID == 3){
+ /* do "stupid" semi "fake" implicit euler */
+ //removed
- if(softbody_read_cache(ob, framenr)) {
- if(sb->particles==0)
- softbody_to_object(ob, vertexCos, numVerts, sb->local);
- sb->ctime = ctime;
- return;
+ }/*SOLVER SELECT*/
+ else{
+ printf("softbody no valid solver ID!");
+ }/*SOLVER SELECT*/
+ if(sb->plastic){ apply_spring_memory(ob);}
+
+ if(sb->solverflags & SBSO_MONITOR ){
+ sct=PIL_check_seconds_timer();
+ if ((sct-sst > 0.5f) || (G.f & G_DEBUG)) printf(" solver time %f sec %s \n",sct-sst,ob->id.name);
}
+}
- /* the simulator */
+/* simulates one step. framenr is in frames */
+void sbObjectStep(Object *ob, float cfra, float (*vertexCos)[3], int numVerts)
+{
+ ParticleSystemModifierData *psmd=0;
+ ParticleData *pa=0;
+ SoftBody *sb= ob->soft;
+ PointCache *cache;
+ PTCacheID pid;
+ float dtime, timescale;
+ int framedelta, framenr, startframe, endframe;
- /* update the vertex locations */
- if (dtime!=0.0) {
- if(sb->particles) {
- pa=sb->particles->particles;
- key = pa->hair;
+ cache= sb->pointcache;
- psys_mat_hair_to_global(ob, psmd->dm, sb->particles->part->from, pa, hairmat);
- }
+ framenr= (int)cfra;
+ framedelta= framenr - cache->simframe;
- for(a=0,bp=sb->bpoint; a<numVerts; a++, bp++) {
- /* store where goals are now */
- VECCOPY(bp->origS, bp->origE);
- /* copy the position of the goals at desired end time */
- if(sb->particles) {
- if(key == pa->hair + pa->totkey) {
- pa++;
- key = pa->hair;
+ BKE_ptcache_id_from_softbody(&pid, ob, sb);
+ BKE_ptcache_id_time(&pid, framenr, &startframe, &endframe, &timescale);
- psys_mat_hair_to_global(ob, psmd->dm, sb->particles->part->from, pa, hairmat);
- }
- VECCOPY(bp->origE, key->co);
- Mat4MulVecfl(hairmat,bp->origE);
+ /* check for changes in mesh, should only happen in case the mesh
+ * structure changes during an animation */
+ if(sb->bpoint && numVerts != sb->totpoint) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
- key++;
- }
- else{
- VECCOPY(bp->origE, vertexCos[a]);
- /* vertexCos came from local world, go global */
- Mat4MulVecfl(ob->obmat, bp->origE);
- }
- /* just to be save give bp->origT a defined value
- will be calulated in interpolate_exciter()*/
- VECCOPY(bp->origT, bp->origE);
- }
+ return;
}
- if((ob->softflag&OB_SB_RESET) || /* got a reset signal */
- (dtime<0.0) || /* back in time */
- (dtime>=9.9*G.scene->r.framelen) /* too far forward in time --> goals won't be accurate enough */
- )
- {
- if(sb->particles) {
- pa=sb->particles->particles;
- key = pa->hair;
+ /* clamp frame ranges */
+ if(framenr < startframe) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
- psys_mat_hair_to_global(ob, psmd->dm, sb->particles->part->from, pa, hairmat);
- }
+ return;
+ }
+ else if(framenr > endframe) {
+ framenr = endframe;
+ }
- for(a=0,bp=sb->bpoint; a<numVerts; a++, bp++) {
- if(sb->particles) {
- if(key == pa->hair + pa->totkey) {
- pa++;
- key = pa->hair;
+ /* verify if we need to create the softbody data */
+ if(sb->bpoint == NULL ||
+ ((ob->softflag & OB_SB_EDGES) && !ob->soft->bspring && object_has_edges(ob))) {
- psys_mat_hair_to_global(ob, psmd->dm, sb->particles->part->from, pa, hairmat);
- }
- VECCOPY(bp->pos, key->co);
- Mat4MulVecfl(hairmat, bp->pos);
- key++;
- }
- else {
- VECCOPY(bp->pos, vertexCos[a]);
- Mat4MulVecfl(ob->obmat, bp->pos); /* yep, sofbody is global coords*/
- }
- VECCOPY(bp->origS, bp->pos);
- VECCOPY(bp->origE, bp->pos);
- VECCOPY(bp->origT, bp->pos);
- bp->vec[0]= bp->vec[1]= bp->vec[2]= 0.0f;
-
- /* the bp->prev*'s are for rolling back from a canceled try to propagate in time
- adaptive step size algo in a nutshell:
- 1. set sheduled time step to new dtime
- 2. try to advance the sheduled time step, beeing optimistic execute it
- 3. check for success
- 3.a we 're fine continue, may be we can increase sheduled time again ?? if so, do so!
- 3.b we did exceed error limit --> roll back, shorten the sheduled time and try again at 2.
- 4. check if we did reach dtime
- 4.a nope we need to do some more at 2.
- 4.b yup we're done
- */
-
- VECCOPY(bp->prevpos, bp->pos);
- VECCOPY(bp->prevvec, bp->vec);
- VECCOPY(bp->prevdx, bp->vec);
- VECCOPY(bp->prevdv, bp->vec);
+ if(sb->particles){
+ particles_to_softbody(ob);
}
- /* make a nice clean scratch struc */
- free_scratch(sb); /* clear if any */
- sb_new_scratch(sb); /* make a new */
- sb->scratch->needstobuildcollider=1;
-
- if((sb->particles)==0) {
- /* copy some info to scratch */
+ else {
switch(ob->type) {
- case OB_MESH:
- if (ob->softflag & OB_SB_FACECOLL) mesh_faces_to_scratch(ob);
- break;
- case OB_LATTICE:
- break;
- case OB_CURVE:
- case OB_SURF:
- break;
- default:
- break;
+ case OB_MESH:
+ mesh_to_softbody(ob);
+ break;
+ case OB_LATTICE:
+ lattice_to_softbody(ob);
+ break;
+ case OB_CURVE:
+ case OB_SURF:
+ curve_surf_to_softbody(ob);
+ break;
+ default:
+ renew_softbody(ob, numVerts, 0);
+ break;
}
}
- ob->softflag &= ~OB_SB_RESET;
+ softbody_update_positions(ob, sb, vertexCos, numVerts);
+ softbody_reset(ob, sb, vertexCos, numVerts);
}
- else if(dtime>0.0) {
- double sct,sst=PIL_check_seconds_timer();
- ccd_update_deflector_hache(ob,sb->scratch->colliderhash);
+ /* continue physics special case */
+ if(BKE_ptcache_get_continue_physics()) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
- if(sb->scratch->needstobuildcollider){
- if (query_external_colliders(ob)){
- ccd_build_deflector_hache(ob,sb->scratch->colliderhash);
- }
- sb->scratch->needstobuildcollider=0;
- }
+ /* do simulation */
+ dtime = timescale;
+ softbody_update_positions(ob, sb, vertexCos, numVerts);
+ softbody_step(ob, sb, dtime);
- if (TRUE) { /* */
- /* special case of 2nd order Runge-Kutta type AKA Heun */
- float forcetimemax = 1.0f;
- float forcetimemin = 0.001f;
- float timedone =0.0; /* how far did we get without violating error condition */
- /* loops = counter for emergency brake
- * we don't want to lock up the system if physics fail
- */
- int loops =0 ;
- SoftHeunTol = sb->rklimit; /* humm .. this should be calculated from sb parameters and sizes */
- if (sb->minloops > 0) forcetimemax = 1.0f / sb->minloops;
-
- if (sb->maxloops > 0) forcetimemin = 1.0f / sb->maxloops;
-
-
- //forcetime = dtime; /* hope for integrating in one step */
- forcetime =forcetimemax; /* hope for integrating in one step */
- while ( (ABS(timedone) < ABS(dtime)) && (loops < 2000) )
- {
- /* set goals in time */
- interpolate_exciter(ob,200,(int)(200.0*(timedone/dtime)));
-
- sb->scratch->flag &= ~SBF_DOFUZZY;
- /* do predictive euler step */
- softbody_calc_forces(ob, forcetime,timedone/dtime);
- softbody_apply_forces(ob, forcetime, 1, NULL);
+ if(sb->particles==0)
+ softbody_to_object(ob, vertexCos, numVerts, 0);
+ return;
+ }
- /* crop new slope values to do averaged slope step */
- softbody_calc_forces(ob, forcetime,timedone/dtime);
- softbody_apply_forces(ob, forcetime, 2, &err);
+ /* still no points? go away */
+ if(sb->totpoint==0) return;
- softbody_apply_goalsnap(ob);
-
- if (err > SoftHeunTol) { /* error needs to be scaled to some quantity */
-
- if (forcetime > forcetimemin){
- forcetime = MAX2(forcetime / 2.0f,forcetimemin);
- softbody_restore_prev_step(ob);
- //printf("down,");
- }
- else {
- timedone += forcetime;
- }
- }
- else {
- float newtime = forcetime * 1.1f; /* hope for 1.1 times better conditions in next step */
-
- if (sb->scratch->flag & SBF_DOFUZZY){
- //if (err > SoftHeunTol/(2.0f*sb->fuzzyness)) { /* stay with this stepsize unless err really small */
- newtime = forcetime;
- //}
- }
- else {
- if (err > SoftHeunTol/2.0f) { /* stay with this stepsize unless err really small */
- newtime = forcetime;
- }
- }
- timedone += forcetime;
- newtime=MIN2(forcetimemax,MAX2(newtime,forcetimemin));
- //if (newtime > forcetime) printf("up,");
- if (forcetime > 0.0)
- forcetime = MIN2(dtime - timedone,newtime);
- else
- forcetime = MAX2(dtime - timedone,newtime);
- }
- loops++;
- if(sb->solverflags & SBSO_MONITOR ){
- sct=PIL_check_seconds_timer();
- if (sct-sst > 0.5f) printf("%3.0f%% \r",100.0f*timedone);
- }
- if (SB_localInterruptCallBack && SB_localInterruptCallBack()) break;
+ if(sb->particles){
+ psmd= psys_get_modifier(ob, sb->particles);
+ pa= sb->particles->particles;
+ }
- }
- /* move snapped to final position */
- interpolate_exciter(ob, 2, 2);
- softbody_apply_goalsnap(ob);
-
- // if(G.f & G_DEBUG){
- if(sb->solverflags & SBSO_MONITOR ){
- if (loops > HEUNWARNLIMIT) /* monitor high loop counts */
- printf("\r needed %d steps/frame ",loops);
- }
-
- }
- else{
- /* do brute force explicit euler */
- /* removed but left this branch for better integrators / solvers (BM) */
- /* yah! Nicholas Guttenberg (NichG) here is the place to plug in */
- }
- if(sb->solverflags & SBSO_MONITOR ){
- sct=PIL_check_seconds_timer();
- if (sct-sst > 0.5f) printf(" solver time %f %s \r",sct-sst,ob->id.name);
- }
+ /* try to read from cache */
+ if(softbody_read_cache(ob, framenr)) {
+ if(sb->particles==0)
+ softbody_to_object(ob, vertexCos, numVerts, sb->local);
+
+ cache->flag |= PTCACHE_SIMULATION_VALID;
+ cache->simframe= framenr;
+
+ return;
+ }
+ else if(ob->id.lib || (cache->flag & PTCACHE_BAKED)) {
+ /* if baked and nothing in cache, do nothing */
+ if(cache->flag & PTCACHE_SIMULATION_VALID) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ }
+
+ return;
}
- if(sb->particles==0)
- softbody_to_object(ob, vertexCos, numVerts, 0);
- sb->ctime= ctime;
+ if(framenr == startframe) {
+ /* first frame, no simulation to do, just set the positions */
+ softbody_update_positions(ob, sb, vertexCos, numVerts);
+
+ cache->flag |= PTCACHE_SIMULATION_VALID;
+ cache->simframe= framenr;
+
+ /* don't write cache on first frame, but on second frame write
+ * cache for frame 1 and 2 */
+ }
+ else if(framedelta == 1) {
+ /* if on second frame, write cache for first frame */
+ if(framenr == startframe+1)
+ sbWriteCache(ob, startframe);
+
+ softbody_update_positions(ob, sb, vertexCos, numVerts);
+
+ /* do simulation */
+ cache->flag |= PTCACHE_SIMULATION_VALID;
+ cache->simframe= framenr;
+
+ /* checking time: */
+ dtime = framedelta*timescale;
- softbody_write_cache(ob, framenr);
+ softbody_step(ob, sb, dtime);
+
+ if(sb->particles==0)
+ softbody_to_object(ob, vertexCos, numVerts, 0);
+
+ sbWriteCache(ob, framenr);
+ }
+ else {
+ /* time step backwards or too large forward - do nothing */
+ if(cache->flag & PTCACHE_SIMULATION_VALID) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ }
+ }
}
diff --git a/source/blender/blenkernel/intern/sound.c b/source/blender/blenkernel/intern/sound.c
index 3b14cb8adac..2c5b49246fb 100644
--- a/source/blender/blenkernel/intern/sound.c
+++ b/source/blender/blenkernel/intern/sound.c
@@ -109,13 +109,13 @@ PackedFile* sound_find_packedfile(bSound *sound)
// convert sound->name to abolute filename
strcpy(soundname, sound->name);
- BLI_convertstringcode(soundname, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(soundname, G.sce);
search = G.main->sound.first;
while (search) {
if (search->sample && search->sample->packedfile) {
strcpy(searchname, search->sample->name);
- BLI_convertstringcode(searchname, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(searchname, G.sce);
if (BLI_streq(searchname, soundname)) {
pf = search->sample->packedfile;
@@ -125,7 +125,7 @@ PackedFile* sound_find_packedfile(bSound *sound)
if (search->newpackedfile) {
strcpy(searchname, search->name);
- BLI_convertstringcode(searchname, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(searchname, G.sce);
if (BLI_streq(searchname, soundname)) {
pf = search->newpackedfile;
break;
diff --git a/source/blender/blenkernel/intern/subsurf_ccg.c b/source/blender/blenkernel/intern/subsurf_ccg.c
index 60e01181f2d..f5124ed9056 100644
--- a/source/blender/blenkernel/intern/subsurf_ccg.c
+++ b/source/blender/blenkernel/intern/subsurf_ccg.c
@@ -39,15 +39,17 @@
#include "DNA_meshdata_types.h"
#include "DNA_modifier_types.h"
#include "DNA_object_types.h"
+#include "DNA_scene_types.h"
#include "BKE_cdderivedmesh.h"
#include "BKE_customdata.h"
+#include "BKE_DerivedMesh.h"
+#include "BKE_displist.h"
#include "BKE_utildefines.h"
#include "BKE_global.h"
#include "BKE_mesh.h"
+#include "BKE_scene.h"
#include "BKE_subsurf.h"
-#include "BKE_displist.h"
-#include "BKE_DerivedMesh.h"
#include "BLI_blenlib.h"
#include "BLI_editVert.h"
@@ -58,6 +60,10 @@
#include "BIF_gl.h"
+#include "GPU_draw.h"
+#include "GPU_extensions.h"
+#include "GPU_material.h"
+
#include "CCGSubSurf.h"
typedef struct _VertData {
@@ -79,9 +85,9 @@ struct CCGDerivedMesh {
typedef struct CCGDerivedMesh CCGDerivedMesh;
-static int ccgDM_getVertMapIndex(CCGDerivedMesh *ccgdm, CCGSubSurf *ss, CCGVert *v);
-static int ccgDM_getEdgeMapIndex(CCGDerivedMesh *ccgdm, CCGSubSurf *ss, CCGEdge *e);
-static int ccgDM_getFaceMapIndex(CCGDerivedMesh *ccgdm, CCGSubSurf *ss, CCGFace *f);
+static int ccgDM_getVertMapIndex(CCGSubSurf *ss, CCGVert *v);
+static int ccgDM_getEdgeMapIndex(CCGSubSurf *ss, CCGEdge *e);
+static int ccgDM_getFaceMapIndex(CCGSubSurf *ss, CCGFace *f);
///
@@ -154,8 +160,8 @@ static CCGSubSurf *_getSubSurf(CCGSubSurf *prevSS, int subdivLevels, int useAgin
}
static int getEdgeIndex(CCGSubSurf *ss, CCGEdge *e, int x, int edgeSize) {
- CCGVert *v0 = ccgSubSurf_getEdgeVert0(ss, e);
- CCGVert *v1 = ccgSubSurf_getEdgeVert1(ss, e);
+ CCGVert *v0 = ccgSubSurf_getEdgeVert0(e);
+ CCGVert *v1 = ccgSubSurf_getEdgeVert1(e);
int v0idx = *((int*) ccgSubSurf_getVertUserData(ss, v0));
int v1idx = *((int*) ccgSubSurf_getVertUserData(ss, v1));
int edgeBase = *((int*) ccgSubSurf_getEdgeUserData(ss, e));
@@ -170,7 +176,7 @@ static int getEdgeIndex(CCGSubSurf *ss, CCGEdge *e, int x, int edgeSize) {
}
static int getFaceIndex(CCGSubSurf *ss, CCGFace *f, int S, int x, int y, int edgeSize, int gridSize) {
int faceBase = *((int*) ccgSubSurf_getFaceUserData(ss, f));
- int numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int numVerts = ccgSubSurf_getFaceNumVerts(f);
if (x==gridSize-1 && y==gridSize-1) {
CCGVert *v = ccgSubSurf_getFaceVert(ss, f, S);
@@ -179,7 +185,7 @@ static int getFaceIndex(CCGSubSurf *ss, CCGFace *f, int S, int x, int y, int edg
CCGVert *v = ccgSubSurf_getFaceVert(ss, f, S);
CCGEdge *e = ccgSubSurf_getFaceEdge(ss, f, S);
int edgeBase = *((int*) ccgSubSurf_getEdgeUserData(ss, e));
- if (v==ccgSubSurf_getEdgeVert0(ss, e)) {
+ if (v==ccgSubSurf_getEdgeVert0(e)) {
return edgeBase + (gridSize-1-y)-1;
} else {
return edgeBase + (edgeSize-2-1)-((gridSize-1-y)-1);
@@ -188,7 +194,7 @@ static int getFaceIndex(CCGSubSurf *ss, CCGFace *f, int S, int x, int y, int edg
CCGVert *v = ccgSubSurf_getFaceVert(ss, f, S);
CCGEdge *e = ccgSubSurf_getFaceEdge(ss, f, (S+numVerts-1)%numVerts);
int edgeBase = *((int*) ccgSubSurf_getEdgeUserData(ss, e));
- if (v==ccgSubSurf_getEdgeVert0(ss, e)) {
+ if (v==ccgSubSurf_getEdgeVert0(e)) {
return edgeBase + (gridSize-1-x)-1;
} else {
return edgeBase + (edgeSize-2-1)-((gridSize-1-x)-1);
@@ -218,7 +224,7 @@ static void get_face_uv_map_vert(UvVertMap *vmap, struct MFace *mf, int fi, CCGV
break;
}
- fverts[j]= (CCGVertHDL)(nv->f*4 + nv->tfindex);
+ fverts[j]= SET_INT_IN_POINTER(nv->f*4 + nv->tfindex);
}
}
@@ -235,7 +241,7 @@ static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm,
EdgeHash *ehash;
float creaseFactor = (float)ccgSubSurf_getSubdivisionLevels(ss);
- limit[0]= limit[1]= 0.0001f;
+ limit[0]= limit[1]= STD_UV_CONNECT_LIMIT;
vmap= make_uv_vert_map(mface, tface, totface, totvert, 0, limit);
if (!vmap)
return 0;
@@ -256,7 +262,7 @@ static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm,
for (v=get_uv_map_vert(vmap, i); v; v=v->next) {
if (v->separate) {
CCGVert *ssv;
- CCGVertHDL vhdl = (CCGVertHDL)(v->f*4 + v->tfindex);
+ CCGVertHDL vhdl = SET_INT_IN_POINTER(v->f*4 + v->tfindex);
float uv[3];
uv[0]= (tface+v->f)->uv[v->tfindex][0];
@@ -274,26 +280,26 @@ static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm,
for (i=0; i<totface; i++) {
MFace *mf = &((MFace*) mface)[i];
int nverts= mf->v4? 4: 3;
- CCGFace *origf= ccgSubSurf_getFace(origss, (CCGFaceHDL)i);
+ CCGFace *origf= ccgSubSurf_getFace(origss, SET_INT_IN_POINTER(i));
unsigned int *fv = &mf->v1;
get_face_uv_map_vert(vmap, mf, i, fverts);
for (j=0; j<nverts; j++) {
- int v0 = (int)fverts[j];
- int v1 = (int)fverts[(j+1)%nverts];
+ int v0 = GET_INT_FROM_POINTER(fverts[j]);
+ int v1 = GET_INT_FROM_POINTER(fverts[(j+1)%nverts]);
MVert *mv0 = mvert + *(fv+j);
MVert *mv1 = mvert + *(fv+((j+1)%nverts));
if (!BLI_edgehash_haskey(ehash, v0, v1)) {
CCGEdge *e, *orige= ccgSubSurf_getFaceEdge(origss, origf, j);
- CCGEdgeHDL ehdl= (CCGEdgeHDL)(i*4 + j);
+ CCGEdgeHDL ehdl= SET_INT_IN_POINTER(i*4 + j);
float crease;
if ((mv0->flag&mv1->flag) & ME_VERT_MERGED)
crease = creaseFactor;
else
- crease = ccgSubSurf_getEdgeCrease(origss, orige);
+ crease = ccgSubSurf_getEdgeCrease(orige);
ccgSubSurf_syncEdge(ss, ehdl, fverts[j], fverts[(j+1)%nverts], crease, &e);
BLI_edgehash_insert(ehash, v0, v1, NULL);
@@ -310,7 +316,7 @@ static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm,
CCGFace *f;
get_face_uv_map_vert(vmap, mf, i, fverts);
- ccgSubSurf_syncFace(ss, (CCGFaceHDL)i, nverts, fverts, &f);
+ ccgSubSurf_syncFace(ss, SET_INT_IN_POINTER(i), nverts, fverts, &f);
}
free_uv_vert_map(vmap);
@@ -352,7 +358,7 @@ static void set_subsurf_uv(CCGSubSurf *ss, DerivedMesh *dm, DerivedMesh *result,
fi = ccgSubSurf_getFaceIterator(uvss);
for(; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- faceMap[(int) ccgSubSurf_getFaceFaceHandle(uvss, f)] = f;
+ faceMap[GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(uvss, f))] = f;
}
ccgFaceIterator_free(fi);
@@ -361,7 +367,7 @@ static void set_subsurf_uv(CCGSubSurf *ss, DerivedMesh *dm, DerivedMesh *result,
for(index = 0; index < totface; index++) {
CCGFace *f = faceMap[index];
- int numVerts = ccgSubSurf_getFaceNumVerts(uvss, f);
+ int numVerts = ccgSubSurf_getFaceNumVerts(f);
for (S=0; S<numVerts; S++) {
VertData *faceGridData= ccgSubSurf_getFaceGridDataArray(uvss, f, S);
@@ -392,12 +398,12 @@ static void set_subsurf_uv(CCGSubSurf *ss, DerivedMesh *dm, DerivedMesh *result,
static unsigned int ss_getEdgeFlags(CCGSubSurf *ss, CCGEdge *e, int ssFromEditmesh, DispListMesh *dlm, MEdge *medge, MTFace *tface)
{
unsigned int flags = 0;
- int N = ccgSubSurf_getEdgeNumFaces(ss, e);
+ int N = ccgSubSurf_getEdgeNumFaces(e);
if (!N) flags |= ME_LOOSEEDGE;
if (ssFromEditmesh) {
- EditEdge *eed = ccgSubSurf_getEdgeEdgeHandle(ss, e);
+ EditEdge *eed = ccgSubSurf_getEdgeEdgeHandle(e);
flags |= ME_EDGEDRAW|ME_EDGERENDER;
if (eed->seam) {
@@ -463,7 +469,7 @@ static void calc_ss_weights(int gridFaces,
}
}
-DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
+static DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
int drawInteriorEdges, int useSubsurfUv,
DerivedMesh *dm)
{
@@ -473,7 +479,6 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
int gridFaces = gridSize - 1;
int edgeBase, faceBase;
int i, j, k, S, x, y, index;
- int vertBase = 0;
CCGVertIterator *vi;
CCGEdgeIterator *ei;
CCGFaceIterator *fi;
@@ -496,7 +501,7 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
for(; !ccgVertIterator_isStopped(vi); ccgVertIterator_next(vi)) {
CCGVert *v = ccgVertIterator_getCurrent(vi);
- vertMap2[(int) ccgSubSurf_getVertVertHandle(ss, v)] = v;
+ vertMap2[GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v))] = v;
}
ccgVertIterator_free(vi);
@@ -506,7 +511,7 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
for(; !ccgEdgeIterator_isStopped(ei); ccgEdgeIterator_next(ei)) {
CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
- edgeMap2[(int) ccgSubSurf_getEdgeEdgeHandle(ss, e)] = e;
+ edgeMap2[GET_INT_FROM_POINTER(ccgSubSurf_getEdgeEdgeHandle(e))] = e;
}
totface = ccgSubSurf_getNumFaces(ss);
@@ -515,7 +520,7 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
for(; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- faceMap2[(int) ccgSubSurf_getFaceFaceHandle(ss, f)] = f;
+ faceMap2[GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(ss, f))] = f;
}
ccgFaceIterator_free(fi);
@@ -536,18 +541,18 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
for(index = 0; index < totface; index++) {
CCGFace *f = faceMap2[index];
- int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
FaceVertWeight *weight = (numVerts == 4) ? qweight : tweight;
int vertIdx[4];
for(S = 0; S < numVerts; S++) {
CCGVert *v = ccgSubSurf_getFaceVert(ss, f, S);
- vertIdx[S] = (int)ccgSubSurf_getVertVertHandle(ss, v);
+ vertIdx[S] = GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v));
}
DM_interp_vert_data(dm, result, vertIdx, weight[0][0], numVerts, i);
- VecCopyf(mvert->co, ccgSubSurf_getFaceCenterData(ss, f));
+ VecCopyf(mvert->co, ccgSubSurf_getFaceCenterData(f));
*origIndex = ORIGINDEX_NONE;
++mvert;
++origIndex;
@@ -606,10 +611,10 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
int vertIdx[2];
CCGVert *v;
- v = ccgSubSurf_getEdgeVert0(ss, e);
- vertIdx[0] = (int)ccgSubSurf_getVertVertHandle(ss, v);
- v = ccgSubSurf_getEdgeVert1(ss, e);
- vertIdx[1] = (int)ccgSubSurf_getVertVertHandle(ss, v);
+ v = ccgSubSurf_getEdgeVert0(e);
+ vertIdx[0] = GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v));
+ v = ccgSubSurf_getEdgeVert1(e);
+ vertIdx[1] = GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v));
for(x = 1; x < edgeSize - 1; x++) {
float w[2];
@@ -627,18 +632,17 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
edgeBase += edgeSize-2;
}
- vertBase = i;
for(index = 0; index < totvert; index++) {
CCGVert *v = vertMap2[index];
int vertIdx;
- vertIdx = (int)ccgSubSurf_getVertVertHandle(ss, v);
+ vertIdx = GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v));
DM_copy_vert_data(dm, result, vertIdx, i, 1);
VecCopyf(mvert->co, ccgSubSurf_getVertData(ss, v));
*((int*)ccgSubSurf_getVertUserData(ss, v)) = i;
- *origIndex = ccgDM_getVertMapIndex(NULL, ss, v);
+ *origIndex = ccgDM_getVertMapIndex(ss, v);
++mvert;
++origIndex;
i++;
@@ -651,7 +655,7 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
for(index = 0; index < totface; index++) {
CCGFace *f = faceMap2[index];
- int numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int numVerts = ccgSubSurf_getFaceNumVerts(f);
for(k = 0; k < numVerts; k++) {
for(x = 0; x < gridFaces; x++) {
@@ -693,9 +697,10 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
for(index = 0; index < totedge; index++) {
CCGEdge *e = edgeMap2[index];
unsigned int flags = 0;
- int edgeIdx = (int)ccgSubSurf_getEdgeEdgeHandle(ss, e);
+ char bweight = 0;
+ int edgeIdx = GET_INT_FROM_POINTER(ccgSubSurf_getEdgeEdgeHandle(e));
- if(!ccgSubSurf_getEdgeNumFaces(ss, e)) flags |= ME_LOOSEEDGE;
+ if(!ccgSubSurf_getEdgeNumFaces(e)) flags |= ME_LOOSEEDGE;
if(edgeIdx != -1 && dm) {
@@ -703,13 +708,15 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
dm->getEdge(dm, edgeIdx, &origMed);
flags |= origMed.flag;
+ bweight = origMed.bweight;
}
for(x = 0; x < edgeSize - 1; x++) {
med->v1 = getEdgeIndex(ss, e, x, edgeSize);
med->v2 = getEdgeIndex(ss, e, x + 1, edgeSize);
med->flag = flags;
- *origIndex = ccgDM_getEdgeMapIndex(NULL, ss, e);
+ med->bweight = bweight;
+ *origIndex = ccgDM_getEdgeMapIndex(ss, e);
++med;
++origIndex;
i++;
@@ -723,11 +730,11 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
for(index = 0; index < totface; index++) {
CCGFace *f = faceMap2[index];
- int numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int numVerts = ccgSubSurf_getFaceNumVerts(f);
int mat_nr;
int flag;
- int mapIndex = ccgDM_getFaceMapIndex(NULL, ss, f);
- int faceIdx = (int)ccgSubSurf_getFaceFaceHandle(ss, f);
+ int mapIndex = ccgDM_getFaceMapIndex(ss, f);
+ int faceIdx = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(ss, f));
if(!ssFromEditmesh) {
MFace origMFace;
@@ -831,9 +838,9 @@ static void ss_sync_from_derivedmesh(CCGSubSurf *ss, DerivedMesh *dm,
CCGVert *v;
if(vertexCos) {
- ccgSubSurf_syncVert(ss, (CCGVertHDL)i, vertexCos[i], 0, &v);
+ ccgSubSurf_syncVert(ss, SET_INT_IN_POINTER(i), vertexCos[i], 0, &v);
} else {
- ccgSubSurf_syncVert(ss, (CCGVertHDL)i, mv->co, 0, &v);
+ ccgSubSurf_syncVert(ss, SET_INT_IN_POINTER(i), mv->co, 0, &v);
}
((int*)ccgSubSurf_getVertUserData(ss, v))[1] = *index;
@@ -848,8 +855,8 @@ static void ss_sync_from_derivedmesh(CCGSubSurf *ss, DerivedMesh *dm,
crease = useFlatSubdiv ? creaseFactor :
me->crease * creaseFactor / 255.0f;
- ccgSubSurf_syncEdge(ss, (CCGEdgeHDL)i, (CCGVertHDL)me->v1,
- (CCGVertHDL)me->v2, crease, &e);
+ ccgSubSurf_syncEdge(ss, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(me->v1),
+ SET_INT_IN_POINTER(me->v2), crease, &e);
((int*)ccgSubSurf_getEdgeUserData(ss, e))[1] = *index;
}
@@ -859,16 +866,16 @@ static void ss_sync_from_derivedmesh(CCGSubSurf *ss, DerivedMesh *dm,
for (i = 0; i < totface; i++, mf++, index++) {
CCGFace *f;
- fVerts[0] = (CCGVertHDL) mf->v1;
- fVerts[1] = (CCGVertHDL) mf->v2;
- fVerts[2] = (CCGVertHDL) mf->v3;
- fVerts[3] = (CCGVertHDL) mf->v4;
+ fVerts[0] = SET_INT_IN_POINTER(mf->v1);
+ fVerts[1] = SET_INT_IN_POINTER(mf->v2);
+ fVerts[2] = SET_INT_IN_POINTER(mf->v3);
+ fVerts[3] = SET_INT_IN_POINTER(mf->v4);
// this is very bad, means mesh is internally consistent.
// it is not really possible to continue without modifying
// other parts of code significantly to handle missing faces.
// since this really shouldn't even be possible we just bail.
- if(ccgSubSurf_syncFace(ss, (CCGFaceHDL)i, fVerts[3] ? 4 : 3,
+ if(ccgSubSurf_syncFace(ss, SET_INT_IN_POINTER(i), fVerts[3] ? 4 : 3,
fVerts, &f) == eCCGError_InvalidValue) {
static int hasGivenError = 0;
@@ -890,15 +897,15 @@ static void ss_sync_from_derivedmesh(CCGSubSurf *ss, DerivedMesh *dm,
/***/
-static int ccgDM_getVertMapIndex(CCGDerivedMesh *ccgdm, CCGSubSurf *ss, CCGVert *v) {
+static int ccgDM_getVertMapIndex(CCGSubSurf *ss, CCGVert *v) {
return ((int*) ccgSubSurf_getVertUserData(ss, v))[1];
}
-static int ccgDM_getEdgeMapIndex(CCGDerivedMesh *ccgdm, CCGSubSurf *ss, CCGEdge *e) {
+static int ccgDM_getEdgeMapIndex(CCGSubSurf *ss, CCGEdge *e) {
return ((int*) ccgSubSurf_getEdgeUserData(ss, e))[1];
}
-static int ccgDM_getFaceMapIndex(CCGDerivedMesh *ccgdm, CCGSubSurf *ss, CCGFace *f) {
+static int ccgDM_getFaceMapIndex(CCGSubSurf *ss, CCGFace *f) {
return ((int*) ccgSubSurf_getFaceUserData(ss, f))[1];
}
@@ -931,7 +938,7 @@ static void ccgDM_getMinMax(DerivedMesh *dm, float min_r[3], float max_r[3]) {
for (; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
for (S=0; S<numVerts; S++) {
VertData *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
@@ -970,7 +977,7 @@ static void ccgDM_getFinalVert(DerivedMesh *dm, int vertNum, MVert *mv)
memset(mv, 0, sizeof(*mv));
- if(vertNum < ccgdm->edgeMap[0].startVert) {
+ if((vertNum < ccgdm->edgeMap[0].startVert) && (ccgSubSurf_getNumFaces(ss) > 0)) {
/* this vert comes from face data */
int lastface = ccgSubSurf_getNumFaces(ss) - 1;
CCGFace *f;
@@ -987,7 +994,7 @@ static void ccgDM_getFinalVert(DerivedMesh *dm, int vertNum, MVert *mv)
++i;
f = ccgdm->faceMap[i].face;
- numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ numVerts = ccgSubSurf_getFaceNumVerts(f);
gridSideVerts = gridSize - 2;
gridInternalVerts = gridSideVerts * gridSideVerts;
@@ -997,7 +1004,7 @@ static void ccgDM_getFinalVert(DerivedMesh *dm, int vertNum, MVert *mv)
offset = vertNum - ccgdm->faceMap[i].startVert;
if(offset < 1) {
- VecCopyf(mv->co, ccgSubSurf_getFaceCenterData(ss, f));
+ VecCopyf(mv->co, ccgSubSurf_getFaceCenterData(f));
} else if(offset < gridSideEnd) {
offset -= 1;
grid = offset / gridSideVerts;
@@ -1011,7 +1018,7 @@ static void ccgDM_getFinalVert(DerivedMesh *dm, int vertNum, MVert *mv)
x = offset % gridSideVerts + 1;
VecCopyf(mv->co, ccgSubSurf_getFaceGridData(ss, f, grid, x, y));
}
- } else if(vertNum < ccgdm->vertMap[0].startVert) {
+ } else if((vertNum < ccgdm->vertMap[0].startVert) && (ccgSubSurf_getNumEdges(ss) > 0)) {
/* this vert comes from edge data */
CCGEdge *e;
int lastedge = ccgSubSurf_getNumEdges(ss) - 1;
@@ -1059,7 +1066,7 @@ static void ccgDM_getFinalEdge(DerivedMesh *dm, int edgeNum, MEdge *med)
++i;
f = ccgdm->faceMap[i].face;
- numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ numVerts = ccgSubSurf_getFaceNumVerts(f);
gridSideEdges = gridSize - 1;
gridInternalEdges = (gridSideEdges - 1) * gridSideEdges * 2;
@@ -1095,7 +1102,7 @@ static void ccgDM_getFinalEdge(DerivedMesh *dm, int edgeNum, MEdge *med)
e = ccgdm->edgeMap[i].edge;
- if(!ccgSubSurf_getEdgeNumFaces(ss, e)) flags |= ME_LOOSEEDGE;
+ if(!ccgSubSurf_getEdgeNumFaces(e)) flags |= ME_LOOSEEDGE;
x = edgeNum - ccgdm->edgeMap[i].startEdge;
@@ -1137,7 +1144,7 @@ static void ccgDM_getFinalFace(DerivedMesh *dm, int faceNum, MFace *mf)
++i;
f = ccgdm->faceMap[i].face;
- numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ numVerts = ccgSubSurf_getFaceNumVerts(f);
offset = faceNum - ccgdm->faceMap[i].startFace;
grid = offset / gridFaces;
@@ -1167,9 +1174,9 @@ static void ccgDM_copyFinalVertArray(DerivedMesh *dm, MVert *mvert)
totface = ccgSubSurf_getNumFaces(ss);
for(index = 0; index < totface; index++) {
CCGFace *f = ccgdm->faceMap[index].face;
- int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
- VecCopyf(mvert[i++].co, ccgSubSurf_getFaceCenterData(ss, f));
+ VecCopyf(mvert[i++].co, ccgSubSurf_getFaceCenterData(f));
for(S = 0; S < numVerts; S++) {
for(x = 1; x < gridSize - 1; x++) {
@@ -1222,7 +1229,7 @@ static void ccgDM_copyFinalEdgeArray(DerivedMesh *dm, MEdge *medge)
totface = ccgSubSurf_getNumFaces(ss);
for(index = 0; index < totface; index++) {
CCGFace *f = ccgdm->faceMap[index].face;
- int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
for(S = 0; S < numVerts; S++) {
for(x = 0; x < gridSize - 1; x++) {
@@ -1266,9 +1273,9 @@ static void ccgDM_copyFinalEdgeArray(DerivedMesh *dm, MEdge *medge)
CCGEdge *e = ccgdm->edgeMap[index].edge;
unsigned int flags = 0;
int x;
- int edgeIdx = (int)ccgSubSurf_getEdgeEdgeHandle(ss, e);
+ int edgeIdx = GET_INT_FROM_POINTER(ccgSubSurf_getEdgeEdgeHandle(e));
- if(!ccgSubSurf_getEdgeNumFaces(ss, e)) flags |= ME_LOOSEEDGE;
+ if(!ccgSubSurf_getEdgeNumFaces(e)) flags |= ME_LOOSEEDGE;
if(edgeFlags) {
if(edgeIdx != -1) {
@@ -1303,7 +1310,7 @@ static void ccgDM_copyFinalFaceArray(DerivedMesh *dm, MFace *mface)
totface = ccgSubSurf_getNumFaces(ss);
for(index = 0; index < totface; index++) {
CCGFace *f = ccgdm->faceMap[index].face;
- int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
int mat_nr = 0;
int flag = ME_SMOOTH; /* assume face is smooth by default */
@@ -1350,7 +1357,7 @@ static void ccgdm_getVertCos(DerivedMesh *dm, float (*cos)[3]) {
for (; !ccgVertIterator_isStopped(vi); ccgVertIterator_next(vi)) {
CCGVert *v = ccgVertIterator_getCurrent(vi);
- vertMap2[(int) ccgSubSurf_getVertVertHandle(ss, v)] = v;
+ vertMap2[GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v))] = v;
}
ccgVertIterator_free(vi);
@@ -1360,7 +1367,7 @@ static void ccgdm_getVertCos(DerivedMesh *dm, float (*cos)[3]) {
for (i=0; !ccgEdgeIterator_isStopped(ei); i++,ccgEdgeIterator_next(ei)) {
CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
- edgeMap2[(int) ccgSubSurf_getEdgeEdgeHandle(ss, e)] = e;
+ edgeMap2[GET_INT_FROM_POINTER(ccgSubSurf_getEdgeEdgeHandle(e))] = e;
}
totface = ccgSubSurf_getNumFaces(ss);
@@ -1369,16 +1376,16 @@ static void ccgdm_getVertCos(DerivedMesh *dm, float (*cos)[3]) {
for (; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- faceMap2[(int) ccgSubSurf_getFaceFaceHandle(ss, f)] = f;
+ faceMap2[GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(ss, f))] = f;
}
ccgFaceIterator_free(fi);
i = 0;
for (index=0; index<totface; index++) {
CCGFace *f = faceMap2[index];
- int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
- VecCopyf(cos[i++], ccgSubSurf_getFaceCenterData(ss, f));
+ VecCopyf(cos[i++], ccgSubSurf_getFaceCenterData(f));
for (S=0; S<numVerts; S++) {
for (x=1; x<gridSize-1; x++) {
@@ -1420,7 +1427,7 @@ static void ccgDM_foreachMappedVert(DerivedMesh *dm, void (*func)(void *userData
for (; !ccgVertIterator_isStopped(vi); ccgVertIterator_next(vi)) {
CCGVert *v = ccgVertIterator_getCurrent(vi);
VertData *vd = ccgSubSurf_getVertData(ccgdm->ss, v);
- int index = ccgDM_getVertMapIndex(ccgdm, ccgdm->ss, v);
+ int index = ccgDM_getVertMapIndex(ccgdm->ss, v);
if (index!=-1)
func(userData, index, vd->co, vd->no, NULL);
@@ -1437,7 +1444,7 @@ static void ccgDM_foreachMappedEdge(DerivedMesh *dm, void (*func)(void *userData
for (; !ccgEdgeIterator_isStopped(ei); ccgEdgeIterator_next(ei)) {
CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
VertData *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
- int index = ccgDM_getEdgeMapIndex(ccgdm, ss, e);
+ int index = ccgDM_getEdgeMapIndex(ss, e);
if (index!=-1) {
for (i=0; i<edgeSize-1; i++)
@@ -1478,9 +1485,9 @@ static void ccgDM_drawVerts(DerivedMesh *dm) {
fi = ccgSubSurf_getFaceIterator(ss);
for (; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
- glVertex3fv(ccgSubSurf_getFaceCenterData(ss, f));
+ glVertex3fv(ccgSubSurf_getFaceCenterData(f));
for (S=0; S<numVerts; S++)
for (x=1; x<gridSize-1; x++)
glVertex3fv(ccgSubSurf_getFaceGridEdgeData(ss, f, S, x));
@@ -1507,7 +1514,7 @@ static void ccgDM_drawEdges(DerivedMesh *dm, int drawLooseEdges) {
CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
VertData *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
- if (!drawLooseEdges && !ccgSubSurf_getEdgeNumFaces(ss, e))
+ if (!drawLooseEdges && !ccgSubSurf_getEdgeNumFaces(e))
continue;
if (useAging && !(G.f&G_BACKBUFSEL)) {
@@ -1530,7 +1537,7 @@ static void ccgDM_drawEdges(DerivedMesh *dm, int drawLooseEdges) {
if (ccgdm->drawInteriorEdges) {
for (; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
for (S=0; S<numVerts; S++) {
VertData *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
@@ -1568,7 +1575,7 @@ static void ccgDM_drawLooseEdges(DerivedMesh *dm) {
CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
VertData *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
- if (!ccgSubSurf_getEdgeNumFaces(ss, e)) {
+ if (!ccgSubSurf_getEdgeNumFaces(e)) {
glBegin(GL_LINE_STRIP);
for (i=0; i<edgeSize-1; i++) {
glVertex3fv(edgeData[i].co);
@@ -1596,7 +1603,7 @@ static void ccgDM_glNormalFast(float *a, float *b, float *c, float *d)
}
/* Only used by non-editmesh types */
-static void ccgDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int)) {
+static void ccgDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int, void *attribs)) {
CCGDerivedMesh *ccgdm = (CCGDerivedMesh*) dm;
CCGSubSurf *ss = ccgdm->ss;
CCGFaceIterator *fi = ccgSubSurf_getFaceIterator(ss);
@@ -1605,8 +1612,8 @@ static void ccgDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int)) {
for (; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
- int index = (int) ccgSubSurf_getFaceFaceHandle(ss, f);
+ int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
+ int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(ss, f));
int drawSmooth, mat_nr;
if(faceFlags) {
@@ -1618,7 +1625,7 @@ static void ccgDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int)) {
mat_nr= 0;
}
- if (!setMaterial(mat_nr+1))
+ if (!setMaterial(mat_nr+1, NULL))
continue;
glShadeModel(drawSmooth? GL_SMOOTH: GL_FLAT);
@@ -1663,6 +1670,168 @@ static void ccgDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int)) {
ccgFaceIterator_free(fi);
}
+
+ /* Only used by non-editmesh types */
+static void ccgDM_drawMappedFacesGLSL(DerivedMesh *dm, int (*setMaterial)(int, void *attribs), int (*setDrawOptions)(void *userData, int index), void *userData) {
+ CCGDerivedMesh *ccgdm = (CCGDerivedMesh*) dm;
+ CCGSubSurf *ss = ccgdm->ss;
+ CCGFaceIterator *fi = ccgSubSurf_getFaceIterator(ss);
+ GPUVertexAttribs gattribs;
+ DMVertexAttribs attribs;
+ MTFace *tf = dm->getFaceDataArray(dm, CD_MTFACE);
+ int gridSize = ccgSubSurf_getGridSize(ss);
+ int gridFaces = gridSize - 1;
+ int edgeSize = ccgSubSurf_getEdgeSize(ss);
+ int transp, orig_transp, new_transp;
+ char *faceFlags = DM_get_face_data_layer(dm, CD_FLAGS);
+ int a, b, i, doDraw, numVerts, matnr, new_matnr, totface;
+
+ doDraw = 0;
+ numVerts = 0;
+ matnr = -1;
+ transp = GPU_get_material_blend_mode();
+ orig_transp = transp;
+
+ memset(&attribs, 0, sizeof(attribs));
+
+#define PASSATTRIB(dx, dy, vert) { \
+ if(attribs.totorco) { \
+ index = getFaceIndex(ss, f, S, x+dx, y+dy, edgeSize, gridSize); \
+ glVertexAttrib3fvARB(attribs.orco.glIndex, attribs.orco.array[index]); \
+ } \
+ for(b = 0; b < attribs.tottface; b++) { \
+ MTFace *tf = &attribs.tface[b].array[a]; \
+ glVertexAttrib2fvARB(attribs.tface[b].glIndex, tf->uv[vert]); \
+ } \
+ for(b = 0; b < attribs.totmcol; b++) { \
+ MCol *cp = &attribs.mcol[b].array[a*4 + vert]; \
+ GLubyte col[4]; \
+ col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a; \
+ glVertexAttrib4ubvARB(attribs.mcol[b].glIndex, col); \
+ } \
+ if(attribs.tottang) { \
+ float *tang = attribs.tang.array[a*4 + vert]; \
+ glVertexAttrib3fvARB(attribs.tang.glIndex, tang); \
+ } \
+}
+
+ totface = ccgSubSurf_getNumFaces(ss);
+ for(a = 0, i = 0; i < totface; i++) {
+ CCGFace *f = ccgdm->faceMap[i].face;
+ int S, x, y, drawSmooth;
+ int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(ss, f));
+ int origIndex = ccgDM_getFaceMapIndex(ss, f);
+
+ numVerts = ccgSubSurf_getFaceNumVerts(f);
+
+ if(faceFlags) {
+ drawSmooth = (faceFlags[index*4] & ME_SMOOTH);
+ new_matnr= faceFlags[index*4 + 1] + 1;
+ }
+ else {
+ drawSmooth = 1;
+ new_matnr= 1;
+ }
+
+ if(new_matnr != matnr) {
+ doDraw = setMaterial(matnr = new_matnr, &gattribs);
+ if(doDraw)
+ DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
+ }
+
+ if(!doDraw || (setDrawOptions && !setDrawOptions(userData, origIndex))) {
+ a += gridFaces*gridFaces*numVerts;
+ continue;
+ }
+
+ if(tf) {
+ new_transp = tf[i].transp;
+
+ if(new_transp != transp) {
+ if(new_transp == GPU_BLEND_SOLID && orig_transp != GPU_BLEND_SOLID)
+ GPU_set_material_blend_mode(orig_transp);
+ else
+ GPU_set_material_blend_mode(new_transp);
+ transp = new_transp;
+ }
+ }
+
+ glShadeModel(drawSmooth? GL_SMOOTH: GL_FLAT);
+ for (S=0; S<numVerts; S++) {
+ VertData *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
+ VertData *vda, *vdb;
+
+ if (drawSmooth) {
+ for (y=0; y<gridFaces; y++) {
+ glBegin(GL_QUAD_STRIP);
+ for (x=0; x<gridFaces; x++) {
+ vda = &faceGridData[(y+0)*gridSize + x];
+ vdb = &faceGridData[(y+1)*gridSize + x];
+
+ PASSATTRIB(0, 0, 0);
+ glNormal3fv(vda->no);
+ glVertex3fv(vda->co);
+
+ PASSATTRIB(0, 1, 1);
+ glNormal3fv(vdb->no);
+ glVertex3fv(vdb->co);
+
+ if(x != gridFaces-1)
+ a++;
+ }
+
+ vda = &faceGridData[(y+0)*gridSize + x];
+ vdb = &faceGridData[(y+1)*gridSize + x];
+
+ PASSATTRIB(0, 0, 3);
+ glNormal3fv(vda->no);
+ glVertex3fv(vda->co);
+
+ PASSATTRIB(0, 1, 2);
+ glNormal3fv(vdb->no);
+ glVertex3fv(vdb->co);
+
+ glEnd();
+
+ a++;
+ }
+ } else {
+ glBegin(GL_QUADS);
+ for (y=0; y<gridFaces; y++) {
+ for (x=0; x<gridFaces; x++) {
+ float *aco = faceGridData[(y+0)*gridSize + x].co;
+ float *bco = faceGridData[(y+0)*gridSize + x + 1].co;
+ float *cco = faceGridData[(y+1)*gridSize + x + 1].co;
+ float *dco = faceGridData[(y+1)*gridSize + x].co;
+
+ ccgDM_glNormalFast(aco, bco, cco, dco);
+
+ PASSATTRIB(0, 1, 1);
+ glVertex3fv(dco);
+ PASSATTRIB(1, 1, 2);
+ glVertex3fv(cco);
+ PASSATTRIB(1, 0, 3);
+ glVertex3fv(bco);
+ PASSATTRIB(0, 0, 0);
+ glVertex3fv(aco);
+
+ a++;
+ }
+ }
+ glEnd();
+ }
+ }
+ }
+
+#undef PASSATTRIB
+
+ ccgFaceIterator_free(fi);
+}
+
+static void ccgDM_drawFacesGLSL(DerivedMesh *dm, int (*setMaterial)(int, void *attribs)) {
+ dm->drawMappedFacesGLSL(dm, setMaterial, NULL, NULL);
+}
+
static void ccgDM_drawFacesColored(DerivedMesh *dm, int useTwoSided, unsigned char *col1, unsigned char *col2) {
CCGDerivedMesh *ccgdm = (CCGDerivedMesh*) dm;
CCGSubSurf *ss = ccgdm->ss;
@@ -1686,7 +1855,7 @@ static void ccgDM_drawFacesColored(DerivedMesh *dm, int useTwoSided, unsigned ch
glBegin(GL_QUADS);
for (; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
for (S=0; S<numVerts; S++) {
VertData *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
@@ -1744,9 +1913,9 @@ static void ccgDM_drawFacesTex_common(DerivedMesh *dm,
totface = ccgSubSurf_getNumFaces(ss);
for(i = 0; i < totface; i++) {
CCGFace *f = ccgdm->faceMap[i].face;
- int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
- int drawSmooth, index = ccgDM_getFaceMapIndex(ccgdm, ss, f);
- int origIndex = (int)ccgSubSurf_getFaceFaceHandle(ss, f);
+ int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
+ int drawSmooth, index = ccgDM_getFaceMapIndex(ss, f);
+ int origIndex = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(ss, f));
unsigned char *cp= NULL;
int mat_nr;
@@ -1827,28 +1996,28 @@ static void ccgDM_drawFacesTex_common(DerivedMesh *dm,
glBegin(GL_QUADS);
for (y=0; y<gridFaces; y++) {
for (x=0; x<gridFaces; x++) {
- float *a = faceGridData[(y+0)*gridSize + x].co;
- float *b = faceGridData[(y+0)*gridSize + x + 1].co;
- float *c = faceGridData[(y+1)*gridSize + x + 1].co;
- float *d = faceGridData[(y+1)*gridSize + x].co;
+ float *a_co = faceGridData[(y+0)*gridSize + x].co;
+ float *b_co = faceGridData[(y+0)*gridSize + x + 1].co;
+ float *c_co = faceGridData[(y+1)*gridSize + x + 1].co;
+ float *d_co = faceGridData[(y+1)*gridSize + x].co;
- ccgDM_glNormalFast(a, b, c, d);
+ ccgDM_glNormalFast(a_co, b_co, c_co, d_co);
if(tf) glTexCoord2fv(tf->uv[1]);
if(cp) glColor3ub(cp[7], cp[6], cp[5]);
- glVertex3fv(d);
+ glVertex3fv(d_co);
if(tf) glTexCoord2fv(tf->uv[2]);
if(cp) glColor3ub(cp[11], cp[10], cp[9]);
- glVertex3fv(c);
+ glVertex3fv(c_co);
if(tf) glTexCoord2fv(tf->uv[3]);
if(cp) glColor3ub(cp[15], cp[14], cp[13]);
- glVertex3fv(b);
+ glVertex3fv(b_co);
if(tf) glTexCoord2fv(tf->uv[0]);
if(cp) glColor3ub(cp[3], cp[2], cp[1]);
- glVertex3fv(a);
+ glVertex3fv(a_co);
if(tf) tf++;
if(cp) cp += 16;
@@ -1904,7 +2073,6 @@ static void ccgDM_drawUVEdges(DerivedMesh *dm)
}
static void ccgDM_drawMappedFaces(DerivedMesh *dm, int (*setDrawOptions)(void *userData, int index, int *drawSmooth_r), void *userData, int useColors) {
- GLubyte act_face_stipple[32*32/8] = DM_FACE_STIPPLE;
CCGDerivedMesh *ccgdm = (CCGDerivedMesh*) dm;
CCGSubSurf *ss = ccgdm->ss;
CCGFaceIterator *fi = ccgSubSurf_getFaceIterator(ss);
@@ -1913,11 +2081,11 @@ static void ccgDM_drawMappedFaces(DerivedMesh *dm, int (*setDrawOptions)(void *u
for (i=0; !ccgFaceIterator_isStopped(fi); i++,ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
- int drawSmooth, index = ccgDM_getFaceMapIndex(ccgdm, ss, f);
+ int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
+ int drawSmooth, index = ccgDM_getFaceMapIndex(ss, f);
int origIndex;
- origIndex = (int)ccgSubSurf_getFaceFaceHandle(ss, f);
+ origIndex = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(ss, f));
if(faceFlags) drawSmooth = (faceFlags[origIndex*4] & ME_SMOOTH);
else drawSmooth = 1;
@@ -1929,7 +2097,7 @@ static void ccgDM_drawMappedFaces(DerivedMesh *dm, int (*setDrawOptions)(void *u
if (draw) {
if (draw==2) {
glEnable(GL_POLYGON_STIPPLE);
- glPolygonStipple(act_face_stipple);
+ glPolygonStipple(0); //XXX stipple_quarttone);
}
for (S=0; S<numVerts; S++) {
@@ -1995,7 +2163,7 @@ static void ccgDM_drawMappedEdges(DerivedMesh *dm, int (*setDrawOptions)(void *u
for (; !ccgEdgeIterator_isStopped(ei); ccgEdgeIterator_next(ei)) {
CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
VertData *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
- int index = ccgDM_getEdgeMapIndex(ccgdm, ss, e);
+ int index = ccgDM_getEdgeMapIndex(ss, e);
glBegin(GL_LINE_STRIP);
if (index!=-1 && (!setDrawOptions || setDrawOptions(userData, index))) {
@@ -2025,7 +2193,7 @@ static void ccgDM_drawMappedEdgesInterp(DerivedMesh *dm, int (*setDrawOptions)(v
for (; !ccgEdgeIterator_isStopped(ei); ccgEdgeIterator_next(ei)) {
CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
VertData *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
- int index = ccgDM_getEdgeMapIndex(ccgdm, ss, e);
+ int index = ccgDM_getEdgeMapIndex(ss, e);
glBegin(GL_LINE_STRIP);
if (index!=-1 && (!setDrawOptions || setDrawOptions(userData, index))) {
@@ -2052,7 +2220,7 @@ static void ccgDM_foreachMappedFaceCenter(DerivedMesh *dm, void (*func)(void *us
for (; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- int index = ccgDM_getFaceMapIndex(ccgdm, ss, f);
+ int index = ccgDM_getFaceMapIndex(ss, f);
if (index!=-1) {
/* Face center data normal isn't updated atm. */
@@ -2088,17 +2256,17 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
int index, totvert, totedge, totface;
int i;
int vertNum, edgeNum, faceNum;
- int *vertOrigIndex, *edgeOrigIndex, *faceOrigIndex;
+ int *vertOrigIndex, *faceOrigIndex; /* *edgeOrigIndex - as yet, unused */
int *edgeFlags;
char *faceFlags;
int edgeSize;
int gridSize;
int gridFaces;
int gridSideVerts;
- int gridInternalVerts;
+ /*int gridInternalVerts; - as yet unused */
int gridSideEdges;
int gridInternalEdges;
- MVert *mvert = NULL;
+ /* MVert *mvert = NULL; - as yet unused */
MEdge *medge = NULL;
MFace *mface = NULL;
FaceVertWeight *qweight, *tweight;
@@ -2141,8 +2309,10 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
ccgdm->dm.drawFacesSolid = ccgDM_drawFacesSolid;
ccgdm->dm.drawFacesColored = ccgDM_drawFacesColored;
ccgdm->dm.drawFacesTex = ccgDM_drawFacesTex;
+ ccgdm->dm.drawFacesGLSL = ccgDM_drawFacesGLSL;
ccgdm->dm.drawMappedFaces = ccgDM_drawMappedFaces;
ccgdm->dm.drawMappedFacesTex = ccgDM_drawMappedFacesTex;
+ ccgdm->dm.drawMappedFacesGLSL = ccgDM_drawMappedFacesGLSL;
ccgdm->dm.drawUVEdges = ccgDM_drawUVEdges;
ccgdm->dm.drawMappedEdgesInterp = ccgDM_drawMappedEdgesInterp;
@@ -2160,7 +2330,7 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
for(; !ccgVertIterator_isStopped(vi); ccgVertIterator_next(vi)) {
CCGVert *v = ccgVertIterator_getCurrent(vi);
- ccgdm->vertMap[(int) ccgSubSurf_getVertVertHandle(ss, v)].vert = v;
+ ccgdm->vertMap[GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v))].vert = v;
}
ccgVertIterator_free(vi);
@@ -2170,7 +2340,7 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
for(; !ccgEdgeIterator_isStopped(ei); ccgEdgeIterator_next(ei)) {
CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
- ccgdm->edgeMap[(int) ccgSubSurf_getEdgeEdgeHandle(ss, e)].edge = e;
+ ccgdm->edgeMap[GET_INT_FROM_POINTER(ccgSubSurf_getEdgeEdgeHandle(e))].edge = e;
}
totface = ccgSubSurf_getNumFaces(ss);
@@ -2179,7 +2349,7 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
for(; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- ccgdm->faceMap[(int) ccgSubSurf_getFaceFaceHandle(ss, f)].face = f;
+ ccgdm->faceMap[GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(ss, f))].face = f;
}
ccgFaceIterator_free(fi);
@@ -2187,7 +2357,7 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
gridSize = ccgSubSurf_getGridSize(ss);
gridFaces = gridSize - 1;
gridSideVerts = gridSize - 2;
- gridInternalVerts = gridSideVerts * gridSideVerts;
+ /*gridInternalVerts = gridSideVerts * gridSideVerts; - as yet, unused */
gridSideEdges = gridSize - 1;
gridInternalEdges = (gridSideEdges - 1) * gridSideEdges * 2;
@@ -2197,22 +2367,22 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
edgeNum = 0;
faceNum = 0;
- mvert = dm->getVertArray(dm);
+ /* mvert = dm->getVertArray(dm); - as yet unused */
medge = dm->getEdgeArray(dm);
mface = dm->getFaceArray(dm);
vertOrigIndex = DM_get_vert_data_layer(&ccgdm->dm, CD_ORIGINDEX);
- edgeOrigIndex = DM_get_edge_data_layer(&ccgdm->dm, CD_ORIGINDEX);
+ /*edgeOrigIndex = DM_get_edge_data_layer(&ccgdm->dm, CD_ORIGINDEX);*/
faceOrigIndex = DM_get_face_data_layer(&ccgdm->dm, CD_ORIGINDEX);
faceFlags = DM_get_face_data_layer(&ccgdm->dm, CD_FLAGS);
for(index = 0; index < totface; ++index) {
CCGFace *f = ccgdm->faceMap[index].face;
- int numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int numVerts = ccgSubSurf_getFaceNumVerts(f);
int numFinalEdges = numVerts * (gridSideEdges + gridInternalEdges);
- int mapIndex = ccgDM_getFaceMapIndex(ccgdm, ss, f);
- int origIndex = (int)ccgSubSurf_getFaceFaceHandle(ss, f);
+ int mapIndex = ccgDM_getFaceMapIndex(ss, f);
+ int origIndex = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(ss, f));
FaceVertWeight *weight = (numVerts == 4) ? qweight : tweight;
int S, x, y;
int vertIdx[4];
@@ -2227,7 +2397,7 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
for(S = 0; S < numVerts; S++) {
CCGVert *v = ccgSubSurf_getFaceVert(ss, f, S);
- vertIdx[S] = (int)ccgSubSurf_getVertVertHandle(ss, v);
+ vertIdx[S] = GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v));
}
DM_interp_vert_data(dm, &ccgdm->dm, vertIdx, weight[0][0],
@@ -2330,16 +2500,16 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
for(index = 0; index < totedge; ++index) {
CCGEdge *e = ccgdm->edgeMap[index].edge;
int numFinalEdges = edgeSize - 1;
- int mapIndex = ccgDM_getEdgeMapIndex(ccgdm, ss, e);
+ int mapIndex = ccgDM_getEdgeMapIndex(ss, e);
int x;
int vertIdx[2];
- int edgeIdx = (int)ccgSubSurf_getEdgeEdgeHandle(ss, e);
+ int edgeIdx = GET_INT_FROM_POINTER(ccgSubSurf_getEdgeEdgeHandle(e));
CCGVert *v;
- v = ccgSubSurf_getEdgeVert0(ss, e);
- vertIdx[0] = (int)ccgSubSurf_getVertVertHandle(ss, v);
- v = ccgSubSurf_getEdgeVert1(ss, e);
- vertIdx[1] = (int)ccgSubSurf_getVertVertHandle(ss, v);
+ v = ccgSubSurf_getEdgeVert0(e);
+ vertIdx[0] = GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v));
+ v = ccgSubSurf_getEdgeVert1(e);
+ vertIdx[1] = GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v));
ccgdm->edgeMap[index].startVert = vertNum;
ccgdm->edgeMap[index].startEdge = edgeNum;
@@ -2370,10 +2540,10 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
for(index = 0; index < totvert; ++index) {
CCGVert *v = ccgdm->vertMap[index].vert;
- int mapIndex = ccgDM_getVertMapIndex(ccgdm, ccgdm->ss, v);
+ int mapIndex = ccgDM_getVertMapIndex(ccgdm->ss, v);
int vertIdx;
- vertIdx = (int)ccgSubSurf_getVertVertHandle(ss, v);
+ vertIdx = GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v));
ccgdm->vertMap[index].startVert = vertNum;
@@ -2417,7 +2587,14 @@ struct DerivedMesh *subsurf_make_derived_from_derived(
useSubsurfUv, dm);
} else if(useRenderParams) {
/* Do not use cache in render mode. */
- CCGSubSurf *ss = _getSubSurf(NULL, smd->renderLevels, 0, 1, useSimple);
+ CCGSubSurf *ss;
+ int levels;
+
+ levels= get_render_subsurf_level(&G.scene->r, smd->renderLevels);
+ if(levels == 0)
+ return dm;
+
+ ss = _getSubSurf(NULL, levels, 0, 1, useSimple);
ss_sync_from_derivedmesh(ss, dm, vertCos, useSimple);
@@ -2499,9 +2676,9 @@ void subsurf_calculate_limit_positions(Mesh *me, float (*positions_r)[3])
vi = ccgSubSurf_getVertIterator(ss);
for (; !ccgVertIterator_isStopped(vi); ccgVertIterator_next(vi)) {
CCGVert *v = ccgVertIterator_getCurrent(vi);
- int idx = (int) ccgSubSurf_getVertVertHandle(ss, v);
- int N = ccgSubSurf_getVertNumEdges(ss, v);
- int numFaces = ccgSubSurf_getVertNumFaces(ss, v);
+ int idx = GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v));
+ int N = ccgSubSurf_getVertNumEdges(v);
+ int numFaces = ccgSubSurf_getVertNumFaces(v);
float *co;
int i;
@@ -2509,12 +2686,12 @@ void subsurf_calculate_limit_positions(Mesh *me, float (*positions_r)[3])
face_sum[0]= face_sum[1]= face_sum[2]= 0.0;
for (i=0; i<N; i++) {
- CCGEdge *e = ccgSubSurf_getVertEdge(ss, v, i);
+ CCGEdge *e = ccgSubSurf_getVertEdge(v, i);
VecAddf(edge_sum, edge_sum, ccgSubSurf_getEdgeData(ss, e, 1));
}
for (i=0; i<numFaces; i++) {
- CCGFace *f = ccgSubSurf_getVertFace(ss, v, i);
- VecAddf(face_sum, face_sum, ccgSubSurf_getFaceCenterData(ss, f));
+ CCGFace *f = ccgSubSurf_getVertFace(v, i);
+ VecAddf(face_sum, face_sum, ccgSubSurf_getFaceCenterData(f));
}
/* ad-hoc correction for boundary vertices, to at least avoid them
diff --git a/source/blender/blenkernel/intern/suggestions.c b/source/blender/blenkernel/intern/suggestions.c
new file mode 100644
index 00000000000..6530909336c
--- /dev/null
+++ b/source/blender/blenkernel/intern/suggestions.c
@@ -0,0 +1,254 @@
+/**
+ * $Id: $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2008, Blender Foundation
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Ian Thompson.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+
+#include "MEM_guardedalloc.h"
+#include "BLI_blenlib.h"
+#include "DNA_text_types.h"
+#include "BKE_text.h"
+#include "BKE_suggestions.h"
+
+/**********************/
+/* Static definitions */
+/**********************/
+
+static Text *activeToolText = NULL;
+static SuggList suggestions = {NULL, NULL, NULL, NULL, NULL};
+static char *documentation = NULL;
+//static int doc_lines = 0;
+
+static int txttl_cmp(const char *first, const char *second, int len) {
+ int cmp, i;
+ for (cmp=0, i=0; i<len; i++) {
+ if ( (cmp= toupper(first[i])-toupper(second[i])) ) {
+ break;
+ }
+ }
+ return cmp;
+}
+
+static void txttl_free_suggest() {
+ SuggItem *item, *prev;
+ for (item = suggestions.last; item; item=prev) {
+ prev = item->prev;
+ MEM_freeN(item);
+ }
+ suggestions.first = suggestions.last = NULL;
+ suggestions.firstmatch = suggestions.lastmatch = NULL;
+ suggestions.selected = NULL;
+ suggestions.top = 0;
+}
+
+static void txttl_free_docs() {
+ if (documentation) {
+ MEM_freeN(documentation);
+ documentation = NULL;
+ }
+}
+
+/**************************/
+/* General tool functions */
+/**************************/
+
+void free_texttools() {
+ txttl_free_suggest();
+ txttl_free_docs();
+}
+
+void texttool_text_set_active(Text *text) {
+ if (activeToolText == text) return;
+ texttool_text_clear();
+ activeToolText = text;
+}
+
+void texttool_text_clear() {
+ free_texttools();
+ activeToolText = NULL;
+}
+
+short texttool_text_is_active(Text *text) {
+ return activeToolText==text ? 1 : 0;
+}
+
+/***************************/
+/* Suggestion list methods */
+/***************************/
+
+void texttool_suggest_add(const char *name, char type) {
+ SuggItem *newitem, *item;
+ int len, cmp;
+
+ newitem = MEM_mallocN(sizeof(SuggItem) + strlen(name) + 1, "SuggestionItem");
+ if (!newitem) {
+ printf("Failed to allocate memory for suggestion.\n");
+ return;
+ }
+
+ newitem->name = (char *) (newitem + 1);
+ len = strlen(name);
+ strncpy(newitem->name, name, len);
+ newitem->name[len] = '\0';
+ newitem->type = type;
+ newitem->prev = newitem->next = NULL;
+
+ /* Perform simple linear search for ordered storage */
+ if (!suggestions.first || !suggestions.last) {
+ suggestions.first = suggestions.last = newitem;
+ } else {
+ cmp = -1;
+ for (item=suggestions.last; item; item=item->prev) {
+ cmp = txttl_cmp(name, item->name, len);
+
+ /* Newitem comes after this item, insert here */
+ if (cmp >= 0) {
+ newitem->prev = item;
+ if (item->next)
+ item->next->prev = newitem;
+ newitem->next = item->next;
+ item->next = newitem;
+
+ /* At last item, set last pointer here */
+ if (item == suggestions.last)
+ suggestions.last = newitem;
+ break;
+ }
+ }
+ /* Reached beginning of list, insert before first */
+ if (cmp < 0) {
+ newitem->next = suggestions.first;
+ suggestions.first->prev = newitem;
+ suggestions.first = newitem;
+ }
+ }
+ suggestions.firstmatch = suggestions.lastmatch = suggestions.selected = NULL;
+ suggestions.top= 0;
+}
+
+void texttool_suggest_prefix(const char *prefix) {
+ SuggItem *match, *first, *last;
+ int cmp, len = strlen(prefix), top = 0;
+
+ if (!suggestions.first) return;
+ if (len==0) {
+ suggestions.selected = suggestions.firstmatch = suggestions.first;
+ suggestions.lastmatch = suggestions.last;
+ return;
+ }
+
+ first = last = NULL;
+ for (match=suggestions.first; match; match=match->next) {
+ cmp = txttl_cmp(prefix, match->name, len);
+ if (cmp==0) {
+ if (!first) {
+ first = match;
+ suggestions.top = top;
+ }
+ } else if (cmp<0) {
+ if (!last) {
+ last = match->prev;
+ break;
+ }
+ }
+ top++;
+ }
+ if (first) {
+ if (!last) last = suggestions.last;
+ suggestions.firstmatch = first;
+ suggestions.lastmatch = last;
+ suggestions.selected = first;
+ } else {
+ suggestions.firstmatch = NULL;
+ suggestions.lastmatch = NULL;
+ suggestions.selected = NULL;
+ suggestions.top = 0;
+ }
+}
+
+void texttool_suggest_clear() {
+ txttl_free_suggest();
+}
+
+SuggItem *texttool_suggest_first() {
+ return suggestions.firstmatch;
+}
+
+SuggItem *texttool_suggest_last() {
+ return suggestions.lastmatch;
+}
+
+void texttool_suggest_select(SuggItem *sel) {
+ suggestions.selected = sel;
+}
+
+SuggItem *texttool_suggest_selected() {
+ return suggestions.selected;
+}
+
+int *texttool_suggest_top() {
+ return &suggestions.top;
+}
+
+/*************************/
+/* Documentation methods */
+/*************************/
+
+void texttool_docs_show(const char *docs) {
+ int len;
+
+ if (!docs) return;
+
+ len = strlen(docs);
+
+ if (documentation) {
+ MEM_freeN(documentation);
+ documentation = NULL;
+ }
+
+ /* Ensure documentation ends with a '\n' */
+ if (docs[len-1] != '\n') {
+ documentation = MEM_mallocN(len+2, "Documentation");
+ strncpy(documentation, docs, len);
+ documentation[len++] = '\n';
+ } else {
+ documentation = MEM_mallocN(len+1, "Documentation");
+ strncpy(documentation, docs, len);
+ }
+ documentation[len] = '\0';
+}
+
+char *texttool_docs_get() {
+ return documentation;
+}
+
+void texttool_docs_clear() {
+ txttl_free_docs();
+}
diff --git a/source/blender/blenkernel/intern/text.c b/source/blender/blenkernel/intern/text.c
index 0dbaa9d3843..d1d252ab210 100644
--- a/source/blender/blenkernel/intern/text.c
+++ b/source/blender/blenkernel/intern/text.c
@@ -30,6 +30,8 @@
*/
#include <string.h> /* strstr */
+#include <sys/types.h>
+#include <sys/stat.h>
#include "MEM_guardedalloc.h"
@@ -44,7 +46,9 @@
#include "BKE_global.h"
#include "BKE_main.h"
+#ifndef DISABLE_PYTHON
#include "BPY_extern.h"
+#endif
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -80,12 +84,19 @@ The st->top determines at what line the top of the text is displayed.
If the user moves the cursor the st containing that cursor should
be popped ... other st's retain their own top location.
-*/ /***************/
-
+Markers
+--
+The mrk->flags define the behaviour and relationships between markers. The
+upper two bytes are used to hold a group ID, the lower two are normal flags. If
+TMARK_EDITALL is set the group ID defines which other markers should be edited.
-/****************/ /*
- Undo
+The mrk->clr field is used to visually group markers where the flags may not
+match. A template system, for example, may allow editing of repeating tokens
+(in one group) but include other marked positions (in another group) all in the
+same template with the same colour.
+Undo
+--
Undo/Redo works by storing
events in a queue, and a pointer
to the current position in the
@@ -144,10 +155,13 @@ void free_text(Text *text)
}
BLI_freelistN(&text->lines);
+ BLI_freelistN(&text->markers);
if(text->name) MEM_freeN(text->name);
MEM_freeN(text->undo_buf);
+#ifndef DISABLE_PYTHON
if (text->compiled) BPY_free_compiled_text(text);
+#endif
}
Text *add_empty_text(char *name)
@@ -168,10 +182,11 @@ Text *add_empty_text(char *name)
ta->flags= TXT_ISDIRTY | TXT_ISTMP | TXT_ISMEM;
ta->lines.first= ta->lines.last= NULL;
+ ta->markers.first= ta->markers.last= NULL;
tmp= (TextLine*) MEM_mallocN(sizeof(TextLine), "textline");
tmp->line= (char*) MEM_mallocN(1, "textline_string");
- tmp->format= (char*) MEM_mallocN(2, "Syntax_format");
+ tmp->format= NULL;
tmp->line[0]=0;
tmp->len= 0;
@@ -208,18 +223,18 @@ static void cleanup_textline(TextLine * tl)
int reopen_text(Text *text)
{
FILE *fp;
- int i, llen, len;
+ int i, llen, len, res;
unsigned char *buffer;
TextLine *tmp;
- char sdir[FILE_MAXDIR];
char sfile[FILE_MAXFILE];
char str[FILE_MAXDIR+FILE_MAXFILE];
+ struct stat st;
if (!text || !text->name) return 0;
BLI_strncpy(str, text->name, FILE_MAXDIR+FILE_MAXFILE);
- BLI_convertstringcode(str, G.sce, G.scene->r.cfra);
- BLI_split_dirfile(str, sdir, sfile);
+ BLI_convertstringcode(str, G.sce);
+ BLI_split_dirfile_basic(str, NULL, sfile);
fp= fopen(str, "r");
if(fp==NULL) return 0;
@@ -242,7 +257,7 @@ int reopen_text(Text *text)
text->undo_len= TXT_INIT_UNDO;
text->undo_buf= MEM_mallocN(text->undo_len, "undo buf");
- text->flags= TXT_ISDIRTY | TXT_ISTMP;
+ text->flags= TXT_ISTMP;
fseek(fp, 0L, SEEK_END);
len= ftell(fp);
@@ -256,6 +271,9 @@ int reopen_text(Text *text)
len = fread(buffer, 1, len, fp);
fclose(fp);
+
+ res= stat(str, &st);
+ text->mtime= st.st_mtime;
text->nlines=0;
i=0;
@@ -264,7 +282,7 @@ int reopen_text(Text *text)
if (buffer[i]=='\n') {
tmp= (TextLine*) MEM_mallocN(sizeof(TextLine), "textline");
tmp->line= (char*) MEM_mallocN(llen+1, "textline_string");
- tmp->format= (char*) MEM_mallocN(llen+2, "Syntax_format");
+ tmp->format= NULL;
if(llen) memcpy(tmp->line, &buffer[i-llen], llen);
tmp->line[llen]=0;
@@ -284,7 +302,7 @@ int reopen_text(Text *text)
if (llen!=0 || text->nlines==0) {
tmp= (TextLine*) MEM_mallocN(sizeof(TextLine), "textline");
tmp->line= (char*) MEM_mallocN(llen+1, "textline_string");
- tmp->format= (char*) MEM_mallocN(llen+2, "Syntax_format");
+ tmp->format= NULL;
if(llen) memcpy(tmp->line, &buffer[i-llen], llen);
@@ -307,18 +325,18 @@ int reopen_text(Text *text)
Text *add_text(char *file)
{
FILE *fp;
- int i, llen, len;
+ int i, llen, len, res;
unsigned char *buffer;
TextLine *tmp;
Text *ta;
- char sdir[FILE_MAXDIR];
char sfile[FILE_MAXFILE];
char str[FILE_MAXDIR+FILE_MAXFILE];
+ struct stat st;
BLI_strncpy(str, file, FILE_MAXDIR+FILE_MAXFILE);
if (G.scene) /* can be NULL (bg mode) */
- BLI_convertstringcode(str, G.sce, G.scene->r.cfra);
- BLI_split_dirfile(str, sdir, sfile);
+ BLI_convertstringcode(str, G.sce);
+ BLI_split_dirfile_basic(str, NULL, sfile);
fp= fopen(str, "r");
if(fp==NULL) return NULL;
@@ -327,6 +345,7 @@ Text *add_text(char *file)
ta->id.us= 1;
ta->lines.first= ta->lines.last= NULL;
+ ta->markers.first= ta->markers.last= NULL;
ta->curl= ta->sell= NULL;
/* ta->flags= TXT_ISTMP | TXT_ISEXT; */
@@ -349,6 +368,9 @@ Text *add_text(char *file)
len = fread(buffer, 1, len, fp);
fclose(fp);
+
+ res= stat(str, &st);
+ ta->mtime= st.st_mtime;
ta->nlines=0;
i=0;
@@ -357,7 +379,7 @@ Text *add_text(char *file)
if (buffer[i]=='\n') {
tmp= (TextLine*) MEM_mallocN(sizeof(TextLine), "textline");
tmp->line= (char*) MEM_mallocN(llen+1, "textline_string");
- tmp->format= (char*) MEM_mallocN(llen+2, "Syntax_format");
+ tmp->format= NULL;
if(llen) memcpy(tmp->line, &buffer[i-llen], llen);
tmp->line[llen]=0;
@@ -377,7 +399,7 @@ Text *add_text(char *file)
if (llen!=0 || ta->nlines==0) {
tmp= (TextLine*) MEM_mallocN(sizeof(TextLine), "textline");
tmp->line= (char*) MEM_mallocN(llen+1, "textline_string");
- tmp->format= (char*) MEM_mallocN(llen+2, "Syntax_format");
+ tmp->format= NULL;
if(llen) memcpy(tmp->line, &buffer[i-llen], llen);
@@ -411,6 +433,7 @@ Text *copy_text(Text *ta)
tan->flags = ta->flags | TXT_ISDIRTY | TXT_ISTMP;
tan->lines.first= tan->lines.last= NULL;
+ tan->markers.first= tan->markers.last= NULL;
tan->curl= tan->sell= NULL;
tan->nlines= ta->nlines;
@@ -420,7 +443,7 @@ Text *copy_text(Text *ta)
while (line) {
tmp= (TextLine*) MEM_mallocN(sizeof(TextLine), "textline");
tmp->line= MEM_mallocN(line->len+1, "textline_string");
- tmp->format= MEM_mallocN(line->len+2, "Syntax_format");
+ tmp->format= NULL;
strcpy(tmp->line, line->line);
@@ -441,14 +464,14 @@ Text *copy_text(Text *ta)
/* Editing utility functions */
/*****************************/
-static void make_new_line (TextLine *line, char *newline, char *newformat)
+static void make_new_line (TextLine *line, char *newline)
{
if (line->line) MEM_freeN(line->line);
if (line->format) MEM_freeN(line->format);
line->line= newline;
line->len= strlen(newline);
- line->format= newformat;
+ line->format= NULL;
}
static TextLine *txt_new_line(char *str)
@@ -459,7 +482,7 @@ static TextLine *txt_new_line(char *str)
tmp= (TextLine *) MEM_mallocN(sizeof(TextLine), "textline");
tmp->line= MEM_mallocN(strlen(str)+1, "textline_string");
- tmp->format= MEM_mallocN(strlen(str)+2, "Syntax_format");
+ tmp->format= NULL;
strcpy(tmp->line, str);
@@ -477,7 +500,7 @@ static TextLine *txt_new_linen(char *str, int n)
tmp= (TextLine *) MEM_mallocN(sizeof(TextLine), "textline");
tmp->line= MEM_mallocN(n+1, "textline_string");
- tmp->format= MEM_mallocN(n+2, "Syntax_format");
+ tmp->format= NULL;
BLI_strncpy(tmp->line, str, n+1);
@@ -551,7 +574,23 @@ int txt_get_span (TextLine *from, TextLine *to)
static void txt_make_dirty (Text *text)
{
text->flags |= TXT_ISDIRTY;
+#ifndef DISABLE_PYTHON
if (text->compiled) BPY_free_compiled_text(text);
+#endif
+}
+
+/* 0:whitespace, 1:punct, 2:alphanumeric */
+static short txt_char_type (char ch)
+{
+ if (ch <= ' ') return 0; /* 32 */
+ if (ch <= '/') return 1; /* 47 */
+ if (ch <= '9') return 2; /* 57 */
+ if (ch <= '@') return 1; /* 64 */
+ if (ch <= 'Z') return 2; /* 90 */
+ if (ch == '_') return 2; /* 95, dont delimit '_' */
+ if (ch <= '`') return 1; /* 96 */
+ if (ch <= 'z') return 2; /* 122 */
+ return 1;
}
/****************************/
@@ -607,8 +646,7 @@ void txt_move_up(Text *text, short sel)
if(!undoing) txt_undo_add_op(text, sel?UNDO_SUP:UNDO_CUP);
}
} else {
- *charp= 0;
- if(!undoing) txt_undo_add_op(text, sel?UNDO_SUP:UNDO_CUP);
+ txt_move_bol(text, sel);
}
if(!sel) txt_pop_sel(text);
@@ -633,8 +671,7 @@ void txt_move_down(Text *text, short sel)
} else
if(!undoing) txt_undo_add_op(text, sel?UNDO_SDOWN:UNDO_CDOWN);
} else {
- *charp= (*linep)->len;
- if(!undoing) txt_undo_add_op(text, sel?UNDO_SDOWN:UNDO_CDOWN);
+ txt_move_eol(text, sel);
}
if(!sel) txt_pop_sel(text);
@@ -690,6 +727,68 @@ void txt_move_right(Text *text, short sel)
if(!sel) txt_pop_sel(text);
}
+void txt_jump_left(Text *text, short sel)
+{
+ TextLine **linep, *oldl;
+ int *charp, oldc, count, i;
+ unsigned char oldu;
+
+ if (!text) return;
+ if(sel) txt_curs_sel(text, &linep, &charp);
+ else { txt_pop_first(text); txt_curs_cur(text, &linep, &charp); }
+ if (!*linep) return;
+
+ oldl= *linep;
+ oldc= *charp;
+ oldu= undoing;
+ undoing= 1; /* Don't push individual moves to undo stack */
+
+ count= 0;
+ for (i=0; i<3; i++) {
+ if (count < 2) {
+ while (*charp>0 && txt_char_type((*linep)->line[*charp-1])==i) {
+ txt_move_left(text, sel);
+ count++;
+ }
+ }
+ }
+ if (count==0) txt_move_left(text, sel);
+
+ undoing= oldu;
+ if(!undoing) txt_undo_add_toop(text, sel?UNDO_STO:UNDO_CTO, txt_get_span(text->lines.first, oldl), oldc, txt_get_span(text->lines.first, *linep), (unsigned short)*charp);
+}
+
+void txt_jump_right(Text *text, short sel)
+{
+ TextLine **linep, *oldl;
+ int *charp, oldc, count, i;
+ unsigned char oldu;
+
+ if (!text) return;
+ if(sel) txt_curs_sel(text, &linep, &charp);
+ else { txt_pop_last(text); txt_curs_cur(text, &linep, &charp); }
+ if (!*linep) return;
+
+ oldl= *linep;
+ oldc= *charp;
+ oldu= undoing;
+ undoing= 1; /* Don't push individual moves to undo stack */
+
+ count= 0;
+ for (i=0; i<3; i++) {
+ if (count < 2) {
+ while (*charp<(*linep)->len && txt_char_type((*linep)->line[*charp])==i) {
+ txt_move_right(text, sel);
+ count++;
+ }
+ }
+ }
+ if (count==0) txt_move_right(text, sel);
+
+ undoing= oldu;
+ if(!undoing) txt_undo_add_toop(text, sel?UNDO_STO:UNDO_CTO, txt_get_span(text->lines.first, oldl), oldc, txt_get_span(text->lines.first, *linep), (unsigned short)*charp);
+}
+
void txt_move_bol (Text *text, short sel)
{
TextLine **linep;
@@ -762,6 +861,11 @@ void txt_move_eof (Text *text, short sel)
void txt_move_toline (Text *text, unsigned int line, short sel)
{
+ txt_move_to(text, line, 0, sel);
+}
+
+void txt_move_to (Text *text, unsigned int line, unsigned int ch, short sel)
+{
TextLine **linep, *oldl;
int *charp, oldc;
unsigned int i;
@@ -778,10 +882,12 @@ void txt_move_toline (Text *text, unsigned int line, short sel)
if ((*linep)->next) *linep= (*linep)->next;
else break;
}
- *charp= 0;
+ if (ch>(*linep)->len)
+ ch= (*linep)->len;
+ *charp= ch;
if(!sel) txt_pop_sel(text);
- if(!undoing) txt_undo_add_toop(text, sel?UNDO_STO:UNDO_CTO, txt_get_span(text->lines.first, oldl), oldc, txt_get_span(text->lines.first, *linep), (unsigned short)*charp);
+ if(!undoing) txt_undo_add_toop(text, sel?UNDO_STO:UNDO_CTO, txt_get_span(text->lines.first, oldl), oldc, txt_get_span(text->lines.first, *linep), (unsigned short)*charp);
}
/****************************/
@@ -866,7 +972,9 @@ int txt_has_sel(Text *text)
static void txt_delete_sel (Text *text)
{
TextLine *tmpl;
- char *buf, *format;
+ TextMarker *mrk;
+ char *buf;
+ int move, lineno;
if (!text) return;
if (!text->curl) return;
@@ -883,13 +991,33 @@ static void txt_delete_sel (Text *text)
}
buf= MEM_mallocN(text->curc+(text->sell->len - text->selc)+1, "textline_string");
- format= MEM_mallocN(text->curc+(text->sell->len - text->selc)+2, "Syntax_format");
+ if (text->curl != text->sell) {
+ txt_clear_marker_region(text, text->curl, text->curc, text->curl->len, 0, 0);
+ move= txt_get_span(text->curl, text->sell);
+ } else {
+ mrk= txt_find_marker_region(text, text->curl, text->curc, text->selc, 0, 0);
+ if (mrk && (mrk->start > text->curc || mrk->end < text->selc))
+ txt_clear_marker_region(text, text->curl, text->curc, text->selc, 0, 0);
+ move= 0;
+ }
+
+ mrk= txt_find_marker_region(text, text->sell, text->selc-1, text->sell->len, 0, 0);
+ if (mrk) {
+ lineno= mrk->lineno;
+ do {
+ mrk->lineno -= move;
+ if (mrk->start > text->curc) mrk->start -= text->selc - text->curc;
+ mrk->end -= text->selc - text->curc;
+ mrk= mrk->next;
+ } while (mrk && mrk->lineno==lineno);
+ }
+
strncpy(buf, text->curl->line, text->curc);
strcpy(buf+text->curc, text->sell->line + text->selc);
buf[text->curc+(text->sell->len - text->selc)]=0;
- make_new_line(text->curl, buf, format);
+ make_new_line(text->curl, buf);
tmpl= text->sell;
while (tmpl != text->curl) {
@@ -943,7 +1071,8 @@ char *txt_to_buf (Text *text)
if (!text) return NULL;
if (!text->curl) return NULL;
if (!text->sell) return NULL;
-
+ if (!text->lines.first) return NULL;
+
linef= text->lines.first;
charf= 0;
@@ -995,22 +1124,31 @@ char *txt_to_buf (Text *text)
return buf;
}
-int txt_find_string(Text *text, char *findstr)
+int txt_find_string(Text *text, char *findstr, int wrap)
{
TextLine *tl, *startl;
char *s= NULL;
+ int oldcl, oldsl, oldcc, oldsc;
if (!text || !text->curl || !text->sell) return 0;
txt_order_cursors(text);
+ oldcl= txt_get_span(text->lines.first, text->curl);
+ oldsl= txt_get_span(text->lines.first, text->sell);
tl= startl= text->sell;
+ oldcc= text->curc;
+ oldsc= text->selc;
s= strstr(&tl->line[text->selc], findstr);
while (!s) {
tl= tl->next;
- if (!tl)
- tl= text->lines.first;
+ if (!tl) {
+ if (wrap)
+ tl= text->lines.first;
+ else
+ break;
+ }
s= strstr(tl->line, findstr);
if (tl==startl)
@@ -1018,10 +1156,10 @@ int txt_find_string(Text *text, char *findstr)
}
if (s) {
- text->curl= text->sell= tl;
- text->curc= (int) (s-tl->line);
- text->selc= text->curc + strlen(findstr);
-
+ int newl= txt_get_span(text->lines.first, tl);
+ int newc= (int)(s-tl->line);
+ txt_move_to(text, newl, newc, 0);
+ txt_move_to(text, newl, newc + strlen(findstr), 1);
return 1;
} else
return 0;
@@ -1029,7 +1167,8 @@ int txt_find_string(Text *text, char *findstr)
void txt_cut_sel (Text *text)
{
- txt_copy_sel(text);
+ if (!G.background) /* Python uses txt_cut_sel, which it should not, working around for now */
+ ; //XXX txt_copy_clipboard(text);
txt_delete_sel(text);
txt_make_dirty(text);
@@ -1620,7 +1759,6 @@ void txt_do_undo(Text *text)
case UNDO_SWAP:
txt_curs_swap(text);
- txt_do_undo(text); /* swaps should appear transparent */
break;
case UNDO_DBLOCK:
@@ -1735,6 +1873,19 @@ void txt_do_undo(Text *text)
break;
}
+
+ /* next undo step may need evaluating */
+ if (text->undo_pos>=0) {
+ switch (text->undo_buf[text->undo_pos]) {
+ case UNDO_STO:
+ txt_do_undo(text);
+ txt_do_redo(text); /* selections need restoring */
+ break;
+ case UNDO_SWAP:
+ txt_do_undo(text); /* swaps should appear transparent */
+ break;
+ }
+ }
undoing= 0;
}
@@ -1809,7 +1960,7 @@ void txt_do_redo(Text *text)
case UNDO_SWAP:
txt_curs_swap(text);
- txt_do_undo(text); /* swaps should appear transparent a*/
+ txt_do_redo(text); /* swaps should appear transparent a*/
break;
case UNDO_CTO:
@@ -1946,22 +2097,37 @@ void txt_do_redo(Text *text)
void txt_split_curline (Text *text)
{
TextLine *ins;
- char *left, *right, *fleft, *fright;
+ TextMarker *mrk;
+ char *left, *right;
+ int lineno= -1;
if (!text) return;
if (!text->curl) return;
- txt_delete_sel(text);
+ txt_delete_sel(text);
+
+ /* Move markers */
+
+ lineno= txt_get_span(text->lines.first, text->curl);
+ mrk= text->markers.first;
+ while (mrk) {
+ if (mrk->lineno==lineno && mrk->start>text->curc) {
+ mrk->lineno++;
+ mrk->start -= text->curc;
+ mrk->end -= text->curc;
+ } else if (mrk->lineno > lineno) {
+ mrk->lineno++;
+ }
+ mrk= mrk->next;
+ }
/* Make the two half strings */
left= MEM_mallocN(text->curc+1, "textline_string");
- fleft= MEM_mallocN(text->curc+2, "Syntax_format");
if (text->curc) memcpy(left, text->curl->line, text->curc);
left[text->curc]=0;
right= MEM_mallocN(text->curl->len - text->curc+1, "textline_string");
- fright= MEM_mallocN(text->curl->len - text->curc+2, "Syntax_format");
if (text->curl->len - text->curc) memcpy(right, text->curl->line+text->curc, text->curl->len-text->curc);
right[text->curl->len - text->curc]=0;
@@ -1972,11 +2138,11 @@ void txt_split_curline (Text *text)
ins= MEM_mallocN(sizeof(TextLine), "textline");
ins->line= left;
- ins->format= fleft;
+ ins->format= NULL;
ins->len= text->curc;
text->curl->line= right;
- text->curl->format= fright;
+ text->curl->format= NULL;
text->curl->len= text->curl->len - text->curc;
BLI_insertlinkbefore(&text->lines, text->curl, ins);
@@ -1992,9 +2158,23 @@ void txt_split_curline (Text *text)
static void txt_delete_line (Text *text, TextLine *line)
{
+ TextMarker *mrk=NULL, *nxt;
+ int lineno= -1;
+
if (!text) return;
if (!text->curl) return;
+ lineno= txt_get_span(text->lines.first, line);
+ mrk= text->markers.first;
+ while (mrk) {
+ nxt= mrk->next;
+ if (mrk->lineno==lineno)
+ BLI_freelinkN(&text->markers, mrk);
+ else if (mrk->lineno > lineno)
+ mrk->lineno--;
+ mrk= nxt;
+ }
+
BLI_remlink (&text->lines, line);
if (line->line) MEM_freeN(line->line);
@@ -2008,21 +2188,35 @@ static void txt_delete_line (Text *text, TextLine *line)
static void txt_combine_lines (Text *text, TextLine *linea, TextLine *lineb)
{
- char *tmp, *format;
+ char *tmp;
+ TextMarker *mrk= NULL;
+ int lineno=-1;
if (!text) return;
if(!linea || !lineb) return;
+
+ mrk= txt_find_marker_region(text, lineb, 0, lineb->len, 0, 0);
+ if (mrk) {
+ lineno= mrk->lineno;
+ do {
+ mrk->lineno--;
+ mrk->start += linea->len;
+ mrk->end += linea->len;
+ mrk= mrk->next;
+ } while (mrk && mrk->lineno==lineno);
+ }
+ if (lineno==-1) lineno= txt_get_span(text->lines.first, lineb);
+ if (!mrk) mrk= text->markers.first;
tmp= MEM_mallocN(linea->len+lineb->len+1, "textline_string");
- format= MEM_mallocN(linea->len+lineb->len+1, "Syntax_format");
strcpy(tmp, linea->line);
strcat(tmp, lineb->line);
- make_new_line(linea, tmp, format);
+ make_new_line(linea, tmp);
- txt_delete_line(text, lineb);
+ txt_delete_line(text, lineb);
txt_make_dirty(text);
txt_clean_text(text);
@@ -2036,7 +2230,9 @@ void txt_delete_char (Text *text)
if (!text->curl) return;
if (txt_has_sel(text)) { /* deleting a selection */
- txt_delete_sel(text);
+ txt_delete_sel(text);
+ txt_make_dirty(text);
+ return;
}
else if (text->curc== text->curl->len) { /* Appending two lines */
if (text->curl->next) {
@@ -2045,6 +2241,24 @@ void txt_delete_char (Text *text)
}
} else { /* Just deleting a char */
int i= text->curc;
+
+ TextMarker *mrk= txt_find_marker_region(text, text->curl, i-1, text->curl->len, 0, 0);
+ if (mrk) {
+ int lineno= mrk->lineno;
+ if (mrk->end==i) {
+ if ((mrk->flags & TMARK_TEMP) && !(mrk->flags & TMARK_EDITALL)) {
+ txt_clear_markers(text, mrk->group, TMARK_TEMP);
+ } else {
+ BLI_freelinkN(&text->markers, mrk);
+ }
+ return;
+ }
+ do {
+ if (mrk->start>i) mrk->start--;
+ mrk->end--;
+ mrk= mrk->next;
+ } while (mrk && mrk->lineno==lineno);
+ }
c= text->curl->line[i];
while(i< text->curl->len) {
@@ -2062,6 +2276,12 @@ void txt_delete_char (Text *text)
if(!undoing) txt_undo_add_charop(text, UNDO_DEL, c);
}
+void txt_delete_word (Text *text)
+{
+ txt_jump_right(text, 1);
+ txt_delete_sel(text);
+}
+
void txt_backspace_char (Text *text)
{
char c='\n';
@@ -2070,29 +2290,49 @@ void txt_backspace_char (Text *text)
if (!text->curl) return;
if (txt_has_sel(text)) { /* deleting a selection */
- txt_delete_sel(text);
+ txt_delete_sel(text);
+ txt_make_dirty(text);
+ return;
}
else if (text->curc==0) { /* Appending two lines */
- if (text->curl->prev) {
- text->curl= text->curl->prev;
- text->curc= text->curl->len;
-
- txt_combine_lines(text, text->curl, text->curl->next);
- txt_pop_sel(text);
- }
- }
- else { /* Just backspacing a char */
- int i= text->curc-1;
+ if (!text->curl->prev) return;
- c= text->curl->line[i];
- while(i< text->curl->len) {
- text->curl->line[i]= text->curl->line[i+1];
- i++;
- }
- text->curl->len--;
- text->curc--;
+ text->curl= text->curl->prev;
+ text->curc= text->curl->len;
- txt_pop_sel(text);
+ txt_combine_lines(text, text->curl, text->curl->next);
+ txt_pop_sel(text);
+ }
+ else { /* Just backspacing a char */
+ int i= text->curc-1;
+
+ TextMarker *mrk= txt_find_marker_region(text, text->curl, i, text->curl->len, 0, 0);
+ if (mrk) {
+ int lineno= mrk->lineno;
+ if (mrk->start==i+1) {
+ if ((mrk->flags & TMARK_TEMP) && !(mrk->flags & TMARK_EDITALL)) {
+ txt_clear_markers(text, mrk->group, TMARK_TEMP);
+ } else {
+ BLI_freelinkN(&text->markers, mrk);
+ }
+ return;
+ }
+ do {
+ if (mrk->start>i) mrk->start--;
+ mrk->end--;
+ mrk= mrk->next;
+ } while (mrk && mrk->lineno==lineno);
+ }
+
+ c= text->curl->line[i];
+ while(i< text->curl->len) {
+ text->curl->line[i]= text->curl->line[i+1];
+ i++;
+ }
+ text->curl->len--;
+ text->curc--;
+
+ txt_pop_sel(text);
}
txt_make_dirty(text);
@@ -2101,10 +2341,17 @@ void txt_backspace_char (Text *text)
if(!undoing) txt_undo_add_charop(text, UNDO_BS, c);
}
+void txt_backspace_word (Text *text)
+{
+ txt_jump_left(text, 1);
+ txt_delete_sel(text);
+}
+
int txt_add_char (Text *text, char add)
{
- int len;
- char *tmp, *format;
+ int len, lineno;
+ char *tmp;
+ TextMarker *mrk;
if (!text) return 0;
if (!text->curl) return 0;
@@ -2116,8 +2363,17 @@ int txt_add_char (Text *text, char add)
txt_delete_sel(text);
+ mrk= txt_find_marker_region(text, text->curl, text->curc-1, text->curl->len, 0, 0);
+ if (mrk) {
+ lineno= mrk->lineno;
+ do {
+ if (mrk->start>text->curc) mrk->start++;
+ mrk->end++;
+ mrk= mrk->next;
+ } while (mrk && mrk->lineno==lineno);
+ }
+
tmp= MEM_mallocN(text->curl->len+2, "textline_string");
- format= MEM_mallocN(text->curl->len+4, "Syntax_format");
if(text->curc) memcpy(tmp, text->curl->line, text->curc);
tmp[text->curc]= add;
@@ -2125,7 +2381,7 @@ int txt_add_char (Text *text, char add)
len= text->curl->len - text->curc;
if(len>0) memcpy(tmp+text->curc+1, text->curl->line+text->curc, len);
tmp[text->curl->len+1]=0;
- make_new_line(text->curl, tmp, format);
+ make_new_line(text->curl, tmp);
text->curc++;
@@ -2138,10 +2394,42 @@ int txt_add_char (Text *text, char add)
return 1;
}
+int txt_replace_char (Text *text, char add)
+{
+ char del;
+
+ if (!text) return 0;
+ if (!text->curl) return 0;
+
+ /* If text is selected or we're at the end of the line just use txt_add_char */
+ if (text->curc==text->curl->len || txt_has_sel(text) || add=='\n') {
+ TextMarker *mrk;
+ int i= txt_add_char(text, add);
+ mrk= txt_find_marker(text, text->curl, text->curc, 0, 0);
+ if (mrk && mrk->end==text->curc) mrk->end--;
+ return i;
+ }
+
+ del= text->curl->line[text->curc];
+ text->curl->line[text->curc]= (unsigned char) add;
+ text->curc++;
+ txt_pop_sel(text);
+
+ txt_make_dirty(text);
+ txt_clean_text(text);
+
+ /* Should probably create a new op for this */
+ if(!undoing) {
+ txt_undo_add_charop(text, UNDO_DEL, del);
+ txt_undo_add_charop(text, UNDO_INSERT, add);
+ }
+ return 1;
+}
+
void indent(Text *text)
{
int len, num;
- char *tmp, *format;
+ char *tmp;
char add = '\t';
if (!text) return;
@@ -2152,7 +2440,6 @@ void indent(Text *text)
while (TRUE)
{
tmp= MEM_mallocN(text->curl->len+2, "textline_string");
- format= MEM_mallocN(text->curl->len+3, "Syntax_format");
text->curc = 0;
if(text->curc) memcpy(tmp, text->curl->line, text->curc);
@@ -2162,7 +2449,7 @@ void indent(Text *text)
if(len>0) memcpy(tmp+text->curc+1, text->curl->line+text->curc, len);
tmp[text->curl->len+1]=0;
- make_new_line(text->curl, tmp, format);
+ make_new_line(text->curl, tmp);
text->curc++;
@@ -2243,7 +2530,7 @@ void unindent(Text *text)
void comment(Text *text)
{
int len, num;
- char *tmp, *format;
+ char *tmp;
char add = '#';
if (!text) return;
@@ -2254,7 +2541,6 @@ void comment(Text *text)
while (TRUE)
{
tmp= MEM_mallocN(text->curl->len+2, "textline_string");
- format = MEM_mallocN(text->curl->len+3, "Syntax_format");
text->curc = 0;
if(text->curc) memcpy(tmp, text->curl->line, text->curc);
@@ -2264,7 +2550,7 @@ void comment(Text *text)
if(len>0) memcpy(tmp+text->curc+1, text->curl->line+text->curc, len);
tmp[text->curl->len+1]=0;
- make_new_line(text->curl, tmp, format);
+ make_new_line(text->curl, tmp);
text->curc++;
@@ -2348,7 +2634,7 @@ int setcurr_tab (Text *text)
int test = 0;
char *word = ":";
char *comm = "#";
- char back_words[3][7] = {"return", "break", "pass"};
+ char back_words[4][7] = {"return", "break", "pass", "yield"};
if (!text) return 0;
if (!text->curl) return 0;
@@ -2365,16 +2651,25 @@ int setcurr_tab (Text *text)
if(strstr(text->curl->line, word))
{
//if we find a : then add a tab but not if it is in a comment
- if(strcspn(text->curl->line, word) < strcspn(text->curl->line, comm))
+ int a, indent = 0;
+ for(a=0; text->curl->line[a] != '\0'; a++)
{
+ if (text->curl->line[a]=='#') {
+ break;
+ } else if (text->curl->line[a]==':') {
+ indent = 1;
+ } else if (text->curl->line[a]==']') {
+ indent = 0;
+ }
+ }
+ if (indent) {
i++;
-
}
}
- while(test < 3)
+ for(test=0; test < 4; test++)
{
- //if there are these 3 key words then remove a tab because we are done with the block
+ //if there are these 4 key words then remove a tab because we are done with the block
if(strstr(text->curl->line, back_words[test]) && i > 0)
{
if(strcspn(text->curl->line, back_words[test]) < strcspn(text->curl->line, comm))
@@ -2382,8 +2677,145 @@ int setcurr_tab (Text *text)
i--;
}
}
- test++;
}
return i;
}
+/*********************************/
+/* Text marker utility functions */
+/*********************************/
+
+/* Creates and adds a marker to the list maintaining sorted order */
+void txt_add_marker(Text *text, TextLine *line, int start, int end, char color[4], int group, int flags) {
+ TextMarker *tmp, *marker;
+
+ marker= MEM_mallocN(sizeof(TextMarker), "text_marker");
+
+ marker->lineno= txt_get_span(text->lines.first, line);
+ marker->start= MIN2(start, end);
+ marker->end= MAX2(start, end);
+ marker->group= group;
+ marker->flags= flags;
+
+ marker->color[0]= color[0];
+ marker->color[1]= color[1];
+ marker->color[2]= color[2];
+ marker->color[3]= color[3];
+
+ for (tmp=text->markers.last; tmp; tmp=tmp->prev)
+ if (tmp->lineno < marker->lineno || (tmp->lineno==marker->lineno && tmp->start < marker->start))
+ break;
+
+ if (tmp) BLI_insertlinkafter(&text->markers, tmp, marker);
+ else BLI_addhead(&text->markers, marker);
+}
+
+/* Returns the first matching marker on the specified line between two points.
+ If the group or flags fields are non-zero the returned flag must be in the
+ specified group and have at least the specified flags set. */
+TextMarker *txt_find_marker_region(Text *text, TextLine *line, int start, int end, int group, int flags) {
+ TextMarker *marker, *next;
+ int lineno= txt_get_span(text->lines.first, line);
+
+ for (marker=text->markers.first; marker; marker=next) {
+ next= marker->next;
+
+ if (group && marker->group != group) continue;
+ else if ((marker->flags & flags) != flags) continue;
+ else if (marker->lineno < lineno) continue;
+ else if (marker->lineno > lineno) break;
+
+ if ((marker->start==marker->end && start<=marker->start && marker->start<=end) ||
+ (marker->start<end && marker->end>start))
+ return marker;
+ }
+ return NULL;
+}
+
+/* Clears all markers on the specified line between two points. If the group or
+ flags fields are non-zero the returned flag must be in the specified group
+ and have at least the specified flags set. */
+short txt_clear_marker_region(Text *text, TextLine *line, int start, int end, int group, int flags) {
+ TextMarker *marker, *next;
+ int lineno= txt_get_span(text->lines.first, line);
+ short cleared= 0;
+
+ for (marker=text->markers.first; marker; marker=next) {
+ next= marker->next;
+
+ if (group && marker->group != group) continue;
+ else if ((marker->flags & flags) != flags) continue;
+ else if (marker->lineno < lineno) continue;
+ else if (marker->lineno > lineno) break;
+
+ if ((marker->start==marker->end && start<=marker->start && marker->start<=end) ||
+ (marker->start<end && marker->end>start)) {
+ BLI_freelinkN(&text->markers, marker);
+ cleared= 1;
+ }
+ }
+ return cleared;
+}
+
+/* Clears all markers in the specified group (if given) with at least the
+ specified flags set. Useful for clearing temporary markers (group=0,
+ flags=TMARK_TEMP) */
+short txt_clear_markers(Text *text, int group, int flags) {
+ TextMarker *marker, *next;
+ short cleared= 0;
+
+ for (marker=text->markers.first; marker; marker=next) {
+ next= marker->next;
+
+ if ((!group || marker->group==group) &&
+ (marker->flags & flags) == flags) {
+ BLI_freelinkN(&text->markers, marker);
+ cleared= 1;
+ }
+ }
+ return cleared;
+}
+
+/* Finds the marker at the specified line and cursor position with at least the
+ specified flags set in the given group (if non-zero). */
+TextMarker *txt_find_marker(Text *text, TextLine *line, int curs, int group, int flags) {
+ TextMarker *marker;
+ int lineno= txt_get_span(text->lines.first, line);
+
+ for (marker=text->markers.first; marker; marker=marker->next) {
+ if (group && marker->group != group) continue;
+ else if ((marker->flags & flags) != flags) continue;
+ else if (marker->lineno < lineno) continue;
+ else if (marker->lineno > lineno) break;
+
+ if (marker->start <= curs && curs <= marker->end)
+ return marker;
+ }
+ return NULL;
+}
+
+/* Finds the previous marker in the same group. If no other is found, the same
+ marker will be returned */
+TextMarker *txt_prev_marker(Text *text, TextMarker *marker) {
+ TextMarker *tmp= marker;
+ while (tmp) {
+ if (tmp->prev) tmp= tmp->prev;
+ else tmp= text->markers.last;
+ if (tmp->group == marker->group)
+ return tmp;
+ }
+ return NULL; /* Only if marker==NULL */
+}
+
+/* Finds the next marker in the same group. If no other is found, the same
+ marker will be returned */
+TextMarker *txt_next_marker(Text *text, TextMarker *marker) {
+ TextMarker *tmp= marker;
+ while (tmp) {
+ if (tmp->next) tmp= tmp->next;
+ else tmp= text->markers.first;
+ if (tmp->group == marker->group)
+ return tmp;
+ }
+ return NULL; /* Only if marker==NULL */
+}
diff --git a/source/blender/blenkernel/intern/texture.c b/source/blender/blenkernel/intern/texture.c
index 859cf663e6d..372c51b0da5 100644
--- a/source/blender/blenkernel/intern/texture.c
+++ b/source/blender/blenkernel/intern/texture.c
@@ -52,6 +52,9 @@
#include "DNA_image_types.h"
#include "DNA_world_types.h"
#include "DNA_brush_types.h"
+#include "DNA_node_types.h"
+#include "DNA_color_types.h"
+#include "DNA_scene_types.h"
#include "IMB_imbuf_types.h"
#include "IMB_imbuf.h"
@@ -71,6 +74,7 @@
#include "BKE_icons.h"
#include "BKE_ipo.h"
#include "BKE_brush.h"
+#include "BKE_node.h"
/* ------------------------------------------------------------------------- */
@@ -103,6 +107,7 @@ void open_plugin_tex(PluginTex *pit)
pit->result= 0;
pit->cfra= 0;
pit->version= 0;
+ pit->instance_init= 0;
/* clear the error list */
PIL_dynlib_get_error_as_string(NULL);
@@ -122,7 +127,7 @@ void open_plugin_tex(PluginTex *pit)
if (version != 0) {
pit->version= version();
- if (pit->version>=2 && pit->version<=5) {
+ if( pit->version >= 2 && pit->version <=6) {
int (*info_func)(PluginInfo *);
PluginInfo *info= (PluginInfo*) MEM_mallocN(sizeof(PluginInfo), "plugin_info");
@@ -342,6 +347,15 @@ int do_colorband(ColorBand *coba, float in, float out[4])
else
fac= 0.0f;
+ if (coba->ipotype==4) {
+ /* constant */
+ out[0]= cbd2->r;
+ out[1]= cbd2->g;
+ out[2]= cbd2->b;
+ out[3]= cbd2->a;
+ return 1;
+ }
+
if(coba->ipotype>=2) {
/* ipo from right to left: 3 2 1 0 */
@@ -385,6 +399,17 @@ int do_colorband(ColorBand *coba, float in, float out[4])
return 1; /* OK */
}
+void colorband_table_RGBA(ColorBand *coba, float **array, int *size)
+{
+ int a;
+
+ *size = CM_TABLE+1;
+ *array = MEM_callocN(sizeof(float)*(*size)*4, "ColorBand");
+
+ for(a=0; a<*size; a++)
+ do_colorband(coba, (float)a/(float)CM_TABLE, &(*array)[a*4]);
+}
+
/* ******************* TEX ************************ */
void free_texture(Tex *tex)
@@ -540,6 +565,8 @@ Tex *copy_texture(Tex *tex)
if(texn->type==TEX_IMAGE) id_us_plus((ID *)texn->ima);
else texn->ima= 0;
+ id_us_plus((ID *)texn->ipo);
+
if(texn->plugin) {
texn->plugin= MEM_dupallocN(texn->plugin);
open_plugin_tex(texn->plugin);
@@ -724,9 +751,10 @@ Tex *give_current_texture(Object *ob, int act)
Lamp *la = 0;
MTex *mtex = 0;
Tex *tex = 0;
+ bNode *node;
if(ob==0) return 0;
- if(ob->totcol==0) return 0;
+ if(ob->totcol==0 && !(ob->type==OB_LAMP)) return 0;
if(ob->type==OB_LAMP) {
la=(Lamp *)ob->data;
@@ -734,7 +762,6 @@ Tex *give_current_texture(Object *ob, int act)
mtex= la->mtex[(int)(la->texact)];
if(mtex) tex= mtex->tex;
}
- else tex= 0;
} else {
if(act>ob->totcol) act= ob->totcol;
else if(act==0) act= 1;
@@ -747,18 +774,42 @@ Tex *give_current_texture(Object *ob, int act)
if(matarar && *matarar) ma= (*matarar)[act-1];
else ma= 0;
-
+ }
+
+ if(ma && ma->use_nodes && ma->nodetree) {
+ node= nodeGetActiveID(ma->nodetree, ID_TE);
+
+ if(node) {
+ tex= (Tex *)node->id;
+ ma= NULL;
+ }
+ else {
+ node= nodeGetActiveID(ma->nodetree, ID_MA);
+ if(node)
+ ma= (Material*)node->id;
+ }
}
if(ma) {
mtex= ma->mtex[(int)(ma->texact)];
if(mtex) tex= mtex->tex;
}
- else tex= 0;
}
return tex;
}
+Tex *give_current_world_texture(void)
+{
+ MTex *mtex = 0;
+ Tex *tex = 0;
+
+ if(!(G.scene->world)) return 0;
+
+ mtex= G.scene->world->mtex[(int)(G.scene->world->texact)];
+ if(mtex) tex= mtex->tex;
+
+ return tex;
+}
/* ------------------------------------------------------------------------- */
@@ -816,3 +867,19 @@ void BKE_free_envmap(EnvMap *env)
}
/* ------------------------------------------------------------------------- */
+int BKE_texture_dependsOnTime(const struct Tex *texture)
+{
+ if(texture->plugin) {
+ // assume all plugins depend on time
+ return 1;
+ } else if( texture->ima &&
+ ELEM(texture->ima->source, IMA_SRC_SEQUENCE, IMA_SRC_MOVIE)) {
+ return 1;
+ } else if(texture->ipo) {
+ // assume any ipo means the texture is animated
+ return 1;
+ }
+ return 0;
+}
+
+/* ------------------------------------------------------------------------- */
diff --git a/source/blender/blenkernel/intern/world.c b/source/blender/blenkernel/intern/world.c
index 44c35252359..bef372e39f1 100644
--- a/source/blender/blenkernel/intern/world.c
+++ b/source/blender/blenkernel/intern/world.c
@@ -53,7 +53,9 @@
#include "BKE_main.h"
#include "BKE_icons.h"
+#ifndef DISABLE_PYTHON
#include "BPY_extern.h"
+#endif
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -63,9 +65,10 @@ void free_world(World *wrld)
{
MTex *mtex;
int a;
-
+
+#ifndef DISABLE_PYTHON
BPY_free_scriptlink(&wrld->scriptlink);
-
+#endif
for(a=0; a<MAX_MTEX; a++) {
mtex= wrld->mtex[a];
if(mtex && mtex->tex) mtex->tex->id.us--;
@@ -94,12 +97,12 @@ World *add_world(char *name)
wrld->exp= 0.0f;
wrld->exposure=wrld->range= 1.0f;
- wrld->aodist= 5.0;
+ wrld->aodist= 5.0f;
wrld->aosamp= 5;
- wrld->aoenergy= 1.0;
- wrld->aobias= 0.05;
+ wrld->aoenergy= 1.0f;
+ wrld->aobias= 0.05f;
wrld->ao_samp_method = WO_AOSAMP_HAMMERSLEY;
-
+ wrld->ao_approx_error= 0.25f;
wrld->physicsEngine= WOPHY_BULLET;//WOPHY_SUMO; Bullet by default
wrld->preview = NULL;
@@ -123,9 +126,9 @@ World *copy_world(World *wrld)
}
if (wrld->preview) wrldn->preview = BKE_previewimg_copy(wrld->preview);
-
+#ifndef DISABLE_PYTHON
BPY_copy_scriptlink(&wrld->scriptlink);
-
+#endif
id_us_plus((ID *)wrldn->ipo);
return wrldn;
diff --git a/source/blender/blenkernel/intern/writeavi.c b/source/blender/blenkernel/intern/writeavi.c
index b70bdc2c07e..e63588e6d7f 100644
--- a/source/blender/blenkernel/intern/writeavi.c
+++ b/source/blender/blenkernel/intern/writeavi.c
@@ -116,7 +116,7 @@ void makeavistring (RenderData *rd, char *string)
if (string==0) return;
strcpy(string, rd->pic);
- BLI_convertstringcode(string, G.sce, rd->cfra);
+ BLI_convertstringcode(string, G.sce);
BLI_make_existing_file(string);
diff --git a/source/blender/blenkernel/intern/writeffmpeg.c b/source/blender/blenkernel/intern/writeffmpeg.c
index e5d8d560a1b..7008f254871 100644
--- a/source/blender/blenkernel/intern/writeffmpeg.c
+++ b/source/blender/blenkernel/intern/writeffmpeg.c
@@ -33,6 +33,7 @@
#include <ffmpeg/avcodec.h>
#include <ffmpeg/rational.h>
#include <ffmpeg/swscale.h>
+#include <ffmpeg/opt.h>
#if LIBAVFORMAT_VERSION_INT < (49 << 16)
#define FFMPEG_OLD_FRAME_RATE 1
@@ -41,6 +42,12 @@
#define FFMPEG_CODEC_TIME_BASE 1
#endif
+#if LIBAVFORMAT_VERSION_INT >= (52 << 16)
+#define OUTFILE_PB (outfile->pb)
+#else
+#define OUTFILE_PB (&outfile->pb)
+#endif
+
#if defined(WIN32) && (!(defined snprintf))
#define snprintf _snprintf
#endif
@@ -51,6 +58,7 @@
#include "BLI_blenlib.h"
#include "BKE_global.h"
+#include "BKE_idprop.h"
#include "IMB_imbuf_types.h"
#include "IMB_imbuf.h"
@@ -210,6 +218,18 @@ static const char** get_file_extensions(int format)
static const char * rv[] = { ".avi", NULL };
return rv;
}
+ case FFMPEG_FLV: {
+ static const char * rv[] = { ".flv", NULL };
+ return rv;
+ }
+ case FFMPEG_MKV: {
+ static const char * rv[] = { ".mkv", NULL };
+ return rv;
+ }
+ case FFMPEG_OGG: {
+ static const char * rv[] = { ".ogg", ".ogv", NULL };
+ return rv;
+ }
default:
return NULL;
}
@@ -231,14 +251,18 @@ static void write_video_frame(AVFrame* frame)
AVPacket packet;
av_init_packet(&packet);
+ if (c->coded_frame->pts != AV_NOPTS_VALUE) {
#ifdef FFMPEG_CODEC_TIME_BASE
- packet.pts = av_rescale_q(c->coded_frame->pts,
- c->time_base,
- video_stream->time_base);
+ packet.pts = av_rescale_q(c->coded_frame->pts,
+ c->time_base,
+ video_stream->time_base);
#else
- packet.pts = c->coded_frame->pts;
+ packet.pts = c->coded_frame->pts;
#endif
- fprintf(stderr, "Video Frame PTS: %lld\n", packet.pts);
+ fprintf(stderr, "Video Frame PTS: %lld\n", packet.pts);
+ } else {
+ fprintf(stderr, "Video Frame PTS: not set\n");
+ }
if (c->coded_frame->key_frame)
packet.flags |= PKT_FLAG_KEY;
packet.stream_index = video_stream->index;
@@ -323,6 +347,75 @@ static AVFrame* generate_video_frame(uint8_t* pixels)
return current_frame;
}
+static void set_ffmpeg_property_option(AVCodecContext* c, IDProperty * prop)
+{
+ char name[128];
+ char * param;
+ const AVOption * rv = NULL;
+
+ fprintf(stderr, "FFMPEG expert option: %s: ", prop->name);
+
+ strncpy(name, prop->name, 128);
+
+ param = strchr(name, ':');
+
+ if (param) {
+ *param++ = 0;
+ }
+
+ switch(prop->type) {
+ case IDP_STRING:
+ fprintf(stderr, "%s.\n", IDP_String(prop));
+ rv = av_set_string(c, prop->name, IDP_String(prop));
+ break;
+ case IDP_FLOAT:
+ fprintf(stderr, "%g.\n", IDP_Float(prop));
+ rv = av_set_double(c, prop->name, IDP_Float(prop));
+ break;
+ case IDP_INT:
+ fprintf(stderr, "%d.\n", IDP_Int(prop));
+
+ if (param) {
+ if (IDP_Int(prop)) {
+ rv = av_set_string(c, name, param);
+ } else {
+ return;
+ }
+ } else {
+ rv = av_set_int(c, prop->name, IDP_Int(prop));
+ }
+ break;
+ }
+
+ if (!rv) {
+ fprintf(stderr, "ffmpeg-option not supported: %s! Skipping.\n",
+ prop->name);
+ }
+}
+
+static void set_ffmpeg_properties(AVCodecContext* c, const char * prop_name)
+{
+ IDProperty * prop;
+ void * iter;
+ IDProperty * curr;
+
+ if (!G.scene->r.ffcodecdata.properties) {
+ return;
+ }
+
+ prop = IDP_GetPropertyFromGroup(
+ G.scene->r.ffcodecdata.properties, (char*) prop_name);
+ if (!prop) {
+ return;
+ }
+
+ iter = IDP_GetGroupIterator(prop);
+
+ while ((curr = IDP_GroupIterNext(iter)) != NULL) {
+ set_ffmpeg_property_option(c, curr);
+ }
+}
+
/* prepare a video stream for the output file */
static AVStream* alloc_video_stream(int codec_id, AVFormatContext* of,
@@ -409,13 +502,18 @@ static AVStream* alloc_video_stream(int codec_id, AVFormatContext* of,
}
/* Determine whether we are encoding interlaced material or not */
- if (G.scene->r.mode & (1 << 6)) {
+ if (G.scene->r.mode & R_FIELDS) {
fprintf(stderr, "Encoding interlaced video\n");
c->flags |= CODEC_FLAG_INTERLACED_DCT;
c->flags |= CODEC_FLAG_INTERLACED_ME;
- }
- c->sample_aspect_ratio.num = G.scene->r.xasp;
- c->sample_aspect_ratio.den = G.scene->r.yasp;
+ }
+
+ /* xasp & yasp got float lately... */
+
+ c->sample_aspect_ratio = av_d2q(
+ ((double) G.scene->r.xasp / (double) G.scene->r.yasp), 255);
+
+ set_ffmpeg_properties(c, "video");
if (avcodec_open(c, codec) < 0) {
//
@@ -461,6 +559,9 @@ static AVStream* alloc_audio_stream(int codec_id, AVFormatContext* of)
//XXX error("Couldn't find a valid audio codec");
return NULL;
}
+
+ set_ffmpeg_properties(c, "audio");
+
if (avcodec_open(c, codec) < 0) {
//XXX error("Couldn't initialize audio codec");
return NULL;
@@ -573,6 +674,8 @@ void start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty)
switch(ffmpeg_type) {
case FFMPEG_AVI:
case FFMPEG_MOV:
+ case FFMPEG_OGG:
+ case FFMPEG_MKV:
fmt->video_codec = ffmpeg_codec;
break;
case FFMPEG_DV:
@@ -590,6 +693,9 @@ void start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty)
case FFMPEG_XVID:
fmt->video_codec = CODEC_ID_XVID;
break;
+ case FFMPEG_FLV:
+ fmt->video_codec = CODEC_ID_FLV1;
+ break;
case FFMPEG_MPEG4:
default:
fmt->video_codec = CODEC_ID_MPEG4;
@@ -615,6 +721,9 @@ void start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty)
return;
}
}
+
+ fmt->audio_codec = ffmpeg_audio_codec;
+
if (ffmpeg_type == FFMPEG_DV) {
fmt->audio_codec = CODEC_ID_PCM_S16LE;
if (ffmpeg_multiplex_audio
@@ -684,7 +793,8 @@ void makeffmpegstring(char* string) {
if (!string || !exts) return;
strcpy(string, G.scene->r.pic);
- BLI_convertstringcode(string, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(string, G.sce);
+ BLI_convertstringframe(string, G.scene->r.cfra);
BLI_make_existing_file(string);
@@ -756,7 +866,7 @@ void append_ffmpeg(int frame, int *pixels, int rectx, int recty)
write_video_frame(generate_video_frame((unsigned char*) pixels));
if (ffmpeg_autosplit) {
- if (url_ftell(&outfile->pb) > FFMPEG_AUTOSPLIT_SIZE) {
+ if (url_ftell(OUTFILE_PB) > FFMPEG_AUTOSPLIT_SIZE) {
end_ffmpeg();
ffmpeg_autosplit_count++;
start_ffmpeg_impl(ffmpeg_renderdata,
@@ -772,7 +882,7 @@ void end_ffmpeg(void)
fprintf(stderr, "Closing ffmpeg...\n");
- if (audio_stream) {
+ if (audio_stream && video_stream) {
write_audio_frames();
}
@@ -803,7 +913,7 @@ void end_ffmpeg(void)
}
if (outfile && outfile->oformat) {
if (!(outfile->oformat->flags & AVFMT_NOFILE)) {
- url_fclose(&outfile->pb);
+ url_fclose(OUTFILE_PB);
}
}
if (outfile) {
diff --git a/source/blender/blenkernel/intern/writeframeserver.c b/source/blender/blenkernel/intern/writeframeserver.c
index c48bea70dc9..64bf5f85d23 100644
--- a/source/blender/blenkernel/intern/writeframeserver.c
+++ b/source/blender/blenkernel/intern/writeframeserver.c
@@ -249,7 +249,7 @@ static int handle_request(char * req)
return -1;
}
-int frameserver_loop()
+int frameserver_loop(void)
{
fd_set readfds;
struct timeval tv;
diff --git a/source/blender/blenlib/BLI_arithb.h b/source/blender/blenlib/BLI_arithb.h
index 6697a7b2ba5..186681fad7d 100644
--- a/source/blender/blenlib/BLI_arithb.h
+++ b/source/blender/blenlib/BLI_arithb.h
@@ -50,10 +50,14 @@ extern "C" {
#ifndef M_SQRT1_2
#define M_SQRT1_2 0.70710678118654752440
#endif
+#ifndef M_1_PI
+#define M_1_PI 0.318309886183790671538
+#endif
#ifdef WIN32
#ifndef FREE_WINDOWS
#define isnan(n) _isnan(n)
+ #define finite _finite
#endif
#endif
@@ -87,6 +91,7 @@ float saasin(float fac);
float sasqrt(float fac);
int FloatCompare(float *v1, float *v2, float limit);
+int FloatCompare4(float *v1, float *v2, float limit);
float FloatLerpf(float target, float origin, float fac);
float CalcNormFloat(float *v1, float *v2, float *v3, float *n);
@@ -95,7 +100,7 @@ float CalcNormFloat4(float *v1, float *v2, float *v3, float *v4, float *n);
void CalcNormLong(int *v1, int *v2, int *v3, float *n);
/* CalcNormShort: is ook uitprodukt - (translates as 'is also out/cross product') */
void CalcNormShort(short *v1, short *v2, short *v3, float *n);
-
+float power_of_2(float val);
/**
* @section Euler conversion routines
@@ -160,6 +165,7 @@ void Mat3Inv(float m1[][3], float m2[][3]);
void Mat3CpyMat4(float m1[][3],float m2[][4]);
void Mat4CpyMat3(float m1[][4], float m2[][3]);
+void Mat3BlendMat3(float out[][3], float dst[][3], float src[][3], float srcweight);
void Mat4BlendMat4(float out[][4], float dst[][4], float src[][4], float srcweight);
float Det2x2(float a,float b,float c, float d);
@@ -239,6 +245,7 @@ void VecMulf(float *v1, float f);
int VecLenCompare(float *v1, float *v2, float limit);
int VecCompare(float *v1, float *v2, float limit);
int VecEqual(float *v1, float *v2);
+int VecIsNull(float *v);
void printvecf(char *str,float v[3]);
void printvec4f(char *str, float v[4]);
@@ -256,15 +263,23 @@ void Vec2Mulf(float *v1, float f);
void Vec2Addf(float *v, float *v1, float *v2);
void Vec2Subf(float *v, float *v1, float *v2);
void Vec2Copyf(float *v1, float *v2);
+void Vec2Lerpf(float *target, float *a, float *b, float t);
-float *vectoquat(float *vec, short axis, short upflag);
+void AxisAngleToQuat(float *q, float *axis, float angle);
+void RotationBetweenVectorsToQuat(float *q, float v1[3], float v2[3]);
+void vectoquat(float *vec, short axis, short upflag, float *q);
float VecAngle2(float *v1, float *v2);
float VecAngle3(float *v1, float *v2, float *v3);
float NormalizedVecAngle2(float *v1, float *v2);
+float VecAngle3_2D(float *v1, float *v2, float *v3);
+float NormalizedVecAngle2_2D(float *v1, float *v2);
+
void euler_rot(float *beul, float ang, char axis);
+void NormalShortToFloat(float *out, short *in);
+void NormalFloatToShort(short *out, float *in);
float DistVL2Dfl(float *v1, float *v2, float *v3);
float PdistVL2Dfl(float *v1, float *v2, float *v3);
@@ -309,6 +324,10 @@ void i_window(
float mat[][4]
);
+#define BLI_CS_SMPTE 0
+#define BLI_CS_REC709 1
+#define BLI_CS_CIE 2
+
void hsv_to_rgb(float h, float s, float v, float *r, float *g, float *b);
void hex_to_rgb(char *hexcol, float *r, float *g, float *b);
void rgb_to_yuv(float r, float g, float b, float *ly, float *lu, float *lv);
@@ -316,6 +335,9 @@ void yuv_to_rgb(float y, float u, float v, float *lr, float *lg, float *lb);
void ycc_to_rgb(float y, float cb, float cr, float *lr, float *lg, float *lb);
void rgb_to_ycc(float r, float g, float b, float *ly, float *lcb, float *lcr);
void rgb_to_hsv(float r, float g, float b, float *lh, float *ls, float *lv);
+void xyz_to_rgb(float x, float y, float z, float *r, float *g, float *b, int colorspace);
+int constrain_rgb(float *r, float *g, float *b);
+void gamma_correct_rgb(float *r, float *g, float *b);
unsigned int hsv_to_cpack(float h, float s, float v);
unsigned int rgb_to_cpack(float r, float g, float b);
void cpack_to_rgb(unsigned int col, float *r, float *g, float *b);
@@ -367,7 +389,9 @@ void LocQuatSizeToMat4(float mat[][4], float loc[3], float quat[4], float size[3
void tubemap(float x, float y, float z, float *u, float *v);
void spheremap(float x, float y, float z, float *u, float *v);
+int LineIntersectLine(float v1[3], float v2[3], float v3[3], float v4[3], float i1[3], float i2[3]);
int LineIntersectsTriangle(float p1[3], float p2[3], float v0[3], float v1[3], float v2[3], float *lambda, float *uv);
+int RayIntersectsTriangle(float p1[3], float d[3], float v0[3], float v1[3], float v2[3], float *lambda, float *uv);
int SweepingSphereIntersectsTriangleUV(float p1[3], float p2[3], float radius, float v0[3], float v1[3], float v2[3], float *lambda, float *ipoint);
int AxialLineIntersectsTriangle(int axis, float co1[3], float co2[3], float v0[3], float v1[3], float v2[3], float *lambda);
int AabbIntersectAabb(float min1[3], float max1[3], float min2[3], float max2[3]);
@@ -395,6 +419,16 @@ void DQuatNormalize(DualQuat *dq, float totweight);
void DQuatMulVecfl(DualQuat *dq, float *co, float mat[][3]);
void DQuatCpyDQuat(DualQuat *dq1, DualQuat *dq2);
+/* Tangent stuff */
+typedef struct VertexTangent {
+ float tang[3], uv[2];
+ struct VertexTangent *next;
+} VertexTangent;
+
+void sum_or_add_vertex_tangent(void *arena, VertexTangent **vtang, float *tang, float *uv);
+float *find_vertex_tangent(VertexTangent *vtang, float *uv);
+void tangent_from_uv(float *uv1, float *uv2, float *uv3, float *co1, float *co2, float *co3, float *n, float *tang);
+
#ifdef __cplusplus
}
#endif
diff --git a/source/blender/blenlib/BLI_blenlib.h b/source/blender/blenlib/BLI_blenlib.h
index efeab705913..f65aaa72a75 100644
--- a/source/blender/blenlib/BLI_blenlib.h
+++ b/source/blender/blenlib/BLI_blenlib.h
@@ -67,14 +67,14 @@
#include "DNA_listBase.h"
#include <stdlib.h>
-
extern ListBase fillfacebase;
extern ListBase fillvertbase;
/**
* @attention Defined in scanfill.c
*/
extern ListBase filledgebase;
-extern int totblock;
+
+extern char btempdir[]; /* creator.c temp dir used instead of U.tempdir, set with BLI_where_is_temp( btempdir, 1 ); */
struct chardesc;
struct direntry;
@@ -94,7 +94,8 @@ char *BLI_gethome(void);
void BLI_make_file_string(const char *relabase, char *string, const char *dir, const char *file);
void BLI_make_exist(char *dir);
void BLI_make_existing_file(char *name);
-void BLI_split_dirfile(const char *string, char *dir, char *file);
+void BLI_split_dirfile(char *string, char *dir, char *file);
+void BLI_split_dirfile_basic(const char *string, char *dir, char *file);
void BLI_join_dirfile(char *string, const char *dir, const char *file);
int BLI_testextensie(const char *str, const char *ext);
void addlisttolist(ListBase *list1, ListBase *list2);
@@ -104,6 +105,7 @@ int BLI_findindex(struct ListBase *listbase, void *vlink);
void BLI_freelistN(struct ListBase *listbase);
void BLI_addtail(struct ListBase *listbase, void *vlink);
void BLI_remlink(struct ListBase *listbase, void *vlink);
+void BLI_uniquename(struct ListBase *list, void *vlink, char defname[], short name_offs, short len);
void BLI_newname(char * name, int add);
int BLI_stringdec(char *string, char *kop, char *start, unsigned short *numlen);
void BLI_stringenc(char *string, char *kop, char *start, unsigned short numlen, int pic);
@@ -135,7 +137,11 @@ void BLI_dlist_reinit(struct DynamicList *dlist);
* converts it to a regular full path.
* Also removes garbage from directory paths, like /../ or double slashes etc
*/
-void BLI_cleanup_dir(const char *relabase, char *dir);
+void BLI_cleanup_file(const char *relabase, char *dir);
+void BLI_cleanup_dir(const char *relabase, char *dir); /* same as above but adds a trailing slash */
+
+/* go back one directory */
+int BLI_parent_dir(char *path);
/**
* Blender's path code replacement function.
@@ -149,7 +155,9 @@ void BLI_cleanup_dir(const char *relabase, char *dir);
* @a framenum The framenumber to replace the frame code with.
* @retval Returns true if the path was relative (started with "//").
*/
-int BLI_convertstringcode(char *path, const char *basepath, int framenum);
+int BLI_convertstringcode(char *path, const char *basepath);
+int BLI_convertstringframe(char *path, int frame);
+int BLI_convertstringcwd(char *path);
void BLI_makestringcode(const char *relfile, char *file);
@@ -222,7 +230,7 @@ int BLI_strcaseeq(char *a, char *b);
/* in util.c */
#ifdef WITH_ICONV
-void BLI_string_to_utf8(char *original, char *utf_8, char *code);
+void BLI_string_to_utf8(char *original, char *utf_8, const char *code);
#endif
/**
@@ -253,7 +261,19 @@ void BLI_free_file_lines(struct LinkNode *lines);
* @param fullname The full path and full name of the executable
* @param name The name of the executable (usually argv[0]) to be checked
*/
-void BLI_where_am_i(char *fullname, char *name);
+void BLI_where_am_i(char *fullname, const char *name);
+
+char *get_install_dir(void);
+ /**
+ * Gets the temp directory when blender first runs.
+ * If the default path is not found, use try $TEMP
+ *
+ * Also make sure the temp dir has a trailing slash
+ *
+ * @param fullname The full path to the temp directory
+ */
+void BLI_where_is_temp(char *fullname, int usertemp);
+
/**
* determines the full path to the application bundle on OS X
@@ -270,6 +290,7 @@ int BLI_getInstallationDir(char *str);
/* BLI_storage.h */
int BLI_filesize(int file);
+int BLI_filepathsize(const char *path);
double BLI_diskfree(char *dir);
char *BLI_getwdN(char *dir);
void BLI_hide_dot_files(int set);
@@ -283,7 +304,6 @@ int BLI_exist(char *name);
/* BLI_fileops.h */
void BLI_recurdir_fileops(char *dirname);
int BLI_link(char *file, char *to);
-int BLI_backup(char *file, char *from, char *to);
int BLI_is_writable(char *filename);
/**
@@ -295,8 +315,10 @@ int BLI_rename(char *from, char *to);
int BLI_gzip(char *from, char *to);
int BLI_delete(char *file, int dir, int recursive);
int BLI_move(char *file, char *to);
-int BLI_touch(char *file);
-char *BLI_last_slash(char *string);
+int BLI_touch(const char *file);
+char *BLI_last_slash(const char *string);
+void BLI_add_slash(char *string);
+void BLI_del_slash(char *string);
/* BLI_rct.c */
/**
@@ -397,7 +419,7 @@ void *BLI_pointer_from_int(int val);
* @param member The name of a member field of @a strct
* @retval The offset in bytes of @a member within @a strct
*/
-#define BLI_STRUCT_OFFSET(strct, member) ((int) &((strct*) 0)->member)
+#define BLI_STRUCT_OFFSET(strct, member) ((int)(intptr_t) &((strct*) 0)->member)
#ifdef __cplusplus
}
diff --git a/source/blender/blenlib/BLI_bpath.h b/source/blender/blenlib/BLI_bpath.h
index 9426064f59f..874c8c7828c 100644
--- a/source/blender/blenlib/BLI_bpath.h
+++ b/source/blender/blenlib/BLI_bpath.h
@@ -29,6 +29,13 @@
/* Based on ghash, difference is ghash is not a fixed size,
* so for BPath we dont need to malloc */
+struct BPathIteratorSeqData {
+ int totseq;
+ int seq;
+ struct Sequence **seqar; /* Sequence */
+ struct Scene *scene; /* Current scene */
+};
+
struct BPathIterator {
char* path;
char* lib;
@@ -36,21 +43,30 @@ struct BPathIterator {
void* data;
int len;
int type;
+
+ void (*setpath_callback)(struct BPathIterator *, char *);
+ void (*getpath_callback)(struct BPathIterator *, char *);
+
+ /* only for seq data */
+ struct BPathIteratorSeqData seqdata;
};
-void BLI_bpathIterator_init (struct BPathIterator *bpi);
-char* BLI_bpathIterator_getPath (struct BPathIterator *bpi);
-char* BLI_bpathIterator_getLib (struct BPathIterator *bpi);
-char* BLI_bpathIterator_getName (struct BPathIterator *bpi);
-int BLI_bpathIterator_getType (struct BPathIterator *bpi);
-int BLI_bpathIterator_getPathMaxLen(struct BPathIterator *bpi);
-void BLI_bpathIterator_step (struct BPathIterator *bpi);
-int BLI_bpathIterator_isDone (struct BPathIterator *bpi);
-void BLI_bpathIterator_copyPathExpanded( struct BPathIterator *bpi, char *path_expanded);
+void BLI_bpathIterator_init (struct BPathIterator *bpi);
+void BLI_bpathIterator_free (struct BPathIterator *bpi);
+char* BLI_bpathIterator_getLib (struct BPathIterator *bpi);
+char* BLI_bpathIterator_getName (struct BPathIterator *bpi);
+int BLI_bpathIterator_getType (struct BPathIterator *bpi);
+int BLI_bpathIterator_getPathMaxLen (struct BPathIterator *bpi);
+void BLI_bpathIterator_step (struct BPathIterator *bpi);
+int BLI_bpathIterator_isDone (struct BPathIterator *bpi);
+void BLI_bpathIterator_getPath (struct BPathIterator *bpi, char *path);
+void BLI_bpathIterator_getPathExpanded (struct BPathIterator *bpi, char *path_expanded);
+void BLI_bpathIterator_setPath (struct BPathIterator *bpi, char *path);
/* high level funcs */
/* creates a text file with missing files if there are any */
-struct Text * checkMissingFiles(void);
-void makeFilesRelative(int *tot, int *changed, int *failed, int *linked);
+void checkMissingFiles(char *txtname );
+void makeFilesRelative(char *txtname, int *tot, int *changed, int *failed, int *linked);
+void makeFilesAbsolute(char *txtname, int *tot, int *changed, int *failed, int *linked);
void findMissingFiles(char *str);
diff --git a/source/blender/blenlib/BLI_edgehash.h b/source/blender/blenlib/BLI_edgehash.h
index f3aa69d77ff..abbd17c3635 100644
--- a/source/blender/blenlib/BLI_edgehash.h
+++ b/source/blender/blenlib/BLI_edgehash.h
@@ -86,6 +86,9 @@ void BLI_edgehashIterator_getKey (EdgeHashIterator *ehi, int *v0_r, int *v1
/* Retrieve the value from an iterator. */
void* BLI_edgehashIterator_getValue (EdgeHashIterator *ehi);
+ /* Set the value for an iterator. */
+void BLI_edgehashIterator_setValue (EdgeHashIterator *ehi, void *val);
+
/* Steps the iterator to the next index. */
void BLI_edgehashIterator_step (EdgeHashIterator *ehi);
diff --git a/source/blender/blenlib/BLI_editVert.h b/source/blender/blenlib/BLI_editVert.h
index ae7697c7c7e..447f6a2a485 100644
--- a/source/blender/blenlib/BLI_editVert.h
+++ b/source/blender/blenlib/BLI_editVert.h
@@ -38,6 +38,8 @@
#include "DNA_customdata_types.h"
#include "DNA_mesh_types.h"
+#include "BLO_sys_types.h" // for intptr_t support
+
struct DerivedMesh;
struct RetopoPaintData;
@@ -53,7 +55,7 @@ typedef struct EditVert
struct EditEdge *e;
struct EditFace *f;
void *p;
- long l;
+ intptr_t l;
float fp;
} tmp;
float no[3]; /*vertex normal */
@@ -64,6 +66,7 @@ typedef struct EditVert
h for hidden. if (!eve->h) {...
f1 and f2 can be used for temp data, clear them first*/
unsigned char f, h, f1, f2;
+ float bweight;
short fast; /* only 0 or 1, for editmesh_fastmalloc, do not store temp data here! */
int hash;
int keyindex; /* original index #, for restoring key information */
@@ -94,12 +97,13 @@ typedef struct EditEdge
struct EditEdge *e;
struct EditFace *f;
void *p;
- long l;
+ intptr_t l;
float fp;
} tmp;
short f1, f2; /* short, f1 is (ab)used in subdiv */
unsigned char f, h, dir, seam, sharp;
float crease;
+ float bweight;
short fast; /* only 0 or 1, for editmesh_fastmalloc */
short fgoni; /* index for fgon, for search */
HashEdge hash;
@@ -120,7 +124,7 @@ typedef struct EditFace
struct EditEdge *e;
struct EditFace *f;
void *p;
- long l;
+ intptr_t l;
float fp;
} tmp;
float n[3], cent[3];
diff --git a/source/blender/blenlib/BLI_ghash.h b/source/blender/blenlib/BLI_ghash.h
index aec77f5f385..c77e82f0a2b 100644
--- a/source/blender/blenlib/BLI_ghash.h
+++ b/source/blender/blenlib/BLI_ghash.h
@@ -34,7 +34,12 @@
struct GHash;
typedef struct GHash GHash;
-typedef struct GHashIterator GHashIterator;
+
+typedef struct GHashIterator {
+ GHash *gh;
+ int curBucket;
+ struct Entry *curEntry;
+} GHashIterator;
typedef unsigned int (*GHashHashFP) (void *key);
typedef int (*GHashCmpFP) (void *a, void *b);
@@ -63,6 +68,15 @@ int BLI_ghash_size (GHash *gh);
*/
GHashIterator* BLI_ghashIterator_new (GHash *gh);
/**
+ * Init an already allocated GHashIterator. The hash table must not
+ * be mutated while the iterator is in use, and the iterator will
+ * step exactly BLI_ghash_size(gh) times before becoming done.
+ *
+ * @param ghi The GHashIterator to initialize.
+ * @param gh The GHash to iterate over.
+ */
+void BLI_ghashIterator_init(GHashIterator *ghi, GHash *gh);
+ /**
* Free a GHashIterator.
*
* @param ghi The iterator to free.
diff --git a/source/blender/blenlib/BLI_graph.h b/source/blender/blenlib/BLI_graph.h
new file mode 100644
index 00000000000..160c2e04cf5
--- /dev/null
+++ b/source/blender/blenlib/BLI_graph.h
@@ -0,0 +1,125 @@
+#ifndef BLI_GRAPH_H_
+#define BLI_GRAPH_H_
+
+#include "DNA_listBase.h"
+
+struct BGraph;
+struct BNode;
+struct BArc;
+
+struct RadialArc;
+
+typedef void (*FreeArc)(struct BArc*);
+typedef void (*FreeNode)(struct BNode*);
+typedef void (*RadialSymmetry)(struct BNode* root_node, struct RadialArc* ring, int total);
+typedef void (*AxialSymmetry)(struct BNode* root_node, struct BNode* node1, struct BNode* node2, struct BArc* arc1, struct BArc* arc2);
+
+/* IF YOU MODIFY THOSE TYPES, YOU NEED TO UPDATE ALL THOSE THAT "INHERIT" FROM THEM
+ *
+ * RigGraph, ReebGraph
+ *
+ * */
+
+typedef struct BGraph {
+ ListBase arcs;
+ ListBase nodes;
+
+ float length;
+
+ /* function pointer to deal with custom fonctionnality */
+ FreeArc free_arc;
+ FreeNode free_node;
+ RadialSymmetry radial_symmetry;
+ AxialSymmetry axial_symmetry;
+} BGraph;
+
+typedef struct BNode {
+ void *next, *prev;
+ float p[3];
+ int flag;
+
+ int degree;
+ struct BArc **arcs;
+
+ int subgraph_index;
+
+ int symmetry_level;
+ int symmetry_flag;
+ float symmetry_axis[3];
+} BNode;
+
+typedef struct BArc {
+ void *next, *prev;
+ struct BNode *head, *tail;
+ int flag;
+
+ float length;
+
+ int symmetry_level;
+ int symmetry_group;
+ int symmetry_flag;
+} BArc;
+
+/* Helper structure for radial symmetry */
+typedef struct RadialArc
+{
+ struct BArc *arc;
+ float n[3]; /* normalized vector joining the nodes of the arc */
+} RadialArc;
+
+BNode *BLI_otherNode(BArc *arc, BNode *node);
+
+void BLI_freeNode(BGraph *graph, BNode *node);
+void BLI_removeNode(BGraph *graph, BNode *node);
+
+void BLI_removeArc(BGraph *graph, BArc *arc);
+
+void BLI_flagNodes(BGraph *graph, int flag);
+void BLI_flagArcs(BGraph *graph, int flag);
+
+int BLI_hasAdjacencyList(BGraph *rg);
+void BLI_buildAdjacencyList(BGraph *rg);
+void BLI_rebuildAdjacencyList(BGraph* rg);
+void BLI_rebuildAdjacencyListForNode(BGraph* rg, BNode *node);
+void BLI_freeAdjacencyList(BGraph *rg);
+
+int BLI_FlagSubgraphs(BGraph *graph);
+void BLI_ReflagSubgraph(BGraph *graph, int old_subgraph, int new_subgraph);
+
+#define SHAPE_RADIX 10 /* each shape level is encoded this base */
+
+int BLI_subtreeShape(BGraph *graph, BNode *node, BArc *rootArc, int include_root);
+float BLI_subtreeLength(BNode *node);
+void BLI_calcGraphLength(BGraph *graph);
+
+void BLI_replaceNode(BGraph *graph, BNode *node_src, BNode *node_replaced);
+void BLI_replaceNodeInArc(BGraph *graph, BArc *arc, BNode *node_src, BNode *node_replaced);
+void BLI_removeDoubleNodes(BGraph *graph, float limit);
+BNode * BLI_FindNodeByPosition(BGraph *graph, float *p, float limit);
+
+BArc * BLI_findConnectedArc(BGraph *graph, BArc *arc, BNode *v);
+
+int BLI_isGraphCyclic(BGraph *graph);
+
+/*------------ Symmetry handling ------------*/
+void BLI_markdownSymmetry(BGraph *graph, BNode *root_node, float limit);
+
+void BLI_mirrorAlongAxis(float v[3], float center[3], float axis[3]);
+
+/* BNode symmetry flags */
+#define SYM_TOPOLOGICAL 1
+#define SYM_PHYSICAL 2
+
+/* the following two are exclusive */
+#define SYM_AXIAL 4
+#define SYM_RADIAL 8
+
+/* BArc symmetry flags
+ *
+ * axial symetry sides */
+#define SYM_SIDE_POSITIVE 1
+#define SYM_SIDE_NEGATIVE 2
+/* Anything higher is the order in radial symmetry */
+#define SYM_SIDE_RADIAL 3
+
+#endif /*BLI_GRAPH_H_*/
diff --git a/source/blender/blenlib/BLI_kdopbvh.h b/source/blender/blenlib/BLI_kdopbvh.h
new file mode 100644
index 00000000000..e3591a84e98
--- /dev/null
+++ b/source/blender/blenlib/BLI_kdopbvh.h
@@ -0,0 +1,97 @@
+/**
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2006 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Daniel Genrich, Andre Pinto
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+
+#ifndef BLI_KDOPBVH_H
+#define BLI_KDOPBVH_H
+
+#include <float.h>
+
+struct BVHTree;
+typedef struct BVHTree BVHTree;
+
+typedef struct BVHTreeOverlap {
+ int indexA;
+ int indexB;
+} BVHTreeOverlap;
+
+typedef struct BVHTreeNearest
+{
+ int index; /* the index of the nearest found (untouched if none is found within a dist radius from the given coordinates) */
+ float co[3]; /* nearest coordinates (untouched it none is found within a dist radius from the given coordinates) */
+ float no[3]; /* normal at nearest coordinates (untouched it none is found within a dist radius from the given coordinates) */
+ float dist; /* squared distance to search arround */
+} BVHTreeNearest;
+
+typedef struct BVHTreeRay
+{
+ float origin[3]; /* ray origin */
+ float direction[3]; /* ray direction */
+ float radius; /* radius around ray */
+} BVHTreeRay;
+
+typedef struct BVHTreeRayHit
+{
+ int index; /* index of the tree node (untouched if no hit is found) */
+ float co[3]; /* coordinates of the hit point */
+ float no[3]; /* normal on hit point */
+ float dist; /* distance to the hit point */
+} BVHTreeRayHit;
+
+/* callback must update nearest in case it finds a nearest result */
+typedef void (*BVHTree_NearestPointCallback) (void *userdata, int index, const float *co, BVHTreeNearest *nearest);
+
+/* callback must update hit in case it finds a nearest successful hit */
+typedef void (*BVHTree_RayCastCallback) (void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit);
+
+
+BVHTree *BLI_bvhtree_new(int maxsize, float epsilon, char tree_type, char axis);
+void BLI_bvhtree_free(BVHTree *tree);
+
+/* construct: first insert points, then call balance */
+int BLI_bvhtree_insert(BVHTree *tree, int index, float *co, int numpoints);
+void BLI_bvhtree_balance(BVHTree *tree);
+
+/* update: first update points/nodes, then call update_tree to refit the bounding volumes */
+int BLI_bvhtree_update_node(BVHTree *tree, int index, float *co, float *co_moving, int numpoints);
+void BLI_bvhtree_update_tree(BVHTree *tree);
+
+/* collision/overlap: check two trees if they overlap, alloc's *overlap with length of the int return value */
+BVHTreeOverlap *BLI_bvhtree_overlap(BVHTree *tree1, BVHTree *tree2, int *result);
+
+float BLI_bvhtree_getepsilon(BVHTree *tree);
+
+/* find nearest node to the given coordinates (if nearest is given it will only search nodes where square distance is smaller than nearest->dist) */
+int BLI_bvhtree_find_nearest(BVHTree *tree, const float *co, BVHTreeNearest *nearest, BVHTree_NearestPointCallback callback, void *userdata);
+
+int BLI_bvhtree_ray_cast(BVHTree *tree, const float *co, const float *dir, float radius, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata);
+
+#endif // BLI_KDOPBVH_H
+
diff --git a/source/blender/blenlib/BLI_mempool.h b/source/blender/blenlib/BLI_mempool.h
new file mode 100644
index 00000000000..8b31459dd38
--- /dev/null
+++ b/source/blender/blenlib/BLI_mempool.h
@@ -0,0 +1,44 @@
+/**
+ * Simple fast memory allocator
+ *
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2008 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Geoffrey Bantle.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef BLI_MEMPOOL_H
+#define BLI_MEMPOOL_H
+
+struct BLI_mempool;
+typedef struct BLI_mempool BLI_mempool;
+
+BLI_mempool *BLI_mempool_create(int esize, int tote, int pchunk);
+void *BLI_mempool_alloc(BLI_mempool *pool);
+void *BLI_mempool_calloc(BLI_mempool *pool);
+void BLI_mempool_free(BLI_mempool *pool, void *addr);
+void BLI_mempool_destroy(BLI_mempool *pool);
+
+
+#endif
diff --git a/source/blender/blenlib/BLI_rand.h b/source/blender/blenlib/BLI_rand.h
index 0e534783c17..266aa347aff 100644
--- a/source/blender/blenlib/BLI_rand.h
+++ b/source/blender/blenlib/BLI_rand.h
@@ -44,6 +44,7 @@ struct RNG* rng_new (unsigned int seed);
void rng_free (struct RNG* rng);
void rng_seed (struct RNG* rng, unsigned int seed);
+void rng_srandom(struct RNG *rng, unsigned int seed);
int rng_getInt (struct RNG* rng);
double rng_getDouble (struct RNG* rng);
float rng_getFloat (struct RNG* rng);
diff --git a/source/blender/blenlib/BLI_threads.h b/source/blender/blenlib/BLI_threads.h
index 60ecce3f9d8..5a7e84c42fb 100644
--- a/source/blender/blenlib/BLI_threads.h
+++ b/source/blender/blenlib/BLI_threads.h
@@ -39,16 +39,41 @@
#define BLENDER_MAX_THREADS 8
struct ListBase;
-
void BLI_init_threads (struct ListBase *threadbase, void *(*do_thread)(void *), int tot);
int BLI_available_threads(struct ListBase *threadbase);
int BLI_available_thread_index(struct ListBase *threadbase);
void BLI_insert_thread (struct ListBase *threadbase, void *callerdata);
void BLI_remove_thread (struct ListBase *threadbase, void *callerdata);
+void BLI_remove_thread_index(struct ListBase *threadbase, int index);
+void BLI_remove_threads(struct ListBase *threadbase);
void BLI_end_threads (struct ListBase *threadbase);
void BLI_lock_thread (int type);
void BLI_unlock_thread (int type);
+int BLI_system_thread_count( void ); /* gets the number of threads the system can make use of */
+
+/* ThreadedWorker is a simple tool for dispatching work to a limited number of threads in a transparent
+ * fashion from the caller's perspective
+ * */
+
+struct ThreadedWorker;
+
+/* Create a new worker supporting tot parallel threads.
+ * When new work in inserted and all threads are busy, sleep(sleep_time) before checking again
+ */
+struct ThreadedWorker *BLI_create_worker(void *(*do_thread)(void *), int tot, int sleep_time);
+
+/* join all working threads */
+void BLI_end_worker(struct ThreadedWorker *worker);
+
+/* also ends all working threads */
+void BLI_destroy_worker(struct ThreadedWorker *worker);
+
+/* Spawns a new work thread if possible, sleeps until one is available otherwise
+ * NOTE: inserting work is NOT thread safe, so make sure it is only done from one thread */
+void BLI_insert_work(struct ThreadedWorker *worker, void *param);
+
+
#endif
diff --git a/source/blender/blenlib/BLI_winstuff.h b/source/blender/blenlib/BLI_winstuff.h
index 54d70626dd5..3bb63506c95 100644
--- a/source/blender/blenlib/BLI_winstuff.h
+++ b/source/blender/blenlib/BLI_winstuff.h
@@ -61,6 +61,10 @@
// These definitions are also in arithb for simplicity
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
@@ -73,6 +77,9 @@
#ifndef M_SQRT1_2
#define M_SQRT1_2 0.70710678118654752440
#endif
+#ifndef M_1_PI
+#define M_1_PI 0.318309886183790671538
+#endif
#define MAXPATHLEN MAX_PATH
@@ -110,7 +117,12 @@ void RegisterBlendExtension(char * str);
DIR *opendir (const char *path);
struct dirent *readdir(DIR *dp);
int closedir (DIR *dp);
-void get_default_root(char* root);
+void get_default_root(char *root);
+int check_file_chars(char *filename);
+
+#ifdef __cplusplus
+}
+#endif
#endif /* __WINSTUFF_H__ */
diff --git a/source/blender/blenlib/CMakeLists.txt b/source/blender/blenlib/CMakeLists.txt
index d5e34d7d4de..4eb01a50f39 100644
--- a/source/blender/blenlib/CMakeLists.txt
+++ b/source/blender/blenlib/CMakeLists.txt
@@ -33,6 +33,13 @@ SET(INC
${ZLIB_INC}
)
+IF(CMAKE_SYSTEM_NAME MATCHES "Linux")
+SET(INC
+ ${INC}
+ ${BINRELOC_INC}
+)
+ENDIF(CMAKE_SYSTEM_NAME MATCHES "Linux")
+
IF(WITH_VERSE)
ADD_DEFINITIONS(-DWITH_VERSE)
SET(INC ${INC} ${VERSE_INC})
diff --git a/source/blender/blenlib/SConscript b/source/blender/blenlib/SConscript
index 9d81ac05472..01a9a1eab0e 100644
--- a/source/blender/blenlib/SConscript
+++ b/source/blender/blenlib/SConscript
@@ -7,20 +7,23 @@ cflags=''
incs = '. ../makesdna ../blenkernel #/intern/guardedalloc ../editors/include'
incs += ' ' + env['BF_FREETYPE_INC']
incs += ' ' + env['BF_ZLIB_INC']
-incs += ' ' + env['BF_SDL_INC']
defs = ''
-if env['WITH_BF_INTERNATIONAL'] == 1:
- defs = 'WITH_FREETYPE2'
+if env['WITH_BF_SDL']:
+ incs += ' ' + env['BF_SDL_INC']
+
+if env['WITH_BF_INTERNATIONAL']:
+ defs = 'WITH_FREETYPE2'
if env['WITH_BF_VERSE']:
defs += ' WITH_VERSE'
incs += ' ' + env['BF_VERSE_INCLUDE']
if env['OURPLATFORM'] == 'linux2':
- cflags='-pthread'
+ cflags='-pthread'
+ incs += ' ../../../extern/binreloc/include'
if env['OURPLATFORM'] in ('win32-vc', 'win32-mingw'):
- incs += ' ' + env['BF_PTHREADS_INC']
+ incs += ' ' + env['BF_PTHREADS_INC']
-env.BlenderLib ( 'bf_blenlib', sources, Split(incs), Split(defs), libtype=['core','player'], priority = [100,195], compileflags =cflags )
+env.BlenderLib ( 'bf_blenlib', sources, Split(incs), Split(defs), libtype=['core', 'intern', 'player'], priority = [85,150,195], compileflags =cflags )
diff --git a/source/blender/blenlib/intern/BLI_ghash.c b/source/blender/blenlib/intern/BLI_ghash.c
index 227cb8f5e9a..1967b8a88e2 100644
--- a/source/blender/blenlib/intern/BLI_ghash.c
+++ b/source/blender/blenlib/intern/BLI_ghash.c
@@ -34,6 +34,8 @@
#include "MEM_guardedalloc.h"
#include "BLI_ghash.h"
+#include "BLO_sys_types.h" // for intptr_t support
+
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
@@ -198,12 +200,6 @@ void BLI_ghash_free(GHash *gh, GHashKeyFreeFP keyfreefp, GHashValFreeFP valfreef
/***/
-struct GHashIterator {
- GHash *gh;
- int curBucket;
- Entry *curEntry;
-};
-
GHashIterator *BLI_ghashIterator_new(GHash *gh) {
GHashIterator *ghi= malloc(sizeof(*ghi));
ghi->gh= gh;
@@ -217,6 +213,17 @@ GHashIterator *BLI_ghashIterator_new(GHash *gh) {
}
return ghi;
}
+void BLI_ghashIterator_init(GHashIterator *ghi, GHash *gh) {
+ ghi->gh= gh;
+ ghi->curEntry= NULL;
+ ghi->curBucket= -1;
+ while (!ghi->curEntry) {
+ ghi->curBucket++;
+ if (ghi->curBucket==ghi->gh->nbuckets)
+ break;
+ ghi->curEntry= ghi->gh->buckets[ghi->curBucket];
+ }
+}
void BLI_ghashIterator_free(GHashIterator *ghi) {
free(ghi);
}
@@ -256,11 +263,7 @@ int BLI_ghashutil_ptrcmp(void *a, void *b) {
}
unsigned int BLI_ghashutil_inthash(void *ptr) {
-#if defined(_WIN64)
- unsigned __int64 key = (unsigned __int64)ptr;
-#else
- unsigned long key = (unsigned long)ptr;
-#endif
+ uintptr_t key = (uintptr_t)ptr;
key += ~(key << 16);
key ^= (key >> 5);
diff --git a/source/blender/blenlib/intern/BLI_kdopbvh.c b/source/blender/blenlib/intern/BLI_kdopbvh.c
new file mode 100644
index 00000000000..30472beb3e6
--- /dev/null
+++ b/source/blender/blenlib/intern/BLI_kdopbvh.c
@@ -0,0 +1,1526 @@
+/**
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2006 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Daniel Genrich, Andre Pinto
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "math.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "BKE_utildefines.h"
+
+#include "BLI_kdopbvh.h"
+#include "BLI_arithb.h"
+
+#ifdef _OPENMP
+#include <omp.h>
+#endif
+
+
+
+#define MAX_TREETYPE 32
+#define DEFAULT_FIND_NEAREST_HEAP_SIZE 1024
+
+typedef struct BVHNode
+{
+ struct BVHNode **children;
+ struct BVHNode *parent; // some user defined traversed need that
+ float *bv; // Bounding volume of all nodes, max 13 axis
+ int index; // face, edge, vertex index
+ char totnode; // how many nodes are used, used for speedup
+ char main_axis; // Axis used to split this node
+} BVHNode;
+
+struct BVHTree
+{
+ BVHNode **nodes;
+ BVHNode *nodearray; /* pre-alloc branch nodes */
+ BVHNode **nodechild; // pre-alloc childs for nodes
+ float *nodebv; // pre-alloc bounding-volumes for nodes
+ float epsilon; /* epslion is used for inflation of the k-dop */
+ int totleaf; // leafs
+ int totbranch;
+ char tree_type; // type of tree (4 => quadtree)
+ char axis; // kdop type (6 => OBB, 7 => AABB, ...)
+ char start_axis, stop_axis; // KDOP_AXES array indices according to axis
+};
+
+typedef struct BVHOverlapData
+{
+ BVHTree *tree1, *tree2;
+ BVHTreeOverlap *overlap;
+ int i, max_overlap; /* i is number of overlaps */
+ int start_axis, stop_axis;
+} BVHOverlapData;
+
+typedef struct BVHNearestData
+{
+ BVHTree *tree;
+ const float *co;
+ BVHTree_NearestPointCallback callback;
+ void *userdata;
+ float proj[13]; //coordinates projection over axis
+ BVHTreeNearest nearest;
+
+} BVHNearestData;
+
+typedef struct BVHRayCastData
+{
+ BVHTree *tree;
+
+ BVHTree_RayCastCallback callback;
+ void *userdata;
+
+
+ BVHTreeRay ray;
+ float ray_dot_axis[13];
+
+ BVHTreeRayHit hit;
+} BVHRayCastData;
+////////////////////////////////////////m
+
+
+////////////////////////////////////////////////////////////////////////
+// Bounding Volume Hierarchy Definition
+//
+// Notes: From OBB until 26-DOP --> all bounding volumes possible, just choose type below
+// Notes: You have to choose the type at compile time ITM
+// Notes: You can choose the tree type --> binary, quad, octree, choose below
+////////////////////////////////////////////////////////////////////////
+
+static float KDOP_AXES[13][3] =
+{ {1.0, 0, 0}, {0, 1.0, 0}, {0, 0, 1.0}, {1.0, 1.0, 1.0}, {1.0, -1.0, 1.0}, {1.0, 1.0, -1.0},
+{1.0, -1.0, -1.0}, {1.0, 1.0, 0}, {1.0, 0, 1.0}, {0, 1.0, 1.0}, {1.0, -1.0, 0}, {1.0, 0, -1.0},
+{0, 1.0, -1.0}
+};
+
+/*
+ * Generic push and pop heap
+ */
+#define PUSH_HEAP_BODY(HEAP_TYPE,PRIORITY,heap,heap_size) \
+{ \
+ HEAP_TYPE element = heap[heap_size-1]; \
+ int child = heap_size-1; \
+ while(child != 0) \
+ { \
+ int parent = (child-1) / 2; \
+ if(PRIORITY(element, heap[parent])) \
+ { \
+ heap[child] = heap[parent]; \
+ child = parent; \
+ } \
+ else break; \
+ } \
+ heap[child] = element; \
+}
+
+#define POP_HEAP_BODY(HEAP_TYPE, PRIORITY,heap,heap_size) \
+{ \
+ HEAP_TYPE element = heap[heap_size-1]; \
+ int parent = 0; \
+ while(parent < (heap_size-1)/2 ) \
+ { \
+ int child2 = (parent+1)*2; \
+ if(PRIORITY(heap[child2-1], heap[child2])) \
+ --child2; \
+ \
+ if(PRIORITY(element, heap[child2])) \
+ break; \
+ \
+ heap[parent] = heap[child2]; \
+ parent = child2; \
+ } \
+ heap[parent] = element; \
+}
+
+int ADJUST_MEMORY(void *local_memblock, void **memblock, int new_size, int *max_size, int size_per_item)
+{
+ int new_max_size = *max_size * 2;
+ void *new_memblock = NULL;
+
+ if(new_size <= *max_size)
+ return TRUE;
+
+ if(*memblock == local_memblock)
+ {
+ new_memblock = malloc( size_per_item * new_max_size );
+ memcpy( new_memblock, *memblock, size_per_item * *max_size );
+ }
+ else
+ new_memblock = realloc(*memblock, size_per_item * new_max_size );
+
+ if(new_memblock)
+ {
+ *memblock = new_memblock;
+ *max_size = new_max_size;
+ return TRUE;
+ }
+ else
+ return FALSE;
+}
+
+
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+// Introsort
+// with permission deriven from the following Java code:
+// http://ralphunden.net/content/tutorials/a-guide-to-introsort/
+// and he derived it from the SUN STL
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+static int size_threshold = 16;
+/*
+* Common methods for all algorithms
+*/
+static int floor_lg(int a)
+{
+ return (int)(floor(log(a)/log(2)));
+}
+
+/*
+* Insertion sort algorithm
+*/
+static void bvh_insertionsort(BVHNode **a, int lo, int hi, int axis)
+{
+ int i,j;
+ BVHNode *t;
+ for (i=lo; i < hi; i++)
+ {
+ j=i;
+ t = a[i];
+ while((j!=lo) && (t->bv[axis] < (a[j-1])->bv[axis]))
+ {
+ a[j] = a[j-1];
+ j--;
+ }
+ a[j] = t;
+ }
+}
+
+static int bvh_partition(BVHNode **a, int lo, int hi, BVHNode * x, int axis)
+{
+ int i=lo, j=hi;
+ while (1)
+ {
+ while ((a[i])->bv[axis] < x->bv[axis]) i++;
+ j--;
+ while (x->bv[axis] < (a[j])->bv[axis]) j--;
+ if(!(i < j))
+ return i;
+ SWAP( BVHNode* , a[i], a[j]);
+ i++;
+ }
+}
+
+/*
+* Heapsort algorithm
+*/
+static void bvh_downheap(BVHNode **a, int i, int n, int lo, int axis)
+{
+ BVHNode * d = a[lo+i-1];
+ int child;
+ while (i<=n/2)
+ {
+ child = 2*i;
+ if ((child < n) && ((a[lo+child-1])->bv[axis] < (a[lo+child])->bv[axis]))
+ {
+ child++;
+ }
+ if (!(d->bv[axis] < (a[lo+child-1])->bv[axis])) break;
+ a[lo+i-1] = a[lo+child-1];
+ i = child;
+ }
+ a[lo+i-1] = d;
+}
+
+static void bvh_heapsort(BVHNode **a, int lo, int hi, int axis)
+{
+ int n = hi-lo, i;
+ for (i=n/2; i>=1; i=i-1)
+ {
+ bvh_downheap(a, i,n,lo, axis);
+ }
+ for (i=n; i>1; i=i-1)
+ {
+ SWAP(BVHNode*, a[lo],a[lo+i-1]);
+ bvh_downheap(a, 1,i-1,lo, axis);
+ }
+}
+
+static BVHNode *bvh_medianof3(BVHNode **a, int lo, int mid, int hi, int axis) // returns Sortable
+{
+ if ((a[mid])->bv[axis] < (a[lo])->bv[axis])
+ {
+ if ((a[hi])->bv[axis] < (a[mid])->bv[axis])
+ return a[mid];
+ else
+ {
+ if ((a[hi])->bv[axis] < (a[lo])->bv[axis])
+ return a[hi];
+ else
+ return a[lo];
+ }
+ }
+ else
+ {
+ if ((a[hi])->bv[axis] < (a[mid])->bv[axis])
+ {
+ if ((a[hi])->bv[axis] < (a[lo])->bv[axis])
+ return a[lo];
+ else
+ return a[hi];
+ }
+ else
+ return a[mid];
+ }
+}
+/*
+* Quicksort algorithm modified for Introsort
+*/
+static void bvh_introsort_loop (BVHNode **a, int lo, int hi, int depth_limit, int axis)
+{
+ int p;
+
+ while (hi-lo > size_threshold)
+ {
+ if (depth_limit == 0)
+ {
+ bvh_heapsort(a, lo, hi, axis);
+ return;
+ }
+ depth_limit=depth_limit-1;
+ p=bvh_partition(a, lo, hi, bvh_medianof3(a, lo, lo+((hi-lo)/2)+1, hi-1, axis), axis);
+ bvh_introsort_loop(a, p, hi, depth_limit, axis);
+ hi=p;
+ }
+}
+
+static void sort(BVHNode **a0, int begin, int end, int axis)
+{
+ if (begin < end)
+ {
+ BVHNode **a=a0;
+ bvh_introsort_loop(a, begin, end, 2*floor_lg(end-begin), axis);
+ bvh_insertionsort(a, begin, end, axis);
+ }
+}
+void sort_along_axis(BVHTree *tree, int start, int end, int axis)
+{
+ sort(tree->nodes, start, end, axis);
+}
+
+//after a call to this function you can expect one of:
+// every node to left of a[n] are smaller or equal to it
+// every node to the right of a[n] are greater or equal to it
+int partition_nth_element(BVHNode **a, int _begin, int _end, int n, int axis){
+ int begin = _begin, end = _end, cut;
+ while(end-begin > 3)
+ {
+ cut = bvh_partition(a, begin, end, bvh_medianof3(a, begin, (begin+end)/2, end-1, axis), axis );
+ if(cut <= n)
+ begin = cut;
+ else
+ end = cut;
+ }
+ bvh_insertionsort(a, begin, end, axis);
+
+ return n;
+}
+
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+
+/*
+ * BVHTree bounding volumes functions
+ */
+static void create_kdop_hull(BVHTree *tree, BVHNode *node, float *co, int numpoints, int moving)
+{
+ float newminmax;
+ float *bv = node->bv;
+ int i, k;
+
+ // don't init boudings for the moving case
+ if(!moving)
+ {
+ for (i = tree->start_axis; i < tree->stop_axis; i++)
+ {
+ bv[2*i] = FLT_MAX;
+ bv[2*i + 1] = -FLT_MAX;
+ }
+ }
+
+ for(k = 0; k < numpoints; k++)
+ {
+ // for all Axes.
+ for (i = tree->start_axis; i < tree->stop_axis; i++)
+ {
+ newminmax = INPR(&co[k * 3], KDOP_AXES[i]);
+ if (newminmax < bv[2 * i])
+ bv[2 * i] = newminmax;
+ if (newminmax > bv[(2 * i) + 1])
+ bv[(2 * i) + 1] = newminmax;
+ }
+ }
+}
+
+// depends on the fact that the BVH's for each face is already build
+static void refit_kdop_hull(BVHTree *tree, BVHNode *node, int start, int end)
+{
+ float newmin,newmax;
+ int i, j;
+ float *bv = node->bv;
+
+
+ for (i = tree->start_axis; i < tree->stop_axis; i++)
+ {
+ bv[2*i] = FLT_MAX;
+ bv[2*i + 1] = -FLT_MAX;
+ }
+
+ for (j = start; j < end; j++)
+ {
+// for all Axes.
+ for (i = tree->start_axis; i < tree->stop_axis; i++)
+ {
+ newmin = tree->nodes[j]->bv[(2 * i)];
+ if ((newmin < bv[(2 * i)]))
+ bv[(2 * i)] = newmin;
+
+ newmax = tree->nodes[j]->bv[(2 * i) + 1];
+ if ((newmax > bv[(2 * i) + 1]))
+ bv[(2 * i) + 1] = newmax;
+ }
+ }
+
+}
+
+// only supports x,y,z axis in the moment
+// but we should use a plain and simple function here for speed sake
+static char get_largest_axis(float *bv)
+{
+ float middle_point[3];
+
+ middle_point[0] = (bv[1]) - (bv[0]); // x axis
+ middle_point[1] = (bv[3]) - (bv[2]); // y axis
+ middle_point[2] = (bv[5]) - (bv[4]); // z axis
+ if (middle_point[0] > middle_point[1])
+ {
+ if (middle_point[0] > middle_point[2])
+ return 1; // max x axis
+ else
+ return 5; // max z axis
+ }
+ else
+ {
+ if (middle_point[1] > middle_point[2])
+ return 3; // max y axis
+ else
+ return 5; // max z axis
+ }
+}
+
+// bottom-up update of bvh node BV
+// join the children on the parent BV
+static void node_join(BVHTree *tree, BVHNode *node)
+{
+ int i, j;
+
+ for (i = tree->start_axis; i < tree->stop_axis; i++)
+ {
+ node->bv[2*i] = FLT_MAX;
+ node->bv[2*i + 1] = -FLT_MAX;
+ }
+
+ for (i = 0; i < tree->tree_type; i++)
+ {
+ if (node->children[i])
+ {
+ for (j = tree->start_axis; j < tree->stop_axis; j++)
+ {
+ // update minimum
+ if (node->children[i]->bv[(2 * j)] < node->bv[(2 * j)])
+ node->bv[(2 * j)] = node->children[i]->bv[(2 * j)];
+
+ // update maximum
+ if (node->children[i]->bv[(2 * j) + 1] > node->bv[(2 * j) + 1])
+ node->bv[(2 * j) + 1] = node->children[i]->bv[(2 * j) + 1];
+ }
+ }
+ else
+ break;
+ }
+}
+
+/*
+ * Debug and information functions
+ */
+static void bvhtree_print_tree(BVHTree *tree, BVHNode *node, int depth)
+{
+ int i;
+ for(i=0; i<depth; i++) printf(" ");
+ printf(" - %d (%ld): ", node->index, node - tree->nodearray);
+ for(i=2*tree->start_axis; i<2*tree->stop_axis; i++)
+ printf("%.3f ", node->bv[i]);
+ printf("\n");
+
+ for(i=0; i<tree->tree_type; i++)
+ if(node->children[i])
+ bvhtree_print_tree(tree, node->children[i], depth+1);
+}
+
+static void bvhtree_info(BVHTree *tree)
+{
+ printf("BVHTree info\n");
+ printf("tree_type = %d, axis = %d, epsilon = %f\n", tree->tree_type, tree->axis, tree->epsilon);
+ printf("nodes = %d, branches = %d, leafs = %d\n", tree->totbranch + tree->totleaf, tree->totbranch, tree->totleaf);
+ printf("Memory per node = %ldbytes\n", sizeof(BVHNode) + sizeof(BVHNode*)*tree->tree_type + sizeof(float)*tree->axis);
+ printf("BV memory = %dbytes\n", MEM_allocN_len(tree->nodebv));
+
+ printf("Total memory = %ldbytes\n", sizeof(BVHTree)
+ + MEM_allocN_len(tree->nodes)
+ + MEM_allocN_len(tree->nodearray)
+ + MEM_allocN_len(tree->nodechild)
+ + MEM_allocN_len(tree->nodebv)
+ );
+
+// bvhtree_print_tree(tree, tree->nodes[tree->totleaf], 0);
+}
+
+#if 0
+
+
+static void verify_tree(BVHTree *tree)
+{
+ int i, j, check = 0;
+
+ // check the pointer list
+ for(i = 0; i < tree->totleaf; i++)
+ {
+ if(tree->nodes[i]->parent == NULL)
+ printf("Leaf has no parent: %d\n", i);
+ else
+ {
+ for(j = 0; j < tree->tree_type; j++)
+ {
+ if(tree->nodes[i]->parent->children[j] == tree->nodes[i])
+ check = 1;
+ }
+ if(!check)
+ {
+ printf("Parent child relationship doesn't match: %d\n", i);
+ }
+ check = 0;
+ }
+ }
+
+ // check the leaf list
+ for(i = 0; i < tree->totleaf; i++)
+ {
+ if(tree->nodearray[i].parent == NULL)
+ printf("Leaf has no parent: %d\n", i);
+ else
+ {
+ for(j = 0; j < tree->tree_type; j++)
+ {
+ if(tree->nodearray[i].parent->children[j] == &tree->nodearray[i])
+ check = 1;
+ }
+ if(!check)
+ {
+ printf("Parent child relationship doesn't match: %d\n", i);
+ }
+ check = 0;
+ }
+ }
+
+ printf("branches: %d, leafs: %d, total: %d\n", tree->totbranch, tree->totleaf, tree->totbranch + tree->totleaf);
+}
+#endif
+
+//Helper data and structures to build a min-leaf generalized implicit tree
+//This code can be easily reduced (basicly this is only method to calculate pow(k, n) in O(1).. and stuff like that)
+typedef struct BVHBuildHelper
+{
+ int tree_type; //
+ int totleafs; //
+
+ int leafs_per_child [32]; //Min number of leafs that are archievable from a node at depth N
+ int branches_on_level[32]; //Number of nodes at depth N (tree_type^N)
+
+ int remain_leafs; //Number of leafs that are placed on the level that is not 100% filled
+
+} BVHBuildHelper;
+
+static void build_implicit_tree_helper(BVHTree *tree, BVHBuildHelper *data)
+{
+ int depth = 0;
+ int remain;
+ int nnodes;
+
+ data->totleafs = tree->totleaf;
+ data->tree_type= tree->tree_type;
+
+ //Calculate the smallest tree_type^n such that tree_type^n >= num_leafs
+ for(
+ data->leafs_per_child[0] = 1;
+ data->leafs_per_child[0] < data->totleafs;
+ data->leafs_per_child[0] *= data->tree_type
+ );
+
+ data->branches_on_level[0] = 1;
+
+ //We could stop the loop first (but I am lazy to find out when)
+ for(depth = 1; depth < 32; depth++)
+ {
+ data->branches_on_level[depth] = data->branches_on_level[depth-1] * data->tree_type;
+ data->leafs_per_child [depth] = data->leafs_per_child [depth-1] / data->tree_type;
+ }
+
+ remain = data->totleafs - data->leafs_per_child[1];
+ nnodes = (remain + data->tree_type - 2) / (data->tree_type - 1);
+ data->remain_leafs = remain + nnodes;
+}
+
+// return the min index of all the leafs archivable with the given branch
+static int implicit_leafs_index(BVHBuildHelper *data, int depth, int child_index)
+{
+ int min_leaf_index = child_index * data->leafs_per_child[depth-1];
+ if(min_leaf_index <= data->remain_leafs)
+ return min_leaf_index;
+ else if(data->leafs_per_child[depth])
+ return data->totleafs - (data->branches_on_level[depth-1] - child_index) * data->leafs_per_child[depth];
+ else
+ return data->remain_leafs;
+}
+
+/**
+ * Generalized implicit tree build
+ *
+ * An implicit tree is a tree where its structure is implied, thus there is no need to store child pointers or indexs.
+ * Its possible to find the position of the child or the parent with simple maths (multiplication and adittion). This type
+ * of tree is for example used on heaps.. where node N has its childs at indexs N*2 and N*2+1.
+ *
+ * Altought in this case the tree type is general.. and not know until runtime.
+ * tree_type stands for the maximum number of childs that a tree node can have.
+ * All tree types >= 2 are supported.
+ *
+ * Advantages of the used trees include:
+ * - No need to store child/parent relations (they are implicit);
+ * - Any node child always has an index greater than the parent;
+ * - Brother nodes are sequencial in memory;
+ *
+ *
+ * Some math relations derived for general implicit trees:
+ *
+ * K = tree_type, ( 2 <= K )
+ * ROOT = 1
+ * N child of node A = A * K + (2 - K) + N, (0 <= N < K)
+ *
+ * Util methods:
+ * TODO...
+ * (looping elements, knowing if its a leaf or not.. etc...)
+ */
+
+// This functions returns the number of branches needed to have the requested number of leafs.
+static int implicit_needed_branches(int tree_type, int leafs)
+{
+ return MAX2(1, (leafs + tree_type - 3) / (tree_type-1) );
+}
+
+/*
+ * This function handles the problem of "sorting" the leafs (along the split_axis).
+ *
+ * It arranges the elements in the given partitions such that:
+ * - any element in partition N is less or equal to any element in partition N+1.
+ * - if all elements are diferent all partition will get the same subset of elements
+ * as if the array was sorted.
+ *
+ * partition P is described as the elements in the range ( nth[P] , nth[P+1] ]
+ *
+ * TODO: This can be optimized a bit by doing a specialized nth_element instead of K nth_elements
+ */
+static void split_leafs(BVHNode **leafs_array, int *nth, int partitions, int split_axis)
+{
+ int i;
+ for(i=0; i < partitions-1; i++)
+ {
+ if(nth[i] >= nth[partitions])
+ break;
+
+ partition_nth_element(leafs_array, nth[i], nth[partitions], nth[i+1], split_axis);
+ }
+}
+
+/*
+ * This functions builds an optimal implicit tree from the given leafs.
+ * Where optimal stands for:
+ * - The resulting tree will have the smallest number of branches;
+ * - At most only one branch will have NULL childs;
+ * - All leafs will be stored at level N or N+1.
+ *
+ * This function creates an implicit tree on branches_array, the leafs are given on the leafs_array.
+ *
+ * The tree is built per depth levels. First branchs at depth 1.. then branches at depth 2.. etc..
+ * The reason is that we can build level N+1 from level N witouth any data dependencies.. thus it allows
+ * to use multithread building.
+ *
+ * To archieve this is necessary to find how much leafs are accessible from a certain branch, BVHBuildHelper
+ * implicit_needed_branches and implicit_leafs_index are auxiliar functions to solve that "optimal-split".
+ */
+static void non_recursive_bvh_div_nodes(BVHTree *tree, BVHNode *branches_array, BVHNode **leafs_array, int num_leafs)
+{
+ int i;
+
+ const int tree_type = tree->tree_type;
+ const int tree_offset = 2 - tree->tree_type; //this value is 0 (on binary trees) and negative on the others
+ const int num_branches= implicit_needed_branches(tree_type, num_leafs);
+
+ BVHBuildHelper data;
+ int depth;
+
+ // set parent from root node to NULL
+ BVHNode *tmp = branches_array+0;
+ tmp->parent = NULL;
+
+ //Most of bvhtree code relies on 1-leaf trees having at least one branch
+ //We handle that special case here
+ if(num_leafs == 1)
+ {
+ BVHNode *root = branches_array+0;
+ refit_kdop_hull(tree, root, 0, num_leafs);
+ root->main_axis = get_largest_axis(root->bv) / 2;
+ root->totnode = 1;
+ root->children[0] = leafs_array[0];
+ root->children[0]->parent = root;
+ return;
+ }
+
+ branches_array--; //Implicit trees use 1-based indexs
+
+ build_implicit_tree_helper(tree, &data);
+
+ //Loop tree levels (log N) loops
+ for(i=1, depth = 1; i <= num_branches; i = i*tree_type + tree_offset, depth++)
+ {
+ const int first_of_next_level = i*tree_type + tree_offset;
+ const int end_j = MIN2(first_of_next_level, num_branches + 1); //index of last branch on this level
+ int j;
+
+ //Loop all branches on this level
+#pragma omp parallel for private(j) schedule(static)
+ for(j = i; j < end_j; j++)
+ {
+ int k;
+ const int parent_level_index= j-i;
+ BVHNode* parent = branches_array + j;
+ int nth_positions[ MAX_TREETYPE + 1];
+ char split_axis;
+
+ int parent_leafs_begin = implicit_leafs_index(&data, depth, parent_level_index);
+ int parent_leafs_end = implicit_leafs_index(&data, depth, parent_level_index+1);
+
+ //This calculates the bounding box of this branch
+ //and chooses the largest axis as the axis to divide leafs
+ refit_kdop_hull(tree, parent, parent_leafs_begin, parent_leafs_end);
+ split_axis = get_largest_axis(parent->bv);
+
+ //Save split axis (this can be used on raytracing to speedup the query time)
+ parent->main_axis = split_axis / 2;
+
+ //Split the childs along the split_axis, note: its not needed to sort the whole leafs array
+ //Only to assure that the elements are partioned on a way that each child takes the elements
+ //it would take in case the whole array was sorted.
+ //Split_leafs takes care of that "sort" problem.
+ nth_positions[ 0] = parent_leafs_begin;
+ nth_positions[tree_type] = parent_leafs_end;
+ for(k = 1; k < tree_type; k++)
+ {
+ int child_index = j * tree_type + tree_offset + k;
+ int child_level_index = child_index - first_of_next_level; //child level index
+ nth_positions[k] = implicit_leafs_index(&data, depth+1, child_level_index);
+ }
+
+ split_leafs(leafs_array, nth_positions, tree_type, split_axis);
+
+
+ //Setup children and totnode counters
+ //Not really needed but currently most of BVH code relies on having an explicit children structure
+ for(k = 0; k < tree_type; k++)
+ {
+ int child_index = j * tree_type + tree_offset + k;
+ int child_level_index = child_index - first_of_next_level; //child level index
+
+ int child_leafs_begin = implicit_leafs_index(&data, depth+1, child_level_index);
+ int child_leafs_end = implicit_leafs_index(&data, depth+1, child_level_index+1);
+
+ if(child_leafs_end - child_leafs_begin > 1)
+ {
+ parent->children[k] = branches_array + child_index;
+ parent->children[k]->parent = parent;
+ }
+ else if(child_leafs_end - child_leafs_begin == 1)
+ {
+ parent->children[k] = leafs_array[ child_leafs_begin ];
+ parent->children[k]->parent = parent;
+ }
+ else
+ break;
+
+ parent->totnode = k+1;
+ }
+ }
+ }
+}
+
+
+/*
+ * BLI_bvhtree api
+ */
+BVHTree *BLI_bvhtree_new(int maxsize, float epsilon, char tree_type, char axis)
+{
+ BVHTree *tree;
+ int numnodes, i;
+
+ // theres not support for trees below binary-trees :P
+ if(tree_type < 2)
+ return NULL;
+
+ if(tree_type > MAX_TREETYPE)
+ return NULL;
+
+ tree = (BVHTree *)MEM_callocN(sizeof(BVHTree), "BVHTree");
+
+ //tree epsilon must be >= FLT_EPSILON
+ //so that tangent rays can still hit a bounding volume..
+ //this bug would show up when casting a ray aligned with a kdop-axis and with an edge of 2 faces
+ epsilon = MAX2(FLT_EPSILON, epsilon);
+
+ if(tree)
+ {
+ tree->epsilon = epsilon;
+ tree->tree_type = tree_type;
+ tree->axis = axis;
+
+ if(axis == 26)
+ {
+ tree->start_axis = 0;
+ tree->stop_axis = 13;
+ }
+ else if(axis == 18)
+ {
+ tree->start_axis = 7;
+ tree->stop_axis = 13;
+ }
+ else if(axis == 14)
+ {
+ tree->start_axis = 0;
+ tree->stop_axis = 7;
+ }
+ else if(axis == 8) // AABB
+ {
+ tree->start_axis = 0;
+ tree->stop_axis = 4;
+ }
+ else if(axis == 6) // OBB
+ {
+ tree->start_axis = 0;
+ tree->stop_axis = 3;
+ }
+ else
+ {
+ MEM_freeN(tree);
+ return NULL;
+ }
+
+
+ //Allocate arrays
+ numnodes = maxsize + implicit_needed_branches(tree_type, maxsize) + tree_type;
+
+ tree->nodes = (BVHNode **)MEM_callocN(sizeof(BVHNode *)*numnodes, "BVHNodes");
+
+ if(!tree->nodes)
+ {
+ MEM_freeN(tree);
+ return NULL;
+ }
+
+ tree->nodebv = (float*)MEM_callocN(sizeof(float)* axis * numnodes, "BVHNodeBV");
+ if(!tree->nodebv)
+ {
+ MEM_freeN(tree->nodes);
+ MEM_freeN(tree);
+ }
+
+ tree->nodechild = (BVHNode**)MEM_callocN(sizeof(BVHNode*) * tree_type * numnodes, "BVHNodeBV");
+ if(!tree->nodechild)
+ {
+ MEM_freeN(tree->nodebv);
+ MEM_freeN(tree->nodes);
+ MEM_freeN(tree);
+ }
+
+ tree->nodearray = (BVHNode *)MEM_callocN(sizeof(BVHNode)* numnodes, "BVHNodeArray");
+
+ if(!tree->nodearray)
+ {
+ MEM_freeN(tree->nodechild);
+ MEM_freeN(tree->nodebv);
+ MEM_freeN(tree->nodes);
+ MEM_freeN(tree);
+ return NULL;
+ }
+
+ //link the dynamic bv and child links
+ for(i=0; i< numnodes; i++)
+ {
+ tree->nodearray[i].bv = tree->nodebv + i * axis;
+ tree->nodearray[i].children = tree->nodechild + i * tree_type;
+ }
+
+ }
+
+ return tree;
+}
+
+void BLI_bvhtree_free(BVHTree *tree)
+{
+ if(tree)
+ {
+ MEM_freeN(tree->nodes);
+ MEM_freeN(tree->nodearray);
+ MEM_freeN(tree->nodebv);
+ MEM_freeN(tree->nodechild);
+ MEM_freeN(tree);
+ }
+}
+
+void BLI_bvhtree_balance(BVHTree *tree)
+{
+ int i;
+
+ BVHNode* branches_array = tree->nodearray + tree->totleaf;
+ BVHNode** leafs_array = tree->nodes;
+
+ //This function should only be called once (some big bug goes here if its being called more than once per tree)
+ assert(tree->totbranch == 0);
+
+ //Build the implicit tree
+ non_recursive_bvh_div_nodes(tree, branches_array, leafs_array, tree->totleaf);
+
+ //current code expects the branches to be linked to the nodes array
+ //we perform that linkage here
+ tree->totbranch = implicit_needed_branches(tree->tree_type, tree->totleaf);
+ for(i = 0; i < tree->totbranch; i++)
+ tree->nodes[tree->totleaf + i] = branches_array + i;
+
+ //bvhtree_info(tree);
+}
+
+int BLI_bvhtree_insert(BVHTree *tree, int index, float *co, int numpoints)
+{
+ int i;
+ BVHNode *node = NULL;
+
+ // insert should only possible as long as tree->totbranch is 0
+ if(tree->totbranch > 0)
+ return 0;
+
+ if(tree->totleaf+1 >= MEM_allocN_len(tree->nodes)/sizeof(*(tree->nodes)))
+ return 0;
+
+ // TODO check if have enough nodes in array
+
+ node = tree->nodes[tree->totleaf] = &(tree->nodearray[tree->totleaf]);
+ tree->totleaf++;
+
+ create_kdop_hull(tree, node, co, numpoints, 0);
+ node->index= index;
+
+ // inflate the bv with some epsilon
+ for (i = tree->start_axis; i < tree->stop_axis; i++)
+ {
+ node->bv[(2 * i)] -= tree->epsilon; // minimum
+ node->bv[(2 * i) + 1] += tree->epsilon; // maximum
+ }
+
+ return 1;
+}
+
+
+// call before BLI_bvhtree_update_tree()
+int BLI_bvhtree_update_node(BVHTree *tree, int index, float *co, float *co_moving, int numpoints)
+{
+ int i;
+ BVHNode *node= NULL;
+
+ // check if index exists
+ if(index > tree->totleaf)
+ return 0;
+
+ node = tree->nodearray + index;
+
+ create_kdop_hull(tree, node, co, numpoints, 0);
+
+ if(co_moving)
+ create_kdop_hull(tree, node, co_moving, numpoints, 1);
+
+ // inflate the bv with some epsilon
+ for (i = tree->start_axis; i < tree->stop_axis; i++)
+ {
+ node->bv[(2 * i)] -= tree->epsilon; // minimum
+ node->bv[(2 * i) + 1] += tree->epsilon; // maximum
+ }
+
+ return 1;
+}
+
+// call BLI_bvhtree_update_node() first for every node/point/triangle
+void BLI_bvhtree_update_tree(BVHTree *tree)
+{
+ //Update bottom=>top
+ //TRICKY: the way we build the tree all the childs have an index greater than the parent
+ //This allows us todo a bottom up update by starting on the biger numbered branch
+
+ BVHNode** root = tree->nodes + tree->totleaf;
+ BVHNode** index = tree->nodes + tree->totleaf + tree->totbranch-1;
+
+ for (; index >= root; index--)
+ node_join(tree, *index);
+}
+
+float BLI_bvhtree_getepsilon(BVHTree *tree)
+{
+ return tree->epsilon;
+}
+
+
+/*
+ * BLI_bvhtree_overlap
+ */
+// overlap - is it possbile for 2 bv's to collide ?
+static int tree_overlap(BVHNode *node1, BVHNode *node2, int start_axis, int stop_axis)
+{
+ float *bv1 = node1->bv;
+ float *bv2 = node2->bv;
+
+ float *bv1_end = bv1 + (stop_axis<<1);
+
+ bv1 += start_axis<<1;
+ bv2 += start_axis<<1;
+
+ // test all axis if min + max overlap
+ for (; bv1 != bv1_end; bv1+=2, bv2+=2)
+ {
+ if ((*(bv1) > *(bv2 + 1)) || (*(bv2) > *(bv1 + 1)))
+ return 0;
+ }
+
+ return 1;
+}
+
+static void traverse(BVHOverlapData *data, BVHNode *node1, BVHNode *node2)
+{
+ int j;
+
+ if(tree_overlap(node1, node2, data->start_axis, data->stop_axis))
+ {
+ // check if node1 is a leaf
+ if(!node1->totnode)
+ {
+ // check if node2 is a leaf
+ if(!node2->totnode)
+ {
+
+ if(node1 == node2)
+ {
+ return;
+ }
+
+ if(data->i >= data->max_overlap)
+ {
+ // try to make alloc'ed memory bigger
+ data->overlap = realloc(data->overlap, sizeof(BVHTreeOverlap)*data->max_overlap*2);
+
+ if(!data->overlap)
+ {
+ printf("Out of Memory in traverse\n");
+ return;
+ }
+ data->max_overlap *= 2;
+ }
+
+ // both leafs, insert overlap!
+ data->overlap[data->i].indexA = node1->index;
+ data->overlap[data->i].indexB = node2->index;
+
+ data->i++;
+ }
+ else
+ {
+ for(j = 0; j < data->tree2->tree_type; j++)
+ {
+ if(node2->children[j])
+ traverse(data, node1, node2->children[j]);
+ }
+ }
+ }
+ else
+ {
+
+ for(j = 0; j < data->tree2->tree_type; j++)
+ {
+ if(node1->children[j])
+ traverse(data, node1->children[j], node2);
+ }
+ }
+ }
+ return;
+}
+
+BVHTreeOverlap *BLI_bvhtree_overlap(BVHTree *tree1, BVHTree *tree2, int *result)
+{
+ int j, total = 0;
+ BVHTreeOverlap *overlap = NULL, *to = NULL;
+ BVHOverlapData **data;
+
+ // check for compatibility of both trees (can't compare 14-DOP with 18-DOP)
+ if((tree1->axis != tree2->axis) && (tree1->axis == 14 || tree2->axis == 14) && (tree1->axis == 18 || tree2->axis == 18))
+ return 0;
+
+ // fast check root nodes for collision before doing big splitting + traversal
+ if(!tree_overlap(tree1->nodes[tree1->totleaf], tree2->nodes[tree2->totleaf], MIN2(tree1->start_axis, tree2->start_axis), MIN2(tree1->stop_axis, tree2->stop_axis)))
+ return 0;
+
+ data = MEM_callocN(sizeof(BVHOverlapData *)* tree1->tree_type, "BVHOverlapData_star");
+
+ for(j = 0; j < tree1->tree_type; j++)
+ {
+ data[j] = (BVHOverlapData *)MEM_callocN(sizeof(BVHOverlapData), "BVHOverlapData");
+
+ // init BVHOverlapData
+ data[j]->overlap = (BVHTreeOverlap *)malloc(sizeof(BVHTreeOverlap)*MAX2(tree1->totleaf, tree2->totleaf));
+ data[j]->tree1 = tree1;
+ data[j]->tree2 = tree2;
+ data[j]->max_overlap = MAX2(tree1->totleaf, tree2->totleaf);
+ data[j]->i = 0;
+ data[j]->start_axis = MIN2(tree1->start_axis, tree2->start_axis);
+ data[j]->stop_axis = MIN2(tree1->stop_axis, tree2->stop_axis );
+ }
+
+#pragma omp parallel for private(j) schedule(static)
+ for(j = 0; j < MIN2(tree1->tree_type, tree1->nodes[tree1->totleaf]->totnode); j++)
+ {
+ traverse(data[j], tree1->nodes[tree1->totleaf]->children[j], tree2->nodes[tree2->totleaf]);
+ }
+
+ for(j = 0; j < tree1->tree_type; j++)
+ total += data[j]->i;
+
+ to = overlap = (BVHTreeOverlap *)MEM_callocN(sizeof(BVHTreeOverlap)*total, "BVHTreeOverlap");
+
+ for(j = 0; j < tree1->tree_type; j++)
+ {
+ memcpy(to, data[j]->overlap, data[j]->i*sizeof(BVHTreeOverlap));
+ to+=data[j]->i;
+ }
+
+ for(j = 0; j < tree1->tree_type; j++)
+ {
+ free(data[j]->overlap);
+ MEM_freeN(data[j]);
+ }
+ MEM_freeN(data);
+
+ (*result) = total;
+ return overlap;
+}
+
+
+/*
+ * Nearest neighbour - BLI_bvhtree_find_nearest
+ */
+static float squared_dist(const float *a, const float *b)
+{
+ float tmp[3];
+ VECSUB(tmp, a, b);
+ return INPR(tmp, tmp);
+}
+
+//Determines the nearest point of the given node BV. Returns the squared distance to that point.
+static float calc_nearest_point(BVHNearestData *data, BVHNode *node, float *nearest)
+{
+ int i;
+ const float *bv = node->bv;
+
+ //nearest on AABB hull
+ for(i=0; i != 3; i++, bv += 2)
+ {
+ if(bv[0] > data->proj[i])
+ nearest[i] = bv[0];
+ else if(bv[1] < data->proj[i])
+ nearest[i] = bv[1];
+ else
+ nearest[i] = data->proj[i];
+ }
+
+/*
+ //nearest on a general hull
+ VECCOPY(nearest, data->co);
+ for(i = data->tree->start_axis; i != data->tree->stop_axis; i++, bv+=2)
+ {
+ float proj = INPR( nearest, KDOP_AXES[i]);
+ float dl = bv[0] - proj;
+ float du = bv[1] - proj;
+
+ if(dl > 0)
+ {
+ VECADDFAC(nearest, nearest, KDOP_AXES[i], dl);
+ }
+ else if(du < 0)
+ {
+ VECADDFAC(nearest, nearest, KDOP_AXES[i], du);
+ }
+ }
+*/
+ return squared_dist(data->co, nearest);
+}
+
+
+typedef struct NodeDistance
+{
+ BVHNode *node;
+ float dist;
+
+} NodeDistance;
+
+#define NodeDistance_priority(a,b) ( (a).dist < (b).dist )
+
+// TODO: use a priority queue to reduce the number of nodes looked on
+static void dfs_find_nearest_dfs(BVHNearestData *data, BVHNode *node)
+{
+ if(node->totnode == 0)
+ {
+ if(data->callback)
+ data->callback(data->userdata , node->index, data->co, &data->nearest);
+ else
+ {
+ data->nearest.index = node->index;
+ data->nearest.dist = calc_nearest_point(data, node, data->nearest.co);
+ }
+ }
+ else
+ {
+ //Better heuristic to pick the closest node to dive on
+ int i;
+ float nearest[3];
+
+ if(data->proj[ node->main_axis ] <= node->children[0]->bv[node->main_axis*2+1])
+ {
+
+ for(i=0; i != node->totnode; i++)
+ {
+ if( calc_nearest_point(data, node->children[i], nearest) >= data->nearest.dist) continue;
+ dfs_find_nearest_dfs(data, node->children[i]);
+ }
+ }
+ else
+ {
+ for(i=node->totnode-1; i >= 0 ; i--)
+ {
+ if( calc_nearest_point(data, node->children[i], nearest) >= data->nearest.dist) continue;
+ dfs_find_nearest_dfs(data, node->children[i]);
+ }
+ }
+ }
+}
+
+static void dfs_find_nearest_begin(BVHNearestData *data, BVHNode *node)
+{
+ float nearest[3], sdist;
+ sdist = calc_nearest_point(data, node, nearest);
+ if(sdist >= data->nearest.dist) return;
+ dfs_find_nearest_dfs(data, node);
+}
+
+
+static void NodeDistance_push_heap(NodeDistance *heap, int heap_size)
+PUSH_HEAP_BODY(NodeDistance, NodeDistance_priority, heap, heap_size)
+
+static void NodeDistance_pop_heap(NodeDistance *heap, int heap_size)
+POP_HEAP_BODY(NodeDistance, NodeDistance_priority, heap, heap_size)
+
+//NN function that uses an heap.. this functions leads to an optimal number of min-distance
+//but for normal tri-faces and BV 6-dop.. a simple dfs with local heuristics (as implemented
+//in source/blender/blenkernel/intern/shrinkwrap.c) works faster.
+//
+//It may make sense to use this function if the callback queries are very slow.. or if its impossible
+//to get a nice heuristic
+//
+//this function uses "malloc/free" instead of the MEM_* because it intends to be openmp safe
+static void bfs_find_nearest(BVHNearestData *data, BVHNode *node)
+{
+ int i;
+ NodeDistance default_heap[DEFAULT_FIND_NEAREST_HEAP_SIZE];
+ NodeDistance *heap=default_heap, current;
+ int heap_size = 0, max_heap_size = sizeof(default_heap)/sizeof(default_heap[0]);
+ float nearest[3];
+
+ int callbacks = 0, push_heaps = 0;
+
+ if(node->totnode == 0)
+ {
+ dfs_find_nearest_dfs(data, node);
+ return;
+ }
+
+ current.node = node;
+ current.dist = calc_nearest_point(data, node, nearest);
+
+ while(current.dist < data->nearest.dist)
+ {
+// printf("%f : %f\n", current.dist, data->nearest.dist);
+ for(i=0; i< current.node->totnode; i++)
+ {
+ BVHNode *child = current.node->children[i];
+ if(child->totnode == 0)
+ {
+ callbacks++;
+ dfs_find_nearest_dfs(data, child);
+ }
+ else
+ {
+ //adjust heap size
+ if(heap_size >= max_heap_size
+ && ADJUST_MEMORY(default_heap, (void**)&heap, heap_size+1, &max_heap_size, sizeof(heap[0])) == FALSE)
+ {
+ printf("WARNING: bvh_find_nearest got out of memory\n");
+
+ if(heap != default_heap)
+ free(heap);
+
+ return;
+ }
+
+ heap[heap_size].node = current.node->children[i];
+ heap[heap_size].dist = calc_nearest_point(data, current.node->children[i], nearest);
+
+ if(heap[heap_size].dist >= data->nearest.dist) continue;
+ heap_size++;
+
+ NodeDistance_push_heap(heap, heap_size);
+ // PUSH_HEAP_BODY(NodeDistance, NodeDistance_priority, heap, heap_size);
+ push_heaps++;
+ }
+ }
+
+ if(heap_size == 0) break;
+
+ current = heap[0];
+ NodeDistance_pop_heap(heap, heap_size);
+// POP_HEAP_BODY(NodeDistance, NodeDistance_priority, heap, heap_size);
+ heap_size--;
+ }
+
+// printf("hsize=%d, callbacks=%d, pushs=%d\n", heap_size, callbacks, push_heaps);
+
+ if(heap != default_heap)
+ free(heap);
+}
+
+
+int BLI_bvhtree_find_nearest(BVHTree *tree, const float *co, BVHTreeNearest *nearest, BVHTree_NearestPointCallback callback, void *userdata)
+{
+ int i;
+
+ BVHNearestData data;
+ BVHNode* root = tree->nodes[tree->totleaf];
+
+ //init data to search
+ data.tree = tree;
+ data.co = co;
+
+ data.callback = callback;
+ data.userdata = userdata;
+
+ for(i = data.tree->start_axis; i != data.tree->stop_axis; i++)
+ {
+ data.proj[i] = INPR(data.co, KDOP_AXES[i]);
+ }
+
+ if(nearest)
+ {
+ memcpy( &data.nearest , nearest, sizeof(*nearest) );
+ }
+ else
+ {
+ data.nearest.index = -1;
+ data.nearest.dist = FLT_MAX;
+ }
+
+ //dfs search
+ if(root)
+ dfs_find_nearest_begin(&data, root);
+
+ //copy back results
+ if(nearest)
+ {
+ memcpy(nearest, &data.nearest, sizeof(*nearest));
+ }
+
+ return data.nearest.index;
+}
+
+
+/*
+ * Raycast - BLI_bvhtree_ray_cast
+ *
+ * raycast is done by performing a DFS on the BVHTree and saving the closest hit
+ */
+
+//Determines the distance that the ray must travel to hit the bounding volume of the given node
+static float ray_nearest_hit(BVHRayCastData *data, BVHNode *node)
+{
+ int i;
+ const float *bv = node->bv;
+
+ float low = 0, upper = data->hit.dist;
+
+ for(i=0; i != 3; i++, bv += 2)
+ {
+ if(data->ray_dot_axis[i] == 0.0f)
+ {
+ //axis aligned ray
+ if(data->ray.origin[i] < bv[0] - data->ray.radius
+ || data->ray.origin[i] > bv[1] + data->ray.radius)
+ return FLT_MAX;
+ }
+ else
+ {
+ float ll = (bv[0] - data->ray.radius - data->ray.origin[i]) / data->ray_dot_axis[i];
+ float lu = (bv[1] + data->ray.radius - data->ray.origin[i]) / data->ray_dot_axis[i];
+
+ if(data->ray_dot_axis[i] > 0.0f)
+ {
+ if(ll > low) low = ll;
+ if(lu < upper) upper = lu;
+ }
+ else
+ {
+ if(lu > low) low = lu;
+ if(ll < upper) upper = ll;
+ }
+
+ if(low > upper) return FLT_MAX;
+ }
+ }
+ return low;
+}
+
+static void dfs_raycast(BVHRayCastData *data, BVHNode *node)
+{
+ int i;
+
+ //ray-bv is really fast.. and simple tests revealed its worth to test it
+ //before calling the ray-primitive functions
+ float dist = ray_nearest_hit(data, node);
+ if(dist >= data->hit.dist) return;
+
+ if(node->totnode == 0)
+ {
+ if(data->callback)
+ data->callback(data->userdata, node->index, &data->ray, &data->hit);
+ else
+ {
+ data->hit.index = node->index;
+ data->hit.dist = dist;
+ VECADDFAC(data->hit.co, data->ray.origin, data->ray.direction, dist);
+ }
+ }
+ else
+ {
+ //pick loop direction to dive into the tree (based on ray direction and split axis)
+ if(data->ray_dot_axis[ node->main_axis ] > 0.0f)
+ {
+ for(i=0; i != node->totnode; i++)
+ {
+ dfs_raycast(data, node->children[i]);
+ }
+ }
+ else
+ {
+ for(i=node->totnode-1; i >= 0; i--)
+ {
+ dfs_raycast(data, node->children[i]);
+ }
+ }
+ }
+}
+
+int BLI_bvhtree_ray_cast(BVHTree *tree, const float *co, const float *dir, float radius, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata)
+{
+ int i;
+ BVHRayCastData data;
+ BVHNode * root = tree->nodes[tree->totleaf];
+
+ data.tree = tree;
+
+ data.callback = callback;
+ data.userdata = userdata;
+
+ VECCOPY(data.ray.origin, co);
+ VECCOPY(data.ray.direction, dir);
+ data.ray.radius = radius;
+
+ Normalize(data.ray.direction);
+
+ for(i=0; i<3; i++)
+ {
+ data.ray_dot_axis[i] = INPR( data.ray.direction, KDOP_AXES[i]);
+
+ if(fabs(data.ray_dot_axis[i]) < FLT_EPSILON)
+ data.ray_dot_axis[i] = 0.0;
+ }
+
+
+ if(hit)
+ memcpy( &data.hit, hit, sizeof(*hit) );
+ else
+ {
+ data.hit.index = -1;
+ data.hit.dist = FLT_MAX;
+ }
+
+ if(root)
+ dfs_raycast(&data, root);
+
+
+ if(hit)
+ memcpy( hit, &data.hit, sizeof(*hit) );
+
+ return data.hit.index;
+}
+
diff --git a/source/blender/blenlib/intern/BLI_kdtree.c b/source/blender/blenlib/intern/BLI_kdtree.c
index 03b7561bad5..8e8b2e9f0e9 100644
--- a/source/blender/blenlib/intern/BLI_kdtree.c
+++ b/source/blender/blenlib/intern/BLI_kdtree.c
@@ -163,11 +163,18 @@ int BLI_kdtree_find_nearest(KDTree *tree, float *co, float *nor, KDTreeNearest *
min_node= root;
min_dist= squared_distance(root->co,co,root->nor,nor);
- if(root->left)
- stack[cur++]=root->left;
-
- if(root->right)
- stack[cur++]=root->right;
+ if(co[root->d] < root->co[root->d]) {
+ if(root->right)
+ stack[cur++]=root->right;
+ if(root->left)
+ stack[cur++]=root->left;
+ }
+ else {
+ if(root->left)
+ stack[cur++]=root->left;
+ if(root->right)
+ stack[cur++]=root->right;
+ }
while(cur--){
node=stack[cur];
@@ -263,11 +270,18 @@ int BLI_kdtree_find_n_nearest(KDTree *tree, int n, float *co, float *nor, KDTree
cur_dist= squared_distance(root->co,co,root->nor,nor);
add_nearest(nearest,&found,n,root->index,cur_dist,root->co);
- if(root->left)
- stack[cur++]=root->left;
-
- if(root->right)
- stack[cur++]=root->right;
+ if(co[root->d] < root->co[root->d]) {
+ if(root->right)
+ stack[cur++]=root->right;
+ if(root->left)
+ stack[cur++]=root->left;
+ }
+ else {
+ if(root->left)
+ stack[cur++]=root->left;
+ if(root->right)
+ stack[cur++]=root->right;
+ }
while(cur--){
node=stack[cur];
diff --git a/source/blender/blenlib/intern/BLI_mempool.c b/source/blender/blenlib/intern/BLI_mempool.c
new file mode 100644
index 00000000000..7ac7b8b1791
--- /dev/null
+++ b/source/blender/blenlib/intern/BLI_mempool.c
@@ -0,0 +1,140 @@
+/**
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2008 by Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/*
+ Simple, fast memory allocator for allocating many elements of the same size.
+*/
+
+#include "MEM_guardedalloc.h"
+#include "BLI_blenlib.h"
+#include "DNA_listBase.h"
+#include "BLI_linklist.h"
+#include <string.h>
+
+typedef struct BLI_freenode{
+ struct BLI_freenode *next;
+}BLI_freenode;
+
+typedef struct BLI_mempool_chunk{
+ struct BLI_mempool_chunk *next, *prev;
+ void *data;
+}BLI_mempool_chunk;
+
+typedef struct BLI_mempool{
+ struct ListBase chunks;
+ int esize, csize, pchunk; /*size of elements and chunks in bytes and number of elements per chunk*/
+ struct BLI_freenode *free; /*free element list. Interleaved into chunk datas.*/
+}BLI_mempool;
+
+BLI_mempool *BLI_mempool_create(int esize, int tote, int pchunk)
+{ BLI_mempool *pool = NULL;
+ BLI_freenode *lasttail = NULL, *curnode = NULL;
+ int i,j, maxchunks;
+ char *addr;
+
+ /*allocate the pool structure*/
+ pool = MEM_mallocN(sizeof(BLI_mempool),"memory pool");
+ pool->esize = esize;
+ pool->pchunk = pchunk;
+ pool->csize = esize * pchunk;
+ pool->chunks.first = pool->chunks.last = NULL;
+
+ maxchunks = tote / pchunk;
+
+ /*allocate the actual chunks*/
+ for(i=0; i < maxchunks; i++){
+ BLI_mempool_chunk *mpchunk = MEM_mallocN(sizeof(BLI_mempool_chunk), "BLI_Mempool Chunk");
+ mpchunk->next = mpchunk->prev = NULL;
+ mpchunk->data = MEM_mallocN(pool->csize, "BLI Mempool Chunk Data");
+ BLI_addtail(&(pool->chunks), mpchunk);
+
+ if(i==0) pool->free = mpchunk->data; /*start of the list*/
+ /*loop through the allocated data, building the pointer structures*/
+ for(addr = mpchunk->data, j=0; j < pool->pchunk; j++){
+ curnode = ((BLI_freenode*)addr);
+ addr += pool->esize;
+ curnode->next = (BLI_freenode*)addr;
+ }
+ /*final pointer in the previously allocated chunk is wrong.*/
+ if(lasttail) lasttail->next = mpchunk->data;
+ /*set the end of this chunks memoryy to the new tail for next iteration*/
+ lasttail = curnode;
+ }
+ /*terminate the list*/
+ curnode->next = NULL;
+ return pool;
+}
+void *BLI_mempool_alloc(BLI_mempool *pool){
+ void *retval=NULL;
+ BLI_freenode *curnode=NULL;
+ char *addr=NULL;
+ int j;
+
+ if(!(pool->free)){
+ /*need to allocate a new chunk*/
+ BLI_mempool_chunk *mpchunk = MEM_mallocN(sizeof(BLI_mempool_chunk), "BLI_Mempool Chunk");
+ mpchunk->next = mpchunk->prev = NULL;
+ mpchunk->data = MEM_mallocN(pool->csize, "BLI_Mempool Chunk Data");
+ BLI_addtail(&(pool->chunks), mpchunk);
+
+ pool->free = mpchunk->data; /*start of the list*/
+ for(addr = mpchunk->data, j=0; j < pool->pchunk; j++){
+ curnode = ((BLI_freenode*)addr);
+ addr += pool->esize;
+ curnode->next = (BLI_freenode*)addr;
+ }
+ curnode->next = NULL; /*terminate the list*/
+ }
+
+ retval = pool->free;
+ pool->free = pool->free->next;
+ //memset(retval, 0, pool->esize);
+ return retval;
+}
+
+void *BLI_mempool_calloc(BLI_mempool *pool){
+ void *retval=NULL;
+ retval = BLI_mempool_alloc(pool);
+ memset(retval, 0, pool->esize);
+ return retval;
+}
+
+
+
+void BLI_mempool_free(BLI_mempool *pool, void *addr){ //doesnt protect against double frees, dont be stupid!
+ BLI_freenode *newhead = addr;
+ newhead->next = pool->free;
+ pool->free = newhead;
+}
+void BLI_mempool_destroy(BLI_mempool *pool)
+{
+ BLI_mempool_chunk *mpchunk=NULL;
+ for(mpchunk = pool->chunks.first; mpchunk; mpchunk = mpchunk->next) MEM_freeN(mpchunk->data);
+ BLI_freelistN(&(pool->chunks));
+ MEM_freeN(pool);
+}
diff --git a/source/blender/blenlib/intern/BLI_storage.h b/source/blender/blenlib/intern/BLI_storage.h
index 022a579fb66..3e0dec367da 100644
--- a/source/blender/blenlib/intern/BLI_storage.h
+++ b/source/blender/blenlib/intern/BLI_storage.h
@@ -28,6 +28,13 @@
#ifndef BLI_STORAGE_H
#define BLI_STORAGE_H
+#ifndef __APPLE__
+#ifndef WIN32
+#define _LARGEFILE_SOURCE 1
+#define _FILE_OFFSET_BITS 64
+#endif
+#endif
+
#include "BLI_storage_types.h"
void BLI_adddirstrings(void);
diff --git a/source/blender/blenlib/intern/Makefile b/source/blender/blenlib/intern/Makefile
index 8d6ca9b6dc3..f92fa0a7e25 100644
--- a/source/blender/blenlib/intern/Makefile
+++ b/source/blender/blenlib/intern/Makefile
@@ -56,3 +56,6 @@ endif
ifeq ($(WITH_FREETYPE2), true)
CPPFLAGS += -DWITH_FREETYPE2
endif
+ifeq ($(OS),linux)
+ CPPFLAGS += -I$(OCGDIR)/extern/binreloc/include
+endif
diff --git a/source/blender/blenlib/intern/arithb.c b/source/blender/blenlib/intern/arithb.c
index 735ff2e65f7..0f2226fc872 100644
--- a/source/blender/blenlib/intern/arithb.c
+++ b/source/blender/blenlib/intern/arithb.c
@@ -54,11 +54,13 @@
#include <stdio.h>
#include "BLI_arithb.h"
+#include "BLI_memarena.h"
/* A few small defines. Keep'em local! */
#define SMALL_NUMBER 1.e-8
#define ABS(x) ((x) < 0 ? -(x) : (x))
#define SWAP(type, a, b) { type sw_ap; sw_ap=(a); (a)=(b); (b)=sw_ap; }
+#define CLAMP(a, b, c) if((a)<(b)) (a)=(b); else if((a)>(c)) (a)=(c)
#if defined(WIN32) || defined(__APPLE__)
@@ -757,6 +759,28 @@ void Mat4MulSerie(float answ[][4], float m1[][4],
}
}
+void Mat3BlendMat3(float out[][3], float dst[][3], float src[][3], float srcweight)
+{
+ float squat[4], dquat[4], fquat[4];
+ float ssize[3], dsize[3], fsize[4];
+ float rmat[3][3], smat[3][3];
+
+ Mat3ToQuat(dst, dquat);
+ Mat3ToSize(dst, dsize);
+
+ Mat3ToQuat(src, squat);
+ Mat3ToSize(src, ssize);
+
+ /* do blending */
+ QuatInterpol(fquat, dquat, squat, srcweight);
+ VecLerpf(fsize, dsize, ssize, srcweight);
+
+ /* compose new matrix */
+ QuatToMat3(fquat, rmat);
+ SizeToMat3(fsize, smat);
+ Mat3MulMat3(out, rmat, smat);
+}
+
void Mat4BlendMat4(float out[][4], float dst[][4], float src[][4], float srcweight)
{
float squat[4], dquat[4], fquat[4];
@@ -1002,6 +1026,19 @@ int FloatCompare( float *v1, float *v2, float limit)
return 0;
}
+int FloatCompare4( float *v1, float *v2, float limit)
+{
+
+ if( fabs(v1[0]-v2[0])<limit ) {
+ if( fabs(v1[1]-v2[1])<limit ) {
+ if( fabs(v1[2]-v2[2])<limit ) {
+ if( fabs(v1[3]-v2[3])<limit ) return 1;
+ }
+ }
+ }
+ return 0;
+}
+
float FloatLerpf( float target, float origin, float fac)
{
return (fac*target) + (1.0f-fac)*origin;
@@ -1334,9 +1371,36 @@ void NormalQuat(float *q)
}
}
-float *vectoquat( float *vec, short axis, short upflag)
+void RotationBetweenVectorsToQuat(float *q, float v1[3], float v2[3])
+{
+ float axis[3];
+ float angle;
+
+ Crossf(axis, v1, v2);
+
+ angle = NormalizedVecAngle2(v1, v2);
+
+ AxisAngleToQuat(q, axis, angle);
+}
+
+void AxisAngleToQuat(float *q, float *axis, float angle)
+{
+ float nor[3];
+ float si;
+
+ VecCopyf(nor, axis);
+ Normalize(nor);
+
+ angle /= 2;
+ si = (float)sin(angle);
+ q[0] = (float)cos(angle);
+ q[1] = nor[0] * si;
+ q[2] = nor[1] * si;
+ q[3] = nor[2] * si;
+}
+
+void vectoquat(float *vec, short axis, short upflag, float *q)
{
- static float q1[4];
float q2[4], nor[3], *fp, mat[3][3], angle, si, co, x2, y2, z2, len1;
/* first rotate to axis */
@@ -1348,11 +1412,11 @@ float *vectoquat( float *vec, short axis, short upflag)
x2= -vec[0] ; y2= -vec[1] ; z2= -vec[2];
}
- q1[0]=1.0;
- q1[1]=q1[2]=q1[3]= 0.0;
+ q[0]=1.0;
+ q[1]=q[2]=q[3]= 0.0;
len1= (float)sqrt(x2*x2+y2*y2+z2*z2);
- if(len1 == 0.0) return(q1);
+ if(len1 == 0.0) return;
/* nasty! I need a good routine for this...
* problem is a rotation of an Y axis to the negative Y-axis for example.
@@ -1363,9 +1427,8 @@ float *vectoquat( float *vec, short axis, short upflag)
nor[1]= -z2;
nor[2]= y2;
- if( fabs(y2)+fabs(z2)<0.0001 ) {
+ if(fabs(y2)+fabs(z2)<0.0001)
nor[1]= 1.0;
- }
co= x2;
}
@@ -1374,9 +1437,8 @@ float *vectoquat( float *vec, short axis, short upflag)
nor[1]= 0.0;
nor[2]= -x2;
- if( fabs(x2)+fabs(z2)<0.0001 ) {
+ if(fabs(x2)+fabs(z2)<0.0001)
nor[2]= 1.0;
- }
co= y2;
}
@@ -1385,9 +1447,8 @@ float *vectoquat( float *vec, short axis, short upflag)
nor[1]= x2;
nor[2]= 0.0;
- if( fabs(x2)+fabs(y2)<0.0001 ) {
+ if(fabs(x2)+fabs(y2)<0.0001)
nor[0]= 1.0;
- }
co= z2;
}
@@ -1397,13 +1458,13 @@ float *vectoquat( float *vec, short axis, short upflag)
angle= 0.5f*saacos(co);
si= (float)sin(angle);
- q1[0]= (float)cos(angle);
- q1[1]= nor[0]*si;
- q1[2]= nor[1]*si;
- q1[3]= nor[2]*si;
+ q[0]= (float)cos(angle);
+ q[1]= nor[0]*si;
+ q[2]= nor[1]*si;
+ q[3]= nor[2]*si;
if(axis!=upflag) {
- QuatToMat3(q1, mat);
+ QuatToMat3(q, mat);
fp= mat[2];
if(axis==0) {
@@ -1426,10 +1487,8 @@ float *vectoquat( float *vec, short axis, short upflag)
q2[2]= y2*si;
q2[3]= z2*si;
- QuatMul(q1,q2,q1);
+ QuatMul(q,q2,q);
}
-
- return(q1);
}
void VecUpMat3old( float *vec, float mat[][3], short axis)
@@ -1729,9 +1788,13 @@ void DQuatToMat4(DualQuat *dq, float mat[][4])
void DQuatAddWeighted(DualQuat *dqsum, DualQuat *dq, float weight)
{
+ int flipped= 0;
+
/* make sure we interpolate quats in the right direction */
- if (QuatDot(dq->quat, dqsum->quat) < 0)
- weight = -weight;
+ if (QuatDot(dq->quat, dqsum->quat) < 0) {
+ flipped= 1;
+ weight= -weight;
+ }
/* interpolate rotation and translation */
dqsum->quat[0] += weight*dq->quat[0];
@@ -1748,6 +1811,9 @@ void DQuatAddWeighted(DualQuat *dqsum, DualQuat *dq, float weight)
if (dq->scale_weight) {
float wmat[4][4];
+ if(flipped) /* we don't want negative weights for scaling */
+ weight= -weight;
+
Mat4CpyMat4(wmat, dq->scale);
Mat4MulFloat((float*)wmat, weight);
Mat4AddMat4(dqsum->scale, dqsum->scale, wmat);
@@ -2094,6 +2160,14 @@ void VecLerpf(float *target, float *a, float *b, float t)
target[2]= s*a[2] + t*b[2];
}
+void Vec2Lerpf(float *target, float *a, float *b, float t)
+{
+ float s = 1.0f-t;
+
+ target[0]= s*a[0] + t*b[0];
+ target[1]= s*a[1] + t*b[1];
+}
+
void VecMidf(float *v, float *v1, float *v2)
{
v[0]= 0.5f*(v1[0]+ v2[0]);
@@ -2111,8 +2185,9 @@ void VecMulf(float *v1, float f)
void VecOrthoBasisf(float *v, float *v1, float *v2)
{
- if (v[0] == 0.0f && v[1] == 0.0f)
- {
+ float f = sqrt(v[0]*v[0] + v[1]*v[1]);
+
+ if (f < 1e-35f) {
// degenerate case
v1[0] = 0.0f; v1[1] = 1.0f; v1[2] = 0.0f;
if (v[2] > 0.0f) {
@@ -2122,9 +2197,8 @@ void VecOrthoBasisf(float *v, float *v1, float *v2)
v2[0] = -1.0f; v2[1] = v2[2] = 0.0f;
}
}
- else
- {
- float f = 1.0f/sqrt(v[0]*v[0] + v[1]*v[1]);
+ else {
+ f = 1.0f/f;
v1[0] = v[1]*f;
v1[1] = -v[0]*f;
v1[2] = 0.0f;
@@ -2157,6 +2231,11 @@ int VecEqual(float *v1, float *v2)
return ((v1[0]==v2[0]) && (v1[1]==v2[1]) && (v1[2]==v2[2]));
}
+int VecIsNull(float *v)
+{
+ return (v[0] == 0 && v[1] == 0 && v[2] == 0);
+}
+
void CalcNormShort( short *v1, short *v2, short *v3, float *n) /* is also cross product */
{
float n1[3],n2[3];
@@ -2256,6 +2335,20 @@ double Sqrt3d(double d)
else return exp(log(d)/3);
}
+void NormalShortToFloat(float *out, short *in)
+{
+ out[0] = in[0] / 32767.0;
+ out[1] = in[1] / 32767.0;
+ out[2] = in[2] / 32767.0;
+}
+
+void NormalFloatToShort(short *out, float *in)
+{
+ out[0] = (short)(in[0] * 32767.0);
+ out[1] = (short)(in[1] * 32767.0);
+ out[2] = (short)(in[2] * 32767.0);
+}
+
/* distance v1 to line v2-v3 */
/* using Hesse formula, NO LINE PIECE! */
float DistVL2Dfl( float *v1, float *v2, float *v3) {
@@ -2427,7 +2520,7 @@ short IsectLL2Df(float *v1, float *v2, float *v3, float *v4)
1: intersection
*/
-short IsectLLPt2Df(float x0,float y0,float x1,float y1,
+static short IsectLLPt2Df(float x0,float y0,float x1,float y1,
float x2,float y2,float x3,float y3, float *xi,float *yi)
{
@@ -2477,37 +2570,50 @@ short IsectLLPt2Df(float x0,float y0,float x1,float y1,
} // end Intersect_Lines
#define SIDE_OF_LINE(pa,pb,pp) ((pa[0]-pp[0])*(pb[1]-pp[1]))-((pb[0]-pp[0])*(pa[1]-pp[1]))
-#define ISECT_EPSILON 1e-6
-
/* point in tri */
int IsectPT2Df(float pt[2], float v1[2], float v2[2], float v3[2])
{
- if ((SIDE_OF_LINE(v1,v2,pt)>=-ISECT_EPSILON) &&
- (SIDE_OF_LINE(v2,v3,pt)>=-ISECT_EPSILON) &&
- (SIDE_OF_LINE(v3,v1,pt)>=-ISECT_EPSILON))
- return 1;
- else {
- return 0;
+ if (SIDE_OF_LINE(v1,v2,pt)>=0.0) {
+ if (SIDE_OF_LINE(v2,v3,pt)>=0.0) {
+ if (SIDE_OF_LINE(v3,v1,pt)>=0.0) {
+ return 1;
+ }
+ }
+ } else {
+ if (! (SIDE_OF_LINE(v2,v3,pt)>=0.0) ) {
+ if (! (SIDE_OF_LINE(v3,v1,pt)>=0.0)) {
+ return -1;
+ }
+ }
}
+
+ return 0;
}
/* point in quad - only convex quads */
int IsectPQ2Df(float pt[2], float v1[2], float v2[2], float v3[2], float v4[2])
{
- if ((SIDE_OF_LINE(v1,v2,pt)>=-ISECT_EPSILON) &&
- (SIDE_OF_LINE(v2,v3,pt)>=-ISECT_EPSILON) &&
- (SIDE_OF_LINE(v3,v4,pt)>=-ISECT_EPSILON) &&
- (SIDE_OF_LINE(v4,v1,pt)>=-ISECT_EPSILON))
- return 1;
- else
- return 0;
+ if (SIDE_OF_LINE(v1,v2,pt)>=0.0) {
+ if (SIDE_OF_LINE(v2,v3,pt)>=0.0) {
+ if (SIDE_OF_LINE(v3,v4,pt)>=0.0) {
+ if (SIDE_OF_LINE(v4,v1,pt)>=0.0) {
+ return 1;
+ }
+ }
+ }
+ } else {
+ if (! (SIDE_OF_LINE(v2,v3,pt)>=0.0) ) {
+ if (! (SIDE_OF_LINE(v3,v4,pt)>=0.0)) {
+ if (! (SIDE_OF_LINE(v4,v1,pt)>=0.0)) {
+ return -1;
+ }
+ }
+ }
+ }
+
+ return 0;
}
-
- /* copied from Geometry.c - todo - move to arithb.c or some other generic place we can reuse */
-#define SIDE_OF_LINE(pa,pb,pp) ((pa[0]-pp[0])*(pb[1]-pp[1]))-((pb[0]-pp[0])*(pa[1]-pp[1]))
-#define POINT_IN_TRI(p0,p1,p2,p3) ((SIDE_OF_LINE(p1,p2,p0)>=0) && (SIDE_OF_LINE(p2,p3,p0)>=0) && (SIDE_OF_LINE(p3,p1,p0)>=0))
-
/**
*
* @param min
@@ -2871,6 +2977,22 @@ float VecAngle3(float *v1, float *v2, float *v3)
return NormalizedVecAngle2(vec1, vec2) * 180.0/M_PI;
}
+float VecAngle3_2D(float *v1, float *v2, float *v3)
+{
+ float vec1[2], vec2[2];
+
+ vec1[0] = v2[0]-v1[0];
+ vec1[1] = v2[1]-v1[1];
+
+ vec2[0] = v2[0]-v3[0];
+ vec2[1] = v2[1]-v3[1];
+
+ Normalize2(vec1);
+ Normalize2(vec2);
+
+ return NormalizedVecAngle2_2D(vec1, vec2) * 180.0/M_PI;
+}
+
/* Return the shortest angle in degrees between the 2 vectors */
float VecAngle2(float *v1, float *v2)
{
@@ -2900,6 +3022,21 @@ float NormalizedVecAngle2(float *v1, float *v2)
return 2.0f*saasin(VecLenf(v2, v1)/2.0);
}
+float NormalizedVecAngle2_2D(float *v1, float *v2)
+{
+ /* this is the same as acos(Inpf(v1, v2)), but more accurate */
+ if (Inp2f(v1, v2) < 0.0f) {
+ float vec[2];
+
+ vec[0]= -v2[0];
+ vec[1]= -v2[1];
+
+ return (float)M_PI - 2.0f*saasin(Vec2Lenf(vec, v1)/2.0f);
+ }
+ else
+ return 2.0f*saasin(Vec2Lenf(v2, v1)/2.0);
+}
+
void euler_rot(float *beul, float ang, char axis)
{
float eul[3], mat1[3][3], mat2[3][3], totmat[3][3];
@@ -3351,6 +3488,80 @@ void rgb_to_hsv(float r, float g, float b, float *lh, float *ls, float *lv)
*lv = v;
}
+/*http://brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html */
+
+void xyz_to_rgb(float xc, float yc, float zc, float *r, float *g, float *b, int colorspace)
+{
+ switch (colorspace) {
+ case BLI_CS_SMPTE:
+ *r = (3.50570 * xc) + (-1.73964 * yc) + (-0.544011 * zc);
+ *g = (-1.06906 * xc) + (1.97781 * yc) + (0.0351720 * zc);
+ *b = (0.0563117 * xc) + (-0.196994 * yc) + (1.05005 * zc);
+ break;
+ case BLI_CS_REC709:
+ *r = (3.240476 * xc) + (-1.537150 * yc) + (-0.498535 * zc);
+ *g = (-0.969256 * xc) + (1.875992 * yc) + (0.041556 * zc);
+ *b = (0.055648 * xc) + (-0.204043 * yc) + (1.057311 * zc);
+ break;
+ case BLI_CS_CIE:
+ *r = (2.28783848734076f * xc) + (-0.833367677835217f * yc) + (-0.454470795871421f * zc);
+ *g = (-0.511651380743862f * xc) + (1.42275837632178f * yc) + (0.0888930017552939f * zc);
+ *b = (0.00572040983140966f * xc) + (-0.0159068485104036f * yc) + (1.0101864083734f * zc);
+ break;
+ }
+}
+
+/*If the requested RGB shade contains a negative weight for
+ one of the primaries, it lies outside the colour gamut
+ accessible from the given triple of primaries. Desaturate
+ it by adding white, equal quantities of R, G, and B, enough
+ to make RGB all positive. The function returns 1 if the
+ components were modified, zero otherwise.*/
+int constrain_rgb(float *r, float *g, float *b)
+{
+ float w;
+
+ /* Amount of white needed is w = - min(0, *r, *g, *b) */
+
+ w = (0 < *r) ? 0 : *r;
+ w = (w < *g) ? w : *g;
+ w = (w < *b) ? w : *b;
+ w = -w;
+
+ /* Add just enough white to make r, g, b all positive. */
+
+ if (w > 0) {
+ *r += w; *g += w; *b += w;
+ return 1; /* Colour modified to fit RGB gamut */
+ }
+
+ return 0; /* Colour within RGB gamut */
+}
+
+/*Transform linear RGB values to nonlinear RGB values. Rec.
+ 709 is ITU-R Recommendation BT. 709 (1990) ``Basic
+ Parameter Values for the HDTV Standard for the Studio and
+ for International Programme Exchange'', formerly CCIR Rec.
+ 709.*/
+static void gamma_correct(float *c)
+{
+ /* Rec. 709 gamma correction. */
+ float cc = 0.018;
+
+ if (*c < cc) {
+ *c *= ((1.099 * pow(cc, 0.45)) - 0.099) / cc;
+ } else {
+ *c = (1.099 * pow(*c, 0.45)) - 0.099;
+ }
+}
+
+void gamma_correct_rgb(float *r, float *g, float *b)
+{
+ gamma_correct(r);
+ gamma_correct(g);
+ gamma_correct(b);
+}
+
/* we define a 'cpack' here as a (3 byte color code) number that can be expressed like 0xFFAA66 or so.
for that reason it is sensitive for endianness... with this function it works correctly
@@ -3412,6 +3623,8 @@ void tubemap(float x, float y, float z, float *u, float *v)
len= sqrt(x*x+y*y);
if(len>0) {
*u = (1.0 - (atan2(x/len,y/len) / M_PI)) / 2.0;
+ } else {
+ *v = *u = 0.0f; /* to avoid un-initialized variables */
}
}
@@ -3429,11 +3642,15 @@ void spheremap(float x, float y, float z, float *u, float *v)
z/=len;
*v = 1.0- saacos(z)/M_PI;
+ } else {
+ *v = *u = 0.0f; /* to avoid un-initialized variables */
}
}
/* ------------------------------------------------------------------------- */
+/* proposed api by ton and zr, not used yet */
+#if 0
/* ***************** m1 = m2 ***************** */
void cpy_m3_m3(float m1[][3], float m2[][3])
{
@@ -3457,7 +3674,6 @@ void ident_m4(float m[][4])
m[3][0]= m[3][1]= m[3][2]= 0.0;
}
-
/* ***************** m1 = m2 (pre) * m3 (post) ***************** */
void mul_m3_m3m3(float m1[][3], float m2[][3], float m3[][3])
{
@@ -3595,6 +3811,8 @@ void mul_v3_v3m4(float *v1, float *v2, float mat[][4])
}
+#endif
+
/* moved from effect.c
test if the line starting at p1 ending at p2 intersects the triangle v0..v2
return non zero if it does
@@ -3634,14 +3852,89 @@ int LineIntersectsTriangle(float p1[3], float p2[3], float v0[3], float v1[3], f
return 1;
}
+/* moved from effect.c
+ test if the ray starting at p1 going in d direction intersects the triangle v0..v2
+ return non zero if it does
+*/
+int RayIntersectsTriangle(float p1[3], float d[3], float v0[3], float v1[3], float v2[3], float *lambda, float *uv)
+{
+ float p[3], s[3], e1[3], e2[3], q[3];
+ float a, f, u, v;
+
+ VecSubf(e1, v1, v0);
+ VecSubf(e2, v2, v0);
+
+ Crossf(p, d, e2);
+ a = Inpf(e1, p);
+ if ((a > -0.000001) && (a < 0.000001)) return 0;
+ f = 1.0f/a;
+
+ VecSubf(s, p1, v0);
+
+ Crossf(q, s, e1);
+ *lambda = f * Inpf(e2, q);
+ if ((*lambda < 0.0)) return 0;
+
+ u = f * Inpf(s, p);
+ if ((u < 0.0)||(u > 1.0)) return 0;
+
+ v = f * Inpf(d, q);
+ if ((v < 0.0)||((u + v) > 1.0)) return 0;
+
+ if(uv) {
+ uv[0]= u;
+ uv[1]= v;
+ }
+
+ return 1;
+}
+
/* Adapted from the paper by Kasper Fauerby */
/* "Improved Collision detection and Response" */
+static int getLowestRoot(float a, float b, float c, float maxR, float* root)
+{
+ // Check if a solution exists
+ float determinant = b*b - 4.0f*a*c;
+
+ // If determinant is negative it means no solutions.
+ if (determinant >= 0.0f)
+ {
+ // calculate the two roots: (if determinant == 0 then
+ // x1==x2 but let’s disregard that slight optimization)
+ float sqrtD = sqrt(determinant);
+ float r1 = (-b - sqrtD) / (2.0f*a);
+ float r2 = (-b + sqrtD) / (2.0f*a);
+
+ // Sort so x1 <= x2
+ if (r1 > r2)
+ SWAP( float, r1, r2);
+
+ // Get lowest root:
+ if (r1 > 0.0f && r1 < maxR)
+ {
+ *root = r1;
+ return 1;
+ }
+
+ // It is possible that we want x2 - this can happen
+ // if x1 < 0
+ if (r2 > 0.0f && r2 < maxR)
+ {
+ *root = r2;
+ return 1;
+ }
+ }
+ // No (valid) solutions
+ return 0;
+}
+
int SweepingSphereIntersectsTriangleUV(float p1[3], float p2[3], float radius, float v0[3], float v1[3], float v2[3], float *lambda, float *ipoint)
{
float e1[3], e2[3], e3[3], point[3], vel[3], /*dist[3],*/ nor[3], temp[3], bv[3];
- float a, b, c, d, e, x, y, z, t, t0, t1, radius2=radius*radius;
+ float a, b, c, d, e, x, y, z, radius2=radius*radius;
float elen2,edotv,edotbv,nordotv,vel2;
- int embedded_in_plane=0, found_by_sweep=0;
+ float newLambda;
+ int found_by_sweep=0;
VecSubf(e1,v1,v0);
VecSubf(e2,v2,v0);
@@ -3650,44 +3943,41 @@ int SweepingSphereIntersectsTriangleUV(float p1[3], float p2[3], float radius, f
/*---test plane of tri---*/
Crossf(nor,e1,e2);
Normalize(nor);
+
/* flip normal */
if(Inpf(nor,vel)>0.0f) VecMulf(nor,-1.0f);
a=Inpf(p1,nor)-Inpf(v0,nor);
-
nordotv=Inpf(nor,vel);
- if ((nordotv > -0.000001) && (nordotv < 0.000001)) {
- if(fabs(a)>=1.0f)
+ if (fabs(nordotv) < 0.000001)
+ {
+ if(fabs(a)>=radius)
+ {
return 0;
- else{
- embedded_in_plane=1;
- t0=0.0f;
- t1=1.0f;
}
}
- else{
- t0=(radius-a)/nordotv;
- t1=(-radius-a)/nordotv;
- /* make t0<t1 */
- if(t0>t1){b=t1; t1=t0; t0=b;}
+ else
+ {
+ float t0=(-a+radius)/nordotv;
+ float t1=(-a-radius)/nordotv;
+
+ if(t0>t1)
+ SWAP(float, t0, t1);
if(t0>1.0f || t1<0.0f) return 0;
/* clamp to [0,1] */
- t0=(t0<0.0f)?0.0f:((t0>1.0f)?1.0:t0);
- t1=(t1<0.0f)?0.0f:((t1>1.0f)?1.0:t1);
- }
+ CLAMP(t0, 0.0f, 1.0f);
+ CLAMP(t1, 0.0f, 1.0f);
-/*---test inside of tri---*/
- if(embedded_in_plane==0){
+ /*---test inside of tri---*/
/* plane intersection point */
- VecCopyf(point,vel);
- VecMulf(point,t0);
- VecAddf(point,point,p1);
- VecCopyf(temp,nor);
- VecMulf(temp,radius);
- VecSubf(point,point,temp);
+
+ point[0] = p1[0] + vel[0]*t0 - nor[0]*radius;
+ point[1] = p1[1] + vel[1]*t0 - nor[1]*radius;
+ point[2] = p1[2] + vel[2]*t0 - nor[2]*radius;
+
/* is the point in the tri? */
a=Inpf(e1,e1);
@@ -3702,14 +3992,19 @@ int SweepingSphereIntersectsTriangleUV(float p1[3], float p2[3], float radius, f
y=e*a-d*b;
z=x+y-(a*c-b*b);
- if(( ((unsigned int)z)& ~(((unsigned int)x)|((unsigned int)y)) ) & 0x80000000){
+
+ if( z <= 0.0f && (x >= 0.0f && y >= 0.0f))
+ {
+ //( ((unsigned int)z)& ~(((unsigned int)x)|((unsigned int)y)) ) & 0x80000000){
*lambda=t0;
VecCopyf(ipoint,point);
return 1;
}
}
+
*lambda=1.0f;
+
/*---test points---*/
a=vel2=Inpf(vel,vel);
@@ -3717,73 +4012,42 @@ int SweepingSphereIntersectsTriangleUV(float p1[3], float p2[3], float radius, f
VecSubf(temp,p1,v0);
b=2.0f*Inpf(vel,temp);
c=Inpf(temp,temp)-radius2;
- d=b*b-4*a*c;
-
- if(d>=0.0f){
- if(d==0.0f)
- t=-b/2*a;
- else{
- z=sqrt(d);
- x=(-b-z)*0.5/a;
- y=(-b+z)*0.5/a;
- t=x<y?x:y;
- }
- if(t>0.0 && t < *lambda){
- *lambda=t;
- VecCopyf(ipoint,v0);
- found_by_sweep=1;
- }
+ if(getLowestRoot(a, b, c, *lambda, lambda))
+ {
+ VecCopyf(ipoint,v0);
+ found_by_sweep=1;
}
/*v1*/
VecSubf(temp,p1,v1);
b=2.0f*Inpf(vel,temp);
c=Inpf(temp,temp)-radius2;
- d=b*b-4*a*c;
-
- if(d>=0.0f){
- if(d==0.0f)
- t=-b/2*a;
- else{
- z=sqrt(d);
- x=(-b-z)*0.5/a;
- y=(-b+z)*0.5/a;
- t=x<y?x:y;
- }
- if(t>0.0 && t < *lambda){
- *lambda=t;
- VecCopyf(ipoint,v1);
- found_by_sweep=1;
- }
+ if(getLowestRoot(a, b, c, *lambda, lambda))
+ {
+ VecCopyf(ipoint,v1);
+ found_by_sweep=1;
}
+
/*v2*/
VecSubf(temp,p1,v2);
b=2.0f*Inpf(vel,temp);
c=Inpf(temp,temp)-radius2;
- d=b*b-4*a*c;
-
- if(d>=0.0f){
- if(d==0.0f)
- t=-b/2*a;
- else{
- z=sqrt(d);
- x=(-b-z)*0.5/a;
- y=(-b+z)*0.5/a;
- t=x<y?x:y;
- }
- if(t>0.0 && t < *lambda){
- *lambda=t;
- VecCopyf(ipoint,v2);
- found_by_sweep=1;
- }
+ if(getLowestRoot(a, b, c, *lambda, lambda))
+ {
+ VecCopyf(ipoint,v2);
+ found_by_sweep=1;
}
/*---test edges---*/
+ VecSubf(e3,v2,v1); //wasnt yet calculated
+
+
/*e1*/
VecSubf(bv,v0,p1);
+
elen2 = Inpf(e1,e1);
edotv = Inpf(e1,vel);
edotbv = Inpf(e1,bv);
@@ -3791,27 +4055,18 @@ int SweepingSphereIntersectsTriangleUV(float p1[3], float p2[3], float radius, f
a=elen2*(-Inpf(vel,vel))+edotv*edotv;
b=2.0f*(elen2*Inpf(vel,bv)-edotv*edotbv);
c=elen2*(radius2-Inpf(bv,bv))+edotbv*edotbv;
- d=b*b-4*a*c;
- if(d>=0.0f){
- if(d==0.0f)
- t=-b/2*a;
- else{
- z=sqrt(d);
- x=(-b-z)*0.5/a;
- y=(-b+z)*0.5/a;
- t=x<y?x:y;
- }
-
- e=(edotv*t-edotbv)/elen2;
- if((e>=0.0f) && (e<=1.0f)){
- if(t>0.0 && t < *lambda){
- *lambda=t;
- VecCopyf(ipoint,e1);
- VecMulf(ipoint,e);
- VecAddf(ipoint,ipoint,v0);
- found_by_sweep=1;
- }
+ if(getLowestRoot(a, b, c, *lambda, &newLambda))
+ {
+ e=(edotv*newLambda-edotbv)/elen2;
+
+ if(e >= 0.0f && e <= 1.0f)
+ {
+ *lambda = newLambda;
+ VecCopyf(ipoint,e1);
+ VecMulf(ipoint,e);
+ VecAddf(ipoint,ipoint,v0);
+ found_by_sweep=1;
}
}
@@ -3824,32 +4079,27 @@ int SweepingSphereIntersectsTriangleUV(float p1[3], float p2[3], float radius, f
a=elen2*(-Inpf(vel,vel))+edotv*edotv;
b=2.0f*(elen2*Inpf(vel,bv)-edotv*edotbv);
c=elen2*(radius2-Inpf(bv,bv))+edotbv*edotbv;
- d=b*b-4*a*c;
- if(d>=0.0f){
- if(d==0.0f)
- t=-b/2*a;
- else{
- z=sqrt(d);
- x=(-b-z)*0.5/a;
- y=(-b+z)*0.5/a;
- t=x<y?x:y;
- }
- e=(edotv*t-edotbv)/elen2;
-
- if((e>=0.0f) && (e<=1.0f)){
- if(t>0.0 && t < *lambda){
- *lambda=t;
- VecCopyf(ipoint,e2);
- VecMulf(ipoint,e);
- VecAddf(ipoint,ipoint,v0);
- found_by_sweep=1;
- }
+ if(getLowestRoot(a, b, c, *lambda, &newLambda))
+ {
+ e=(edotv*newLambda-edotbv)/elen2;
+
+ if(e >= 0.0f && e <= 1.0f)
+ {
+ *lambda = newLambda;
+ VecCopyf(ipoint,e2);
+ VecMulf(ipoint,e);
+ VecAddf(ipoint,ipoint,v0);
+ found_by_sweep=1;
}
}
/*e3*/
- VecSubf(e3,v2,v1);
+ VecSubf(bv,v0,p1);
+ elen2 = Inpf(e1,e1);
+ edotv = Inpf(e1,vel);
+ edotbv = Inpf(e1,bv);
+
VecSubf(bv,v1,p1);
elen2 = Inpf(e3,e3);
edotv = Inpf(e3,vel);
@@ -3858,30 +4108,22 @@ int SweepingSphereIntersectsTriangleUV(float p1[3], float p2[3], float radius, f
a=elen2*(-Inpf(vel,vel))+edotv*edotv;
b=2.0f*(elen2*Inpf(vel,bv)-edotv*edotbv);
c=elen2*(radius2-Inpf(bv,bv))+edotbv*edotbv;
- d=b*b-4*a*c;
- if(d>=0.0f){
- if(d==0.0f)
- t=-b/2*a;
- else{
- z=sqrt(d);
- x=(-b-z)*0.5/a;
- y=(-b+z)*0.5/a;
- t=x<y?x:y;
- }
- e=(edotv*t-edotbv)/elen2;
-
- if((e>=0.0f) && (e<=1.0f)){
- if(t>0.0 && t < *lambda){
- *lambda=t;
- VecCopyf(ipoint,e3);
- VecMulf(ipoint,e);
- VecAddf(ipoint,ipoint,v1);
- found_by_sweep=1;
- }
+ if(getLowestRoot(a, b, c, *lambda, &newLambda))
+ {
+ e=(edotv*newLambda-edotbv)/elen2;
+
+ if(e >= 0.0f && e <= 1.0f)
+ {
+ *lambda = newLambda;
+ VecCopyf(ipoint,e3);
+ VecMulf(ipoint,e);
+ VecAddf(ipoint,ipoint,v1);
+ found_by_sweep=1;
}
}
+
return found_by_sweep;
}
int AxialLineIntersectsTriangle(int axis, float p1[3], float p2[3], float v0[3], float v1[3], float v2[3], float *lambda)
@@ -3928,6 +4170,74 @@ int AxialLineIntersectsTriangle(int axis, float p1[3], float p2[3], float v0[3],
return 1;
}
+/* Returns the number of point of interests
+ * 0 - lines are colinear
+ * 1 - lines are coplanar, i1 is set to intersection
+ * 2 - i1 and i2 are the nearest points on line 1 (v1, v2) and line 2 (v3, v4) respectively
+ * */
+int LineIntersectLine(float v1[3], float v2[3], float v3[3], float v4[3], float i1[3], float i2[3])
+{
+ float a[3], b[3], c[3], ab[3], cb[3], dir1[3], dir2[3];
+ float d;
+
+ VecSubf(c, v3, v1);
+ VecSubf(a, v2, v1);
+ VecSubf(b, v4, v3);
+
+ VecCopyf(dir1, a);
+ Normalize(dir1);
+ VecCopyf(dir2, b);
+ Normalize(dir2);
+ d = Inpf(dir1, dir2);
+ if (d == 1.0f || d == -1.0f) {
+ /* colinear */
+ return 0;
+ }
+
+ Crossf(ab, a, b);
+ d = Inpf(c, ab);
+
+ /* test if the two lines are coplanar */
+ if (d > -0.000001f && d < 0.000001f) {
+ Crossf(cb, c, b);
+
+ VecMulf(a, Inpf(cb, ab) / Inpf(ab, ab));
+ VecAddf(i1, v1, a);
+ VecCopyf(i2, i1);
+
+ return 1; /* one intersection only */
+ }
+ /* if not */
+ else {
+ float n[3], t[3];
+ float v3t[3], v4t[3];
+ VecSubf(t, v1, v3);
+
+ /* offset between both plane where the lines lies */
+ Crossf(n, a, b);
+ Projf(t, t, n);
+
+ /* for the first line, offset the second line until it is coplanar */
+ VecAddf(v3t, v3, t);
+ VecAddf(v4t, v4, t);
+
+ VecSubf(c, v3t, v1);
+ VecSubf(a, v2, v1);
+ VecSubf(b, v4t, v3);
+
+ Crossf(ab, a, b);
+ Crossf(cb, c, b);
+
+ VecMulf(a, Inpf(cb, ab) / Inpf(ab, ab));
+ VecAddf(i1, v1, a);
+
+ /* for the second line, just substract the offset from the first intersection point */
+ VecSubf(i2, i1, t);
+
+ return 2; /* two nearest points */
+ }
+}
+
int AabbIntersectAabb(float min1[3], float max1[3], float min2[3], float max2[3])
{
return (min1[0]<max2[0] && min1[1]<max2[1] && min1[2]<max2[2] &&
@@ -3950,7 +4260,7 @@ float lambda_cp_line_ex(float p[3], float l1[3], float l2[3], float cp[3])
}
/* little sister we only need to know lambda */
-float lambda_cp_line(float p[3], float l1[3], float l2[3])
+static float lambda_cp_line(float p[3], float l1[3], float l2[3])
{
float h[3],u[3];
VecSubf(u, l2, l1);
@@ -4166,7 +4476,7 @@ void VecfCubicInterpol(float *x1, float *v1, float *x2, float *v2, float t, floa
v[2]= 3*a[2]*t2 + 2*b[2]*t + v1[2];
}
-int point_in_slice(float p[3], float v1[3], float l1[3], float l2[3])
+static int point_in_slice(float p[3], float v1[3], float l1[3], float l2[3])
{
/*
what is a slice ?
@@ -4193,7 +4503,7 @@ but see a 'spat' which is a deformed cube with paired parallel planes needs only
/*adult sister defining the slice planes by the origin and the normal
NOTE |normal| may not be 1 but defining the thickness of the slice*/
-int point_in_slice_as(float p[3],float origin[3],float normal[3])
+static int point_in_slice_as(float p[3],float origin[3],float normal[3])
{
float h,rp[3];
VecSubf(rp,p,origin);
@@ -4203,7 +4513,7 @@ int point_in_slice_as(float p[3],float origin[3],float normal[3])
}
/*mama (knowing the squared lenght of the normal)*/
-int point_in_slice_m(float p[3],float origin[3],float normal[3],float lns)
+static int point_in_slice_m(float p[3],float origin[3],float normal[3],float lns)
{
float h,rp[3];
VecSubf(rp,p,origin);
@@ -4293,3 +4603,80 @@ void LocQuatSizeToMat4(float mat[][4], float loc[3], float quat[4], float size[3
mat[3][1] = loc[1];
mat[3][2] = loc[2];
}
+
+/* Tangents */
+
+/* For normal map tangents we need to detect uv boundaries, and only average
+ * tangents in case the uvs are connected. Alternative would be to store 1
+ * tangent per face rather than 4 per face vertex, but that's not compatible
+ * with games */
+
+
+/* from BKE_mesh.h */
+#define STD_UV_CONNECT_LIMIT 0.0001f
+
+void sum_or_add_vertex_tangent(void *arena, VertexTangent **vtang, float *tang, float *uv)
+{
+ VertexTangent *vt;
+
+ /* find a tangent with connected uvs */
+ for(vt= *vtang; vt; vt=vt->next) {
+ if(fabs(uv[0]-vt->uv[0]) < STD_UV_CONNECT_LIMIT && fabs(uv[1]-vt->uv[1]) < STD_UV_CONNECT_LIMIT) {
+ VecAddf(vt->tang, vt->tang, tang);
+ return;
+ }
+ }
+
+ /* if not found, append a new one */
+ vt= BLI_memarena_alloc((MemArena *)arena, sizeof(VertexTangent));
+ VecCopyf(vt->tang, tang);
+ vt->uv[0]= uv[0];
+ vt->uv[1]= uv[1];
+
+ if(*vtang)
+ vt->next= *vtang;
+ *vtang= vt;
+}
+
+float *find_vertex_tangent(VertexTangent *vtang, float *uv)
+{
+ VertexTangent *vt;
+ static float nulltang[3] = {0.0f, 0.0f, 0.0f};
+
+ for(vt= vtang; vt; vt=vt->next)
+ if(fabs(uv[0]-vt->uv[0]) < STD_UV_CONNECT_LIMIT && fabs(uv[1]-vt->uv[1]) < STD_UV_CONNECT_LIMIT)
+ return vt->tang;
+
+ return nulltang; /* shouldn't happen, except for nan or so */
+}
+
+void tangent_from_uv(float *uv1, float *uv2, float *uv3, float *co1, float *co2, float *co3, float *n, float *tang)
+{
+ float tangv[3], ct[3], e1[3], e2[3], s1, t1, s2, t2, det;
+
+ s1= uv2[0] - uv1[0];
+ s2= uv3[0] - uv1[0];
+ t1= uv2[1] - uv1[1];
+ t2= uv3[1] - uv1[1];
+ det= 1.0f / (s1 * t2 - s2 * t1);
+
+ /* normals in render are inversed... */
+ VecSubf(e1, co1, co2);
+ VecSubf(e2, co1, co3);
+ tang[0] = (t2*e1[0] - t1*e2[0])*det;
+ tang[1] = (t2*e1[1] - t1*e2[1])*det;
+ tang[2] = (t2*e1[2] - t1*e2[2])*det;
+ tangv[0] = (s1*e2[0] - s2*e1[0])*det;
+ tangv[1] = (s1*e2[1] - s2*e1[1])*det;
+ tangv[2] = (s1*e2[2] - s2*e1[2])*det;
+ Crossf(ct, tang, tangv);
+
+ /* check flip */
+ if ((ct[0]*n[0] + ct[1]*n[1] + ct[2]*n[2]) < 0.0f)
+ VecMulf(tang, -1.0f);
+}
+
+/* used for zoom values*/
+float power_of_2(float val) {
+ return pow(2, ceil(log(val) / log(2)));
+}
diff --git a/source/blender/blenlib/intern/boxpack2d.c b/source/blender/blenlib/intern/boxpack2d.c
index 21810613c7f..db7bae8a91d 100644
--- a/source/blender/blenlib/intern/boxpack2d.c
+++ b/source/blender/blenlib/intern/boxpack2d.c
@@ -42,6 +42,8 @@
#define TRF 2
#define TLF 4
#define BRF 8
+#define CORNERFLAGS (BLF|TRF|TLF|BRF)
+
#define BL 0
#define TR 1
#define TL 2
@@ -130,7 +132,7 @@ static int vertex_sort(const void *p1, const void *p2)
* 'box->index' is not used at all, the only reason its there
* is that the box array is sorted by area and programs need to be able
* to have some way of writing the boxes back to the original data.
- * len - the number of boxes in teh array.
+ * len - the number of boxes in the array.
* tot_width and tot_height are set so you can normalize the data.
* */
void boxPack2D(boxPack *boxarray, int len, float *tot_width, float *tot_height)
@@ -159,7 +161,7 @@ void boxPack2D(boxPack *boxarray, int len, float *tot_width, float *tot_height)
vert->blb = vert->brb = vert->tlb =\
vert->isect_cache[0] = vert->isect_cache[1] =\
vert->isect_cache[2] = vert->isect_cache[3] = NULL;
- vert->free = 15 &~ TRF;
+ vert->free = CORNERFLAGS &~ TRF;
vert->trb = box;
vert->index = i; i++;
box->v[BL] = vert; vert++;
@@ -167,7 +169,7 @@ void boxPack2D(boxPack *boxarray, int len, float *tot_width, float *tot_height)
vert->trb= vert->brb = vert->tlb =\
vert->isect_cache[0] = vert->isect_cache[1] =\
vert->isect_cache[2] = vert->isect_cache[3] = NULL;
- vert->free = 15 &~ BLF;
+ vert->free = CORNERFLAGS &~ BLF;
vert->blb = box;
vert->index = i; i++;
box->v[TR] = vert; vert++;
@@ -175,7 +177,7 @@ void boxPack2D(boxPack *boxarray, int len, float *tot_width, float *tot_height)
vert->trb = vert->blb = vert->tlb =\
vert->isect_cache[0] = vert->isect_cache[1] =\
vert->isect_cache[2] = vert->isect_cache[3] = NULL;
- vert->free = 15 &~ BRF;
+ vert->free = CORNERFLAGS &~ BRF;
vert->brb = box;
vert->index = i; i++;
box->v[TL] = vert; vert++;
@@ -183,7 +185,7 @@ void boxPack2D(boxPack *boxarray, int len, float *tot_width, float *tot_height)
vert->trb = vert->blb = vert->brb =\
vert->isect_cache[0] = vert->isect_cache[1] =\
vert->isect_cache[2] = vert->isect_cache[3] = NULL;
- vert->free = 15 &~ TLF;
+ vert->free = CORNERFLAGS &~ TLF;
vert->tlb = box;
vert->index = i; i++;
box->v[BR] = vert; vert++;
diff --git a/source/blender/blenlib/intern/bpath.c b/source/blender/blenlib/intern/bpath.c
index 17d428a6b10..16eb3ff3865 100644
--- a/source/blender/blenlib/intern/bpath.c
+++ b/source/blender/blenlib/intern/bpath.c
@@ -28,11 +28,13 @@
#include "BLI_bpath.h"
#include "BKE_global.h"
+//XXX #include "BIF_screen.h" /* only for wait cursor */
#include "DNA_ID.h" /* Library */
#include "DNA_vfont_types.h"
#include "DNA_image_types.h"
#include "DNA_sound_types.h"
#include "DNA_scene_types.h" /* to get the current frame */
+#include "DNA_sequence_types.h"
#include <stdlib.h>
#include <string.h>
@@ -40,6 +42,10 @@
#include "BKE_image.h" /* so we can check the image's type */
#include "BKE_utildefines.h"
+#include "MEM_guardedalloc.h"
+
+/* for sequence */
+//XXX #include "BSE_sequence.h"
/* for writing to a textblock */
#include "BKE_text.h"
@@ -66,39 +72,66 @@
#define FILE_MAX 240
-
/* TODO - BPATH_PLUGIN, BPATH_SEQ */
enum BPathTypes {
BPATH_IMAGE = 0,
BPATH_SOUND,
BPATH_FONT,
BPATH_LIB,
+ BPATH_SEQ,
BPATH_DONE
};
-
void BLI_bpathIterator_init( struct BPathIterator *bpi ) {
bpi->type = BPATH_IMAGE;
bpi->data = NULL;
+
+ bpi->getpath_callback = NULL;
+ bpi->setpath_callback = NULL;
+
+ /* Sequencer spesific */
+ bpi->seqdata.totseq = 0;
+ bpi->seqdata.seq = 0;
+ bpi->seqdata.seqar = NULL;
+ bpi->seqdata.scene = NULL;
+
BLI_bpathIterator_step(bpi);
}
-char* BLI_bpathIterator_getPath( struct BPathIterator *bpi) {
- return bpi->path;
+void BLI_bpathIterator_free( struct BPathIterator *bpi ) {
+ if (bpi->seqdata.seqar)
+ MEM_freeN((void *)bpi->seqdata.seqar);
+ bpi->seqdata.seqar = NULL;
+ bpi->seqdata.scene = NULL;
}
-void BLI_bpathIterator_copyPathExpanded( struct BPathIterator *bpi, char *path_expanded) {
- char *filepath, *libpath;
+
+void BLI_bpathIterator_getPath( struct BPathIterator *bpi, char *path) {
+ if (bpi->getpath_callback) {
+ bpi->getpath_callback( bpi, path );
+ } else {
+ strcpy(path, bpi->path); /* warning, we assume 'path' are long enough */
+ }
+}
+
+void BLI_bpathIterator_setPath( struct BPathIterator *bpi, char *path) {
+ if (bpi->setpath_callback) {
+ bpi->setpath_callback( bpi, path );
+ } else {
+ strcpy(bpi->path, path); /* warning, we assume 'path' are long enough */
+ }
+}
+
+void BLI_bpathIterator_getPathExpanded( struct BPathIterator *bpi, char *path_expanded) {
+ char *libpath;
- filepath = BLI_bpathIterator_getPath(bpi);
+ BLI_bpathIterator_getPath(bpi, path_expanded);
libpath = BLI_bpathIterator_getLib(bpi);
- BLI_strncpy(path_expanded, filepath, FILE_MAXDIR*2);
-
if (libpath) { /* check the files location relative to its library path */
- BLI_convertstringcode(path_expanded, libpath, G.scene->r.cfra);
+ BLI_convertstringcode(path_expanded, libpath);
} else { /* local data, use the blend files path */
- BLI_convertstringcode(path_expanded, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(path_expanded, G.sce);
}
}
char* BLI_bpathIterator_getLib( struct BPathIterator *bpi) {
@@ -115,7 +148,7 @@ int BLI_bpathIterator_getPathMaxLen( struct BPathIterator *bpi) {
}
/* gets the first or the next image that has a path - not a viewer node or generated image */
-static struct Image *ima_getpath__internal(struct Image *ima, int step_next) {
+static struct Image *ima_stepdata__internal(struct Image *ima, int step_next) {
if (ima==NULL)
return NULL;
@@ -131,7 +164,7 @@ static struct Image *ima_getpath__internal(struct Image *ima, int step_next) {
return ima;
}
-static struct VFont *vf_getpath__internal(struct VFont *vf, int step_next) {
+static struct VFont *vf_stepdata__internal(struct VFont *vf, int step_next) {
if (vf==NULL)
return NULL;
@@ -149,7 +182,7 @@ static struct VFont *vf_getpath__internal(struct VFont *vf, int step_next) {
return vf;
}
-static struct bSound *snd_getpath__internal(struct bSound *snd, int step_next) {
+static struct bSound *snd_stepdata__internal(struct bSound *snd, int step_next) {
if (snd==NULL)
return NULL;
@@ -167,13 +200,117 @@ static struct bSound *snd_getpath__internal(struct bSound *snd, int step_next) {
return snd;
}
+static struct Sequence *seq_stepdata__internal(struct BPathIterator *bpi, int step_next) {
+ Sequence *seq;
+
+ /* Initializing */
+ if (bpi->seqdata.scene==NULL) {
+ bpi->seqdata.scene= G.main->scene.first;
+ }
+
+ if (step_next) {
+ bpi->seqdata.seq++;
+ }
+
+ while (bpi->seqdata.scene) {
+
+ if (bpi->seqdata.scene->ed) {
+ if (bpi->seqdata.seqar == NULL) {
+ /* allocate the sequencer array */
+ build_seqar( &(((Editing *)bpi->seqdata.scene->ed)->seqbase), &bpi->seqdata.seqar, &bpi->seqdata.totseq);
+ bpi->seqdata.seq = 0;
+ }
+
+ if (bpi->seqdata.seq >= bpi->seqdata.totseq) {
+ seq = NULL;
+ } else {
+ seq = bpi->seqdata.seqar[bpi->seqdata.seq];
+ while (!SEQ_HAS_PATH(seq)) {
+ bpi->seqdata.seq++;
+ if (bpi->seqdata.seq >= bpi->seqdata.totseq) {
+ seq = NULL;
+ break;
+ }
+ seq = bpi->seqdata.seqar[bpi->seqdata.seq];
+ }
+ }
+ if (seq) {
+ return seq;
+ } else {
+ /* keep looking through the next scene, reallocate seq array */
+ if (bpi->seqdata.seqar) {
+ MEM_freeN((void *)bpi->seqdata.seqar);
+ bpi->seqdata.seqar = NULL;
+ }
+ bpi->seqdata.scene = bpi->seqdata.scene->id.next;
+ }
+ } else {
+ /* no seq data in this scene, next */
+ bpi->seqdata.scene = bpi->seqdata.scene->id.next;
+ }
+ }
+
+ return NULL;
+}
+
+static void seq_getpath(struct BPathIterator *bpi, char *path) {
+ Sequence *seq = (Sequence *)bpi->data;
+
+
+ path[0] = '\0'; /* incase we cant get the path */
+ if (seq==NULL) return;
+ if (SEQ_HAS_PATH(seq)) {
+ if (seq->type == SEQ_IMAGE || seq->type == SEQ_MOVIE) {
+ BLI_strncpy(path, seq->strip->dir, FILE_MAX);
+ BLI_add_slash(path); /* incase its missing */
+ if (seq->strip->stripdata) { /* should always be true! */
+ /* Using the first image is weak for image sequences */
+ strcat(path, seq->strip->stripdata->name);
+ }
+ } else {
+ /* simple case */
+ BLI_strncpy(seq->strip->dir, path, sizeof(seq->strip->dir));
+ }
+ }
+}
+
+static void seq_setpath(struct BPathIterator *bpi, char *path) {
+ Sequence *seq = (Sequence *)bpi->data;
+ if (seq==NULL) return;
+
+ if (SEQ_HAS_PATH(seq)) {
+ if (seq->type == SEQ_IMAGE || seq->type == SEQ_MOVIE) {
+ BLI_split_dirfile_basic(path, seq->strip->dir, seq->strip->stripdata->name);
+ } else {
+ /* simple case */
+ BLI_strncpy(seq->strip->dir, path, sizeof(seq->strip->dir));
+ }
+ }
+}
+
+static void bpi_type_step__internal( struct BPathIterator *bpi) {
+ bpi->type++; /* advance to the next type */
+ bpi->data = NULL;
+
+ switch (bpi->type) {
+ case BPATH_SEQ:
+ bpi->getpath_callback = seq_getpath;
+ bpi->setpath_callback = seq_setpath;
+ break;
+ default:
+ bpi->getpath_callback = NULL;
+ bpi->setpath_callback = NULL;
+ break;
+ }
+}
+
void BLI_bpathIterator_step( struct BPathIterator *bpi) {
while (bpi->type != BPATH_DONE) {
if ((bpi->type) == BPATH_IMAGE) {
/*if (bpi->data) bpi->data = ((ID *)bpi->data)->next;*/
- if (bpi->data) bpi->data = ima_getpath__internal( (Image *)bpi->data, 1 ); /* must skip images that have no path */
- else bpi->data = ima_getpath__internal(G.main->image.first, 0);
+ if (bpi->data) bpi->data = ima_stepdata__internal( (Image *)bpi->data, 1 ); /* must skip images that have no path */
+ else bpi->data = ima_stepdata__internal(G.main->image.first, 0);
if (bpi->data) {
/* get the path info from this datatype */
@@ -188,13 +325,13 @@ void BLI_bpathIterator_step( struct BPathIterator *bpi) {
break;
} else {
- bpi->type+=1; /* advance to the next type */
+ bpi_type_step__internal(bpi);
}
} else if ((bpi->type) == BPATH_SOUND) {
- if (bpi->data) bpi->data = snd_getpath__internal( (bSound *)bpi->data, 1 ); /* must skip images that have no path */
- else bpi->data = snd_getpath__internal(G.main->sound.first, 0);
+ if (bpi->data) bpi->data = snd_stepdata__internal( (bSound *)bpi->data, 1 ); /* must skip images that have no path */
+ else bpi->data = snd_stepdata__internal(G.main->sound.first, 0);
if (bpi->data) {
/* get the path info from this datatype */
@@ -208,14 +345,14 @@ void BLI_bpathIterator_step( struct BPathIterator *bpi) {
/* we are done, advancing to the next item, this type worked fine */
break;
} else {
- bpi->type+=1; /* advance to the next type */
+ bpi_type_step__internal(bpi);
}
} else if ((bpi->type) == BPATH_FONT) {
- if (bpi->data) bpi->data = vf_getpath__internal( (VFont *)bpi->data, 1 );
- else bpi->data = vf_getpath__internal( G.main->vfont.first, 0 );
+ if (bpi->data) bpi->data = vf_stepdata__internal( (VFont *)bpi->data, 1 );
+ else bpi->data = vf_stepdata__internal( G.main->vfont.first, 0 );
if (bpi->data) {
/* get the path info from this datatype */
@@ -229,12 +366,10 @@ void BLI_bpathIterator_step( struct BPathIterator *bpi) {
/* we are done, advancing to the next item, this type worked fine */
break;
} else {
- bpi->type+=1; /* advance to the next type */
+ bpi_type_step__internal(bpi);
}
-
} else if ((bpi->type) == BPATH_LIB) {
-
if (bpi->data) bpi->data = ((ID *)bpi->data)->next;
else bpi->data = G.main->library.first;
@@ -250,7 +385,19 @@ void BLI_bpathIterator_step( struct BPathIterator *bpi) {
/* we are done, advancing to the next item, this type worked fine */
break;
} else {
- bpi->type+=1; /* advance to the next type */
+ bpi_type_step__internal(bpi);
+ }
+ } else if ((bpi->type) == BPATH_SEQ) {
+ if (bpi->data) bpi->data = seq_stepdata__internal( bpi, 1 );
+ else bpi->data = seq_stepdata__internal( bpi, 0 );
+ if (bpi->data) {
+ Sequence *seq = (Sequence *)bpi->data;
+ bpi->lib = NULL;
+ bpi->name = seq->name+2;
+ bpi->len = sizeof(seq->strip->stripdata->name);
+ break;
+ } else {
+ bpi_type_step__internal(bpi);
}
}
}
@@ -279,6 +426,9 @@ static void bpathToText(Text *btxt, struct BPathIterator *bpi)
case BPATH_LIB:
txt_insert_buf( btxt, "Library \"" );
break;
+ case BPATH_SEQ:
+ txt_insert_buf( btxt, "Sequence \"" );
+ break;
default:
txt_insert_buf( btxt, "Unknown \"" );
break;
@@ -291,7 +441,7 @@ static void bpathToText(Text *btxt, struct BPathIterator *bpi)
}
txt_insert_buf( btxt, "\" " );
- BLI_bpathIterator_copyPathExpanded(bpi, path_expanded);
+ BLI_bpathIterator_getPathExpanded(bpi, path_expanded);
txt_insert_buf( btxt, path_expanded );
txt_insert_buf( btxt, "\n" );
@@ -299,74 +449,148 @@ static void bpathToText(Text *btxt, struct BPathIterator *bpi)
}
/* high level function */
-Text *checkMissingFiles(void) {
+void checkMissingFiles( char *txtname ) {
Text *btxt = NULL;
struct BPathIterator bpi;
/* be sure there is low chance of the path being too short */
char filepath_expanded[FILE_MAXDIR*2];
- char *filepath, *libpath;
- int files_missing = 0;
BLI_bpathIterator_init(&bpi);
while (!BLI_bpathIterator_isDone(&bpi)) {
- filepath = BLI_bpathIterator_getPath(&bpi);
- libpath = BLI_bpathIterator_getLib(&bpi);
-
- BLI_bpathIterator_copyPathExpanded( &bpi, filepath_expanded );
+ BLI_bpathIterator_getPathExpanded( &bpi, filepath_expanded );
if (!BLI_exists(filepath_expanded)) {
- if (!btxt)
- btxt = add_empty_text( "missing_files.txt" );
-
+ if (!btxt) {
+ btxt = add_empty_text( "missing_files.log" );
+ if (txtname) {
+ BLI_strncpy(txtname, btxt->id.name+2, 24);
+ }
+ }
bpathToText(btxt, &bpi);
- files_missing = 1;
}
BLI_bpathIterator_step(&bpi);
}
- return btxt;
+ BLI_bpathIterator_free(&bpi);
}
/* dont log any errors at the moment, should probably do this */
-void makeFilesRelative(int *tot, int *changed, int *failed, int *linked) {
+void makeFilesRelative(char *txtname, int *tot, int *changed, int *failed, int *linked) {
struct BPathIterator bpi;
- char *filepath, *libpath;
+ char filepath[FILE_MAX], *libpath;
/* be sure there is low chance of the path being too short */
char filepath_relative[(FILE_MAXDIR * 2) + FILE_MAXFILE];
+ Text *btxt = NULL;
+
*tot = *changed = *failed = *linked = 0;
BLI_bpathIterator_init(&bpi);
while (!BLI_bpathIterator_isDone(&bpi)) {
- filepath = BLI_bpathIterator_getPath(&bpi);
+ BLI_bpathIterator_getPath(&bpi, filepath);
libpath = BLI_bpathIterator_getLib(&bpi);
if(strncmp(filepath, "//", 2)) {
- if (libpath) { /* cant make relative if we are kibrary - TODO, LOG THIS */
+ if (libpath) { /* cant make relative if we are library - TODO, LOG THIS */
(*linked)++;
} else { /* local data, use the blend files path */
BLI_strncpy(filepath_relative, filepath, sizeof(filepath_relative));
+ /* Important BLI_cleanup_dir runs before the path is made relative
+ * because it wont work for paths that start with "//../" */
+ BLI_cleanup_file(G.sce, filepath_relative); /* fix any /foo/../foo/ */
BLI_makestringcode(G.sce, filepath_relative);
- if (BLI_bpathIterator_getPathMaxLen(&bpi) < strlen(filepath_relative)) {
+ /* be safe and check the length */
+ if (BLI_bpathIterator_getPathMaxLen(&bpi) <= strlen(filepath_relative)) {
+ if (!btxt) {
+ btxt = add_empty_text( "missing_no_rel.log" );
+ if (txtname) {
+ BLI_strncpy(txtname, btxt->id.name+2, 24);
+ }
+ }
+ bpathToText(btxt, &bpi);
(*failed)++;
} else {
- /* safe to to check the length */
if(strncmp(filepath_relative, "//", 2)==0) {
- strcpy(filepath, filepath_relative);
+ BLI_bpathIterator_setPath(&bpi, filepath_relative);
(*changed)++;
} else {
+ if (!btxt) {
+ btxt = add_empty_text( "missing_no_rel.log" );
+ if (txtname) {
+ BLI_strncpy(txtname, btxt->id.name+2, 24);
+ }
+ }
+ bpathToText(btxt, &bpi);
(*failed)++;
}
}
}
}
+ BLI_bpathIterator_step(&bpi);
+ (*tot)++;
+ }
+ BLI_bpathIterator_free(&bpi);
+}
+
+/* dont log any errors at the moment, should probably do this -
+ * Verry similar to makeFilesRelative - keep in sync! */
+void makeFilesAbsolute(char *txtname, int *tot, int *changed, int *failed, int *linked) {
+ struct BPathIterator bpi;
+ char filepath[FILE_MAX], *libpath;
+
+ /* be sure there is low chance of the path being too short */
+ char filepath_absolute[(FILE_MAXDIR * 2) + FILE_MAXFILE];
+
+ Text *btxt = NULL;
+
+ *tot = *changed = *failed = *linked = 0;
+
+ BLI_bpathIterator_init(&bpi);
+ while (!BLI_bpathIterator_isDone(&bpi)) {
+ BLI_bpathIterator_getPath(&bpi, filepath);
+ libpath = BLI_bpathIterator_getLib(&bpi);
+ if(strncmp(filepath, "//", 2)==0) {
+ if (libpath) { /* cant make absolute if we are library - TODO, LOG THIS */
+ (*linked)++;
+ } else { /* get the expanded path and check it is relative or too long */
+ BLI_bpathIterator_getPathExpanded( &bpi, filepath_absolute );
+ BLI_cleanup_file(G.sce, filepath_absolute); /* fix any /foo/../foo/ */
+ /* to be safe, check the length */
+ if (BLI_bpathIterator_getPathMaxLen(&bpi) <= strlen(filepath_absolute)) {
+ if (!btxt) {
+ btxt = add_empty_text( "missing_no_abs.log" );
+ if (txtname) {
+ BLI_strncpy(txtname, btxt->id.name+2, 24);
+ }
+ }
+ bpathToText(btxt, &bpi);
+ (*failed)++;
+ } else {
+ if(strncmp(filepath_absolute, "//", 2)) {
+ BLI_bpathIterator_setPath(&bpi, filepath_absolute);
+ (*changed)++;
+ } else {
+ if (!btxt) {
+ btxt = add_empty_text( "missing_no_abs.log" );
+ if (txtname) {
+ BLI_strncpy(txtname, btxt->id.name+2, 24);
+ }
+ }
+ bpathToText(btxt, &bpi);
+ (*failed)++;
+ }
+ }
+ }
+ }
BLI_bpathIterator_step(&bpi);
(*tot)++;
}
+ BLI_bpathIterator_free(&bpi);
}
+
/* find this file recursively, use the biggest file so thumbnails dont get used by mistake
- dir: subdir to search
- filename: set this filename
@@ -377,14 +601,11 @@ static int findFileRecursive(char *filename_new, const char *dirname, const char
{
/* file searching stuff */
DIR *dir;
- int file = 0;
struct dirent *de;
struct stat status;
char path[FILE_MAX];
int size;
- printf("DIR %s\n", dirname);
-
dir = opendir(dirname);
if (dir==0)
@@ -406,14 +627,10 @@ static int findFileRecursive(char *filename_new, const char *dirname, const char
if (S_ISREG(status.st_mode)) { /* is file */
if (strncmp(filename, de->d_name, FILE_MAX)==0) { /* name matches */
/* open the file to read its size */
- file = open(path, O_BINARY|O_RDONLY);
- if (file >=0 ) {
- size = BLI_filesize(file);
- if (size > *filesize) { /* find the biggest file */
- *filesize = size;
- BLI_strncpy(filename_new, path, FILE_MAX);
- }
- close(file);
+ size = BLI_filepathsize(path);
+ if ((size > 0) && (size > *filesize)) { /* find the biggest file */
+ *filesize = size;
+ BLI_strncpy(filename_new, path, FILE_MAX);
}
}
} else if (S_ISDIR(status.st_mode)) { /* is subdir */
@@ -434,28 +651,35 @@ void findMissingFiles(char *str) {
/* be sure there is low chance of the path being too short */
char filepath_expanded[FILE_MAXDIR*2];
- char *filepath, *libpath;
+ char filepath[FILE_MAX], *libpath;
int filesize, recur_depth;
- char dirname[FILE_MAX], filename[FILE_MAX], filename_new[FILE_MAX], dummyname[FILE_MAX];
+ char dirname[FILE_MAX], filename[FILE_MAX], filename_new[FILE_MAX];
+
+ //XXX waitcursor( 1 );
- BLI_split_dirfile(str, dirname, dummyname);
+ BLI_split_dirfile_basic(str, dirname, NULL);
BLI_bpathIterator_init(&bpi);
while (!BLI_bpathIterator_isDone(&bpi)) {
- filepath = BLI_bpathIterator_getPath(&bpi);
+ BLI_bpathIterator_getPath(&bpi, filepath);
libpath = BLI_bpathIterator_getLib(&bpi);
+ /* Check if esc was pressed because searching files can be slow */
+ /*XXX if (blender_test_break()) {
+ break;
+ }*/
+
if (libpath==NULL) {
- BLI_bpathIterator_copyPathExpanded( &bpi, filepath_expanded );
+ BLI_bpathIterator_getPathExpanded( &bpi, filepath_expanded );
if (!BLI_exists(filepath_expanded)) {
/* can the dir be opened? */
filesize = -1;
recur_depth = 0;
- BLI_split_dirfile(filepath, dummyname, filename); /* the file to find */
+ BLI_split_dirfile_basic(filepath, NULL, filename); /* the file to find */
findFileRecursive(filename_new, dirname, filename, &filesize, &recur_depth);
if (filesize == -1) { /* could not open dir */
@@ -472,11 +696,14 @@ void findMissingFiles(char *str) {
if (G.relbase_valid)
BLI_makestringcode(G.sce, filename_new);
- strcpy( BLI_bpathIterator_getPath( &bpi ), filename_new );
+ BLI_bpathIterator_setPath( &bpi, filename_new );
}
}
}
}
BLI_bpathIterator_step(&bpi);
}
+ BLI_bpathIterator_free(&bpi);
+
+ //XXX waitcursor( 0 );
}
diff --git a/source/blender/blenlib/intern/dynlib.c b/source/blender/blenlib/intern/dynlib.c
index c4692995f20..858aa6e60bf 100644
--- a/source/blender/blenlib/intern/dynlib.c
+++ b/source/blender/blenlib/intern/dynlib.c
@@ -77,12 +77,9 @@ char *PIL_dynlib_get_error_as_string(PILdynlib* lib) {
int err;
/* if lib is NULL reset the last error code */
- if (!lib) {
- SetLastError(ERROR_SUCCESS);
- return NULL;
- }
-
err= GetLastError();
+ if (!lib) SetLastError(ERROR_SUCCESS);
+
if (err) {
static char buf[1024];
@@ -96,7 +93,7 @@ char *PIL_dynlib_get_error_as_string(PILdynlib* lib) {
return buf;
}
- return NULL;
+ return err;
}
void PIL_dynlib_close(PILdynlib *lib) {
diff --git a/source/blender/blenlib/intern/edgehash.c b/source/blender/blenlib/intern/edgehash.c
index 6aa0ded63b9..603c85655d7 100644
--- a/source/blender/blenlib/intern/edgehash.c
+++ b/source/blender/blenlib/intern/edgehash.c
@@ -77,8 +77,12 @@ void BLI_edgehash_insert(EdgeHash *eh, int v0, int v1, void *val) {
unsigned int hash;
Entry *e= malloc(sizeof(*e));
- if (v1<v0) v0 ^= v1 ^= v0 ^= v1;
- hash = EDGEHASH(v0,v1)%eh->nbuckets;
+ if (v1<v0) {
+ v0 ^= v1;
+ v1 ^= v0;
+ v0 ^= v1;
+ }
+ hash = EDGEHASH(v0,v1)%eh->nbuckets;
e->v0 = v0;
e->v1 = v1;
@@ -114,7 +118,11 @@ void** BLI_edgehash_lookup_p(EdgeHash *eh, int v0, int v1) {
unsigned int hash;
Entry *e;
- if (v1<v0) v0 ^= v1 ^= v0 ^= v1;
+ if (v1<v0) {
+ v0 ^= v1;
+ v1 ^= v0;
+ v0 ^= v1;
+ }
hash = EDGEHASH(v0,v1)%eh->nbuckets;
for (e= eh->buckets[hash]; e; e= e->next)
if (v0==e->v0 && v1==e->v1)
@@ -200,6 +208,11 @@ void *BLI_edgehashIterator_getValue(EdgeHashIterator *ehi) {
return ehi->curEntry?ehi->curEntry->val:NULL;
}
+void BLI_edgehashIterator_setValue(EdgeHashIterator *ehi, void *val) {
+ if(ehi->curEntry)
+ ehi->curEntry->val= val;
+}
+
void BLI_edgehashIterator_step(EdgeHashIterator *ehi) {
if (ehi->curEntry) {
ehi->curEntry= ehi->curEntry->next;
diff --git a/source/blender/blenlib/intern/fileops.c b/source/blender/blenlib/intern/fileops.c
index f55cd05e53e..a64185a896a 100644
--- a/source/blender/blenlib/intern/fileops.c
+++ b/source/blender/blenlib/intern/fileops.c
@@ -6,7 +6,7 @@
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
+ * of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -56,6 +56,8 @@
#include "BKE_utildefines.h"
#include <errno.h>
+#include "BLO_sys_types.h" // for intptr_t support
+
/* implementations: */
char *first_slash(char *string) {
char *ffslash, *fbslash;
@@ -66,11 +68,11 @@ char *first_slash(char *string) {
if (!ffslash) return fbslash;
else if (!fbslash) return ffslash;
- if ((long)ffslash < (long)fbslash) return ffslash;
+ if ((intptr_t)ffslash < (intptr_t)fbslash) return ffslash;
else return fbslash;
}
-char *BLI_last_slash(char *string) {
+char *BLI_last_slash(const char *string) {
char *lfslash, *lbslash;
lfslash= strrchr(string, '/');
@@ -79,10 +81,43 @@ char *BLI_last_slash(char *string) {
if (!lfslash) return lbslash;
else if (!lbslash) return lfslash;
- if ((long)lfslash < (long)lbslash) return lbslash;
+ if ((intptr_t)lfslash < (intptr_t)lbslash) return lbslash;
else return lfslash;
}
+/* adds a slash if there isnt one there alredy */
+void BLI_add_slash(char *string) {
+ int len = strlen(string);
+#ifdef WIN32
+ if (len==0 || string[len-1]!='\\') {
+ string[len] = '\\';
+ string[len+1] = '\0';
+ }
+#else
+ if (len==0 || string[len-1]!='/') {
+ string[len] = '/';
+ string[len+1] = '\0';
+ }
+#endif
+}
+
+/* removes a slash if there is one */
+void BLI_del_slash(char *string) {
+ int len = strlen(string);
+ while (len) {
+#ifdef WIN32
+ if (string[len-1]=='\\') {
+#else
+ if (string[len-1]=='/') {
+#endif
+ string[len-1] = '\0';
+ len--;
+ } else {
+ break;
+ }
+ }
+}
+
/* gzip the file in from and write it to "to".
return -1 if zlib fails, -2 if the originating file does not exist
note: will remove the "from" file
@@ -131,6 +166,23 @@ int BLI_is_writable(char *filename)
}
}
+int BLI_touch(const char *file)
+{
+ FILE *f = fopen(file,"r+b");
+ if (f != NULL) {
+ char c = getc(f);
+ rewind(f);
+ putc(c,f);
+ } else {
+ f = fopen(file,"wb");
+ }
+ if (f) {
+ fclose(f);
+ return 1;
+ }
+ return 0;
+}
+
#ifdef WIN32
static char str[MAXPATHLEN+12];
@@ -152,12 +204,6 @@ int BLI_delete(char *file, int dir, int recursive) {
return err;
}
-int BLI_touch(char *file) {
- callLocalErrorCallBack("Touching files is unsupported on Windows");
-
- return 1;
-}
-
int BLI_move(char *file, char *to) {
int err;
@@ -214,12 +260,6 @@ int BLI_link(char *file, char *to) {
return 1;
}
-int BLI_backup(char *file, char *from, char *to) {
- callLocalErrorCallBack("Backing up files is unsupported on Windows");
-
- return 1;
-}
-
int BLI_exists(char *file) {
return (GetFileAttributes(file) != 0xFFFFFFFF);
}
@@ -257,7 +297,8 @@ void BLI_recurdir_fileops(char *dirname) {
int BLI_rename(char *from, char *to) {
if (!BLI_exists(from)) return 0;
- if (BLI_exists(to))
+ /* make sure the filenames are different (case insensitive) before removing */
+ if (BLI_exists(to) && BLI_strcasecmp(from, to))
if(BLI_delete(to, 0, 0)) return 1;
return rename(from, to);
@@ -278,26 +319,21 @@ int BLI_delete(char *file, int dir, int recursive)
printf("Error: not deleted file %s because of quote!\n", file);
}
else {
- if (recursive) sprintf(str, "/bin/rm -rf \"%s\"", file);
- else if (dir) sprintf(str, "/bin/rmdir \"%s\"", file);
- else sprintf(str, "/bin/rm -f \"%s\"", file);
-
- return system(str);
+ if (recursive) {
+ sprintf(str, "/bin/rm -rf \"%s\"", file);
+ return system(str);
+ }
+ else if (dir) {
+ sprintf(str, "/bin/rmdir \"%s\"", file);
+ return system(str);
+ }
+ else {
+ return remove(file); //sprintf(str, "/bin/rm -f \"%s\"", file);
+ }
}
return -1;
}
-int BLI_touch(char *file)
-{
-
- if( BLI_exists("/bin/touch") )
- sprintf(str, "/bin/touch %s", file);
- else
- sprintf(str, "/usr/bin/touch %s", file);
-
- return system(str);
-}
-
int BLI_move(char *file, char *to) {
sprintf(str, "/bin/mv -f \"%s\" \"%s\"", file, to);
@@ -316,12 +352,6 @@ int BLI_link(char *file, char *to) {
return system(str);
}
-int BLI_backup(char *file, char *from, char *to) {
- sprintf(str, "/bin/su root -c 'cd %s; /bin/tar cf - \"%s\" | (/bin/cd %s; /bin/tar xf -)'", from, file, to);
-
- return system(str);
-}
-
int BLI_exists(char *file) {
return BLI_exist(file);
}
diff --git a/source/blender/blenlib/intern/freetypefont.c b/source/blender/blenlib/intern/freetypefont.c
index f788f9cf255..2c114ea6971 100644
--- a/source/blender/blenlib/intern/freetypefont.c
+++ b/source/blender/blenlib/intern/freetypefont.c
@@ -151,7 +151,7 @@ void freetypechar_to_vchar(FT_Face face, FT_ULong charcode, VFontData *vfd)
nu->type= CU_BEZIER+CU_2D;
nu->pntsu = onpoints[j];
nu->resolu= 8;
- nu->flagu= 1;
+ nu->flagu= CU_CYCLIC;
nu->bezt = bezt;
//individual curve loop, start-end
@@ -399,8 +399,6 @@ static VFontData *objfnt_to_ftvfontdata(PackedFile * pf)
break;
lcode = charcode;
}
-
- err = FT_Set_Charmap( face, (FT_CharMap) FT_ENCODING_UNICODE );
return vfd;
}
diff --git a/source/blender/blenlib/intern/graph.c b/source/blender/blenlib/intern/graph.c
new file mode 100644
index 00000000000..8f35b38379e
--- /dev/null
+++ b/source/blender/blenlib/intern/graph.c
@@ -0,0 +1,1087 @@
+/**
+ * $Id:
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * Contributor(s): Martin Poirier
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ * graph.c: Common graph interface and methods
+ */
+
+#include <float.h>
+#include <math.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_graph.h"
+#include "BLI_blenlib.h"
+#include "BLI_arithb.h"
+
+#include "BKE_utildefines.h"
+
+static void testRadialSymmetry(BGraph *graph, BNode* root_node, RadialArc* ring, int total, float axis[3], float limit, int group);
+
+static void handleAxialSymmetry(BGraph *graph, BNode *root_node, int depth, float axis[3], float limit);
+static void testAxialSymmetry(BGraph *graph, BNode* root_node, BNode* node1, BNode* node2, BArc* arc1, BArc* arc2, float axis[3], float limit, int group);
+static void flagAxialSymmetry(BNode *root_node, BNode *end_node, BArc *arc, int group);
+
+void BLI_freeNode(BGraph *graph, BNode *node)
+{
+ if (node->arcs)
+ {
+ MEM_freeN(node->arcs);
+ }
+
+ if (graph->free_node)
+ {
+ graph->free_node(node);
+ }
+}
+
+void BLI_removeNode(BGraph *graph, BNode *node)
+{
+ BLI_freeNode(graph, node);
+ BLI_freelinkN(&graph->nodes, node);
+}
+
+BNode *BLI_otherNode(BArc *arc, BNode *node)
+{
+ return (arc->head == node) ? arc->tail : arc->head;
+}
+
+void BLI_removeArc(BGraph *graph, BArc *arc)
+{
+ if (graph->free_arc)
+ {
+ graph->free_arc(arc);
+ }
+
+ BLI_freelinkN(&graph->arcs, arc);
+}
+
+void BLI_flagNodes(BGraph *graph, int flag)
+{
+ BNode *node;
+
+ for(node = graph->nodes.first; node; node = node->next)
+ {
+ node->flag = flag;
+ }
+}
+
+void BLI_flagArcs(BGraph *graph, int flag)
+{
+ BArc *arc;
+
+ for(arc = graph->arcs.first; arc; arc = arc->next)
+ {
+ arc->flag = flag;
+ }
+}
+
+static void addArcToNodeAdjacencyList(BNode *node, BArc *arc)
+{
+ node->arcs[node->flag] = arc;
+ node->flag++;
+}
+
+void BLI_buildAdjacencyList(BGraph *graph)
+{
+ BNode *node;
+ BArc *arc;
+
+ for(node = graph->nodes.first; node; node = node->next)
+ {
+ if (node->arcs != NULL)
+ {
+ MEM_freeN(node->arcs);
+ }
+
+ node->arcs = MEM_callocN((node->degree) * sizeof(BArc*), "adjacency list");
+
+ /* temporary use to indicate the first index available in the lists */
+ node->flag = 0;
+ }
+
+ for(arc = graph->arcs.first; arc; arc= arc->next)
+ {
+ addArcToNodeAdjacencyList(arc->head, arc);
+ addArcToNodeAdjacencyList(arc->tail, arc);
+ }
+
+ for(node = graph->nodes.first; node; node = node->next)
+ {
+ if (node->degree != node->flag)
+ {
+ printf("error in node [%p]. Added only %i arcs out of %i\n", node, node->flag, node->degree);
+ }
+ }
+}
+
+void BLI_rebuildAdjacencyListForNode(BGraph* graph, BNode *node)
+{
+ BArc *arc;
+
+ if (node->arcs != NULL)
+ {
+ MEM_freeN(node->arcs);
+ }
+
+ node->arcs = MEM_callocN((node->degree) * sizeof(BArc*), "adjacency list");
+
+ /* temporary use to indicate the first index available in the lists */
+ node->flag = 0;
+
+ for(arc = graph->arcs.first; arc; arc= arc->next)
+ {
+ if (arc->head == node)
+ {
+ addArcToNodeAdjacencyList(arc->head, arc);
+ }
+ else if (arc->tail == node)
+ {
+ addArcToNodeAdjacencyList(arc->tail, arc);
+ }
+ }
+
+ if (node->degree != node->flag)
+ {
+ printf("error in node [%p]. Added only %i arcs out of %i\n", node, node->flag, node->degree);
+ }
+}
+
+void BLI_freeAdjacencyList(BGraph *graph)
+{
+ BNode *node;
+
+ for(node = graph->nodes.first; node; node = node->next)
+ {
+ if (node->arcs != NULL)
+ {
+ MEM_freeN(node->arcs);
+ node->arcs = NULL;
+ }
+ }
+}
+
+int BLI_hasAdjacencyList(BGraph *graph)
+{
+ BNode *node;
+
+ for(node = graph->nodes.first; node; node = node->next)
+ {
+ if (node->arcs == NULL)
+ {
+ return 0;
+ }
+ }
+
+ return 1;
+}
+
+void BLI_replaceNodeInArc(BGraph *graph, BArc *arc, BNode *node_src, BNode *node_replaced)
+{
+ if (arc->head == node_replaced)
+ {
+ arc->head = node_src;
+ node_src->degree++;
+ }
+
+ if (arc->tail == node_replaced)
+ {
+ arc->tail = node_src;
+ node_src->degree++;
+ }
+
+ if (arc->head == arc->tail)
+ {
+ node_src->degree -= 2;
+
+ graph->free_arc(arc);
+ BLI_freelinkN(&graph->arcs, arc);
+ }
+
+ if (node_replaced->degree == 0)
+ {
+ BLI_removeNode(graph, node_replaced);
+ }
+}
+
+void BLI_replaceNode(BGraph *graph, BNode *node_src, BNode *node_replaced)
+{
+ BArc *arc, *next_arc;
+
+ for (arc = graph->arcs.first; arc; arc = next_arc)
+ {
+ next_arc = arc->next;
+
+ if (arc->head == node_replaced)
+ {
+ arc->head = node_src;
+ node_replaced->degree--;
+ node_src->degree++;
+ }
+
+ if (arc->tail == node_replaced)
+ {
+ arc->tail = node_src;
+ node_replaced->degree--;
+ node_src->degree++;
+ }
+
+ if (arc->head == arc->tail)
+ {
+ node_src->degree -= 2;
+
+ graph->free_arc(arc);
+ BLI_freelinkN(&graph->arcs, arc);
+ }
+ }
+
+ if (node_replaced->degree == 0)
+ {
+ BLI_removeNode(graph, node_replaced);
+ }
+}
+
+void BLI_removeDoubleNodes(BGraph *graph, float limit)
+{
+ BNode *node_src, *node_replaced;
+
+ for(node_src = graph->nodes.first; node_src; node_src = node_src->next)
+ {
+ for(node_replaced = graph->nodes.first; node_replaced; node_replaced = node_replaced->next)
+ {
+ if (node_replaced != node_src && VecLenf(node_replaced->p, node_src->p) <= limit)
+ {
+ BLI_replaceNode(graph, node_src, node_replaced);
+ }
+ }
+ }
+
+}
+
+BNode * BLI_FindNodeByPosition(BGraph *graph, float *p, float limit)
+{
+ BNode *closest_node = NULL, *node;
+ float min_distance;
+
+ for(node = graph->nodes.first; node; node = node->next)
+ {
+ float distance = VecLenf(p, node->p);
+ if (distance <= limit && (closest_node == NULL || distance < min_distance))
+ {
+ closest_node = node;
+ min_distance = distance;
+ }
+ }
+
+ return closest_node;
+}
+/************************************* SUBGRAPH DETECTION **********************************************/
+
+void flagSubgraph(BNode *node, int subgraph)
+{
+ if (node->subgraph_index == 0)
+ {
+ BArc *arc;
+ int i;
+
+ node->subgraph_index = subgraph;
+
+ for(i = 0; i < node->degree; i++)
+ {
+ arc = node->arcs[i];
+ flagSubgraph(BLI_otherNode(arc, node), subgraph);
+ }
+ }
+}
+
+int BLI_FlagSubgraphs(BGraph *graph)
+{
+ BNode *node;
+ int subgraph = 0;
+
+ if (BLI_hasAdjacencyList(graph) == 0)
+ {
+ BLI_buildAdjacencyList(graph);
+ }
+
+ for(node = graph->nodes.first; node; node = node->next)
+ {
+ node->subgraph_index = 0;
+ }
+
+ for (node = graph->nodes.first; node; node = node->next)
+ {
+ if (node->subgraph_index == 0)
+ {
+ subgraph++;
+ flagSubgraph(node, subgraph);
+ }
+ }
+
+ return subgraph;
+}
+
+void BLI_ReflagSubgraph(BGraph *graph, int old_subgraph, int new_subgraph)
+{
+ BNode *node;
+
+ for (node = graph->nodes.first; node; node = node->next)
+ {
+ if (node->flag == old_subgraph)
+ {
+ node->flag = new_subgraph;
+ }
+ }
+}
+
+/*************************************** CYCLE DETECTION ***********************************************/
+
+int detectCycle(BNode *node, BArc *src_arc)
+{
+ int value = 0;
+
+ if (node->flag == 0)
+ {
+ int i;
+
+ /* mark node as visited */
+ node->flag = 1;
+
+ for(i = 0; i < node->degree && value == 0; i++)
+ {
+ BArc *arc = node->arcs[i];
+
+ /* don't go back on the source arc */
+ if (arc != src_arc)
+ {
+ value = detectCycle(BLI_otherNode(arc, node), arc);
+ }
+ }
+ }
+ else
+ {
+ value = 1;
+ }
+
+ return value;
+}
+
+int BLI_isGraphCyclic(BGraph *graph)
+{
+ BNode *node;
+ int value = 0;
+
+ /* NEED TO CHECK IF ADJACENCY LIST EXIST */
+
+ /* Mark all nodes as not visited */
+ BLI_flagNodes(graph, 0);
+
+ /* detectCycles in subgraphs */
+ for(node = graph->nodes.first; node && value == 0; node = node->next)
+ {
+ /* only for nodes in subgraphs that haven't been visited yet */
+ if (node->flag == 0)
+ {
+ value = value || detectCycle(node, NULL);
+ }
+ }
+
+ return value;
+}
+
+BArc * BLI_findConnectedArc(BGraph *graph, BArc *arc, BNode *v)
+{
+ BArc *nextArc = arc->next;
+
+ for(nextArc = graph->arcs.first; nextArc; nextArc = nextArc->next)
+ {
+ if (arc != nextArc && (nextArc->head == v || nextArc->tail == v))
+ {
+ break;
+ }
+ }
+
+ return nextArc;
+}
+
+/*********************************** GRAPH AS TREE FUNCTIONS *******************************************/
+
+int subtreeShape(BNode *node, BArc *rootArc, int include_root)
+{
+ int depth = 0;
+
+ node->flag = 1;
+
+ if (include_root)
+ {
+ BNode *newNode = BLI_otherNode(rootArc, node);
+ return subtreeShape(newNode, rootArc, 0);
+ }
+ else
+ {
+ /* Base case, no arcs leading away */
+ if (node->arcs == NULL || *(node->arcs) == NULL)
+ {
+ return 0;
+ }
+ else
+ {
+ int i;
+
+ for(i = 0; i < node->degree; i++)
+ {
+ BArc *arc = node->arcs[i];
+ BNode *newNode = BLI_otherNode(arc, node);
+
+ /* stop immediate and cyclic backtracking */
+ if (arc != rootArc && newNode->flag == 0)
+ {
+ depth += subtreeShape(newNode, arc, 0);
+ }
+ }
+ }
+
+ return SHAPE_RADIX * depth + 1;
+ }
+}
+
+int BLI_subtreeShape(BGraph *graph, BNode *node, BArc *rootArc, int include_root)
+{
+ BNode *test_node;
+
+ BLI_flagNodes(graph, 0);
+ return subtreeShape(node, rootArc, include_root);
+}
+
+float BLI_subtreeLength(BNode *node)
+{
+ float length = 0;
+ int i;
+
+ node->flag = 0; /* flag node as visited */
+
+ for(i = 0; i < node->degree; i++)
+ {
+ BArc *arc = node->arcs[i];
+ BNode *other_node = BLI_otherNode(arc, node);
+
+ if (other_node->flag != 0)
+ {
+ float subgraph_length = arc->length + BLI_subtreeLength(other_node);
+ length = MAX2(length, subgraph_length);
+ }
+ }
+
+ return length;
+}
+
+void BLI_calcGraphLength(BGraph *graph)
+{
+ float length = 0;
+ int nb_subgraphs;
+ int i;
+
+ nb_subgraphs = BLI_FlagSubgraphs(graph);
+
+ for (i = 1; i <= nb_subgraphs; i++)
+ {
+ BNode *node;
+
+ for (node = graph->nodes.first; node; node = node->next)
+ {
+ /* start on an external node of the subgraph */
+ if (node->subgraph_index == i && node->degree == 1)
+ {
+ float subgraph_length = BLI_subtreeLength(node);
+ length = MAX2(length, subgraph_length);
+ break;
+ }
+ }
+ }
+
+ graph->length = length;
+}
+
+/********************************* SYMMETRY DETECTION **************************************************/
+
+void markdownSymmetryArc(BGraph *graph, BArc *arc, BNode *node, int level, float limit);
+
+void BLI_mirrorAlongAxis(float v[3], float center[3], float axis[3])
+{
+ float dv[3], pv[3];
+
+ VecSubf(dv, v, center);
+ Projf(pv, dv, axis);
+ VecMulf(pv, -2);
+ VecAddf(v, v, pv);
+}
+
+static void testRadialSymmetry(BGraph *graph, BNode* root_node, RadialArc* ring, int total, float axis[3], float limit, int group)
+{
+ int symmetric = 1;
+ int i;
+
+ /* sort ring by angle */
+ for (i = 0; i < total - 1; i++)
+ {
+ float minAngle = FLT_MAX;
+ int minIndex = -1;
+ int j;
+
+ for (j = i + 1; j < total; j++)
+ {
+ float angle = Inpf(ring[i].n, ring[j].n);
+
+ /* map negative values to 1..2 */
+ if (angle < 0)
+ {
+ angle = 1 - angle;
+ }
+
+ if (angle < minAngle)
+ {
+ minIndex = j;
+ minAngle = angle;
+ }
+ }
+
+ /* swap if needed */
+ if (minIndex != i + 1)
+ {
+ RadialArc tmp;
+ tmp = ring[i + 1];
+ ring[i + 1] = ring[minIndex];
+ ring[minIndex] = tmp;
+ }
+ }
+
+ for (i = 0; i < total && symmetric; i++)
+ {
+ BNode *node1, *node2;
+ float tangent[3];
+ float normal[3];
+ float p[3];
+ int j = (i + 1) % total; /* next arc in the circular list */
+
+ VecAddf(tangent, ring[i].n, ring[j].n);
+ Crossf(normal, tangent, axis);
+
+ node1 = BLI_otherNode(ring[i].arc, root_node);
+ node2 = BLI_otherNode(ring[j].arc, root_node);
+
+ VECCOPY(p, node2->p);
+ BLI_mirrorAlongAxis(p, root_node->p, normal);
+
+ /* check if it's within limit before continuing */
+ if (VecLenf(node1->p, p) > limit)
+ {
+ symmetric = 0;
+ }
+
+ }
+
+ if (symmetric)
+ {
+ /* mark node as symmetric physically */
+ VECCOPY(root_node->symmetry_axis, axis);
+ root_node->symmetry_flag |= SYM_PHYSICAL;
+ root_node->symmetry_flag |= SYM_RADIAL;
+
+ /* FLAG SYMMETRY GROUP */
+ for (i = 0; i < total; i++)
+ {
+ ring[i].arc->symmetry_group = group;
+ ring[i].arc->symmetry_flag = SYM_SIDE_RADIAL + i;
+ }
+
+ if (graph->radial_symmetry)
+ {
+ graph->radial_symmetry(root_node, ring, total);
+ }
+ }
+}
+
+static void handleRadialSymmetry(BGraph *graph, BNode *root_node, int depth, float axis[3], float limit)
+{
+ RadialArc *ring = NULL;
+ RadialArc *unit;
+ int total = 0;
+ int group;
+ int first;
+ int i;
+
+ /* mark topological symmetry */
+ root_node->symmetry_flag |= SYM_TOPOLOGICAL;
+
+ /* total the number of arcs in the symmetry ring */
+ for (i = 0; i < root_node->degree; i++)
+ {
+ BArc *connectedArc = root_node->arcs[i];
+
+ /* depth is store as a negative in flag. symmetry level is positive */
+ if (connectedArc->symmetry_level == -depth)
+ {
+ total++;
+ }
+ }
+
+ ring = MEM_callocN(sizeof(RadialArc) * total, "radial symmetry ring");
+ unit = ring;
+
+ /* fill in the ring */
+ for (unit = ring, i = 0; i < root_node->degree; i++)
+ {
+ BArc *connectedArc = root_node->arcs[i];
+
+ /* depth is store as a negative in flag. symmetry level is positive */
+ if (connectedArc->symmetry_level == -depth)
+ {
+ BNode *otherNode = BLI_otherNode(connectedArc, root_node);
+ float vec[3];
+
+ unit->arc = connectedArc;
+
+ /* project the node to node vector on the symmetry plane */
+ VecSubf(unit->n, otherNode->p, root_node->p);
+ Projf(vec, unit->n, axis);
+ VecSubf(unit->n, unit->n, vec);
+
+ Normalize(unit->n);
+
+ unit++;
+ }
+ }
+
+ /* sort ring by arc length
+ * using a rather bogus insertion sort
+ * butrings will never get too big to matter
+ * */
+ for (i = 0; i < total; i++)
+ {
+ int j;
+
+ for (j = i - 1; j >= 0; j--)
+ {
+ BArc *arc1, *arc2;
+
+ arc1 = ring[j].arc;
+ arc2 = ring[j + 1].arc;
+
+ if (arc1->length > arc2->length)
+ {
+ /* swap with smaller */
+ RadialArc tmp;
+
+ tmp = ring[j + 1];
+ ring[j + 1] = ring[j];
+ ring[j] = tmp;
+ }
+ else
+ {
+ break;
+ }
+ }
+ }
+
+ /* Dispatch to specific symmetry tests */
+ first = 0;
+ group = 0;
+
+ for (i = 1; i < total; i++)
+ {
+ int dispatch = 0;
+ int last = i - 1;
+
+ if (fabs(ring[first].arc->length - ring[i].arc->length) > limit)
+ {
+ dispatch = 1;
+ }
+
+ /* if not dispatching already and on last arc
+ * Dispatch using current arc as last
+ * */
+ if (dispatch == 0 && i == total - 1)
+ {
+ last = i;
+ dispatch = 1;
+ }
+
+ if (dispatch)
+ {
+ int sub_total = last - first + 1;
+
+ group += 1;
+
+ if (sub_total == 1)
+ {
+ group -= 1; /* not really a group so decrement */
+ /* NOTHING TO DO */
+ }
+ else if (sub_total == 2)
+ {
+ BArc *arc1, *arc2;
+ BNode *node1, *node2;
+
+ arc1 = ring[first].arc;
+ arc2 = ring[last].arc;
+
+ node1 = BLI_otherNode(arc1, root_node);
+ node2 = BLI_otherNode(arc2, root_node);
+
+ testAxialSymmetry(graph, root_node, node1, node2, arc1, arc2, axis, limit, group);
+ }
+ else if (sub_total != total) /* allocate a new sub ring if needed */
+ {
+ RadialArc *sub_ring = MEM_callocN(sizeof(RadialArc) * sub_total, "radial symmetry ring");
+ int sub_i;
+
+ /* fill in the sub ring */
+ for (sub_i = 0; sub_i < sub_total; sub_i++)
+ {
+ sub_ring[sub_i] = ring[first + sub_i];
+ }
+
+ testRadialSymmetry(graph, root_node, sub_ring, sub_total, axis, limit, group);
+
+ MEM_freeN(sub_ring);
+ }
+ else if (sub_total == total)
+ {
+ testRadialSymmetry(graph, root_node, ring, total, axis, limit, group);
+ }
+
+ first = i;
+ }
+ }
+
+
+ MEM_freeN(ring);
+}
+
+static void flagAxialSymmetry(BNode *root_node, BNode *end_node, BArc *arc, int group)
+{
+ float vec[3];
+
+ arc->symmetry_group = group;
+
+ VecSubf(vec, end_node->p, root_node->p);
+
+ if (Inpf(vec, root_node->symmetry_axis) < 0)
+ {
+ arc->symmetry_flag |= SYM_SIDE_NEGATIVE;
+ }
+ else
+ {
+ arc->symmetry_flag |= SYM_SIDE_POSITIVE;
+ }
+}
+
+static void testAxialSymmetry(BGraph *graph, BNode* root_node, BNode* node1, BNode* node2, BArc* arc1, BArc* arc2, float axis[3], float limit, int group)
+{
+ float nor[3], vec[3], p[3];
+
+ VecSubf(p, node1->p, root_node->p);
+ Crossf(nor, p, axis);
+
+ VecSubf(p, root_node->p, node2->p);
+ Crossf(vec, p, axis);
+ VecAddf(vec, vec, nor);
+
+ Crossf(nor, vec, axis);
+
+ if (abs(nor[0]) > abs(nor[1]) && abs(nor[0]) > abs(nor[2]) && nor[0] < 0)
+ {
+ VecMulf(nor, -1);
+ }
+ else if (abs(nor[1]) > abs(nor[0]) && abs(nor[1]) > abs(nor[2]) && nor[1] < 0)
+ {
+ VecMulf(nor, -1);
+ }
+ else if (abs(nor[2]) > abs(nor[1]) && abs(nor[2]) > abs(nor[0]) && nor[2] < 0)
+ {
+ VecMulf(nor, -1);
+ }
+
+ /* mirror node2 along axis */
+ VECCOPY(p, node2->p);
+ BLI_mirrorAlongAxis(p, root_node->p, nor);
+
+ /* check if it's within limit before continuing */
+ if (VecLenf(node1->p, p) <= limit)
+ {
+ /* mark node as symmetric physically */
+ VECCOPY(root_node->symmetry_axis, nor);
+ root_node->symmetry_flag |= SYM_PHYSICAL;
+ root_node->symmetry_flag |= SYM_AXIAL;
+
+ /* flag side on arcs */
+ flagAxialSymmetry(root_node, node1, arc1, group);
+ flagAxialSymmetry(root_node, node2, arc2, group);
+
+ if (graph->axial_symmetry)
+ {
+ graph->axial_symmetry(root_node, node1, node2, arc1, arc2);
+ }
+ }
+ else
+ {
+ /* NOT SYMMETRIC */
+ }
+}
+
+static void handleAxialSymmetry(BGraph *graph, BNode *root_node, int depth, float axis[3], float limit)
+{
+ BArc *arc1 = NULL, *arc2 = NULL;
+ BNode *node1 = NULL, *node2 = NULL;
+ int i;
+
+ /* mark topological symmetry */
+ root_node->symmetry_flag |= SYM_TOPOLOGICAL;
+
+ for (i = 0; i < root_node->degree; i++)
+ {
+ BArc *connectedArc = root_node->arcs[i];
+
+ /* depth is store as a negative in flag. symmetry level is positive */
+ if (connectedArc->symmetry_level == -depth)
+ {
+ if (arc1 == NULL)
+ {
+ arc1 = connectedArc;
+ node1 = BLI_otherNode(arc1, root_node);
+ }
+ else
+ {
+ arc2 = connectedArc;
+ node2 = BLI_otherNode(arc2, root_node);
+ break; /* Can stop now, the two arcs have been found */
+ }
+ }
+ }
+
+ /* shouldn't happen, but just to be sure */
+ if (node1 == NULL || node2 == NULL)
+ {
+ return;
+ }
+
+ testAxialSymmetry(graph, root_node, node1, node2, arc1, arc2, axis, limit, 1);
+}
+
+static void markdownSecondarySymmetry(BGraph *graph, BNode *node, int depth, int level, float limit)
+{
+ float axis[3] = {0, 0, 0};
+ int count = 0;
+ int i;
+
+ /* count the number of branches in this symmetry group
+ * and determinte the axis of symmetry
+ * */
+ for (i = 0; i < node->degree; i++)
+ {
+ BArc *connectedArc = node->arcs[i];
+
+ /* depth is store as a negative in flag. symmetry level is positive */
+ if (connectedArc->symmetry_level == -depth)
+ {
+ count++;
+ }
+ /* If arc is on the axis */
+ else if (connectedArc->symmetry_level == level)
+ {
+ VecAddf(axis, axis, connectedArc->head->p);
+ VecSubf(axis, axis, connectedArc->tail->p);
+ }
+ }
+
+ Normalize(axis);
+
+ /* Split between axial and radial symmetry */
+ if (count == 2)
+ {
+ handleAxialSymmetry(graph, node, depth, axis, limit);
+ }
+ else
+ {
+ handleRadialSymmetry(graph, node, depth, axis, limit);
+ }
+
+ /* markdown secondary symetries */
+ for (i = 0; i < node->degree; i++)
+ {
+ BArc *connectedArc = node->arcs[i];
+
+ if (connectedArc->symmetry_level == -depth)
+ {
+ /* markdown symmetry for branches corresponding to the depth */
+ markdownSymmetryArc(graph, connectedArc, node, level + 1, limit);
+ }
+ }
+}
+
+void markdownSymmetryArc(BGraph *graph, BArc *arc, BNode *node, int level, float limit)
+{
+ int i;
+
+ /* if arc is null, we start straight from a node */
+ if (arc)
+ {
+ arc->symmetry_level = level;
+
+ node = BLI_otherNode(arc, node);
+ }
+
+ for (i = 0; i < node->degree; i++)
+ {
+ BArc *connectedArc = node->arcs[i];
+
+ if (connectedArc != arc)
+ {
+ BNode *connectedNode = BLI_otherNode(connectedArc, node);
+
+ /* symmetry level is positive value, negative values is subtree depth */
+ connectedArc->symmetry_level = -BLI_subtreeShape(graph, connectedNode, connectedArc, 0);
+ }
+ }
+
+ arc = NULL;
+
+ for (i = 0; i < node->degree; i++)
+ {
+ int issymmetryAxis = 0;
+ BArc *connectedArc = node->arcs[i];
+
+ /* only arcs not already marked as symetric */
+ if (connectedArc->symmetry_level < 0)
+ {
+ int j;
+
+ /* true by default */
+ issymmetryAxis = 1;
+
+ for (j = 0; j < node->degree; j++)
+ {
+ BArc *otherArc = node->arcs[j];
+
+ /* different arc, same depth */
+ if (otherArc != connectedArc && otherArc->symmetry_level == connectedArc->symmetry_level)
+ {
+ /* not on the symmetry axis */
+ issymmetryAxis = 0;
+ break;
+ }
+ }
+ }
+
+ /* arc could be on the symmetry axis */
+ if (issymmetryAxis == 1)
+ {
+ /* no arc as been marked previously, keep this one */
+ if (arc == NULL)
+ {
+ arc = connectedArc;
+ }
+ else if (connectedArc->symmetry_level < arc->symmetry_level)
+ {
+ /* go with more complex subtree as symmetry arc */
+ arc = connectedArc;
+ }
+ }
+ }
+
+ /* go down the arc continuing the symmetry axis */
+ if (arc)
+ {
+ markdownSymmetryArc(graph, arc, node, level, limit);
+ }
+
+
+ /* secondary symmetry */
+ for (i = 0; i < node->degree; i++)
+ {
+ BArc *connectedArc = node->arcs[i];
+
+ /* only arcs not already marked as symetric and is not the next arc on the symmetry axis */
+ if (connectedArc->symmetry_level < 0)
+ {
+ /* subtree depth is store as a negative value in the symmetry */
+ markdownSecondarySymmetry(graph, node, -connectedArc->symmetry_level, level, limit);
+ }
+ }
+}
+
+void BLI_markdownSymmetry(BGraph *graph, BNode *root_node, float limit)
+{
+ BNode *node;
+ BArc *arc;
+
+ if (BLI_isGraphCyclic(graph))
+ {
+ return;
+ }
+
+ /* mark down all arcs as non-symetric */
+ BLI_flagArcs(graph, 0);
+
+ /* mark down all nodes as not on the symmetry axis */
+ BLI_flagNodes(graph, 0);
+
+ node = root_node;
+
+ /* sanity check REMOVE ME */
+ if (node->degree > 0)
+ {
+ arc = node->arcs[0];
+
+ if (node->degree == 1)
+ {
+ markdownSymmetryArc(graph, arc, node, 1, limit);
+ }
+ else
+ {
+ markdownSymmetryArc(graph, NULL, node, 1, limit);
+ }
+
+
+
+ /* mark down non-symetric arcs */
+ for (arc = graph->arcs.first; arc; arc = arc->next)
+ {
+ if (arc->symmetry_level < 0)
+ {
+ arc->symmetry_level = 0;
+ }
+ else
+ {
+ /* mark down nodes with the lowest level symmetry axis */
+ if (arc->head->symmetry_level == 0 || arc->head->symmetry_level > arc->symmetry_level)
+ {
+ arc->head->symmetry_level = arc->symmetry_level;
+ }
+ if (arc->tail->symmetry_level == 0 || arc->tail->symmetry_level > arc->symmetry_level)
+ {
+ arc->tail->symmetry_level = arc->symmetry_level;
+ }
+ }
+ }
+ }
+}
+
diff --git a/source/blender/blenlib/intern/noise.c b/source/blender/blenlib/intern/noise.c
index a678c44d4bf..0bd30a69d05 100644
--- a/source/blender/blenlib/intern/noise.c
+++ b/source/blender/blenlib/intern/noise.c
@@ -387,55 +387,521 @@ static char p[512+2]= {
float g[512+2][3]= {
-0.33783,0.715698,-0.611206,-0.944031,-0.326599,-0.045624,-0.101074,-0.416443,-0.903503,0.799286,0.49411,-0.341949,-0.854645,0.518036,0.033936,0.42514,-0.437866,-0.792114,-0.358948,0.597046,0.717377,-0.985413,0.144714,0.089294,-0.601776,-0.33728,-0.723907,-0.449921,0.594513,0.666382,0.208313,-0.10791,
-0.972076,0.575317,0.060425,0.815643,0.293365,-0.875702,-0.383453,0.293762,0.465759,0.834686,-0.846008,-0.233398,-0.47934,-0.115814,0.143036,-0.98291,0.204681,-0.949036,-0.239532,0.946716,-0.263947,0.184326,-0.235596,0.573822,0.784332,0.203705,-0.372253,-0.905487,0.756989,-0.651031,0.055298,0.497803,
-0.814697,-0.297363,-0.16214,0.063995,-0.98468,-0.329254,0.834381,0.441925,0.703827,-0.527039,-0.476227,0.956421,0.266113,0.119781,0.480133,0.482849,0.7323,-0.18631,0.961212,-0.203125,-0.748474,-0.656921,-0.090393,-0.085052,-0.165253,0.982544,-0.76947,0.628174,-0.115234,0.383148,0.537659,0.751068,
-0.616486,-0.668488,-0.415924,-0.259979,-0.630005,0.73175,0.570953,-0.087952,0.816223,-0.458008,0.023254,0.888611,-0.196167,0.976563,-0.088287,-0.263885,-0.69812,-0.665527,0.437134,-0.892273,-0.112793,-0.621674,-0.230438,0.748566,0.232422,0.900574,-0.367249,0.22229,-0.796143,0.562744,-0.665497,-0.73764,
-0.11377,0.670135,0.704803,0.232605,0.895599,0.429749,-0.114655,-0.11557,-0.474243,0.872742,0.621826,0.604004,-0.498444,-0.832214,0.012756,0.55426,-0.702484,0.705994,-0.089661,-0.692017,0.649292,0.315399,-0.175995,-0.977997,0.111877,0.096954,-0.04953,0.994019,0.635284,-0.606689,-0.477783,-0.261261,
--0.607422,-0.750153,0.983276,0.165436,0.075958,-0.29837,0.404083,-0.864655,-0.638672,0.507721,0.578156,0.388214,0.412079,0.824249,0.556183,-0.208832,0.804352,0.778442,0.562012,0.27951,-0.616577,0.781921,-0.091522,0.196289,0.051056,0.979187,-0.121216,0.207153,-0.970734,-0.173401,-0.384735,0.906555,
-0.161499,-0.723236,-0.671387,0.178497,-0.006226,-0.983887,-0.126038,0.15799,0.97934,0.830475,-0.024811,0.556458,-0.510132,-0.76944,0.384247,0.81424,0.200104,-0.544891,-0.112549,-0.393311,-0.912445,0.56189,0.152222,-0.813049,0.198914,-0.254517,-0.946381,-0.41217,0.690979,-0.593811,-0.407257,0.324524,
-0.853668,-0.690186,0.366119,-0.624115,-0.428345,0.844147,-0.322296,-0.21228,-0.297546,-0.930756,-0.273071,0.516113,0.811798,0.928314,0.371643,0.007233,0.785828,-0.479218,-0.390778,-0.704895,0.058929,0.706818,0.173248,0.203583,0.963562,0.422211,-0.904297,-0.062469,-0.363312,-0.182465,0.913605,0.254028,
--0.552307,-0.793945,-0.28891,-0.765747,-0.574554,0.058319,0.291382,0.954803,0.946136,-0.303925,0.111267,-0.078156,0.443695,-0.892731,0.182098,0.89389,0.409515,-0.680298,-0.213318,0.701141,0.062469,0.848389,-0.525635,-0.72879,-0.641846,0.238342,-0.88089,0.427673,0.202637,-0.532501,-0.21405,0.818878,
-0.948975,-0.305084,0.07962,0.925446,0.374664,0.055817,0.820923,0.565491,0.079102,0.25882,0.099792,-0.960724,-0.294617,0.910522,0.289978,0.137115,0.320038,-0.937408,-0.908386,0.345276,-0.235718,-0.936218,0.138763,0.322754,0.366577,0.925934,-0.090637,0.309296,-0.686829,-0.657684,0.66983,0.024445,
-0.742065,-0.917999,-0.059113,-0.392059,0.365509,0.462158,-0.807922,0.083374,0.996399,-0.014801,0.593842,0.253143,-0.763672,0.974976,-0.165466,0.148285,0.918976,0.137299,0.369537,0.294952,0.694977,0.655731,0.943085,0.152618,-0.295319,0.58783,-0.598236,0.544495,0.203796,0.678223,0.705994,-0.478821,
--0.661011,0.577667,0.719055,-0.1698,-0.673828,-0.132172,-0.965332,0.225006,-0.981873,-0.14502,0.121979,0.763458,0.579742,0.284546,-0.893188,0.079681,0.442474,-0.795776,-0.523804,0.303802,0.734955,0.67804,-0.007446,0.15506,0.986267,-0.056183,0.258026,0.571503,-0.778931,-0.681549,-0.702087,-0.206116,
--0.96286,-0.177185,0.203613,-0.470978,-0.515106,0.716095,-0.740326,0.57135,0.354095,-0.56012,-0.824982,-0.074982,-0.507874,0.753204,0.417969,-0.503113,0.038147,0.863342,0.594025,0.673553,-0.439758,-0.119873,-0.005524,-0.992737,0.098267,-0.213776,0.971893,-0.615631,0.643951,0.454163,0.896851,-0.441071,
-0.032166,-0.555023,0.750763,-0.358093,0.398773,0.304688,0.864929,-0.722961,0.303589,0.620544,-0.63559,-0.621948,-0.457306,-0.293243,0.072327,0.953278,-0.491638,0.661041,-0.566772,-0.304199,-0.572083,-0.761688,0.908081,-0.398956,0.127014,-0.523621,-0.549683,-0.650848,-0.932922,-0.19986,0.299408,0.099426,
-0.140869,0.984985,-0.020325,-0.999756,-0.002319,0.952667,0.280853,-0.11615,-0.971893,0.082581,0.220337,0.65921,0.705292,-0.260651,0.733063,-0.175537,0.657043,-0.555206,0.429504,-0.712189,0.400421,-0.89859,0.179352,0.750885,-0.19696,0.630341,0.785675,-0.569336,0.241821,-0.058899,-0.464111,0.883789,
-0.129608,-0.94519,0.299622,-0.357819,0.907654,0.219238,-0.842133,-0.439117,-0.312927,-0.313477,0.84433,0.434479,-0.241211,0.053253,0.968994,0.063873,0.823273,0.563965,0.476288,0.862152,-0.172516,0.620941,-0.298126,0.724915,0.25238,-0.749359,-0.612122,-0.577545,0.386566,0.718994,-0.406342,-0.737976,
-0.538696,0.04718,0.556305,0.82959,-0.802856,0.587463,0.101166,-0.707733,-0.705963,0.026428,0.374908,0.68457,0.625092,0.472137,0.208405,-0.856506,-0.703064,-0.581085,-0.409821,-0.417206,-0.736328,0.532623,-0.447876,-0.20285,-0.870728,0.086945,-0.990417,0.107086,0.183685,0.018341,-0.982788,0.560638,
--0.428864,0.708282,0.296722,-0.952576,-0.0672,0.135773,0.990265,0.030243,-0.068787,0.654724,0.752686,0.762604,-0.551758,0.337585,-0.819611,-0.407684,0.402466,-0.727844,-0.55072,-0.408539,-0.855774,-0.480011,0.19281,0.693176,-0.079285,0.716339,0.226013,0.650116,-0.725433,0.246704,0.953369,-0.173553,
--0.970398,-0.239227,-0.03244,0.136383,-0.394318,0.908752,0.813232,0.558167,0.164368,0.40451,0.549042,-0.731323,-0.380249,-0.566711,0.730865,0.022156,0.932739,0.359741,0.00824,0.996552,-0.082306,0.956635,-0.065338,-0.283722,-0.743561,0.008209,0.668579,-0.859589,-0.509674,0.035767,-0.852234,0.363678,
--0.375977,-0.201965,-0.970795,-0.12915,0.313477,0.947327,0.06546,-0.254028,-0.528259,0.81015,0.628052,0.601105,0.49411,-0.494385,0.868378,0.037933,0.275635,-0.086426,0.957336,-0.197937,0.468903,-0.860748,0.895599,0.399384,0.195801,0.560791,0.825012,-0.069214,0.304199,-0.849487,0.43103,0.096375,
-0.93576,0.339111,-0.051422,0.408966,-0.911072,0.330444,0.942841,-0.042389,-0.452362,-0.786407,0.420563,0.134308,-0.933472,-0.332489,0.80191,-0.566711,-0.188934,-0.987946,-0.105988,0.112518,-0.24408,0.892242,-0.379791,-0.920502,0.229095,-0.316376,0.7789,0.325958,0.535706,-0.912872,0.185211,-0.36377,
--0.184784,0.565369,-0.803833,-0.018463,0.119537,0.992615,-0.259247,-0.935608,0.239532,-0.82373,-0.449127,-0.345947,-0.433105,0.659515,0.614349,-0.822754,0.378845,-0.423676,0.687195,-0.674835,-0.26889,-0.246582,-0.800842,0.545715,-0.729187,-0.207794,0.651978,0.653534,-0.610443,-0.447388,0.492584,-0.023346,
-0.869934,0.609039,0.009094,-0.79306,0.962494,-0.271088,-0.00885,0.2659,-0.004913,0.963959,0.651245,0.553619,-0.518951,0.280548,-0.84314,0.458618,-0.175293,-0.983215,0.049805,0.035339,-0.979919,0.196045,-0.982941,0.164307,-0.082245,0.233734,-0.97226,-0.005005,-0.747253,-0.611328,0.260437,0.645599,
-0.592773,0.481384,0.117706,-0.949524,-0.29068,-0.535004,-0.791901,-0.294312,-0.627167,-0.214447,0.748718,-0.047974,-0.813477,-0.57959,-0.175537,0.477264,-0.860992,0.738556,-0.414246,-0.53183,0.562561,-0.704071,0.433289,-0.754944,0.64801,-0.100586,0.114716,0.044525,-0.992371,0.966003,0.244873,-0.082764,
-0.33783,0.715698,-0.611206,-0.944031,-0.326599,-0.045624,-0.101074,-0.416443,-0.903503,0.799286,0.49411,-0.341949,-0.854645,0.518036,0.033936,0.42514,-0.437866,-0.792114,-0.358948,0.597046,0.717377,-0.985413,0.144714,0.089294,-0.601776,-0.33728,-0.723907,-0.449921,0.594513,0.666382,0.208313,-0.10791,
-0.972076,0.575317,0.060425,0.815643,0.293365,-0.875702,-0.383453,0.293762,0.465759,0.834686,-0.846008,-0.233398,-0.47934,-0.115814,0.143036,-0.98291,0.204681,-0.949036,-0.239532,0.946716,-0.263947,0.184326,-0.235596,0.573822,0.784332,0.203705,-0.372253,-0.905487,0.756989,-0.651031,0.055298,0.497803,
-0.814697,-0.297363,-0.16214,0.063995,-0.98468,-0.329254,0.834381,0.441925,0.703827,-0.527039,-0.476227,0.956421,0.266113,0.119781,0.480133,0.482849,0.7323,-0.18631,0.961212,-0.203125,-0.748474,-0.656921,-0.090393,-0.085052,-0.165253,0.982544,-0.76947,0.628174,-0.115234,0.383148,0.537659,0.751068,
-0.616486,-0.668488,-0.415924,-0.259979,-0.630005,0.73175,0.570953,-0.087952,0.816223,-0.458008,0.023254,0.888611,-0.196167,0.976563,-0.088287,-0.263885,-0.69812,-0.665527,0.437134,-0.892273,-0.112793,-0.621674,-0.230438,0.748566,0.232422,0.900574,-0.367249,0.22229,-0.796143,0.562744,-0.665497,-0.73764,
-0.11377,0.670135,0.704803,0.232605,0.895599,0.429749,-0.114655,-0.11557,-0.474243,0.872742,0.621826,0.604004,-0.498444,-0.832214,0.012756,0.55426,-0.702484,0.705994,-0.089661,-0.692017,0.649292,0.315399,-0.175995,-0.977997,0.111877,0.096954,-0.04953,0.994019,0.635284,-0.606689,-0.477783,-0.261261,
--0.607422,-0.750153,0.983276,0.165436,0.075958,-0.29837,0.404083,-0.864655,-0.638672,0.507721,0.578156,0.388214,0.412079,0.824249,0.556183,-0.208832,0.804352,0.778442,0.562012,0.27951,-0.616577,0.781921,-0.091522,0.196289,0.051056,0.979187,-0.121216,0.207153,-0.970734,-0.173401,-0.384735,0.906555,
-0.161499,-0.723236,-0.671387,0.178497,-0.006226,-0.983887,-0.126038,0.15799,0.97934,0.830475,-0.024811,0.556458,-0.510132,-0.76944,0.384247,0.81424,0.200104,-0.544891,-0.112549,-0.393311,-0.912445,0.56189,0.152222,-0.813049,0.198914,-0.254517,-0.946381,-0.41217,0.690979,-0.593811,-0.407257,0.324524,
-0.853668,-0.690186,0.366119,-0.624115,-0.428345,0.844147,-0.322296,-0.21228,-0.297546,-0.930756,-0.273071,0.516113,0.811798,0.928314,0.371643,0.007233,0.785828,-0.479218,-0.390778,-0.704895,0.058929,0.706818,0.173248,0.203583,0.963562,0.422211,-0.904297,-0.062469,-0.363312,-0.182465,0.913605,0.254028,
--0.552307,-0.793945,-0.28891,-0.765747,-0.574554,0.058319,0.291382,0.954803,0.946136,-0.303925,0.111267,-0.078156,0.443695,-0.892731,0.182098,0.89389,0.409515,-0.680298,-0.213318,0.701141,0.062469,0.848389,-0.525635,-0.72879,-0.641846,0.238342,-0.88089,0.427673,0.202637,-0.532501,-0.21405,0.818878,
-0.948975,-0.305084,0.07962,0.925446,0.374664,0.055817,0.820923,0.565491,0.079102,0.25882,0.099792,-0.960724,-0.294617,0.910522,0.289978,0.137115,0.320038,-0.937408,-0.908386,0.345276,-0.235718,-0.936218,0.138763,0.322754,0.366577,0.925934,-0.090637,0.309296,-0.686829,-0.657684,0.66983,0.024445,
-0.742065,-0.917999,-0.059113,-0.392059,0.365509,0.462158,-0.807922,0.083374,0.996399,-0.014801,0.593842,0.253143,-0.763672,0.974976,-0.165466,0.148285,0.918976,0.137299,0.369537,0.294952,0.694977,0.655731,0.943085,0.152618,-0.295319,0.58783,-0.598236,0.544495,0.203796,0.678223,0.705994,-0.478821,
--0.661011,0.577667,0.719055,-0.1698,-0.673828,-0.132172,-0.965332,0.225006,-0.981873,-0.14502,0.121979,0.763458,0.579742,0.284546,-0.893188,0.079681,0.442474,-0.795776,-0.523804,0.303802,0.734955,0.67804,-0.007446,0.15506,0.986267,-0.056183,0.258026,0.571503,-0.778931,-0.681549,-0.702087,-0.206116,
--0.96286,-0.177185,0.203613,-0.470978,-0.515106,0.716095,-0.740326,0.57135,0.354095,-0.56012,-0.824982,-0.074982,-0.507874,0.753204,0.417969,-0.503113,0.038147,0.863342,0.594025,0.673553,-0.439758,-0.119873,-0.005524,-0.992737,0.098267,-0.213776,0.971893,-0.615631,0.643951,0.454163,0.896851,-0.441071,
-0.032166,-0.555023,0.750763,-0.358093,0.398773,0.304688,0.864929,-0.722961,0.303589,0.620544,-0.63559,-0.621948,-0.457306,-0.293243,0.072327,0.953278,-0.491638,0.661041,-0.566772,-0.304199,-0.572083,-0.761688,0.908081,-0.398956,0.127014,-0.523621,-0.549683,-0.650848,-0.932922,-0.19986,0.299408,0.099426,
-0.140869,0.984985,-0.020325,-0.999756,-0.002319,0.952667,0.280853,-0.11615,-0.971893,0.082581,0.220337,0.65921,0.705292,-0.260651,0.733063,-0.175537,0.657043,-0.555206,0.429504,-0.712189,0.400421,-0.89859,0.179352,0.750885,-0.19696,0.630341,0.785675,-0.569336,0.241821,-0.058899,-0.464111,0.883789,
-0.129608,-0.94519,0.299622,-0.357819,0.907654,0.219238,-0.842133,-0.439117,-0.312927,-0.313477,0.84433,0.434479,-0.241211,0.053253,0.968994,0.063873,0.823273,0.563965,0.476288,0.862152,-0.172516,0.620941,-0.298126,0.724915,0.25238,-0.749359,-0.612122,-0.577545,0.386566,0.718994,-0.406342,-0.737976,
-0.538696,0.04718,0.556305,0.82959,-0.802856,0.587463,0.101166,-0.707733,-0.705963,0.026428,0.374908,0.68457,0.625092,0.472137,0.208405,-0.856506,-0.703064,-0.581085,-0.409821,-0.417206,-0.736328,0.532623,-0.447876,-0.20285,-0.870728,0.086945,-0.990417,0.107086,0.183685,0.018341,-0.982788,0.560638,
--0.428864,0.708282,0.296722,-0.952576,-0.0672,0.135773,0.990265,0.030243,-0.068787,0.654724,0.752686,0.762604,-0.551758,0.337585,-0.819611,-0.407684,0.402466,-0.727844,-0.55072,-0.408539,-0.855774,-0.480011,0.19281,0.693176,-0.079285,0.716339,0.226013,0.650116,-0.725433,0.246704,0.953369,-0.173553,
--0.970398,-0.239227,-0.03244,0.136383,-0.394318,0.908752,0.813232,0.558167,0.164368,0.40451,0.549042,-0.731323,-0.380249,-0.566711,0.730865,0.022156,0.932739,0.359741,0.00824,0.996552,-0.082306,0.956635,-0.065338,-0.283722,-0.743561,0.008209,0.668579,-0.859589,-0.509674,0.035767,-0.852234,0.363678,
--0.375977,-0.201965,-0.970795,-0.12915,0.313477,0.947327,0.06546,-0.254028,-0.528259,0.81015,0.628052,0.601105,0.49411,-0.494385,0.868378,0.037933,0.275635,-0.086426,0.957336,-0.197937,0.468903,-0.860748,0.895599,0.399384,0.195801,0.560791,0.825012,-0.069214,0.304199,-0.849487,0.43103,0.096375,
-0.93576,0.339111,-0.051422,0.408966,-0.911072,0.330444,0.942841,-0.042389,-0.452362,-0.786407,0.420563,0.134308,-0.933472,-0.332489,0.80191,-0.566711,-0.188934,-0.987946,-0.105988,0.112518,-0.24408,0.892242,-0.379791,-0.920502,0.229095,-0.316376,0.7789,0.325958,0.535706,-0.912872,0.185211,-0.36377,
--0.184784,0.565369,-0.803833,-0.018463,0.119537,0.992615,-0.259247,-0.935608,0.239532,-0.82373,-0.449127,-0.345947,-0.433105,0.659515,0.614349,-0.822754,0.378845,-0.423676,0.687195,-0.674835,-0.26889,-0.246582,-0.800842,0.545715,-0.729187,-0.207794,0.651978,0.653534,-0.610443,-0.447388,0.492584,-0.023346,
-0.869934,0.609039,0.009094,-0.79306,0.962494,-0.271088,-0.00885,0.2659,-0.004913,0.963959,0.651245,0.553619,-0.518951,0.280548,-0.84314,0.458618,-0.175293,-0.983215,0.049805,0.035339,-0.979919,0.196045,-0.982941,0.164307,-0.082245,0.233734,-0.97226,-0.005005,-0.747253,-0.611328,0.260437,0.645599,
-0.592773,0.481384,0.117706,-0.949524,-0.29068,-0.535004,-0.791901,-0.294312,-0.627167,-0.214447,0.748718,-0.047974,-0.813477,-0.57959,-0.175537,0.477264,-0.860992,0.738556,-0.414246,-0.53183,0.562561,-0.704071,0.433289,-0.754944,0.64801,-0.100586,0.114716,0.044525,-0.992371,0.966003,0.244873,-0.082764,
-0.33783,0.715698,-0.611206,-0.944031,-0.326599,-0.045624};
+ {0.33783, 0.715698, -0.611206},
+ {-0.944031, -0.326599, -0.045624},
+ {-0.101074, -0.416443, -0.903503},
+ {0.799286, 0.49411, -0.341949},
+ {-0.854645, 0.518036, 0.033936},
+ {0.42514, -0.437866, -0.792114},
+ {-0.358948, 0.597046, 0.717377},
+ {-0.985413, 0.144714, 0.089294},
+ {-0.601776, -0.33728, -0.723907},
+ {-0.449921, 0.594513, 0.666382},
+ {0.208313, -0.10791, 0.972076},
+ {0.575317, 0.060425, 0.815643},
+ {0.293365, -0.875702, -0.383453},
+ {0.293762, 0.465759, 0.834686},
+ {-0.846008, -0.233398, -0.47934},
+ {-0.115814, 0.143036, -0.98291},
+ {0.204681, -0.949036, -0.239532},
+ {0.946716, -0.263947, 0.184326},
+ {-0.235596, 0.573822, 0.784332},
+ {0.203705, -0.372253, -0.905487},
+ {0.756989, -0.651031, 0.055298},
+ {0.497803, 0.814697, -0.297363},
+ {-0.16214, 0.063995, -0.98468},
+ {-0.329254, 0.834381, 0.441925},
+ {0.703827, -0.527039, -0.476227},
+ {0.956421, 0.266113, 0.119781},
+ {0.480133, 0.482849, 0.7323},
+ {-0.18631, 0.961212, -0.203125},
+ {-0.748474, -0.656921, -0.090393},
+ {-0.085052, -0.165253, 0.982544},
+ {-0.76947, 0.628174, -0.115234},
+ {0.383148, 0.537659, 0.751068},
+ {0.616486, -0.668488, -0.415924},
+ {-0.259979, -0.630005, 0.73175},
+ {0.570953, -0.087952, 0.816223},
+ {-0.458008, 0.023254, 0.888611},
+ {-0.196167, 0.976563, -0.088287},
+ {-0.263885, -0.69812, -0.665527},
+ {0.437134, -0.892273, -0.112793},
+ {-0.621674, -0.230438, 0.748566},
+ {0.232422, 0.900574, -0.367249},
+ {0.22229, -0.796143, 0.562744},
+ {-0.665497, -0.73764, 0.11377},
+ {0.670135, 0.704803, 0.232605},
+ {0.895599, 0.429749, -0.114655},
+ {-0.11557, -0.474243, 0.872742},
+ {0.621826, 0.604004, -0.498444},
+ {-0.832214, 0.012756, 0.55426},
+ {-0.702484, 0.705994, -0.089661},
+ {-0.692017, 0.649292, 0.315399},
+ {-0.175995, -0.977997, 0.111877},
+ {0.096954, -0.04953, 0.994019},
+ {0.635284, -0.606689, -0.477783},
+ {-0.261261, -0.607422, -0.750153},
+ {0.983276, 0.165436, 0.075958},
+ {-0.29837, 0.404083, -0.864655},
+ {-0.638672, 0.507721, 0.578156},
+ {0.388214, 0.412079, 0.824249},
+ {0.556183, -0.208832, 0.804352},
+ {0.778442, 0.562012, 0.27951},
+ {-0.616577, 0.781921, -0.091522},
+ {0.196289, 0.051056, 0.979187},
+ {-0.121216, 0.207153, -0.970734},
+ {-0.173401, -0.384735, 0.906555},
+ {0.161499, -0.723236, -0.671387},
+ {0.178497, -0.006226, -0.983887},
+ {-0.126038, 0.15799, 0.97934},
+ {0.830475, -0.024811, 0.556458},
+ {-0.510132, -0.76944, 0.384247},
+ {0.81424, 0.200104, -0.544891},
+ {-0.112549, -0.393311, -0.912445},
+ {0.56189, 0.152222, -0.813049},
+ {0.198914, -0.254517, -0.946381},
+ {-0.41217, 0.690979, -0.593811},
+ {-0.407257, 0.324524, 0.853668},
+ {-0.690186, 0.366119, -0.624115},
+ {-0.428345, 0.844147, -0.322296},
+ {-0.21228, -0.297546, -0.930756},
+ {-0.273071, 0.516113, 0.811798},
+ {0.928314, 0.371643, 0.007233},
+ {0.785828, -0.479218, -0.390778},
+ {-0.704895, 0.058929, 0.706818},
+ {0.173248, 0.203583, 0.963562},
+ {0.422211, -0.904297, -0.062469},
+ {-0.363312, -0.182465, 0.913605},
+ {0.254028, -0.552307, -0.793945},
+ {-0.28891, -0.765747, -0.574554},
+ {0.058319, 0.291382, 0.954803},
+ {0.946136, -0.303925, 0.111267},
+ {-0.078156, 0.443695, -0.892731},
+ {0.182098, 0.89389, 0.409515},
+ {-0.680298, -0.213318, 0.701141},
+ {0.062469, 0.848389, -0.525635},
+ {-0.72879, -0.641846, 0.238342},
+ {-0.88089, 0.427673, 0.202637},
+ {-0.532501, -0.21405, 0.818878},
+ {0.948975, -0.305084, 0.07962},
+ {0.925446, 0.374664, 0.055817},
+ {0.820923, 0.565491, 0.079102},
+ {0.25882, 0.099792, -0.960724},
+ {-0.294617, 0.910522, 0.289978},
+ {0.137115, 0.320038, -0.937408},
+ {-0.908386, 0.345276, -0.235718},
+ {-0.936218, 0.138763, 0.322754},
+ {0.366577, 0.925934, -0.090637},
+ {0.309296, -0.686829, -0.657684},
+ {0.66983, 0.024445, 0.742065},
+ {-0.917999, -0.059113, -0.392059},
+ {0.365509, 0.462158, -0.807922},
+ {0.083374, 0.996399, -0.014801},
+ {0.593842, 0.253143, -0.763672},
+ {0.974976, -0.165466, 0.148285},
+ {0.918976, 0.137299, 0.369537},
+ {0.294952, 0.694977, 0.655731},
+ {0.943085, 0.152618, -0.295319},
+ {0.58783, -0.598236, 0.544495},
+ {0.203796, 0.678223, 0.705994},
+ {-0.478821, -0.661011, 0.577667},
+ {0.719055, -0.1698, -0.673828},
+ {-0.132172, -0.965332, 0.225006},
+ {-0.981873, -0.14502, 0.121979},
+ {0.763458, 0.579742, 0.284546},
+ {-0.893188, 0.079681, 0.442474},
+ {-0.795776, -0.523804, 0.303802},
+ {0.734955, 0.67804, -0.007446},
+ {0.15506, 0.986267, -0.056183},
+ {0.258026, 0.571503, -0.778931},
+ {-0.681549, -0.702087, -0.206116},
+ {-0.96286, -0.177185, 0.203613},
+ {-0.470978, -0.515106, 0.716095},
+ {-0.740326, 0.57135, 0.354095},
+ {-0.56012, -0.824982, -0.074982},
+ {-0.507874, 0.753204, 0.417969},
+ {-0.503113, 0.038147, 0.863342},
+ {0.594025, 0.673553, -0.439758},
+ {-0.119873, -0.005524, -0.992737},
+ {0.098267, -0.213776, 0.971893},
+ {-0.615631, 0.643951, 0.454163},
+ {0.896851, -0.441071, 0.032166},
+ {-0.555023, 0.750763, -0.358093},
+ {0.398773, 0.304688, 0.864929},
+ {-0.722961, 0.303589, 0.620544},
+ {-0.63559, -0.621948, -0.457306},
+ {-0.293243, 0.072327, 0.953278},
+ {-0.491638, 0.661041, -0.566772},
+ {-0.304199, -0.572083, -0.761688},
+ {0.908081, -0.398956, 0.127014},
+ {-0.523621, -0.549683, -0.650848},
+ {-0.932922, -0.19986, 0.299408},
+ {0.099426, 0.140869, 0.984985},
+ {-0.020325, -0.999756, -0.002319},
+ {0.952667, 0.280853, -0.11615},
+ {-0.971893, 0.082581, 0.220337},
+ {0.65921, 0.705292, -0.260651},
+ {0.733063, -0.175537, 0.657043},
+ {-0.555206, 0.429504, -0.712189},
+ {0.400421, -0.89859, 0.179352},
+ {0.750885, -0.19696, 0.630341},
+ {0.785675, -0.569336, 0.241821},
+ {-0.058899, -0.464111, 0.883789},
+ {0.129608, -0.94519, 0.299622},
+ {-0.357819, 0.907654, 0.219238},
+ {-0.842133, -0.439117, -0.312927},
+ {-0.313477, 0.84433, 0.434479},
+ {-0.241211, 0.053253, 0.968994},
+ {0.063873, 0.823273, 0.563965},
+ {0.476288, 0.862152, -0.172516},
+ {0.620941, -0.298126, 0.724915},
+ {0.25238, -0.749359, -0.612122},
+ {-0.577545, 0.386566, 0.718994},
+ {-0.406342, -0.737976, 0.538696},
+ {0.04718, 0.556305, 0.82959},
+ {-0.802856, 0.587463, 0.101166},
+ {-0.707733, -0.705963, 0.026428},
+ {0.374908, 0.68457, 0.625092},
+ {0.472137, 0.208405, -0.856506},
+ {-0.703064, -0.581085, -0.409821},
+ {-0.417206, -0.736328, 0.532623},
+ {-0.447876, -0.20285, -0.870728},
+ {0.086945, -0.990417, 0.107086},
+ {0.183685, 0.018341, -0.982788},
+ {0.560638, -0.428864, 0.708282},
+ {0.296722, -0.952576, -0.0672},
+ {0.135773, 0.990265, 0.030243},
+ {-0.068787, 0.654724, 0.752686},
+ {0.762604, -0.551758, 0.337585},
+ {-0.819611, -0.407684, 0.402466},
+ {-0.727844, -0.55072, -0.408539},
+ {-0.855774, -0.480011, 0.19281},
+ {0.693176, -0.079285, 0.716339},
+ {0.226013, 0.650116, -0.725433},
+ {0.246704, 0.953369, -0.173553},
+ {-0.970398, -0.239227, -0.03244},
+ {0.136383, -0.394318, 0.908752},
+ {0.813232, 0.558167, 0.164368},
+ {0.40451, 0.549042, -0.731323},
+ {-0.380249, -0.566711, 0.730865},
+ {0.022156, 0.932739, 0.359741},
+ {0.00824, 0.996552, -0.082306},
+ {0.956635, -0.065338, -0.283722},
+ {-0.743561, 0.008209, 0.668579},
+ {-0.859589, -0.509674, 0.035767},
+ {-0.852234, 0.363678, -0.375977},
+ {-0.201965, -0.970795, -0.12915},
+ {0.313477, 0.947327, 0.06546},
+ {-0.254028, -0.528259, 0.81015},
+ {0.628052, 0.601105, 0.49411},
+ {-0.494385, 0.868378, 0.037933},
+ {0.275635, -0.086426, 0.957336},
+ {-0.197937, 0.468903, -0.860748},
+ {0.895599, 0.399384, 0.195801},
+ {0.560791, 0.825012, -0.069214},
+ {0.304199, -0.849487, 0.43103},
+ {0.096375, 0.93576, 0.339111},
+ {-0.051422, 0.408966, -0.911072},
+ {0.330444, 0.942841, -0.042389},
+ {-0.452362, -0.786407, 0.420563},
+ {0.134308, -0.933472, -0.332489},
+ {0.80191, -0.566711, -0.188934},
+ {-0.987946, -0.105988, 0.112518},
+ {-0.24408, 0.892242, -0.379791},
+ {-0.920502, 0.229095, -0.316376},
+ {0.7789, 0.325958, 0.535706},
+ {-0.912872, 0.185211, -0.36377},
+ {-0.184784, 0.565369, -0.803833},
+ {-0.018463, 0.119537, 0.992615},
+ {-0.259247, -0.935608, 0.239532},
+ {-0.82373, -0.449127, -0.345947},
+ {-0.433105, 0.659515, 0.614349},
+ {-0.822754, 0.378845, -0.423676},
+ {0.687195, -0.674835, -0.26889},
+ {-0.246582, -0.800842, 0.545715},
+ {-0.729187, -0.207794, 0.651978},
+ {0.653534, -0.610443, -0.447388},
+ {0.492584, -0.023346, 0.869934},
+ {0.609039, 0.009094, -0.79306},
+ {0.962494, -0.271088, -0.00885},
+ {0.2659, -0.004913, 0.963959},
+ {0.651245, 0.553619, -0.518951},
+ {0.280548, -0.84314, 0.458618},
+ {-0.175293, -0.983215, 0.049805},
+ {0.035339, -0.979919, 0.196045},
+ {-0.982941, 0.164307, -0.082245},
+ {0.233734, -0.97226, -0.005005},
+ {-0.747253, -0.611328, 0.260437},
+ {0.645599, 0.592773, 0.481384},
+ {0.117706, -0.949524, -0.29068},
+ {-0.535004, -0.791901, -0.294312},
+ {-0.627167, -0.214447, 0.748718},
+ {-0.047974, -0.813477, -0.57959},
+ {-0.175537, 0.477264, -0.860992},
+ {0.738556, -0.414246, -0.53183},
+ {0.562561, -0.704071, 0.433289},
+ {-0.754944, 0.64801, -0.100586},
+ {0.114716, 0.044525, -0.992371},
+ {0.966003, 0.244873, -0.082764},
+ {0.33783, 0.715698, -0.611206},
+ {-0.944031, -0.326599, -0.045624},
+ {-0.101074, -0.416443, -0.903503},
+ {0.799286, 0.49411, -0.341949},
+ {-0.854645, 0.518036, 0.033936},
+ {0.42514, -0.437866, -0.792114},
+ {-0.358948, 0.597046, 0.717377},
+ {-0.985413, 0.144714, 0.089294},
+ {-0.601776, -0.33728, -0.723907},
+ {-0.449921, 0.594513, 0.666382},
+ {0.208313, -0.10791, 0.972076},
+ {0.575317, 0.060425, 0.815643},
+ {0.293365, -0.875702, -0.383453},
+ {0.293762, 0.465759, 0.834686},
+ {-0.846008, -0.233398, -0.47934},
+ {-0.115814, 0.143036, -0.98291},
+ {0.204681, -0.949036, -0.239532},
+ {0.946716, -0.263947, 0.184326},
+ {-0.235596, 0.573822, 0.784332},
+ {0.203705, -0.372253, -0.905487},
+ {0.756989, -0.651031, 0.055298},
+ {0.497803, 0.814697, -0.297363},
+ {-0.16214, 0.063995, -0.98468},
+ {-0.329254, 0.834381, 0.441925},
+ {0.703827, -0.527039, -0.476227},
+ {0.956421, 0.266113, 0.119781},
+ {0.480133, 0.482849, 0.7323},
+ {-0.18631, 0.961212, -0.203125},
+ {-0.748474, -0.656921, -0.090393},
+ {-0.085052, -0.165253, 0.982544},
+ {-0.76947, 0.628174, -0.115234},
+ {0.383148, 0.537659, 0.751068},
+ {0.616486, -0.668488, -0.415924},
+ {-0.259979, -0.630005, 0.73175},
+ {0.570953, -0.087952, 0.816223},
+ {-0.458008, 0.023254, 0.888611},
+ {-0.196167, 0.976563, -0.088287},
+ {-0.263885, -0.69812, -0.665527},
+ {0.437134, -0.892273, -0.112793},
+ {-0.621674, -0.230438, 0.748566},
+ {0.232422, 0.900574, -0.367249},
+ {0.22229, -0.796143, 0.562744},
+ {-0.665497, -0.73764, 0.11377},
+ {0.670135, 0.704803, 0.232605},
+ {0.895599, 0.429749, -0.114655},
+ {-0.11557, -0.474243, 0.872742},
+ {0.621826, 0.604004, -0.498444},
+ {-0.832214, 0.012756, 0.55426},
+ {-0.702484, 0.705994, -0.089661},
+ {-0.692017, 0.649292, 0.315399},
+ {-0.175995, -0.977997, 0.111877},
+ {0.096954, -0.04953, 0.994019},
+ {0.635284, -0.606689, -0.477783},
+ {-0.261261, -0.607422, -0.750153},
+ {0.983276, 0.165436, 0.075958},
+ {-0.29837, 0.404083, -0.864655},
+ {-0.638672, 0.507721, 0.578156},
+ {0.388214, 0.412079, 0.824249},
+ {0.556183, -0.208832, 0.804352},
+ {0.778442, 0.562012, 0.27951},
+ {-0.616577, 0.781921, -0.091522},
+ {0.196289, 0.051056, 0.979187},
+ {-0.121216, 0.207153, -0.970734},
+ {-0.173401, -0.384735, 0.906555},
+ {0.161499, -0.723236, -0.671387},
+ {0.178497, -0.006226, -0.983887},
+ {-0.126038, 0.15799, 0.97934},
+ {0.830475, -0.024811, 0.556458},
+ {-0.510132, -0.76944, 0.384247},
+ {0.81424, 0.200104, -0.544891},
+ {-0.112549, -0.393311, -0.912445},
+ {0.56189, 0.152222, -0.813049},
+ {0.198914, -0.254517, -0.946381},
+ {-0.41217, 0.690979, -0.593811},
+ {-0.407257, 0.324524, 0.853668},
+ {-0.690186, 0.366119, -0.624115},
+ {-0.428345, 0.844147, -0.322296},
+ {-0.21228, -0.297546, -0.930756},
+ {-0.273071, 0.516113, 0.811798},
+ {0.928314, 0.371643, 0.007233},
+ {0.785828, -0.479218, -0.390778},
+ {-0.704895, 0.058929, 0.706818},
+ {0.173248, 0.203583, 0.963562},
+ {0.422211, -0.904297, -0.062469},
+ {-0.363312, -0.182465, 0.913605},
+ {0.254028, -0.552307, -0.793945},
+ {-0.28891, -0.765747, -0.574554},
+ {0.058319, 0.291382, 0.954803},
+ {0.946136, -0.303925, 0.111267},
+ {-0.078156, 0.443695, -0.892731},
+ {0.182098, 0.89389, 0.409515},
+ {-0.680298, -0.213318, 0.701141},
+ {0.062469, 0.848389, -0.525635},
+ {-0.72879, -0.641846, 0.238342},
+ {-0.88089, 0.427673, 0.202637},
+ {-0.532501, -0.21405, 0.818878},
+ {0.948975, -0.305084, 0.07962},
+ {0.925446, 0.374664, 0.055817},
+ {0.820923, 0.565491, 0.079102},
+ {0.25882, 0.099792, -0.960724},
+ {-0.294617, 0.910522, 0.289978},
+ {0.137115, 0.320038, -0.937408},
+ {-0.908386, 0.345276, -0.235718},
+ {-0.936218, 0.138763, 0.322754},
+ {0.366577, 0.925934, -0.090637},
+ {0.309296, -0.686829, -0.657684},
+ {0.66983, 0.024445, 0.742065},
+ {-0.917999, -0.059113, -0.392059},
+ {0.365509, 0.462158, -0.807922},
+ {0.083374, 0.996399, -0.014801},
+ {0.593842, 0.253143, -0.763672},
+ {0.974976, -0.165466, 0.148285},
+ {0.918976, 0.137299, 0.369537},
+ {0.294952, 0.694977, 0.655731},
+ {0.943085, 0.152618, -0.295319},
+ {0.58783, -0.598236, 0.544495},
+ {0.203796, 0.678223, 0.705994},
+ {-0.478821, -0.661011, 0.577667},
+ {0.719055, -0.1698, -0.673828},
+ {-0.132172, -0.965332, 0.225006},
+ {-0.981873, -0.14502, 0.121979},
+ {0.763458, 0.579742, 0.284546},
+ {-0.893188, 0.079681, 0.442474},
+ {-0.795776, -0.523804, 0.303802},
+ {0.734955, 0.67804, -0.007446},
+ {0.15506, 0.986267, -0.056183},
+ {0.258026, 0.571503, -0.778931},
+ {-0.681549, -0.702087, -0.206116},
+ {-0.96286, -0.177185, 0.203613},
+ {-0.470978, -0.515106, 0.716095},
+ {-0.740326, 0.57135, 0.354095},
+ {-0.56012, -0.824982, -0.074982},
+ {-0.507874, 0.753204, 0.417969},
+ {-0.503113, 0.038147, 0.863342},
+ {0.594025, 0.673553, -0.439758},
+ {-0.119873, -0.005524, -0.992737},
+ {0.098267, -0.213776, 0.971893},
+ {-0.615631, 0.643951, 0.454163},
+ {0.896851, -0.441071, 0.032166},
+ {-0.555023, 0.750763, -0.358093},
+ {0.398773, 0.304688, 0.864929},
+ {-0.722961, 0.303589, 0.620544},
+ {-0.63559, -0.621948, -0.457306},
+ {-0.293243, 0.072327, 0.953278},
+ {-0.491638, 0.661041, -0.566772},
+ {-0.304199, -0.572083, -0.761688},
+ {0.908081, -0.398956, 0.127014},
+ {-0.523621, -0.549683, -0.650848},
+ {-0.932922, -0.19986, 0.299408},
+ {0.099426, 0.140869, 0.984985},
+ {-0.020325, -0.999756, -0.002319},
+ {0.952667, 0.280853, -0.11615},
+ {-0.971893, 0.082581, 0.220337},
+ {0.65921, 0.705292, -0.260651},
+ {0.733063, -0.175537, 0.657043},
+ {-0.555206, 0.429504, -0.712189},
+ {0.400421, -0.89859, 0.179352},
+ {0.750885, -0.19696, 0.630341},
+ {0.785675, -0.569336, 0.241821},
+ {-0.058899, -0.464111, 0.883789},
+ {0.129608, -0.94519, 0.299622},
+ {-0.357819, 0.907654, 0.219238},
+ {-0.842133, -0.439117, -0.312927},
+ {-0.313477, 0.84433, 0.434479},
+ {-0.241211, 0.053253, 0.968994},
+ {0.063873, 0.823273, 0.563965},
+ {0.476288, 0.862152, -0.172516},
+ {0.620941, -0.298126, 0.724915},
+ {0.25238, -0.749359, -0.612122},
+ {-0.577545, 0.386566, 0.718994},
+ {-0.406342, -0.737976, 0.538696},
+ {0.04718, 0.556305, 0.82959},
+ {-0.802856, 0.587463, 0.101166},
+ {-0.707733, -0.705963, 0.026428},
+ {0.374908, 0.68457, 0.625092},
+ {0.472137, 0.208405, -0.856506},
+ {-0.703064, -0.581085, -0.409821},
+ {-0.417206, -0.736328, 0.532623},
+ {-0.447876, -0.20285, -0.870728},
+ {0.086945, -0.990417, 0.107086},
+ {0.183685, 0.018341, -0.982788},
+ {0.560638, -0.428864, 0.708282},
+ {0.296722, -0.952576, -0.0672},
+ {0.135773, 0.990265, 0.030243},
+ {-0.068787, 0.654724, 0.752686},
+ {0.762604, -0.551758, 0.337585},
+ {-0.819611, -0.407684, 0.402466},
+ {-0.727844, -0.55072, -0.408539},
+ {-0.855774, -0.480011, 0.19281},
+ {0.693176, -0.079285, 0.716339},
+ {0.226013, 0.650116, -0.725433},
+ {0.246704, 0.953369, -0.173553},
+ {-0.970398, -0.239227, -0.03244},
+ {0.136383, -0.394318, 0.908752},
+ {0.813232, 0.558167, 0.164368},
+ {0.40451, 0.549042, -0.731323},
+ {-0.380249, -0.566711, 0.730865},
+ {0.022156, 0.932739, 0.359741},
+ {0.00824, 0.996552, -0.082306},
+ {0.956635, -0.065338, -0.283722},
+ {-0.743561, 0.008209, 0.668579},
+ {-0.859589, -0.509674, 0.035767},
+ {-0.852234, 0.363678, -0.375977},
+ {-0.201965, -0.970795, -0.12915},
+ {0.313477, 0.947327, 0.06546},
+ {-0.254028, -0.528259, 0.81015},
+ {0.628052, 0.601105, 0.49411},
+ {-0.494385, 0.868378, 0.037933},
+ {0.275635, -0.086426, 0.957336},
+ {-0.197937, 0.468903, -0.860748},
+ {0.895599, 0.399384, 0.195801},
+ {0.560791, 0.825012, -0.069214},
+ {0.304199, -0.849487, 0.43103},
+ {0.096375, 0.93576, 0.339111},
+ {-0.051422, 0.408966, -0.911072},
+ {0.330444, 0.942841, -0.042389},
+ {-0.452362, -0.786407, 0.420563},
+ {0.134308, -0.933472, -0.332489},
+ {0.80191, -0.566711, -0.188934},
+ {-0.987946, -0.105988, 0.112518},
+ {-0.24408, 0.892242, -0.379791},
+ {-0.920502, 0.229095, -0.316376},
+ {0.7789, 0.325958, 0.535706},
+ {-0.912872, 0.185211, -0.36377},
+ {-0.184784, 0.565369, -0.803833},
+ {-0.018463, 0.119537, 0.992615},
+ {-0.259247, -0.935608, 0.239532},
+ {-0.82373, -0.449127, -0.345947},
+ {-0.433105, 0.659515, 0.614349},
+ {-0.822754, 0.378845, -0.423676},
+ {0.687195, -0.674835, -0.26889},
+ {-0.246582, -0.800842, 0.545715},
+ {-0.729187, -0.207794, 0.651978},
+ {0.653534, -0.610443, -0.447388},
+ {0.492584, -0.023346, 0.869934},
+ {0.609039, 0.009094, -0.79306},
+ {0.962494, -0.271088, -0.00885},
+ {0.2659, -0.004913, 0.963959},
+ {0.651245, 0.553619, -0.518951},
+ {0.280548, -0.84314, 0.458618},
+ {-0.175293, -0.983215, 0.049805},
+ {0.035339, -0.979919, 0.196045},
+ {-0.982941, 0.164307, -0.082245},
+ {0.233734, -0.97226, -0.005005},
+ {-0.747253, -0.611328, 0.260437},
+ {0.645599, 0.592773, 0.481384},
+ {0.117706, -0.949524, -0.29068},
+ {-0.535004, -0.791901, -0.294312},
+ {-0.627167, -0.214447, 0.748718},
+ {-0.047974, -0.813477, -0.57959},
+ {-0.175537, 0.477264, -0.860992},
+ {0.738556, -0.414246, -0.53183},
+ {0.562561, -0.704071, 0.433289},
+ {-0.754944, 0.64801, -0.100586},
+ {0.114716, 0.044525, -0.992371},
+ {0.966003, 0.244873, -0.082764},
+ {0.33783, 0.715698, -0.611206},
+ {-0.944031, -0.326599, -0.045624},
+};
diff --git a/source/blender/blenlib/intern/psfont.c b/source/blender/blenlib/intern/psfont.c
index cf58f44ad2c..54d7f8ec1af 100644
--- a/source/blender/blenlib/intern/psfont.c
+++ b/source/blender/blenlib/intern/psfont.c
@@ -43,6 +43,8 @@
#include "DNA_packedFile_types.h"
#include "DNA_curve_types.h"
+#include "BLO_sys_types.h" // for intptr_t support
+
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
@@ -54,7 +56,7 @@ typedef struct chardesc {
short llx, lly; /* bounding box */
short urx, ury;
short *data; /* char data */
- long datalen;
+ intptr_t datalen;
} chardesc;
typedef struct objfnt {
@@ -256,290 +258,290 @@ static int sp;
static int savesplines = 1;
static pschar ISOcharlist[NASCII] = {
- "/space", 040, 0,
- "/exclam", 041, 0,
- "/quotedbl", 042, 0,
- "/numbersign", 043, 0,
- "/dollar", 044, 0,
- "/percent", 045, 0,
- "/ampersand", 046, 0,
- "/quoteright", 047, 0,
-
- "/parenleft", 050, 0,
- "/parenright", 051, 0,
- "/asterisk", 052, 0,
- "/plus", 053, 0,
- "/comma", 054, 0,
- "/hyphen", 055, 0,
- "/period", 056, 0,
- "/slash", 057, 0,
-
- "/zero", 060, 0,
- "/one", 061, 0,
- "/two", 062, 0,
- "/three", 063, 0,
- "/four", 064, 0,
- "/five", 065, 0,
- "/six", 066, 0,
- "/seven", 067, 0,
-
- "/eight", 070, 0,
- "/nine", 071, 0,
- "/colon", 072, 0,
- "/semicolon", 073, 0,
- "/less", 074, 0,
- "/equal", 075, 0,
- "/greater", 076, 0,
- "/question", 077, 0,
-
- "/at", 0100, 0,
- "/A", 0101, 0,
- "/B", 0102, 0,
- "/C", 0103, 0,
- "/D", 0104, 0,
- "/E", 0105, 0,
- "/F", 0106, 0,
- "/G", 0107, 0,
-
- "/H", 0110, 0,
- "/I", 0111, 0,
- "/J", 0112, 0,
- "/K", 0113, 0,
- "/L", 0114, 0,
- "/M", 0115, 0,
- "/N", 0116, 0,
- "/O", 0117, 0,
-
- "/P", 0120, 0,
- "/Q", 0121, 0,
- "/R", 0122, 0,
- "/S", 0123, 0,
- "/T", 0124, 0,
- "/U", 0125, 0,
- "/V", 0126, 0,
- "/W", 0127, 0,
-
- "/X", 0130, 0,
- "/Y", 0131, 0,
- "/Z", 0132, 0,
- "/bracketleft", 0133, 0,
- "/backslash", 0134, 0,
- "/bracketright", 0135, 0,
- "/asciicircum", 0136, 0,
- "/underscore", 0137, 0,
-
- "/quoteleft", 0140, 0,
- "/a", 0141, 0,
- "/b", 0142, 0,
- "/c", 0143, 0,
- "/d", 0144, 0,
- "/e", 0145, 0,
- "/f", 0146, 0,
- "/g", 0147, 0,
-
- "/h", 0150, 0,
- "/i", 0151, 0,
- "/j", 0152, 0,
- "/k", 0153, 0,
- "/l", 0154, 0,
- "/m", 0155, 0,
- "/n", 0156, 0,
- "/o", 0157, 0,
-
- "/p", 0160, 0,
- "/q", 0161, 0,
- "/r", 0162, 0,
- "/s", 0163, 0,
- "/t", 0164, 0,
- "/u", 0165, 0,
- "/v", 0166, 0,
- "/w", 0167, 0,
-
- "/x", 0170, 0,
- "/y", 0171, 0,
- "/z", 0172, 0,
- "/braceleft", 0173, 0,
- "/bar", 0174, 0,
- "/braceright", 0175, 0,
- "/asciitilde", 0176, 0,
- "/", 0177, 0,
+ {"/space", 040, 0},
+ {"/exclam", 041, 0},
+ {"/quotedbl", 042, 0},
+ {"/numbersign", 043, 0},
+ {"/dollar", 044, 0},
+ {"/percent", 045, 0},
+ {"/ampersand", 046, 0},
+ {"/quoteright", 047, 0},
+
+ {"/parenleft", 050, 0},
+ {"/parenright", 051, 0},
+ {"/asterisk", 052, 0},
+ {"/plus", 053, 0},
+ {"/comma", 054, 0},
+ {"/hyphen", 055, 0},
+ {"/period", 056, 0},
+ {"/slash", 057, 0},
+
+ {"/zero", 060, 0},
+ {"/one", 061, 0},
+ {"/two", 062, 0},
+ {"/three", 063, 0},
+ {"/four", 064, 0},
+ {"/five", 065, 0},
+ {"/six", 066, 0},
+ {"/seven", 067, 0},
+
+ {"/eight", 070, 0},
+ {"/nine", 071, 0},
+ {"/colon", 072, 0},
+ {"/semicolon", 073, 0},
+ {"/less", 074, 0},
+ {"/equal", 075, 0},
+ {"/greater", 076, 0},
+ {"/question", 077, 0},
+
+ {"/at", 0100, 0},
+ {"/A", 0101, 0},
+ {"/B", 0102, 0},
+ {"/C", 0103, 0},
+ {"/D", 0104, 0},
+ {"/E", 0105, 0},
+ {"/F", 0106, 0},
+ {"/G", 0107, 0},
+
+ {"/H", 0110, 0},
+ {"/I", 0111, 0},
+ {"/J", 0112, 0},
+ {"/K", 0113, 0},
+ {"/L", 0114, 0},
+ {"/M", 0115, 0},
+ {"/N", 0116, 0},
+ {"/O", 0117, 0},
+
+ {"/P", 0120, 0},
+ {"/Q", 0121, 0},
+ {"/R", 0122, 0},
+ {"/S", 0123, 0},
+ {"/T", 0124, 0},
+ {"/U", 0125, 0},
+ {"/V", 0126, 0},
+ {"/W", 0127, 0},
+
+ {"/X", 0130, 0},
+ {"/Y", 0131, 0},
+ {"/Z", 0132, 0},
+ {"/bracketleft", 0133, 0},
+ {"/backslash", 0134, 0},
+ {"/bracketright", 0135, 0},
+ {"/asciicircum", 0136, 0},
+ {"/underscore", 0137, 0},
+
+ {"/quoteleft", 0140, 0},
+ {"/a", 0141, 0},
+ {"/b", 0142, 0},
+ {"/c", 0143, 0},
+ {"/d", 0144, 0},
+ {"/e", 0145, 0},
+ {"/f", 0146, 0},
+ {"/g", 0147, 0},
+
+ {"/h", 0150, 0},
+ {"/i", 0151, 0},
+ {"/j", 0152, 0},
+ {"/k", 0153, 0},
+ {"/l", 0154, 0},
+ {"/m", 0155, 0},
+ {"/n", 0156, 0},
+ {"/o", 0157, 0},
+
+ {"/p", 0160, 0},
+ {"/q", 0161, 0},
+ {"/r", 0162, 0},
+ {"/s", 0163, 0},
+ {"/t", 0164, 0},
+ {"/u", 0165, 0},
+ {"/v", 0166, 0},
+ {"/w", 0167, 0},
+
+ {"/x", 0170, 0},
+ {"/y", 0171, 0},
+ {"/z", 0172, 0},
+ {"/braceleft", 0173, 0},
+ {"/bar", 0174, 0},
+ {"/braceright", 0175, 0},
+ {"/asciitilde", 0176, 0},
+ {"/", 0177, 0},
/* nonstandard defs */
- "/quotedblleft", 0200, 0,
- "/quotedblright", 0201, 0,
- "/quotedblbase", 0202, 0,
- "/quotesinglbase", 0203, 0,
- "/guilsinglleft", 0204, 0,
- "/guilsinglright", 0205, 0,
- "/endash", 0206, 0,
- "/dagger", 0207, 0,
-
- "/daggerdbl", 0210, 0,
- "/trademark", 0211, 0,
- "/bullet", 0212, 0,
- "/perthousand", 0213, 0,
- "/Lslash", 0214, 0,
- "/OE", 0215, 0,
- "/lslash", 0216, 0,
- "/oe", 0217, 0,
+ {"/quotedblleft", 0200, 0},
+ {"/quotedblright", 0201, 0},
+ {"/quotedblbase", 0202, 0},
+ {"/quotesinglbase", 0203, 0},
+ {"/guilsinglleft", 0204, 0},
+ {"/guilsinglright", 0205, 0},
+ {"/endash", 0206, 0},
+ {"/dagger", 0207, 0},
+
+ {"/daggerdbl", 0210, 0},
+ {"/trademark", 0211, 0},
+ {"/bullet", 0212, 0},
+ {"/perthousand", 0213, 0},
+ {"/Lslash", 0214, 0},
+ {"/OE", 0215, 0},
+ {"/lslash", 0216, 0},
+ {"/oe", 0217, 0},
/* endnonstandard defs */
- "/dotlessi", 0220, 0,
- "/grave", 0221, 0,
- "/acute", 0222, 0,
- "/circumflex", 0223, 0,
- "/tilde", 0224, 0,
- "/", 0225, 0,
- "/breve", 0226, 0,
- "/dotaccent", 0227, 0,
-
- "/", 0230, 0,
- "/", 0231, 0,
- "/ring", 0232, 0,
- "/", 0233, 0,
- "/", 0234, 0,
- "/hungarumlaut", 0235, 0,
- "/ogonek", 0236, 0,
- "/caron", 0237, 0,
-
- "/", 0240, 0,
- "/exclamdown", 0241, 0,
- "/cent", 0242, 0,
- "/sterling", 0243, 0,
- "/florin", 0244, 0,
- "/yen", 0245, 0,
- "/brokenbar", 0246, 0,
- "/section", 0247, 0,
-
- "/dieresis", 0250, 0,
- "/copyright", 0251, 0,
- "/ordfeminine", 0252, 0,
- "/guillemotleft", 0253, 0,
- "/logicalnot", 0254, 0,
- "/hyphen", 0255, 0,
- "/registered", 0256, 0,
- "/macron", 0257, 0,
-
- "/degree", 0260, 0,
- "/plusminus", 0261, 0,
- "/twosuperior", 0262, 0,
- "/threesuperior", 0263, 0,
- "/acute", 0264, 0,
- "/mu", 0265, 0,
- "/paragraph", 0266, 0,
- "/periodcentered", 0267, 0,
-
- "/cedilla", 0270, 0,
- "/onesuperior", 0271, 0,
- "/ordmasculine", 0272, 0,
- "/guillemotright", 0273, 0,
- "/onequarter", 0274, 0,
- "/onehalf", 0275, 0,
- "/threequarters", 0276, 0,
- "/questiondown", 0277, 0,
-
- "/Agrave", 0300, 0,
- "/Aacute", 0301, 0,
- "/Acircumflex", 0302, 0,
- "/Atilde", 0303, 0,
- "/Adieresis", 0304, 0,
- "/Aring", 0305, 0,
- "/AE", 0306, 0,
- "/Ccedilla", 0307, 0,
-
- "/Egrave", 0310, 0,
- "/Eacute", 0311, 0,
- "/Ecircumflex", 0312, 0,
- "/Edieresis", 0313, 0,
- "/Igrave", 0314, 0,
- "/Iacute", 0315, 0,
- "/Icircumflex", 0316, 0,
- "/Idieresis", 0317, 0,
-
- "/Eth", 0320, 0,
- "/Ntilde", 0321, 0,
- "/Ograve", 0322, 0,
- "/Oacute", 0323, 0,
- "/Ocircumflex", 0324, 0,
- "/Otilde", 0325, 0,
- "/Odieresis", 0326, 0,
- "/multiply", 0327, 0,
-
- "/Oslash", 0330, 0,
- "/Ugrave", 0331, 0,
- "/Uacute", 0332, 0,
- "/Ucircumflex", 0333, 0,
- "/Udieresis", 0334, 0,
- "/Yacute", 0335, 0,
- "/Thorn", 0336, 0,
- "/germandbls", 0337, 0,
-
- "/agrave", 0340, 0,
- "/aacute", 0341, 0,
- "/acircumflex", 0342, 0,
- "/atilde", 0343, 0,
- "/adieresis", 0344, 0,
- "/aring", 0345, 0,
- "/ae", 0346, 0,
- "/ccedilla", 0347, 0,
-
- "/egrave", 0350, 0,
- "/eacute", 0351, 0,
- "/ecircumflex", 0352, 0,
- "/edieresis", 0353, 0,
- "/igrave", 0354, 0,
- "/iacute", 0355, 0,
- "/icircumflex", 0356, 0,
- "/idieresis", 0357, 0,
-
- "/eth", 0360, 0,
- "/ntilde", 0361, 0,
- "/ograve", 0362, 0,
- "/oacute", 0363, 0,
- "/ocircumflex", 0364, 0,
- "/otilde", 0365, 0,
- "/odieresis", 0366, 0,
- "/divide", 0367, 0,
-
- "/oslash", 0370, 0,
- "/ugrave", 0371, 0,
- "/uacute", 0372, 0,
- "/ucircumflex", 0373, 0,
- "/udieresis", 0374, 0,
- "/yacute", 0375, 0,
- "/thorn", 0376, 0,
- "/ydieresis", 0377, 0,
+ {"/dotlessi", 0220, 0},
+ {"/grave", 0221, 0},
+ {"/acute", 0222, 0},
+ {"/circumflex", 0223, 0},
+ {"/tilde", 0224, 0},
+ {"/", 0225, 0},
+ {"/breve", 0226, 0},
+ {"/dotaccent", 0227, 0},
+
+ {"/", 0230, 0},
+ {"/", 0231, 0},
+ {"/ring", 0232, 0},
+ {"/", 0233, 0},
+ {"/", 0234, 0},
+ {"/hungarumlaut", 0235, 0},
+ {"/ogonek", 0236, 0},
+ {"/caron", 0237, 0},
+
+ {"/", 0240, 0},
+ {"/exclamdown", 0241, 0},
+ {"/cent", 0242, 0},
+ {"/sterling", 0243, 0},
+ {"/florin", 0244, 0},
+ {"/yen", 0245, 0},
+ {"/brokenbar", 0246, 0},
+ {"/section", 0247, 0},
+
+ {"/dieresis", 0250, 0},
+ {"/copyright", 0251, 0},
+ {"/ordfeminine", 0252, 0},
+ {"/guillemotleft", 0253, 0},
+ {"/logicalnot", 0254, 0},
+ {"/hyphen", 0255, 0},
+ {"/registered", 0256, 0},
+ {"/macron", 0257, 0},
+
+ {"/degree", 0260, 0},
+ {"/plusminus", 0261, 0},
+ {"/twosuperior", 0262, 0},
+ {"/threesuperior", 0263, 0},
+ {"/acute", 0264, 0},
+ {"/mu", 0265, 0},
+ {"/paragraph", 0266, 0},
+ {"/periodcentered", 0267, 0},
+
+ {"/cedilla", 0270, 0},
+ {"/onesuperior", 0271, 0},
+ {"/ordmasculine", 0272, 0},
+ {"/guillemotright", 0273, 0},
+ {"/onequarter", 0274, 0},
+ {"/onehalf", 0275, 0},
+ {"/threequarters", 0276, 0},
+ {"/questiondown", 0277, 0},
+
+ {"/Agrave", 0300, 0},
+ {"/Aacute", 0301, 0},
+ {"/Acircumflex", 0302, 0},
+ {"/Atilde", 0303, 0},
+ {"/Adieresis", 0304, 0},
+ {"/Aring", 0305, 0},
+ {"/AE", 0306, 0},
+ {"/Ccedilla", 0307, 0},
+
+ {"/Egrave", 0310, 0},
+ {"/Eacute", 0311, 0},
+ {"/Ecircumflex", 0312, 0},
+ {"/Edieresis", 0313, 0},
+ {"/Igrave", 0314, 0},
+ {"/Iacute", 0315, 0},
+ {"/Icircumflex", 0316, 0},
+ {"/Idieresis", 0317, 0},
+
+ {"/Eth", 0320, 0},
+ {"/Ntilde", 0321, 0},
+ {"/Ograve", 0322, 0},
+ {"/Oacute", 0323, 0},
+ {"/Ocircumflex", 0324, 0},
+ {"/Otilde", 0325, 0},
+ {"/Odieresis", 0326, 0},
+ {"/multiply", 0327, 0},
+
+ {"/Oslash", 0330, 0},
+ {"/Ugrave", 0331, 0},
+ {"/Uacute", 0332, 0},
+ {"/Ucircumflex",0333, 0},
+ {"/Udieresis", 0334, 0},
+ {"/Yacute", 0335, 0},
+ {"/Thorn", 0336, 0},
+ {"/germandbls", 0337, 0},
+
+ {"/agrave", 0340, 0},
+ {"/aacute", 0341, 0},
+ {"/acircumflex",0342, 0},
+ {"/atilde", 0343, 0},
+ {"/adieresis", 0344, 0},
+ {"/aring", 0345, 0},
+ {"/ae", 0346, 0},
+ {"/ccedilla", 0347, 0},
+
+ {"/egrave", 0350, 0},
+ {"/eacute", 0351, 0},
+ {"/ecircumflex", 0352, 0},
+ {"/edieresis", 0353, 0},
+ {"/igrave", 0354, 0},
+ {"/iacute", 0355, 0},
+ {"/icircumflex", 0356, 0},
+ {"/idieresis", 0357, 0},
+
+ {"/eth", 0360, 0},
+ {"/ntilde", 0361, 0},
+ {"/ograve", 0362, 0},
+ {"/oacute", 0363, 0},
+ {"/ocircumflex",0364, 0},
+ {"/otilde", 0365, 0},
+ {"/odieresis", 0366, 0},
+ {"/divide", 0367, 0},
+
+ {"/oslash", 0370, 0},
+ {"/ugrave", 0371, 0},
+ {"/uacute", 0372, 0},
+ {"/ucircumflex",0373, 0},
+ {"/udieresis", 0374, 0},
+ {"/yacute", 0375, 0},
+ {"/thorn", 0376, 0},
+ {"/ydieresis", 0377, 0},
};
static short STDvsISO [][2] = {
- 0341, 0306, /* AE */
- 0351, 0330, /* Oslash */
- 0302, 0222, /* acute */
- 0361, 0346, /* ae */
- 0306, 0226, /* breve */
- 0317, 0237, /* caron */
- 0313, 0270, /* cedilla */
- 0303, 0223, /* circumflex */
- 0250, 0244, /* currency */
- 0310, 0250, /* dieresis */
- 0307, 0227, /* dotaccent */
- 0365, 0220, /* dotlessi */
- 0373, 0337, /* germandbls */
- 0301, 0221, /* grave */
- 0315, 0235, /* hungarumlaut */
- 0055, 0255, /* hyphen */
- 0305, 0257, /* macron */
- 0316, 0236, /* ogenek */
- 0343, 0252, /* ordfeminine */
- 0353, 0272, /* ordmasculine */
- 0371, 0370, /* oslash */
- 0264, 0267, /* periodcentered */
- 0312, 0232, /* ring */
- 0304, 0224, /* tilde */
+ {0341, 0306}, /* AE */
+ {0351, 0330}, /* Oslash */
+ {0302, 0222}, /* acute */
+ {0361, 0346}, /* ae */
+ {0306, 0226}, /* breve */
+ {0317, 0237}, /* caron */
+ {0313, 0270}, /* cedilla */
+ {0303, 0223}, /* circumflex */
+ {0250, 0244}, /* currency */
+ {0310, 0250}, /* dieresis */
+ {0307, 0227}, /* dotaccent */
+ {0365, 0220}, /* dotlessi */
+ {0373, 0337}, /* germandbls */
+ {0301, 0221}, /* grave */
+ {0315, 0235}, /* hungarumlaut */
+ {0055, 0255}, /* hyphen */
+ {0305, 0257}, /* macron */
+ {0316, 0236}, /* ogenek */
+ {0343, 0252}, /* ordfeminine */
+ {0353, 0272}, /* ordmasculine */
+ {0371, 0370}, /* oslash */
+ {0264, 0267}, /* periodcentered */
+ {0312, 0232}, /* ring */
+ {0304, 0224}, /* tilde */
};
/* from objfont.c, rest is in lfm_s !!*/
@@ -975,7 +977,7 @@ static void applymat(float mat[][2], float *x, float *y)
static void setcharlist(void)
{
- char *name, found;
+ char *name; /*found;*/
int i, j;
for(i=0; i<NASCII; i++) ISOcharlist[i].prog = -1;
@@ -983,11 +985,11 @@ static void setcharlist(void)
for(j=0; j<my_nchars; j++) {
name = my_charname[j];
if(name) {
- found = 0;
+ /*found = 0;*/
for(i=0; i<NASCII; i++) {
if(ISOcharlist[i].name && (strcmp(name,ISOcharlist[i].name) == 0)){
ISOcharlist[i].prog = j;
- found = 1;
+ /*found = 1;*/
}
}
/*if (found == 0) printf("no match found for: %s\n", name);*/
@@ -1256,10 +1258,10 @@ static void subr0(void)
int x1, y1;
int x2, y2;
int x3, y3;
- int xpos, ypos, noise;
+ int noise;
- ypos = pop();
- xpos = pop();
+ pop(); /* xpos, unused */
+ pop(); /* ypos, unused */
noise = pop();
if(coordpos!=7) {
fprintf(stderr,"subr0: bad poop\n");
@@ -1946,7 +1948,7 @@ static VFontData *objfnt_to_vfontdata(objfnt *fnt)
chardesc *cd;
short *_data, *data;
int a, i, count, stop, ready, meet;
- short first[2], last[2];
+ short first[2]={0,0}, last[2]={0,0};
struct Nurb *nu;
struct BezTriple *bezt, *bez2;
float scale, dx, dy;
@@ -2017,7 +2019,7 @@ static VFontData *objfnt_to_vfontdata(objfnt *fnt)
nu->type= CU_BEZIER+CU_2D;
nu->pntsu = count;
nu->resolu= 8;
- nu->flagu= 1;
+ nu->flagu= CU_CYCLIC;
nu->bezt = bezt;
stop = 0;
diff --git a/source/blender/blenlib/intern/rand.c b/source/blender/blenlib/intern/rand.c
index ccc478203fe..c484a307393 100644
--- a/source/blender/blenlib/intern/rand.c
+++ b/source/blender/blenlib/intern/rand.c
@@ -81,6 +81,16 @@ void rng_seed(RNG *rng, unsigned int seed) {
rng->X= (((r_uint64) seed)<<16) | LOWSEED;
}
+void rng_srandom(RNG *rng, unsigned int seed) {
+ extern unsigned char hash[]; // noise.c
+
+ rng_seed(rng, seed + hash[seed & 255]);
+ seed= rng_getInt(rng);
+ rng_seed(rng, seed + hash[seed & 255]);
+ seed= rng_getInt(rng);
+ rng_seed(rng, seed + hash[seed & 255]);
+}
+
int rng_getInt(RNG *rng) {
rng->X= (MULTIPLIER*rng->X + ADDEND)&MASK;
return (int) (rng->X>>17);
@@ -132,13 +142,7 @@ void BLI_srand(unsigned int seed) {
/* using hash table to create better seed */
void BLI_srandom(unsigned int seed) {
- extern unsigned char hash[]; // noise.c
-
- rng_seed(&theBLI_rng, seed + hash[seed & 255]);
- seed= rng_getInt(&theBLI_rng);
- rng_seed(&theBLI_rng, seed + hash[seed & 255]);
- seed= rng_getInt(&theBLI_rng);
- rng_seed(&theBLI_rng, seed + hash[seed & 255]);
+ rng_srandom(&theBLI_rng, seed);
}
int BLI_rand(void) {
diff --git a/source/blender/blenlib/intern/storage.c b/source/blender/blenlib/intern/storage.c
index 6e64a98af2a..ca7a376d3a2 100644
--- a/source/blender/blenlib/intern/storage.c
+++ b/source/blender/blenlib/intern/storage.c
@@ -47,7 +47,9 @@
#include <time.h>
#include <sys/stat.h>
-#if !defined(linux) && (defined(__sgi) || defined(__sun__) || defined(__sun) || defined(__sparc) || defined(__sparc__))
+#if defined (__sun__) || defined (__sun)
+#include <sys/statvfs.h> /* Other modern unix os's should probably use this also */
+#elif !defined(__FreeBSD__) && !defined(linux) && (defined(__sgi) || defined(__sparc) || defined(__sparc__))
#include <sys/statfs.h>
#endif
@@ -176,7 +178,12 @@ double BLI_diskfree(char *dir)
return (double) (freec*bytesps*sectorspc);
#else
+
+#if defined (__sun__) || defined (__sun)
+ struct statvfs disk;
+#else
struct statfs disk;
+#endif
char name[FILE_MAXDIR],*slash;
int len = strlen(dir);
@@ -196,12 +203,12 @@ double BLI_diskfree(char *dir)
#ifdef __BeOS
return -1;
#endif
-#if !defined(linux) && (defined (__sgi) || defined (__sun__) || defined (__sun) || defined(__sparc) || defined(__sparc__))
- if (statfs(name, &disk, sizeof(struct statfs), 0)){
- /* printf("diskfree: Couldn't get information about %s.\n",dir); */
- return(-1);
- }
+#if defined (__sun__) || defined (__sun)
+ if (statvfs(name, &disk)) return(-1);
+#elif !defined(__FreeBSD__) && !defined(linux) && (defined (__sgi) || defined(__sparc) || defined(__sparc__))
+ /* WARNING - This may not be supported by geeneric unix os's - Campbell */
+ if (statfs(name, &disk, sizeof(struct statfs), 0)) return(-1);
#endif
return ( ((double) disk.f_bsize) * ((double) disk.f_bfree));
@@ -326,11 +333,11 @@ void BLI_adddirstrings()
char size[250];
static char * types[8] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
int num, mode;
- int num1, num2, num3, num4;
+ off_t num1, num2, num3, num4, num5;
#ifdef WIN32
__int64 st_size;
#else
- long long st_size;
+ off_t st_size;
#endif
struct direntry * file;
@@ -392,7 +399,7 @@ void BLI_adddirstrings()
* will buy us some time until files get bigger than 4GB or until
* everyone starts using __USE_FILE_OFFSET64 or equivalent.
*/
- st_size= (unsigned int)files[num].s.st_size;
+ st_size= (off_t)files[num].s.st_size;
num1= st_size % 1000;
num2= st_size/1000;
@@ -401,11 +408,15 @@ void BLI_adddirstrings()
num3= num3 % 1000;
num4= st_size/(1000*1000*1000);
num4= num4 % 1000;
-
- if(num4) sprintf(files[num].size, "%3d %03d %03d %03d", num4, num3, num2, num1);
- else if(num3) sprintf(files[num].size, "%7d %03d %03d", num3, num2, num1);
- else if(num2) sprintf(files[num].size, "%11d %03d", num2, num1);
- else if(num1) sprintf(files[num].size, "%15d", num1);
+ num5= st_size/(1000000000000LL);
+ num5= num5 % 1000;
+
+ if(num5)
+ sprintf(files[num].size, "%1d %03d %03d %03d K", (int)num5, (int)num4, (int)num3, (int)num2);
+ else if(num4) sprintf(files[num].size, "%3d %03d %03d %03d", (int)num4, (int)num3, (int)num2, (int)num1);
+ else if(num3) sprintf(files[num].size, "%7d %03d %03d", (int)num3, (int)num2, (int)num1);
+ else if(num2) sprintf(files[num].size, "%11d %03d", (int)num2, (int)num1);
+ else if(num1) sprintf(files[num].size, "%15d", (int)num1);
else sprintf(files[num].size, "0");
strftime(datum, 32, "%d-%b-%y %H:%M", tm);
@@ -469,6 +480,17 @@ int BLI_filesize(int file)
return (buf.st_size);
}
+int BLI_filepathsize(const char *path)
+{
+ int size, file = open(path, O_BINARY|O_RDONLY);
+
+ if (file <= 0)
+ return -1;
+
+ size = BLI_filesize(file);
+ close(file);
+ return size;
+}
int BLI_exist(char *name)
diff --git a/source/blender/blenlib/intern/threads.c b/source/blender/blenlib/intern/threads.c
index 1f05070b034..9df8bbc81e3 100644
--- a/source/blender/blenlib/intern/threads.c
+++ b/source/blender/blenlib/intern/threads.c
@@ -1,6 +1,6 @@
/**
*
- * $Id:
+ * $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -38,6 +38,17 @@
#include "BLI_blenlib.h"
#include "BLI_threads.h"
+#include "PIL_time.h"
+
+/* for checking system threads - BLI_system_thread_count */
+#ifdef WIN32
+#include "Windows.h"
+#elif defined(__APPLE__)
+#include <sys/types.h>
+#include <sys/sysctl.h>
+#else
+#include <unistd.h>
+#endif
/* ********** basic thread control API ************
@@ -190,6 +201,34 @@ void BLI_remove_thread(ListBase *threadbase, void *callerdata)
}
}
+void BLI_remove_thread_index(ListBase *threadbase, int index)
+{
+ ThreadSlot *tslot;
+ int counter=0;
+
+ for(tslot = threadbase->first; tslot; tslot = tslot->next, counter++) {
+ if (counter == index && tslot->avail == 0) {
+ tslot->callerdata = NULL;
+ pthread_join(tslot->pthread, NULL);
+ tslot->avail = 1;
+ break;
+ }
+ }
+}
+
+void BLI_remove_threads(ListBase *threadbase)
+{
+ ThreadSlot *tslot;
+
+ for(tslot = threadbase->first; tslot; tslot = tslot->next) {
+ if (tslot->avail == 0) {
+ tslot->callerdata = NULL;
+ pthread_join(tslot->pthread, NULL);
+ tslot->avail = 1;
+ }
+ }
+}
+
void BLI_end_threads(ListBase *threadbase)
{
ThreadSlot *tslot;
@@ -224,4 +263,136 @@ void BLI_unlock_thread(int type)
pthread_mutex_unlock(&_custom1_lock);
}
+/* how many threads are native on this system? */
+int BLI_system_thread_count( void )
+{
+ int t;
+#ifdef WIN32
+ SYSTEM_INFO info;
+ GetSystemInfo(&info);
+ t = (int) info.dwNumberOfProcessors;
+#else
+# ifdef __APPLE__
+ int mib[2];
+ size_t len;
+
+ mib[0] = CTL_HW;
+ mib[1] = HW_NCPU;
+ len = sizeof(t);
+ sysctl(mib, 2, &t, &len, NULL, 0);
+# elif defined(__sgi)
+ t = sysconf(_SC_NPROC_ONLN);
+# else
+ t = (int)sysconf(_SC_NPROCESSORS_ONLN);
+# endif
+#endif
+
+ if (t>RE_MAX_THREAD)
+ return RE_MAX_THREAD;
+ if (t<1)
+ return 1;
+
+ return t;
+}
+
+/* ************************************************ */
+
+typedef struct ThreadedWorker {
+ ListBase threadbase;
+ void *(*work_fnct)(void *);
+ char busy[RE_MAX_THREAD];
+ int total;
+ int sleep_time;
+} ThreadedWorker;
+
+typedef struct WorkParam {
+ ThreadedWorker *worker;
+ void *param;
+ int index;
+} WorkParam;
+
+void *exec_work_fnct(void *v_param)
+{
+ WorkParam *p = (WorkParam*)v_param;
+ void *value;
+
+ value = p->worker->work_fnct(p->param);
+
+ p->worker->busy[p->index] = 0;
+ MEM_freeN(p);
+
+ return value;
+}
+
+ThreadedWorker *BLI_create_worker(void *(*do_thread)(void *), int tot, int sleep_time)
+{
+ ThreadedWorker *worker;
+
+ worker = MEM_callocN(sizeof(ThreadedWorker), "threadedworker");
+
+ if (tot > RE_MAX_THREAD)
+ {
+ tot = RE_MAX_THREAD;
+ }
+ else if (tot < 1)
+ {
+ tot= 1;
+ }
+
+ worker->total = tot;
+ worker->work_fnct = do_thread;
+
+ BLI_init_threads(&worker->threadbase, exec_work_fnct, tot);
+
+ return worker;
+}
+
+void BLI_end_worker(ThreadedWorker *worker)
+{
+ BLI_remove_threads(&worker->threadbase);
+}
+
+void BLI_destroy_worker(ThreadedWorker *worker)
+{
+ BLI_end_worker(worker);
+ BLI_freelistN(&worker->threadbase);
+ MEM_freeN(worker);
+}
+
+void BLI_insert_work(ThreadedWorker *worker, void *param)
+{
+ WorkParam *p = MEM_callocN(sizeof(WorkParam), "workparam");
+ int index;
+
+ if (BLI_available_threads(&worker->threadbase) == 0)
+ {
+ index = worker->total;
+ while(index == worker->total)
+ {
+ PIL_sleep_ms(worker->sleep_time);
+
+ for (index = 0; index < worker->total; index++)
+ {
+ if (worker->busy[index] == 0)
+ {
+ BLI_remove_thread_index(&worker->threadbase, index);
+ break;
+ }
+ }
+ }
+ }
+ else
+ {
+ index = BLI_available_thread_index(&worker->threadbase);
+ }
+
+ worker->busy[index] = 1;
+
+ p->param = param;
+ p->index = index;
+ p->worker = worker;
+
+ BLI_insert_thread(&worker->threadbase, p);
+}
+
/* eof */
diff --git a/source/blender/blenlib/intern/util.c b/source/blender/blenlib/intern/util.c
index 97ed881fcc8..d3cfdf6417c 100644
--- a/source/blender/blenlib/intern/util.c
+++ b/source/blender/blenlib/intern/util.c
@@ -38,11 +38,14 @@
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
+#include <math.h> /* for log10 */
#include "MEM_guardedalloc.h"
-#include "BLI_blenlib.h"
#include "DNA_listBase.h"
+#include "DNA_userdef_types.h"
+
+#include "BLI_blenlib.h"
#include "BLI_storage.h"
#include "BLI_storage_types.h"
#include "BLI_dynamiclist.h"
@@ -62,6 +65,14 @@
#endif
#ifdef WIN32
+
+#ifdef _WIN32_IE
+#undef _WIN32_IE
+#endif
+#define _WIN32_IE 0x0501
+#include <windows.h>
+#include <shlobj.h>
+
#include "BLI_winstuff.h"
/* for duplicate_defgroup */
@@ -81,6 +92,10 @@
#include <CoreFoundation/CoreFoundation.h>
#endif
+#ifdef __linux__
+#include "binreloc.h"
+#endif
+
/* local */
static int add_win32_extension(char *name);
@@ -213,6 +228,79 @@ void BLI_newname(char *name, int add)
BLI_stringenc(name, head, tail, digits, pic);
}
+/* little helper macro for BLI_uniquename */
+#ifndef GIVE_STRADDR
+ #define GIVE_STRADDR(data, offset) ( ((char *)data) + offset )
+#endif
+
+/* Generic function to set a unique name. It is only designed to be used in situations
+ * where the name is part of the struct, and also that the name is at most 128 chars long.
+ *
+ * For places where this is used, see constraint.c for example...
+ *
+ * name_offs: should be calculated using offsetof(structname, membername) macro from stddef.h
+ * len: maximum length of string (to prevent overflows, etc.)
+ * defname: the name that should be used by default if none is specified already
+ */
+void BLI_uniquename(ListBase *list, void *vlink, char defname[], short name_offs, short len)
+{
+ Link *link;
+ char tempname[128];
+ int number = 1, exists = 0;
+ char *dot;
+
+ /* Make sure length can be handled */
+ if ((len < 0) || (len > 128))
+ return;
+
+ /* See if we are given an empty string */
+ if (ELEM(NULL, vlink, defname))
+ return;
+
+ if (GIVE_STRADDR(vlink, name_offs) == '\0') {
+ /* give it default name first */
+ BLI_strncpy(GIVE_STRADDR(vlink, name_offs), defname, len);
+ }
+
+ /* See if we even need to do this */
+ if (list == NULL)
+ return;
+
+ for (link = list->first; link; link= link->next) {
+ if (link != vlink) {
+ if (!strcmp(GIVE_STRADDR(link, name_offs), GIVE_STRADDR(vlink, name_offs))) {
+ exists = 1;
+ break;
+ }
+ }
+ }
+ if (exists == 0)
+ return;
+
+ /* Strip off the suffix */
+ dot = strchr(GIVE_STRADDR(vlink, name_offs), '.');
+ if (dot)
+ *dot=0;
+
+ for (number = 1; number <= 999; number++) {
+ BLI_snprintf(tempname, 128, "%s.%03d", GIVE_STRADDR(vlink, name_offs), number);
+
+ exists = 0;
+ for (link= list->first; link; link= link->next) {
+ if (vlink != link) {
+ if (!strcmp(GIVE_STRADDR(link, name_offs), tempname)) {
+ exists = 1;
+ break;
+ }
+ }
+ }
+ if (exists == 0) {
+ BLI_strncpy(GIVE_STRADDR(vlink, name_offs), tempname, len);
+ return;
+ }
+ }
+}
+
void BLI_addhead(ListBase *listbase, void *vlink)
{
@@ -787,17 +875,45 @@ int BLI_strcaseeq(char *a, char *b) {
* take the dir name, make it absolute, and clean it up, replacing
* excess file entry stuff (like /tmp/../tmp/../)
* note that dir isn't protected for max string names...
+ *
+ * If relbase is NULL then its ignored
*/
void BLI_cleanup_dir(const char *relabase, char *dir)
{
+ BLI_cleanup_file(relabase, dir);
+ BLI_add_slash(dir);
+
+}
+
+void BLI_cleanup_file(const char *relabase, char *dir)
+{
short a;
char *start, *eind;
+ if (relabase) {
+ BLI_convertstringcode(dir, relabase);
+ } else {
+ if (dir[0]=='/' && dir[1]=='/') {
+ if (dir[2]== '\0') {
+ return; /* path is "//" - cant clean it */
+ }
+ dir = dir+2; /* skip the first // */
+ }
+ }
- BLI_convertstringcode(dir, relabase, 0);
+ /* Note
+ * memmove( start, eind, strlen(eind)+1 );
+ * is the same as
+ * strcpy( start, eind );
+ * except strcpy should not be used because there is overlap,
+ * so use memmove's slightly more obscure syntax - Campbell
+ */
#ifdef WIN32
- if(dir[0]=='.') { /* happens for example in FILE_MAIN */
+
+ /* Note, this should really be moved to the file selector,
+ * since this function is used in many areas */
+ if(strcmp(dir, ".")==0) { /* happens for example in FILE_MAIN */
get_default_root(dir);
return;
}
@@ -809,17 +925,21 @@ void BLI_cleanup_dir(const char *relabase, char *dir)
if (dir[a] == '\\') break;
a--;
}
- strcpy(dir+a,eind);
+ if (a<0) {
+ break;
+ } else {
+ memmove( dir+a, eind, strlen(eind)+1 );
+ }
}
while ( (start = strstr(dir,"\\.\\")) ){
eind = start + strlen("\\.\\") - 1;
- strcpy(start,eind);
+ memmove( start, eind, strlen(eind)+1 );
}
while ( (start = strstr(dir,"\\\\" )) ){
eind = start + strlen("\\\\") - 1;
- strcpy(start,eind);
+ memmove( start, eind, strlen(eind)+1 );
}
if((a = strlen(dir))){ /* remove the '\\' at the end */
@@ -828,9 +948,7 @@ void BLI_cleanup_dir(const char *relabase, char *dir)
dir[a] = 0;
}
}
-
- strcat(dir, "\\");
-#else
+#else
if(dir[0]=='.') { /* happens, for example in FILE_MAIN */
dir[0]= '/';
dir[1]= 0;
@@ -844,17 +962,21 @@ void BLI_cleanup_dir(const char *relabase, char *dir)
if (dir[a] == '/') break;
a--;
}
- strcpy(dir+a,eind);
+ if (a<0) {
+ break;
+ } else {
+ memmove( dir+a, eind, strlen(eind)+1 );
+ }
}
while ( (start = strstr(dir,"/./")) ){
eind = start + strlen("/./") - 1;
- strcpy(start,eind);
+ memmove( start, eind, strlen(eind)+1 );
}
while ( (start = strstr(dir,"//" )) ){
eind = start + strlen("//") - 1;
- strcpy(start,eind);
+ memmove( start, eind, strlen(eind)+1 );
}
if( (a = strlen(dir)) ){ /* remove all '/' at the end */
@@ -864,8 +986,6 @@ void BLI_cleanup_dir(const char *relabase, char *dir)
if (a<=0) break;
}
}
-
- strcat(dir, "/");
#endif
}
@@ -877,7 +997,7 @@ void BLI_makestringcode(const char *relfile, char *file)
char * lslash;
char temp[FILE_MAXDIR+FILE_MAXFILE];
char res[FILE_MAXDIR+FILE_MAXFILE];
-
+
/* if file is already relative, bail out */
if(file[0]=='/' && file[1]=='/') return;
@@ -909,7 +1029,11 @@ void BLI_makestringcode(const char *relfile, char *file)
BLI_char_switch(temp, '\\', '/');
BLI_char_switch(file, '\\', '/');
-
+
+ /* remove /./ which confuse the following slash counting... */
+ BLI_cleanup_file(NULL, file);
+ BLI_cleanup_file(NULL, temp);
+
/* the last slash in the file indicates where the path part ends */
lslash = BLI_last_slash(temp);
@@ -954,17 +1078,104 @@ void BLI_makestringcode(const char *relfile, char *file)
}
}
-int BLI_convertstringcode(char *path, const char *basepath, int framenum)
+int BLI_parent_dir(char *path)
{
- int len, wasrelative;
- char tmp[FILE_MAXDIR+FILE_MAXFILE];
- char base[FILE_MAXDIR];
- char vol[3] = {'\0', '\0', '\0'};
+#ifdef WIN32
+ static char *parent_dir="..\\";
+#else
+ static char *parent_dir="../";
+#endif
+ char tmp[FILE_MAXDIR+FILE_MAXFILE+4];
+ BLI_strncpy(tmp, path, sizeof(tmp));
+ BLI_add_slash(tmp);
+ strcat(tmp, parent_dir);
+ BLI_cleanup_dir(NULL, tmp);
+
+ if (!BLI_testextensie(tmp, parent_dir)) {
+ BLI_strncpy(path, tmp, sizeof(tmp));
+ return 1;
+ } else {
+ return 0;
+ }
+}
+
+int BLI_convertstringframe(char *path, int frame)
+{
+ int ch_sta, ch_end, i;
+ /* Insert current frame: file### -> file001 */
+ ch_sta = ch_end = 0;
+ for (i = 0; path[i] != '\0'; i++) {
+ if (path[i] == '\\' || path[i] == '/') {
+ ch_end = 0; /* this is a directory name, dont use any hashes we found */
+ } else if (path[i] == '#') {
+ ch_sta = i;
+ ch_end = ch_sta+1;
+ while (path[ch_end] == '#') {
+ ch_end++;
+ }
+ i = ch_end-1; /* keep searching */
+
+ /* dont break, there may be a slash after this that invalidates the previous #'s */
+ }
+ }
+ if (ch_end) { /* warning, ch_end is the last # +1 */
+ /* Add the frame number? */
+ short numlen, hashlen;
+ char tmp[FILE_MAX];
+
+ char format[16]; /* 6 is realistically the maxframe (300000), so 8 should be enough, but 16 to be safe. */
+ if (((ch_end-1)-ch_sta) >= 16) {
+ ch_end = ch_sta+15; /* disallow values longer then 'format' can hold */
+ }
+
+ strcpy(tmp, path);
+
+ numlen = 1 + (int)log10((double)frame); /* this is the number of chars in the number */
+ hashlen = ch_end - ch_sta;
+
+ sprintf(format, "%d", frame);
+
+ if (numlen==hashlen) { /* simple case */
+ memcpy(tmp+ch_sta, format, numlen);
+ } else if (numlen < hashlen) {
+ memcpy(tmp+ch_sta + (hashlen-numlen), format, numlen); /*dont copy the string terminator */
+ memset(tmp+ch_sta, '0', hashlen-numlen);
+ } else {
+ /* number is longer then number of #'s */
+ if (tmp[ch_end] == '\0') { /* hashes are last, no need to move any string*/
+ /* bad juju - not testing string length here :/ */
+ memcpy(tmp+ch_sta, format, numlen+1); /* add 1 to get the string terminator \0 */
+ } else {
+ /* we need to move the end characters, reuse i */
+ int j;
+
+ i = strlen(tmp); /* +1 to copy the string terminator */
+ j = i + (numlen-hashlen); /* from/to */
+
+ while (i >= ch_end) {
+ tmp[j] = tmp[i];
+ i--;
+ j--;
+ }
+ memcpy(tmp + ch_sta, format, numlen);
+ }
+ }
+ strcpy(path, tmp);
+ return 1;
+ }
+ return 0;
+}
- BLI_strncpy(vol, path, 3);
- wasrelative= (strncmp(vol, "//", 2)==0);
+int BLI_convertstringcode(char *path, const char *basepath)
+{
+ int wasrelative = (strncmp(path, "//", 2)==0);
+ char tmp[FILE_MAX];
+ char base[FILE_MAX];
#ifdef WIN32
+ char vol[3] = {'\0', '\0', '\0'};
+
+ BLI_strncpy(vol, path, 3);
/* we are checking here if we have an absolute path that is not in the current
blend file as a lib main - we are basically checking for the case that a
UNIX root '/' is passed.
@@ -979,13 +1190,29 @@ int BLI_convertstringcode(char *path, const char *basepath, int framenum)
strcat(tmp, p);
}
else {
- strcpy(tmp, path);
+ BLI_strncpy(tmp, path, FILE_MAX);
}
#else
- strcpy(tmp, path);
+ BLI_strncpy(tmp, path, FILE_MAX);
+
+ /* Check for loading a windows path on a posix system
+ * in this case, there is no use in trying C:/ since it
+ * will never exist on a unix os.
+ *
+ * Add a / prefix and lowercase the driveletter, remove the :
+ * C:\foo.JPG -> /c/foo.JPG */
+
+ if (isalpha(tmp[0]) && tmp[1] == ':' && (tmp[2]=='\\' || tmp[2]=='/') ) {
+ tmp[1] = tolower(tmp[0]); /* replace ':' with driveletter */
+ tmp[0] = '/';
+ /* '\' the slash will be converted later */
+ }
+
#endif
- strcpy(base, basepath);
+ BLI_strncpy(base, basepath, FILE_MAX);
+
+ BLI_cleanup_file(NULL, base);
/* push slashes into unix mode - strings entering this part are
potentially messed up: having both back- and forward slashes.
@@ -996,28 +1223,33 @@ int BLI_convertstringcode(char *path, const char *basepath, int framenum)
BLI_char_switch(tmp, '\\', '/');
BLI_char_switch(base, '\\', '/');
- if (tmp[0] == '/' && tmp[1] == '/') {
- char *filepart= BLI_strdup(tmp+2); /* skip code */
+ /* Paths starting with // will get the blend file as their base,
+ * this isnt standard in any os but is uesed in blender all over the place */
+ if (wasrelative) {
char *lslash= BLI_last_slash(base);
-
if (lslash) {
int baselen= (int) (lslash-base) + 1;
-
+ /* use path for for temp storage here, we copy back over it right away */
+ BLI_strncpy(path, tmp+2, FILE_MAX);
+
memcpy(tmp, base, baselen);
- strcpy(tmp+baselen, filepart);
+ strcpy(tmp+baselen, path);
+ strcpy(path, tmp);
} else {
- strcpy(tmp, filepart);
+ strcpy(path, tmp+2);
}
-
- MEM_freeN(filepart);
+ } else {
+ strcpy(path, tmp);
}
-
- len= strlen(tmp);
- if(len && tmp[len-1]=='#') {
- sprintf(tmp+len-1, "%04d", framenum);
+
+ if (path[0]!='\0') {
+ if ( path[strlen(path)-1]=='/') {
+ BLI_cleanup_dir(NULL, path);
+ } else {
+ BLI_cleanup_file(NULL, path);
+ }
}
-
- strcpy(path, tmp);
+
#ifdef WIN32
/* skip first two chars, which in case of
absolute path will be drive:/blabla and
@@ -1027,11 +1259,54 @@ int BLI_convertstringcode(char *path, const char *basepath, int framenum)
*/
BLI_char_switch(path+2, '/', '\\');
#endif
+
+ return wasrelative;
+}
+
+/*
+ * Should only be done with command line paths.
+ * this is NOT somthing blenders internal paths support like the // prefix
+ */
+int BLI_convertstringcwd(char *path)
+{
+ int wasrelative = 1;
+ int filelen = strlen(path);
+
+#ifdef WIN32
+ if (filelen >= 3 && path[1] == ':' && (path[2] == '\\' || path[2] == '/'))
+ wasrelative = 0;
+#else
+ if (filelen >= 2 && path[0] == '/')
+ wasrelative = 0;
+#endif
+
+ if (wasrelative==1) {
+ char cwd[FILE_MAXDIR + FILE_MAXFILE];
+ BLI_getwdN(cwd); /* incase the full path to the blend isnt used */
+
+ if (cwd[0] == '\0') {
+ printf( "Could not get the current working directory - $PWD for an unknown reason.");
+ } else {
+ /* uses the blend path relative to cwd important for loading relative linked files.
+ *
+ * cwd should contain c:\ etc on win32 so the relbase can be NULL
+ * relbase being NULL also prevents // being misunderstood as relative to the current
+ * blend file which isnt a feature we want to use in this case since were dealing
+ * with a path from the command line, rather then from inside Blender */
+
+ char origpath[FILE_MAXDIR + FILE_MAXFILE];
+ BLI_strncpy(origpath, path, FILE_MAXDIR + FILE_MAXFILE);
+
+ BLI_make_file_string(NULL, path, cwd, origpath);
+ }
+ }
+
return wasrelative;
}
-/* copy di to fi without directory only */
+
+/* copy di to fi, filename only */
void BLI_splitdirstring(char *di, char *fi)
{
char *lslash= BLI_last_slash(di);
@@ -1055,6 +1330,8 @@ char *BLI_gethome(void) {
#else /* Windows */
char * ret;
static char dir[512];
+ static char appdatapath[MAXPATHLEN];
+ HRESULT hResult;
/* Check for %HOME% env var */
@@ -1076,9 +1353,36 @@ char *BLI_gethome(void) {
/* add user profile support for WIN 2K / NT */
+ hResult = SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, appdatapath);
+
+ if (hResult == S_OK)
+ {
+ if (BLI_exists(appdatapath)) { /* from fop, also below... */
+ sprintf(dir, "%s\\Blender Foundation\\Blender", appdatapath);
+ BLI_recurdir_fileops(dir);
+ if (BLI_exists(dir)) {
+ strcat(dir,"\\.blender");
+ if(BLI_exists(dir)) return(dir);
+ }
+ }
+ hResult = SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, appdatapath);
+ if (hResult == S_OK)
+ {
+ if (BLI_exists(appdatapath))
+ { /* from fop, also below... */
+ sprintf(dir, "%s\\Blender Foundation\\Blender", appdatapath);
+ BLI_recurdir_fileops(dir);
+ if (BLI_exists(dir)) {
+ strcat(dir,"\\.blender");
+ if(BLI_exists(dir)) return(dir);
+ }
+ }
+ }
+ }
+#if 0
ret = getenv("USERPROFILE");
if (ret) {
- if (BLI_exists(ret)) { /* from fop, also below... */
+ if (BLI_exists(ret)) { /* from fop, also below... */
sprintf(dir, "%s\\Application Data\\Blender Foundation\\Blender", ret);
BLI_recurdir_fileops(dir);
if (BLI_exists(dir)) {
@@ -1087,6 +1391,7 @@ char *BLI_gethome(void) {
}
}
}
+#endif
/*
Saving in the Windows dir is less than desirable.
@@ -1276,9 +1581,42 @@ int BLI_testextensie(const char *str, const char *ext)
return (retval);
}
+/*
+ * This is a simple version of BLI_split_dirfile that has the following advantages...
+ *
+ * Converts "/foo/bar.txt" to "/foo/" and "bar.txt"
+ * - wont change 'string'
+ * - wont create any directories
+ * - dosnt use CWD, or deal with relative paths.
+ * - Only fill's in *dir and *file when they are non NULL
+ * */
+void BLI_split_dirfile_basic(const char *string, char *dir, char *file)
+{
+ int lslash=0, i = 0;
+ for (i=0; string[i]!='\0'; i++) {
+ if (string[i]=='\\' || string[i]=='/')
+ lslash = i+1;
+ }
+ if (dir) {
+ if (lslash) {
+ BLI_strncpy( dir, string, lslash+1); /* +1 to include the slash and the last char */
+ } else {
+ dir[0] = '\0';
+ }
+ }
+
+ if (file) {
+ strcpy( file, string+lslash);
+ }
+}
-void BLI_split_dirfile(const char *string, char *dir, char *file)
+/* Warning,
+ * - May modify 'string' variable
+ * - May create the directory if it dosnt exist
+ * if this is not needed use BLI_split_dirfile_basic(...)
+ */
+void BLI_split_dirfile(char *string, char *dir, char *file)
{
int a;
#ifdef WIN32
@@ -1400,12 +1738,20 @@ void BLI_join_dirfile(char *string, const char *dir, const char *file)
int sl_dir = strlen(dir);
BLI_strncpy(string, dir, FILE_MAX);
if (sl_dir > FILE_MAX-1) sl_dir = FILE_MAX-1;
+
+ /* only add seperator if needed */
#ifdef WIN32
- string[sl_dir] = '\\';
+ if (string[sl_dir-1] != '\\') {
+ string[sl_dir] = '\\';
+ sl_dir++;
+ }
#else
- string[sl_dir] = '/';
+ if (string[sl_dir-1] != '/') {
+ string[sl_dir] = '/';
+ sl_dir++;
+ }
#endif
- sl_dir++;
+
if (sl_dir <FILE_MAX) {
BLI_strncpy(string + sl_dir, file, FILE_MAX-sl_dir);
}
@@ -1452,10 +1798,10 @@ static int add_win32_extension(char *name)
return (retval);
}
-void BLI_where_am_i(char *fullname, char *name)
+void BLI_where_am_i(char *fullname, const char *name)
{
char filename[FILE_MAXDIR+FILE_MAXFILE];
- char *path, *temp;
+ char *path = NULL, *temp;
int len;
#ifdef _WIN32
char *seperator = ";";
@@ -1465,6 +1811,18 @@ void BLI_where_am_i(char *fullname, char *name)
char *slash = "/";
#endif
+
+#ifdef __linux__
+ /* linux uses binreloc since argv[0] is not relyable, call br_init( NULL ) first */
+ path = br_find_exe( NULL );
+ if (path) {
+ strcpy(fullname, path);
+ free(path);
+ return;
+ }
+#endif
+
+ /* unix and non linux */
if (name && fullname && strlen(name)) {
strcpy(fullname, name);
if (name[0] == '.') {
@@ -1525,6 +1883,47 @@ void BLI_where_am_i(char *fullname, char *name)
}
}
+void BLI_where_is_temp(char *fullname, int usertemp)
+{
+ fullname[0] = '\0';
+
+ if (usertemp && BLI_exists(U.tempdir)) {
+ strcpy(fullname, U.tempdir);
+ }
+
+
+#ifdef WIN32
+ if (fullname[0] == '\0') {
+ char *tmp = getenv("TEMP"); /* Windows */
+ if (tmp && BLI_exists(tmp)) {
+ strcpy(fullname, tmp);
+ }
+ }
+#else
+ /* Other OS's - Try TMP and TMPDIR */
+ if (fullname[0] == '\0') {
+ char *tmp = getenv("TMP");
+ if (tmp && BLI_exists(tmp)) {
+ strcpy(fullname, tmp);
+ }
+ }
+
+ if (fullname[0] == '\0') {
+ char *tmp = getenv("TMPDIR");
+ if (tmp && BLI_exists(tmp)) {
+ strcpy(fullname, tmp);
+ }
+ }
+#endif
+
+ if (fullname[0] == '\0') {
+ strcpy(fullname, "/tmp/");
+ } else {
+ /* add a trailing slash if needed */
+ BLI_add_slash(fullname);
+ }
+}
+
/*
* returns absolute path to the app bundle
* only useful on OS X
@@ -1608,7 +2007,7 @@ int BLI_strncasecmp(const char *s1, const char *s2, int n) {
#include "iconv.h"
#include "localcharset.h"
-void BLI_string_to_utf8(char *original, char *utf_8, char *code)
+void BLI_string_to_utf8(char *original, char *utf_8, const char *code)
{
size_t inbytesleft=strlen(original);
size_t outbytesleft=512;
@@ -1666,7 +2065,7 @@ void BLI_timestr(double _time, char *str)
int BLI_int_from_pointer(void *poin)
{
- long lval= (long)poin;
+ intptr_t lval= (intptr_t)poin;
return (int)(lval>>3);
}
@@ -1674,17 +2073,17 @@ int BLI_int_from_pointer(void *poin)
void *BLI_pointer_from_int(int val)
{
static int firsttime= 1;
- static long basevalue= 0;
+ static intptr_t basevalue= 0;
if(firsttime) {
void *poin= malloc(10000);
- basevalue= (long)poin;
+ basevalue= (intptr_t)poin;
basevalue &= ~PMASK;
printf("base: %d pointer %p\n", basevalue, poin); /* debug */
firsttime= 0;
free(poin);
}
- return (void *)(basevalue | (((long)val)<<3));
+ return (void *)(basevalue | (((intptr_t)val)<<3));
}
#else
diff --git a/source/blender/blenlib/intern/winstuff.c b/source/blender/blenlib/intern/winstuff.c
index ace677e6045..666a54b54cc 100644
--- a/source/blender/blenlib/intern/winstuff.c
+++ b/source/blender/blenlib/intern/winstuff.c
@@ -196,6 +196,27 @@ void get_default_root(char* root) {
}
}
+int check_file_chars(char *filename)
+{
+ char *p = filename;
+ while (*p) {
+ switch (*p) {
+ case ':':
+ case '?':
+ case '*':
+ case '|':
+ case '\\':
+ case '/':
+ case '\"':
+ return 0;
+ break;
+ }
+
+ p++;
+ }
+ return 1;
+}
+
#else
static void BLI_WINSTUFF_C_IS_EMPTY_FOR_UNIX(void)
diff --git a/source/blender/blenloader/BLO_readfile.h b/source/blender/blenloader/BLO_readfile.h
index 9cf300ea460..1219b1ba0c5 100644
--- a/source/blender/blenloader/BLO_readfile.h
+++ b/source/blender/blenloader/BLO_readfile.h
@@ -237,9 +237,9 @@ int BLO_has_bfile_extension(char *str);
void BLO_library_append(struct SpaceFile *sfile, char *dir, int idcode, struct Scene *scene);
void BLO_library_append_(BlendHandle **libfiledata, struct direntry* filelist, int totfile,
char *dir, char* file, short flag, int idcode, struct Scene *scene);
-void BLO_script_library_append(BlendHandle *bh, char *dir, char *name, int idcode, short flag, struct Scene *scene);
+void BLO_script_library_append(BlendHandle **bh, char *dir, char *name, int idcode, short flag, struct Scene *scene);
-BlendFileData* blo_read_blendafterruntime(int file, int actualsize, BlendReadError *error_r);
+BlendFileData* blo_read_blendafterruntime(int file, char *name, int actualsize, BlendReadError *error_r);
#ifdef __cplusplus
}
diff --git a/source/blender/blenloader/BLO_soundfile.h b/source/blender/blenloader/BLO_soundfile.h
index 3d133b2d3bd..a239c7d8965 100644
--- a/source/blender/blenloader/BLO_soundfile.h
+++ b/source/blender/blenloader/BLO_soundfile.h
@@ -35,7 +35,5 @@
struct bSound;
struct PackedFile;
-//void sound_read_wav_data(bSound * sound, PackedFile * pf);
-
#endif
diff --git a/source/blender/blenloader/BLO_sys_types.h b/source/blender/blenloader/BLO_sys_types.h
index a1885894fe3..49155260b31 100644
--- a/source/blender/blenloader/BLO_sys_types.h
+++ b/source/blender/blenloader/BLO_sys_types.h
@@ -43,17 +43,13 @@
#ifdef __cplusplus
extern "C" {
#endif
-
-#ifdef FREE_WINDOWS
-typedef unsigned char uint8_t;
-typedef unsigned int uint32_t;
-#endif
#if defined(_WIN32) && !defined(FREE_WINDOWS)
/* The __intXX are built-in types of the visual complier! So we don't
* need to include anything else here. */
+
typedef signed __int8 int8_t;
typedef signed __int16 int16_t;
typedef signed __int32 int32_t;
@@ -64,6 +60,24 @@ typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
+#ifndef _INTPTR_T_DEFINED
+#ifdef _WIN64
+typedef __int64 intptr_t;
+#else
+typedef long intptr_t;
+#endif
+#define _INTPTR_T_DEFINED
+#endif
+
+#ifndef _UINTPTR_T_DEFINED
+#ifdef _WIN64
+typedef unsigned __int64 uintptr_t;
+#else
+typedef unsigned long uintptr_t;
+#endif
+#define _UINTPTR_T_DEFINED
+#endif
+
#elif defined(__linux__)
/* Linux-i386, Linux-Alpha, Linux-ppc */
@@ -73,6 +87,10 @@ typedef unsigned __int64 uint64_t;
#include <inttypes.h>
+#elif defined(FREE_WINDOWS)
+
+#include <stdint.h>
+
#else
/* FreeBSD, Irix, Solaris */
@@ -80,6 +98,7 @@ typedef unsigned __int64 uint64_t;
#endif /* ifdef platform for types */
+
#ifdef _WIN32
#define htonl(x) correctByteOrder(x)
#define ntohl(x) correctByteOrder(x)
diff --git a/source/blender/blenloader/SConscript b/source/blender/blenloader/SConscript
index 37d5f5381fa..ac3b1262cb7 100644
--- a/source/blender/blenloader/SConscript
+++ b/source/blender/blenloader/SConscript
@@ -5,7 +5,6 @@ sources = env.Glob('intern/*.c')
incs = '. #/intern/guardedalloc ../blenlib ../blenkernel'
incs += ' ../makesdna ../readblenfile ../editors/include'
-incs += ' ../python ../../kernel/gen_messaging'
incs += ' ../render/extern/include'
incs += ' ' + env['BF_ZLIB_INC']
@@ -15,4 +14,4 @@ if env['WITH_BF_VERSE']:
defs += ' WITH_VERSE'
incs += ' ' + env['BF_VERSE_INCLUDE']
-env.BlenderLib ( 'bf_blenloader', sources, Split(incs), Split(defs), libtype=['core','player'], priority = [85, 25] )
+env.BlenderLib ( 'bf_blenloader', sources, Split(incs), Split(defs), libtype=['core','player'], priority = [70, 30] )
diff --git a/source/blender/blenloader/intern/readblenentry.c b/source/blender/blenloader/intern/readblenentry.c
index 24239b3e088..d5f5bb663ab 100644
--- a/source/blender/blenloader/intern/readblenentry.c
+++ b/source/blender/blenloader/intern/readblenentry.c
@@ -63,6 +63,8 @@
#include "BLO_readblenfile.h"
+#include "BLO_sys_types.h" // needed for intptr_t
+
/**
* IDType stuff, I plan to move this
* out into its own file + prefix, and
@@ -193,7 +195,7 @@ void BLO_blendhandle_print_sizes(BlendHandle *bh, void *fp)
buf[2]= buf[2]?buf[2]:' ';
buf[3]= buf[3]?buf[3]:' ';
- fprintf(fp, "['%.4s', '%s', %d, %ld ], \n", buf, name, bhead->nr, (long)bhead->len+sizeof(BHead));
+ fprintf(fp, "['%.4s', '%s', %d, %ld ], \n", buf, name, bhead->nr, (intptr_t)bhead->len+sizeof(BHead));
}
}
fprintf(fp, "]\n");
@@ -362,6 +364,9 @@ BlendFileData *BLO_read_from_memfile(const char *filename, MemFile *memfile, Ble
if (fd) {
strcpy(fd->filename, filename);
+ /* clear ob->proxy_from pointers in G.main */
+ blo_clear_proxy_pointers_from_lib(fd);
+
/* separate libraries from G.main */
blo_split_main(&mainlist, G.main);
/* add the library pointers in oldmap lookup */
diff --git a/source/blender/blenloader/intern/readfile.c b/source/blender/blenloader/intern/readfile.c
index 5c8583cd5ee..1ecd402bd56 100644
--- a/source/blender/blenloader/intern/readfile.c
+++ b/source/blender/blenloader/intern/readfile.c
@@ -34,6 +34,7 @@
#include "BLI_winstuff.h"
#endif
+#include <limits.h>
#include <stdio.h> // for printf fopen fwrite fclose sprintf FILE
#include <stdlib.h> // for getenv atoi
#include <fcntl.h> // for open
@@ -53,6 +54,7 @@
#include "DNA_actuator_types.h"
#include "DNA_brush_types.h"
#include "DNA_camera_types.h"
+#include "DNA_cloth_types.h"
#include "DNA_color_types.h"
#include "DNA_controller_types.h"
#include "DNA_constraint_types.h"
@@ -62,6 +64,7 @@
#include "DNA_fileglobal_types.h"
#include "DNA_genfile.h"
#include "DNA_group_types.h"
+#include "DNA_gpencil_types.h"
#include "DNA_ipo_types.h"
#include "DNA_image_types.h"
#include "DNA_key_types.h"
@@ -104,13 +107,14 @@
#include "BKE_action.h"
#include "BKE_armature.h"
+#include "BKE_cloth.h"
#include "BKE_colortools.h"
#include "BKE_constraint.h"
#include "BKE_curve.h"
#include "BKE_customdata.h"
#include "BKE_deform.h"
#include "BKE_depsgraph.h"
-#include "BKE_effect.h" // for give_parteff
+#include "BKE_effect.h" /* give_parteff */
#include "BKE_global.h" // for G
#include "BKE_group.h"
#include "BKE_image.h"
@@ -123,10 +127,13 @@
#include "BKE_node.h" // for tree type defines
#include "BKE_object.h"
#include "BKE_particle.h"
-#include "BKE_property.h" // for get_property
+#include "BKE_pointcache.h"
+#include "BKE_property.h" // for get_ob_property
#include "BKE_sca.h" // for init_actuator
#include "BKE_scene.h"
#include "BKE_softbody.h" // sbNew()
+#include "BKE_bullet.h" // bsbNew()
+#include "BKE_sculpt.h"
#include "BKE_texture.h" // for open_plugin_tex
#include "BKE_utildefines.h" // SWITCH_INT DATA ENDB DNA1 O_BINARY GLOB USER TEST REND
#include "BKE_idprop.h"
@@ -704,7 +711,7 @@ BHead *blo_firstbhead(FileData *fd)
BHead *blo_prevbhead(FileData *fd, BHead *thisblock)
{
- BHeadN *bheadn= (BHeadN *) (((char *) thisblock) - (int) (&((BHeadN*)0)->bhead));
+ BHeadN *bheadn= (BHeadN *) (((char *) thisblock) - GET_INT_FROM_POINTER( &((BHeadN*)0)->bhead) );
BHeadN *prev= bheadn->prev;
return prev?&prev->bhead:NULL;
@@ -712,13 +719,13 @@ BHead *blo_prevbhead(FileData *fd, BHead *thisblock)
BHead *blo_nextbhead(FileData *fd, BHead *thisblock)
{
- BHeadN *new_bhead = 0;
- BHead *bhead = 0;
+ BHeadN *new_bhead = NULL;
+ BHead *bhead = NULL;
if (thisblock) {
// bhead is actually a sub part of BHeadN
// We calculate the BHeadN pointer from the BHead pointer below
- new_bhead = (BHeadN *) (((char *) thisblock) - (int) (&((BHeadN*)0)->bhead));
+ new_bhead = (BHeadN *) (((char *) thisblock) - GET_INT_FROM_POINTER( &((BHeadN*)0)->bhead) );
// get the next BHeadN. If it doesn't exist we read in the next one
new_bhead = new_bhead->next;
@@ -843,6 +850,7 @@ static int fd_read_from_memfile(FileData *filedata, void *buffer, int size)
static unsigned int seek= 1<<30; /* the current position */
static unsigned int offset= 0; /* size of previous chunks */
static MemFileChunk *chunk=NULL;
+ unsigned int chunkoffset, readsize, totread;
if(size==0) return 0;
@@ -860,29 +868,39 @@ static int fd_read_from_memfile(FileData *filedata, void *buffer, int size)
}
if(chunk) {
- /* first check if it's on the end if current chunk */
- if( seek-offset == chunk->size) {
- offset+= chunk->size;
- chunk= chunk->next;
- }
-
- /* debug, should never happen */
- if(chunk==NULL) {
- printf("illegal read, chunk zero\n");
- return 0;
- }
- else if( (seek-offset)+size > chunk->size) {
- size= chunk->size - (seek-offset);
- printf("chunk too large, clipped to %d\n", size);
- }
-
- memcpy(buffer, chunk->buf + (seek-offset), size);
- filedata->seek += size;
- seek+= size;
-
- return (size);
+ totread= 0;
+
+ do {
+ /* first check if it's on the end if current chunk */
+ if(seek-offset == chunk->size) {
+ offset+= chunk->size;
+ chunk= chunk->next;
+ }
+
+ /* debug, should never happen */
+ if(chunk==NULL) {
+ printf("illegal read, chunk zero\n");
+ return 0;
+ }
+
+ chunkoffset= seek-offset;
+ readsize= size-totread;
+
+ /* data can be spread over multiple chunks, so clamp size
+ * to within this chunk, and then it will read further in
+ * the next chunk */
+ if(chunkoffset+readsize > chunk->size)
+ readsize= chunk->size-chunkoffset;
+
+ memcpy((char*)buffer+totread, chunk->buf+chunkoffset, readsize);
+ totread += readsize;
+ filedata->seek += readsize;
+ seek += readsize;
+ } while(totread < size);
+ return totread;
}
+
return 0;
}
@@ -940,9 +958,11 @@ FileData *blo_openblenderfile(char *name, BlendReadError *error_r)
} else {
FileData *fd = filedata_new();
fd->gzfiledes = gzfile;
- BLI_strncpy(fd->filename, name, sizeof(fd->filename)); // now only in use by library append
fd->read = fd_read_gzip_from_file;
+ /* needed for library_append and read_libraries */
+ BLI_strncpy(fd->filename, name, sizeof(fd->filename));
+
return blo_decode_and_check(fd, error_r);
}
}
@@ -1016,7 +1036,9 @@ void blo_freefiledata(FileData *fd)
oldnewmap_free(fd->imamap);
if (fd->libmap && !(fd->flags & FD_FLAGS_NOT_MY_LIBMAP))
oldnewmap_free(fd->libmap);
-
+ if (fd->bheadmap)
+ MEM_freeN(fd->bheadmap);
+
MEM_freeN(fd);
}
}
@@ -1094,6 +1116,19 @@ static void change_idid_adr(ListBase *mainlist, FileData *basefd, void *old, voi
}
}
+/* lib linked proxy objects point to our local data, we need
+ * to clear that pointer before reading the undo memfile since
+ * the object might be removed, it is set again in reading
+ * if the local object still exists */
+void blo_clear_proxy_pointers_from_lib(FileData *fd)
+{
+ Object *ob= G.main->object.first;
+
+ for(;ob; ob= ob->id.next)
+ if(ob->id.lib)
+ ob->proxy_from= NULL;
+}
+
/* assumed; G.main still exists */
void blo_make_image_pointer_map(FileData *fd)
{
@@ -1106,6 +1141,8 @@ void blo_make_image_pointer_map(FileData *fd)
Link *ibuf= ima->ibufs.first;
for(; ibuf; ibuf= ibuf->next)
oldnewmap_insert(fd->imamap, ibuf, ibuf, 0);
+ if(ima->gputexture)
+ oldnewmap_insert(fd->imamap, ima->gputexture, ima->gputexture, 0);
}
for(; sce; sce= sce->id.next) {
if(sce->nodetree) {
@@ -1140,8 +1177,11 @@ void blo_end_image_pointer_map(FileData *fd)
if(NULL==newimaadr(fd, ibuf)) { /* so was restored */
BLI_remlink(&ima->ibufs, ibuf);
ima->bindcode= 0;
+ ima->gputexture= NULL;
}
}
+
+ ima->gputexture= newimaadr(fd, ima->gputexture);
}
for(; sce; sce= sce->id.next) {
if(sce->nodetree) {
@@ -1306,7 +1346,7 @@ static void test_pointer_array(FileData *fd, void **mat)
void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, void *fd);
void IDP_LibLinkProperty(IDProperty *prop, int switch_endian, void *fd);
-void IDP_DirectLinkArray(IDProperty *prop, int switch_endian, void *fd)
+static void IDP_DirectLinkArray(IDProperty *prop, int switch_endian, void *fd)
{
int i;
@@ -1315,20 +1355,26 @@ void IDP_DirectLinkArray(IDProperty *prop, int switch_endian, void *fd)
prop->data.pointer = newdataadr(fd, prop->data.pointer);
if (switch_endian) {
- for (i=0; i<prop->len; i++) {
- SWITCH_INT(((int*)prop->data.pointer)[i]);
+ if (prop->subtype != IDP_DOUBLE) {
+ for (i=0; i<prop->len; i++) {
+ SWITCH_INT(((int*)prop->data.pointer)[i]);
+ }
+ } else {
+ for (i=0; i<prop->len; i++) {
+ SWITCH_LONGINT(((double*)prop->data.pointer)[i]);
+ }
}
}
}
-void IDP_DirectLinkString(IDProperty *prop, int switch_endian, void *fd)
+static void IDP_DirectLinkString(IDProperty *prop, int switch_endian, void *fd)
{
/*since we didn't save the extra string buffer, set totallen to len.*/
prop->totallen = prop->len;
prop->data.pointer = newdataadr(fd, prop->data.pointer);
}
-void IDP_DirectLinkGroup(IDProperty *prop, int switch_endian, void *fd)
+static void IDP_DirectLinkGroup(IDProperty *prop, int switch_endian, void *fd)
{
ListBase *lb = &prop->data.group;
IDProperty *loop;
@@ -1353,6 +1399,24 @@ void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, void *fd)
case IDP_ARRAY:
IDP_DirectLinkArray(prop, switch_endian, fd);
break;
+ case IDP_DOUBLE:
+ /*erg, stupid doubles. since I'm storing them
+ in the same field as int val; val2 in the
+ IDPropertyData struct, they have to deal with
+ endianness specifically
+
+ in theory, val and val2 would've already been swapped
+ if switch_endian is true, so we have to first unswap
+ them then reswap them as a single 64-bit entity.
+ */
+
+ if (switch_endian) {
+ SWITCH_INT(prop->data.val);
+ SWITCH_INT(prop->data.val2);
+ SWITCH_LONGINT(prop->data.val);
+ }
+
+ break;
}
}
@@ -1392,6 +1456,12 @@ static void direct_link_brush(FileData *fd, Brush *brush)
brush->mtex[a]= newdataadr(fd, brush->mtex[a]);
}
+static void direct_link_script(FileData *fd, Script *script)
+{
+ script->id.us = 1;
+ SCRIPT_SET_NULL(script)
+}
+
/* ************ READ CurveMapping *************** */
/* cuma itself has been read! */
@@ -1434,11 +1504,18 @@ static void lib_link_nodetree(FileData *fd, Main *main)
}
/* verify types for nodes and groups, all data has to be read */
-static void lib_verify_nodetree(Main *main)
+/* open = 0: appending/linking, open = 1: open new file (need to clean out dynamic
+ * typedefs*/
+static void lib_verify_nodetree(Main *main, int open)
{
Scene *sce;
Material *ma;
bNodeTree *ntree;
+
+ /* this crashes blender on undo/redo
+ if(open==1) {
+ reinit_nodesystem();
+ }*/
/* now create the own typeinfo structs an verify nodes */
/* here we still assume no groups in groups */
@@ -1475,6 +1552,12 @@ static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
link_list(fd, &ntree->nodes);
for(node= ntree->nodes.first; node; node= node->next) {
+ if(node->type == NODE_DYNAMIC) {
+ node->custom1= 0;
+ node->custom1= BSET(node->custom1, NODE_DYNAMIC_LOADED);
+ node->typeinfo= NULL;
+ }
+
node->storage= newdataadr(fd, node->storage);
if(node->storage) {
@@ -1509,6 +1592,22 @@ static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
link->tosock= newdataadr(fd, link->tosock);
}
+ /* set selin and selout */
+ for(node= ntree->nodes.first; node; node= node->next) {
+ for(sock= node->inputs.first; sock; sock= sock->next) {
+ if(sock->flag & SOCK_SEL) {
+ ntree->selin= sock;
+ break;
+ }
+ }
+ for(sock= node->outputs.first; sock; sock= sock->next) {
+ if(sock->flag & SOCK_SEL) {
+ ntree->selout= sock;
+ break;
+ }
+ }
+ }
+
/* type verification is in lib-link */
}
@@ -1721,6 +1820,13 @@ static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
data->tar = newlibadr(fd, id->lib, data->tar);
}
break;
+ case CONSTRAINT_TYPE_DISTLIMIT:
+ {
+ bDistLimitConstraint *data;
+ data= ((bDistLimitConstraint*)con->data);
+ data->tar = newlibadr(fd, id->lib, data->tar);
+ }
+ break;
case CONSTRAINT_TYPE_NULL:
break;
}
@@ -1734,6 +1840,7 @@ static void direct_link_constraints(FileData *fd, ListBase *lb)
link_list(fd, lb);
for (cons=lb->first; cons; cons=cons->next) {
cons->data = newdataadr(fd, cons->data);
+
if (cons->type == CONSTRAINT_TYPE_PYTHON) {
bPythonConstraint *data= cons->data;
link_list(fd, &data->targets);
@@ -1800,12 +1907,12 @@ static void lib_link_action(FileData *fd, Main *main)
while(act) {
if(act->id.flag & LIB_NEEDLINK) {
act->id.flag -= LIB_NEEDLINK;
-
+
for (chan=act->chanbase.first; chan; chan=chan->next) {
chan->ipo= newlibadr_us(fd, act->id.lib, chan->ipo);
lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
}
-
+
}
act= act->id.next;
}
@@ -1828,12 +1935,24 @@ static void direct_link_bones(FileData *fd, Bone* bone)
static void direct_link_action(FileData *fd, bAction *act)
{
bActionChannel *achan;
+ bActionGroup *agrp;
link_list(fd, &act->chanbase);
+ link_list(fd, &act->groups);
+ link_list(fd, &act->markers);
- for (achan = act->chanbase.first; achan; achan=achan->next)
+ for (achan = act->chanbase.first; achan; achan=achan->next) {
+ achan->grp= newdataadr(fd, achan->grp);
+
link_list(fd, &achan->constraintChannels);
-
+ }
+
+ for (agrp = act->groups.first; agrp; agrp= agrp->next) {
+ if (agrp->channels.first) {
+ agrp->channels.first= newdataadr(fd, agrp->channels.first);
+ agrp->channels.last= newdataadr(fd, agrp->channels.last);
+ }
+ }
}
static void direct_link_armature(FileData *fd, bArmature *arm)
@@ -2162,6 +2281,7 @@ static void direct_link_text(FileData *fd, Text *text)
*/
link_list(fd, &text->lines);
+ link_list(fd, &text->markers);
text->curl= newdataadr(fd, text->curl);
text->sell= newdataadr(fd, text->sell);
@@ -2228,8 +2348,10 @@ static void direct_link_image(FileData *fd, Image *ima)
ima->ibufs.first= ima->ibufs.last= NULL;
/* if not restored, we keep the binded opengl index */
- if(ima->ibufs.first==NULL)
+ if(ima->ibufs.first==NULL) {
ima->bindcode= 0;
+ ima->gputexture= NULL;
+ }
ima->anim= NULL;
ima->rr= NULL;
@@ -2440,10 +2562,17 @@ static void direct_link_material(FileData *fd, Material *ma)
direct_link_nodetree(fd, ma->nodetree);
ma->preview = direct_link_preview_image(fd, ma->preview);
+ ma->gpumaterial.first = ma->gpumaterial.last = NULL;
}
/* ************ READ PARTICLE SETTINGS ***************** */
+static void direct_link_pointcache(FileData *fd, PointCache *cache)
+{
+ cache->flag &= ~(PTCACHE_SIMULATION_VALID|PTCACHE_BAKE_EDIT_ACTIVE);
+ cache->simframe= 0;
+}
+
static void lib_link_particlesettings(FileData *fd, Main *main)
{
ParticleSettings *part;
@@ -2465,21 +2594,36 @@ static void lib_link_particlesettings(FileData *fd, Main *main)
static void direct_link_particlesettings(FileData *fd, ParticleSettings *part)
{
part->pd= newdataadr(fd, part->pd);
+ part->pd2= newdataadr(fd, part->pd2);
}
-static void lib_link_particlesystems(FileData *fd, ID *id, ListBase *particles)
+static void lib_link_particlesystems(FileData *fd, Object *ob, ID *id, ListBase *particles)
{
- ParticleSystem *psys;
+ ParticleSystem *psys, *psysnext;
int a;
- for(psys=particles->first; psys; psys=psys->next){
+ for(psys=particles->first; psys; psys=psysnext){
ParticleData *pa;
+
+ psysnext= psys->next;
+
psys->part = newlibadr_us(fd, id->lib, psys->part);
- psys->target_ob = newlibadr(fd, id->lib, psys->target_ob);
- psys->keyed_ob = newlibadr(fd, id->lib, psys->keyed_ob);
+ if(psys->part) {
+ psys->target_ob = newlibadr(fd, id->lib, psys->target_ob);
+ psys->keyed_ob = newlibadr(fd, id->lib, psys->keyed_ob);
+
+ for(a=0,pa=psys->particles; a<psys->totpart; a++,pa++){
+ pa->stick_ob=newlibadr(fd, id->lib, pa->stick_ob);
+ }
+ }
+ else {
+ /* particle modifier must be removed before particle system */
+ ParticleSystemModifierData *psmd= psys_get_modifier(ob,psys);
+ BLI_remlink(&ob->modifiers, psmd);
+ modifier_free((ModifierData *)psmd);
- for(a=0,pa=psys->particles; a<psys->totpart; a++,pa++){
- pa->stick_ob=newlibadr(fd, id->lib, pa->stick_ob);
+ BLI_remlink(particles, psys);
+ MEM_freeN(psys);
}
}
}
@@ -2495,6 +2639,15 @@ static void direct_link_particlesystems(FileData *fd, ListBase *particles)
for(a=0; a<psys->totpart; a++, pa++)
pa->hair=newdataadr(fd,pa->hair);
}
+ if(psys->particles && psys->particles->keys){
+ ParticleData *pa = psys->particles;
+ for(a=0; a<psys->totpart; a++, pa++) {
+ pa->keys= NULL;
+ pa->totkey= 0;
+ }
+
+ psys->flag &= ~PSYS_KEYED;
+ }
psys->child=newdataadr(fd,psys->child);
psys->effectors.first=psys->effectors.last=0;
@@ -2505,12 +2658,22 @@ static void direct_link_particlesystems(FileData *fd, ListBase *particles)
sb->bpoint= NULL; // init pointers so it gets rebuilt nicely
sb->bspring= NULL;
sb->scratch= NULL;
+
+ sb->pointcache= newdataadr(fd, sb->pointcache);
+ if(sb->pointcache)
+ direct_link_pointcache(fd, sb->pointcache);
}
psys->edit = 0;
psys->pathcache = 0;
psys->childcache = 0;
+ psys->pathcachebufs.first = psys->pathcachebufs.last = 0;
+ psys->childcachebufs.first = psys->childcachebufs.last = 0;
psys->reactevents.first = psys->reactevents.last = 0;
+
+ psys->pointcache= newdataadr(fd, psys->pointcache);
+ if(psys->pointcache)
+ direct_link_pointcache(fd, psys->pointcache);
}
return;
}
@@ -2753,6 +2916,7 @@ static void lib_link_object(FileData *fd, Main *main)
ob->track= newlibadr(fd, ob->id.lib, ob->track);
ob->ipo= newlibadr_us(fd, ob->id.lib, ob->ipo);
ob->action = newlibadr_us(fd, ob->id.lib, ob->action);
+ ob->poselib= newlibadr_us(fd, ob->id.lib, ob->poselib);
ob->dup_group= newlibadr_us(fd, ob->id.lib, ob->dup_group);
ob->proxy= newlibadr_us(fd, ob->id.lib, ob->proxy);
@@ -2781,8 +2945,7 @@ static void lib_link_object(FileData *fd, Main *main)
else printf("Object %s lost data.", ob->id.name+2);
if(ob->pose) {
- free_pose_channels(ob->pose);
- MEM_freeN(ob->pose);
+ free_pose(ob->pose);
ob->pose= NULL;
ob->flag &= ~OB_POSEMODE;
}
@@ -2806,11 +2969,9 @@ static void lib_link_object(FileData *fd, Main *main)
sens= ob->sensors.first;
while(sens) {
- if(ob->id.lib==NULL) { // done in expand_main
- for(a=0; a<sens->totlinks; a++) {
- sens->links[a]= newglobadr(fd, sens->links[a]);
- }
- }
+ for(a=0; a<sens->totlinks; a++)
+ sens->links[a]= newglobadr(fd, sens->links[a]);
+
if(sens->type==SENS_TOUCH) {
bTouchSensor *ts= sens->data;
ts->ma= newlibadr(fd, ob->id.lib, ts->ma);
@@ -2825,11 +2986,9 @@ static void lib_link_object(FileData *fd, Main *main)
cont= ob->controllers.first;
while(cont) {
- if(ob->id.lib==NULL) { // done in expand_main
- for(a=0; a<cont->totlinks; a++) {
- cont->links[a]= newglobadr(fd, cont->links[a]);
- }
- }
+ for(a=0; a<cont->totlinks; a++)
+ cont->links[a]= newglobadr(fd, cont->links[a]);
+
if(cont->type==CONT_PYTHON) {
bPythonCont *pc= cont->data;
pc->text= newlibadr(fd, ob->id.lib, pc->text);
@@ -2880,6 +3039,10 @@ static void lib_link_object(FileData *fd, Main *main)
bActionActuator *aa= act->data;
aa->act= newlibadr(fd, ob->id.lib, aa->act);
}
+ else if(act->type==ACT_SHAPEACTION) {
+ bActionActuator *aa= act->data;
+ aa->act= newlibadr(fd, ob->id.lib, aa->act);
+ }
else if(act->type==ACT_PROPERTY) {
bPropertyActuator *pa= act->data;
pa->ob= newlibadr(fd, ob->id.lib, pa->ob);
@@ -2888,11 +3051,25 @@ static void lib_link_object(FileData *fd, Main *main)
bMessageActuator *ma= act->data;
ma->toObject= newlibadr(fd, ob->id.lib, ma->toObject);
}
+ else if(act->type==ACT_2DFILTER){
+ bTwoDFilterActuator *_2dfa = act->data;
+ _2dfa->text= newlibadr(fd, ob->id.lib, _2dfa->text);
+ }
+ else if(act->type==ACT_PARENT) {
+ bParentActuator *parenta = act->data;
+ parenta->ob = newlibadr(fd, ob->id.lib, parenta->ob);
+ }
+ else if(act->type==ACT_STATE) {
+ /* bStateActuator *statea = act->data; */
+ }
act= act->next;
}
-
- if(ob->fluidsimSettings) {
- ob->fluidsimSettings->ipo = newlibadr_us(fd, ob->id.lib, ob->fluidsimSettings->ipo);
+
+ {
+ FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
+
+ if(fluidmd && fluidmd->fss)
+ fluidmd->fss->ipo = newlibadr_us(fd, ob->id.lib, fluidmd->fss->ipo);
}
/* texture field */
@@ -2901,7 +3078,7 @@ static void lib_link_object(FileData *fd, Main *main)
ob->pd->tex=newlibadr_us(fd, ob->id.lib, ob->pd->tex);
lib_link_scriptlink(fd, &ob->id, &ob->scriptlink);
- lib_link_particlesystems(fd, &ob->id, &ob->particlesystem);
+ lib_link_particlesystems(fd, ob, &ob->id, &ob->particlesystem);
lib_link_modifiers(fd, ob);
}
ob= ob->id.next;
@@ -2911,14 +3088,15 @@ static void lib_link_object(FileData *fd, Main *main)
}
-static void direct_link_pose(FileData *fd, bPose *pose) {
-
+static void direct_link_pose(FileData *fd, bPose *pose)
+{
bPoseChannel *pchan;
if (!pose)
return;
link_list(fd, &pose->chanbase);
+ link_list(fd, &pose->agroups);
for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
pchan->bone= NULL;
@@ -2928,7 +3106,6 @@ static void direct_link_pose(FileData *fd, bPose *pose) {
pchan->iktree.first= pchan->iktree.last= NULL;
pchan->path= NULL;
}
-
}
static void direct_link_modifiers(FileData *fd, ListBase *lb)
@@ -2948,7 +3125,57 @@ static void direct_link_modifiers(FileData *fd, ListBase *lb)
SubsurfModifierData *smd = (SubsurfModifierData*) md;
smd->emCache = smd->mCache = 0;
- } else if (md->type==eModifierType_Hook) {
+ }
+ else if (md->type==eModifierType_Cloth) {
+ ClothModifierData *clmd = (ClothModifierData*) md;
+
+ clmd->clothObject = NULL;
+
+ clmd->sim_parms= newdataadr(fd, clmd->sim_parms);
+ clmd->coll_parms= newdataadr(fd, clmd->coll_parms);
+ clmd->point_cache= newdataadr(fd, clmd->point_cache);
+
+ if(clmd->point_cache)
+ direct_link_pointcache(fd, clmd->point_cache);
+
+ if(clmd->sim_parms) {
+ if(clmd->sim_parms->presets > 10)
+ clmd->sim_parms->presets = 0;
+ }
+
+ }
+ else if (md->type==eModifierType_Fluidsim) {
+ FluidsimModifierData *fluidmd = (FluidsimModifierData*) md;
+
+ fluidmd->fss= newdataadr(fd, fluidmd->fss);
+ }
+ else if (md->type==eModifierType_Collision) {
+
+ CollisionModifierData *collmd = (CollisionModifierData*) md;
+ /*
+ // TODO: CollisionModifier should use pointcache
+ // + have proper reset events before enabling this
+ collmd->x = newdataadr(fd, collmd->x);
+ collmd->xnew = newdataadr(fd, collmd->xnew);
+ collmd->mfaces = newdataadr(fd, collmd->mfaces);
+
+ collmd->current_x = MEM_callocN(sizeof(MVert)*collmd->numverts,"current_x");
+ collmd->current_xnew = MEM_callocN(sizeof(MVert)*collmd->numverts,"current_xnew");
+ collmd->current_v = MEM_callocN(sizeof(MVert)*collmd->numverts,"current_v");
+ */
+
+ collmd->x = NULL;
+ collmd->xnew = NULL;
+ collmd->current_x = NULL;
+ collmd->current_xnew = NULL;
+ collmd->current_v = NULL;
+ collmd->time = -1;
+ collmd->numverts = 0;
+ collmd->bvhtree = NULL;
+ collmd->mfaces = NULL;
+
+ }
+ else if (md->type==eModifierType_Hook) {
HookModifierData *hmd = (HookModifierData*) md;
hmd->indexar= newdataadr(fd, hmd->indexar);
@@ -3093,7 +3320,6 @@ static void direct_link_object(FileData *fd, Object *ob)
sb->bpoint= NULL; // init pointers so it gets rebuilt nicely
sb->bspring= NULL;
sb->scratch= NULL;
-
/* although not used anymore */
/* still have to be loaded to be compatible with old files */
sb->keys= newdataadr(fd, sb->keys);
@@ -3103,15 +3329,13 @@ static void direct_link_object(FileData *fd, Object *ob)
sb->keys[a]= newdataadr(fd, sb->keys[a]);
}
}
+
+ sb->pointcache= newdataadr(fd, sb->pointcache);
+ if(sb->pointcache)
+ direct_link_pointcache(fd, sb->pointcache);
}
+ ob->bsoft= newdataadr(fd, ob->bsoft);
ob->fluidsimSettings= newdataadr(fd, ob->fluidsimSettings); /* NT */
- if(ob->fluidsimSettings) {
- // reinit mesh pointers
- ob->fluidsimSettings->orgMesh = NULL; //ob->data;
- ob->fluidsimSettings->meshSurface = NULL;
- ob->fluidsimSettings->meshBB = NULL;
- ob->fluidsimSettings->meshSurfNormals = NULL;
- }
link_list(fd, &ob->particlesystem);
direct_link_particlesystems(fd,&ob->particlesystem);
@@ -3136,11 +3360,19 @@ static void direct_link_object(FileData *fd, Object *ob)
direct_link_constraints(fd, &ob->constraints);
link_glob_list(fd, &ob->controllers);
+ if (ob->init_state) {
+ /* if a known first state is specified, set it so that the game will start ok */
+ ob->state = ob->init_state;
+ } else if (!ob->state) {
+ ob->state = 1;
+ }
cont= ob->controllers.first;
while(cont) {
cont->data= newdataadr(fd, cont->data);
cont->links= newdataadr(fd, cont->links);
test_pointer_array(fd, (void **)&cont->links);
+ if (cont->state_mask == 0)
+ cont->state_mask = 1;
cont= cont->next;
}
@@ -3185,6 +3417,7 @@ static void direct_link_object(FileData *fd, Object *ob)
ob->bb= NULL;
ob->derivedDeform= NULL;
ob->derivedFinal= NULL;
+ ob->gpulamp.first= ob->gpulamp.last= NULL;
}
/* ************ READ SCENE ***************** */
@@ -3340,6 +3573,10 @@ static void direct_link_scene(FileData *fd, Scene *sce)
if(seq->strip && seq->strip->done==0) {
seq->strip->done= 1;
seq->strip->tstripdata = 0;
+ seq->strip->tstripdata_startstill = 0;
+ seq->strip->tstripdata_endstill = 0;
+ seq->strip->ibuf_startstill = 0;
+ seq->strip->ibuf_endstill = 0;
if(seq->type == SEQ_IMAGE ||
seq->type == SEQ_MOVIE ||
@@ -3350,6 +3587,30 @@ static void direct_link_scene(FileData *fd, Scene *sce)
} else {
seq->strip->stripdata = 0;
}
+ if (seq->flag & SEQ_USE_CROP) {
+ seq->strip->crop = newdataadr(
+ fd, seq->strip->crop);
+ } else {
+ seq->strip->crop = 0;
+ }
+ if (seq->flag & SEQ_USE_TRANSFORM) {
+ seq->strip->transform = newdataadr(
+ fd, seq->strip->transform);
+ } else {
+ seq->strip->transform = 0;
+ }
+ if (seq->flag & SEQ_USE_PROXY) {
+ seq->strip->proxy = newdataadr(
+ fd, seq->strip->proxy);
+ } else {
+ seq->strip->proxy = 0;
+ }
+ if (seq->flag & SEQ_USE_COLOR_BALANCE) {
+ seq->strip->color_balance = newdataadr(
+ fd, seq->strip->color_balance);
+ } else {
+ seq->strip->color_balance = 0;
+ }
}
}
END_SEQ
@@ -3358,9 +3619,9 @@ static void direct_link_scene(FileData *fd, Scene *sce)
{
Sequence temp;
char *poin;
- long offset;
+ intptr_t offset;
- offset= ((long)&(temp.seqbase)) - ((long)&temp);
+ offset= ((intptr_t)&(temp.seqbase)) - ((intptr_t)&temp);
/* root pointer */
if(ed->seqbasep == old_seqbasep) {
@@ -3406,8 +3667,18 @@ static void direct_link_scene(FileData *fd, Scene *sce)
if (sce->r.qtcodecdata) {
sce->r.qtcodecdata->cdParms = newdataadr(fd, sce->r.qtcodecdata->cdParms);
}
-
+ if (sce->r.ffcodecdata.properties) {
+ sce->r.ffcodecdata.properties = newdataadr(
+ fd, sce->r.ffcodecdata.properties);
+ if (sce->r.ffcodecdata.properties) {
+ IDP_DirectLinkProperty(
+ sce->r.ffcodecdata.properties,
+ (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
+ }
+ }
+
link_list(fd, &(sce->markers));
+ link_list(fd, &(sce->transform_spaces));
link_list(fd, &(sce->r.layers));
sce->nodetree= newdataadr(fd, sce->nodetree);
@@ -3521,6 +3792,32 @@ static void lib_link_windowmanager(FileData *fd, Main *main)
/* ************ READ SCREEN ***************** */
+/* relinks grease-pencil data for 3d-view(s) - used for direct_link */
+static void link_gpencil(FileData *fd, bGPdata *gpd)
+{
+ bGPDlayer *gpl;
+ bGPDframe *gpf;
+ bGPDstroke *gps;
+
+ /* relink layers */
+ link_list(fd, &gpd->layers);
+
+ for (gpl= gpd->layers.first; gpl; gpl= gpl->next) {
+ /* relink frames */
+ link_list(fd, &gpl->frames);
+ gpl->actframe= newdataadr(fd, gpl->actframe);
+
+ for (gpf= gpl->frames.first; gpf; gpf= gpf->next) {
+ /* relink strokes (and their points) */
+ link_list(fd, &gpf->strokes);
+
+ for (gps= gpf->strokes.first; gps; gps= gps->next) {
+ gps->points= newdataadr(fd, gps->points);
+ }
+ }
+ }
+}
+
/* note: file read without screens option G_FILE_NO_UI;
check lib pointers in call below */
static void lib_link_screen(FileData *fd, Main *main)
@@ -3532,23 +3829,23 @@ static void lib_link_screen(FileData *fd, Main *main)
if(sc->id.flag & LIB_NEEDLINK) {
sc->id.us= 1;
sc->scene= newlibadr(fd, sc->id.lib, sc->scene);
-
+
sa= sc->areabase.first;
while(sa) {
SpaceLink *sl;
-
+
sa->full= newlibadr(fd, sc->id.lib, sa->full);
-
+
/* space handler scriptlinks */
lib_link_scriptlink(fd, &sc->id, &sa->scriptlink);
-
+
for (sl= sa->spacedata.first; sl; sl= sl->next) {
if(sl->spacetype==SPACE_VIEW3D) {
View3D *v3d= (View3D*) sl;
-
+
v3d->camera= newlibadr(fd, sc->id.lib, v3d->camera);
v3d->ob_centre= newlibadr(fd, sc->id.lib, v3d->ob_centre);
-
+
if(v3d->bgpic) {
v3d->bgpic->ima= newlibadr_us(fd, sc->id.lib, v3d->bgpic->ima);
}
@@ -3611,9 +3908,15 @@ static void lib_link_screen(FileData *fd, Main *main)
}
else if(sl->spacetype==SPACE_SCRIPT) {
- SpaceScript *sc= (SpaceScript *)sl;
- sc->script = NULL;
+ SpaceScript *scpt= (SpaceScript *)sl;
+ /*scpt->script = NULL; - 2.45 set to null, better re-run the script */
+ if (scpt->script) {
+ scpt->script= newlibadr(fd, sc->id.lib, scpt->script);
+ if (scpt->script) {
+ SCRIPT_SET_NULL(scpt->script)
+ }
+ }
}
else if(sl->spacetype==SPACE_OOPS) {
SpaceOops *so= (SpaceOops *)sl;
@@ -3686,7 +3989,9 @@ void lib_link_screen_restore(Main *newmain, Scene *curscene)
for(sc= newmain->screen.first; sc; sc= sc->id.next) {
- sc->scene= curscene;
+ sc->scene= restore_pointer_by_name(newmain, (ID *)sc->scene, 1);
+ if(sc->scene==NULL)
+ sc->scene= curscene;
sa= sc->areabase.first;
while(sa) {
@@ -3784,9 +4089,14 @@ void lib_link_screen_restore(Main *newmain, Scene *curscene)
if(st->text==NULL) st->text= newmain->text.first;
}
else if(sl->spacetype==SPACE_SCRIPT) {
- SpaceScript *sc= (SpaceScript *)sl;
-
- sc->script = NULL;
+ SpaceScript *scpt= (SpaceScript *)sl;
+
+ scpt->script= restore_pointer_by_name(newmain, (ID *)scpt->script, 1);
+
+ /*sc->script = NULL; - 2.45 set to null, better re-run the script */
+ if (scpt->script) {
+ SCRIPT_SET_NULL(scpt->script)
+ }
}
else if(sl->spacetype==SPACE_OOPS) {
SpaceOops *so= (SpaceOops *)sl;
@@ -3854,7 +4164,7 @@ static void direct_link_screen(FileData *fd, bScreen *sc)
for(se= sc->edgebase.first; se; se= se->next) {
se->v1= newdataadr(fd, se->v1);
se->v2= newdataadr(fd, se->v2);
- if( (long)se->v1 > (long)se->v2) {
+ if( (intptr_t)se->v1 > (intptr_t)se->v2) {
sv= se->v1;
se->v1= se->v2;
se->v2= sv;
@@ -3897,6 +4207,10 @@ static void direct_link_screen(FileData *fd, bScreen *sc)
v3d->bgpic= newdataadr(fd, v3d->bgpic);
if(v3d->bgpic)
v3d->bgpic->iuser.ok= 1;
+ if(v3d->gpd) {
+ v3d->gpd= newdataadr(fd, v3d->gpd);
+ link_gpencil(fd, v3d->gpd);
+ }
v3d->localvd= newdataadr(fd, v3d->localvd);
v3d->afterdraw.first= v3d->afterdraw.last= NULL;
v3d->clipbb= newdataadr(fd, v3d->clipbb);
@@ -3927,15 +4241,28 @@ static void direct_link_screen(FileData *fd, bScreen *sc)
sima->cumap= newdataadr(fd, sima->cumap);
if(sima->cumap)
direct_link_curvemapping(fd, sima->cumap);
- sima->info_str= sima->info_spare= NULL;
- sima->spare= NULL;
+ sima->gpd= newdataadr(fd, sima->gpd);
+ if (sima->gpd)
+ link_gpencil(fd, sima->gpd);
sima->iuser.ok= 1;
}
else if(sl->spacetype==SPACE_NODE) {
SpaceNode *snode= (SpaceNode *)sl;
+
+ if(snode->gpd) {
+ snode->gpd= newdataadr(fd, snode->gpd);
+ link_gpencil(fd, snode->gpd);
+ }
snode->nodetree= snode->edittree= NULL;
snode->flag |= SNODE_DO_PREVIEW;
}
+ else if(sl->spacetype==SPACE_SEQ) {
+ SpaceSeq *sseq= (SpaceSeq *)sl;
+ if(sseq->gpd) {
+ sseq->gpd= newdataadr(fd, sseq->gpd);
+ link_gpencil(fd, sseq->gpd);
+ }
+ }
}
for(ar= sa->regionbase.first; ar; ar= ar->next) {
@@ -4000,11 +4327,26 @@ static void direct_link_library(FileData *fd, Library *lib, Main *main)
static void lib_link_library(FileData *fd, Main *main)
{
Library *lib;
-
- lib= main->library.first;
- while(lib) {
+ for(lib= main->library.first; lib; lib= lib->id.next) {
lib->id.us= 1;
- lib= lib->id.next;
+ }
+}
+
+/* Always call this once you havbe loaded new library data to set the relative paths correctly in relation to the blend file */
+static void fix_relpaths_library(const char *basepath, Main *main)
+{
+ Library *lib;
+ /* BLO_read_from_memory uses a blank filename */
+ if (basepath==NULL || basepath[0] == '\0')
+ return;
+
+ for(lib= main->library.first; lib; lib= lib->id.next) {
+ /* Libraries store both relative and abs paths, recreate relative paths,
+ * relative to the blend file since indirectly linked libs will be relative to their direct linked library */
+ if (strncmp(lib->name, "//", 2)==0) { /* if this is relative to begin with? */
+ strncpy(lib->name, lib->filename, sizeof(lib->name));
+ BLI_makestringcode(basepath, lib->name);
+ }
}
}
@@ -4245,12 +4587,17 @@ static BHead *read_libblock(FileData *fd, Main *main, BHead *bhead, int flag, ID
case ID_PA:
direct_link_particlesettings(fd, (ParticleSettings*)id);
break;
+ case ID_SCRIPT:
+ direct_link_script(fd, (Script*)id);
+ break;
}
/*link direct data of ID properties*/
if (id->properties) {
id->properties = newdataadr(fd, id->properties);
- IDP_DirectLinkProperty(id->properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
+ if (id->properties) { /* this case means the data was written incorrectly, it should not happen */
+ IDP_DirectLinkProperty(id->properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
+ }
}
oldnewmap_free_unused(fd->datamap);
@@ -4566,6 +4913,118 @@ static void do_version_ntree_242_2(bNodeTree *ntree)
}
}
+static void ntree_version_245(FileData *fd, Library *lib, bNodeTree *ntree)
+{
+ bNode *node;
+ NodeTwoFloats *ntf;
+ ID *nodeid;
+ Image *image;
+ ImageUser *iuser;
+
+ if(ntree->type==NTREE_COMPOSIT) {
+ for(node= ntree->nodes.first; node; node= node->next) {
+ if(node->type == CMP_NODE_ALPHAOVER) {
+ if(!node->storage) {
+ ntf= MEM_callocN(sizeof(NodeTwoFloats), "NodeTwoFloats");
+ node->storage= ntf;
+ if(node->custom1)
+ ntf->x= 1.0f;
+ }
+ }
+
+ /* fix for temporary flag changes during 245 cycle */
+ nodeid= newlibadr(fd, lib, node->id);
+ if(node->storage && nodeid && GS(nodeid->name) == ID_IM) {
+ image= (Image*)nodeid;
+ iuser= node->storage;
+ if(iuser->flag & IMA_OLD_PREMUL) {
+ iuser->flag &= ~IMA_OLD_PREMUL;
+ iuser->flag |= IMA_DO_PREMUL;
+ }
+ if(iuser->flag & IMA_DO_PREMUL) {
+ image->flag &= ~IMA_OLD_PREMUL;
+ image->flag |= IMA_DO_PREMUL;
+ }
+ }
+ }
+ }
+}
+
+static void idproperties_fix_groups_lengths_recurse(IDProperty *prop)
+{
+ IDProperty *loop;
+ int i;
+
+ for (loop=prop->data.group.first, i=0; loop; loop=loop->next, i++) {
+ if (loop->type == IDP_GROUP) idproperties_fix_groups_lengths_recurse(loop);
+ }
+
+ if (prop->len != i) {
+ printf("Found and fixed bad id property group length.\n");
+ prop->len = i;
+ }
+}
+
+static void idproperties_fix_group_lengths(ListBase idlist)
+{
+ ID *id;
+
+ for (id=idlist.first; id; id=id->next) {
+ if (id->properties) {
+ idproperties_fix_groups_lengths_recurse(id->properties);
+ }
+ }
+}
+
+static void alphasort_version_246(FileData *fd, Library *lib, Mesh *me)
+{
+ Material *ma;
+ MFace *mf;
+ MTFace *tf;
+ int a, b, texalpha;
+
+ /* verify we have a tface layer */
+ for(b=0; b<me->fdata.totlayer; b++)
+ if(me->fdata.layers[b].type == CD_MTFACE)
+ break;
+
+ if(b == me->fdata.totlayer)
+ return;
+
+ /* if we do, set alpha sort if the game engine did it before */
+ for(a=0, mf=me->mface; a<me->totface; a++, mf++) {
+ if(mf->mat_nr < me->totcol) {
+ ma= newlibadr(fd, lib, me->mat[mf->mat_nr]);
+ texalpha = 0;
+
+ /* we can't read from this if it comes from a library,
+ * because direct_link might not have happened on it,
+ * so ma->mtex is not pointing to valid memory yet */
+ if(ma && ma->id.lib)
+ ma= NULL;
+
+ for(b=0; ma && b<MAX_MTEX; b++)
+ if(ma->mtex && ma->mtex[b] && ma->mtex[b]->mapto & MAP_ALPHA)
+ texalpha = 1;
+ }
+ else {
+ ma= NULL;
+ texalpha = 0;
+ }
+
+ for(b=0; b<me->fdata.totlayer; b++) {
+ if(me->fdata.layers[b].type == CD_MTFACE) {
+ tf = ((MTFace*)me->fdata.layers[b].data) + a;
+
+ tf->mode &= ~TF_ALPHASORT;
+ if(ma && (ma->mode & MA_ZTRA))
+ if(ELEM(tf->transp, TF_ALPHA, TF_ADD) || (texalpha && (tf->transp != TF_CLIP)))
+ tf->mode |= TF_ALPHASORT;
+ }
+ }
+ }
+}
+
static void do_versions_windowmanager_2_50(bScreen *screen)
{
struct ScrArea *sa;
@@ -4908,7 +5367,7 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
while(ob) {
ob->mass= 1.0f;
ob->damping= 0.1f;
- ob->quat[1]= 1.0f;
+ /*ob->quat[1]= 1.0f;*/ /* quats arnt used yet */
ob= ob->id.next;
}
@@ -4978,7 +5437,7 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
while (act) {
if(act->type==ACT_IPO) {
ia= act->data;
- prop= get_property(ob, ia->name);
+ prop= get_ob_property(ob, ia->name);
if(prop) {
ia->type= ACT_IPO_FROM_PROP;
}
@@ -6282,7 +6741,7 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
sce->toolsettings->uvcalc_cubesize = 1.0f;
sce->toolsettings->uvcalc_mapdir = 1;
sce->toolsettings->uvcalc_mapalign = 1;
- sce->toolsettings->uvcalc_flag = 1;
+ sce->toolsettings->uvcalc_flag = UVCALC_FILLHOLES;
sce->toolsettings->unwrapper = 1;
}
@@ -6746,7 +7205,12 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
Lamp *la;
Material *ma;
ParticleSettings *part;
+ World *wrld;
Mesh *me;
+ bNodeTree *ntree;
+ Tex *tex;
+ ModifierData *md;
+ ParticleSystem *psys;
/* unless the file was created 2.44.3 but not 2.45, update the constraints */
if ( !(main->versionfile==244 && main->subversionfile==3) &&
@@ -6776,14 +7240,6 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
curcon->ownspace = CONSTRAINT_SPACE_LOCAL;
}
break;
- case CONSTRAINT_TYPE_STRETCHTO:
- {
- bStretchToConstraint *data= (bStretchToConstraint *)curcon->data;
-
- /* force recalc of rest-length */
- data->orglength = 0;
- }
- break;
}
}
}
@@ -6815,14 +7271,6 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
curcon->tarspace = CONSTRAINT_SPACE_LOCAL;
}
break;
- case CONSTRAINT_TYPE_STRETCHTO:
- {
- bStretchToConstraint *data= (bStretchToConstraint *)curcon->data;
-
- /* force recalc of rest-length */
- data->orglength = 0;
- }
- break;
}
}
@@ -6887,6 +7335,27 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
}
}
+ /* add point caches */
+ for(ob=main->object.first; ob; ob=ob->id.next) {
+ if(ob->soft && !ob->soft->pointcache)
+ ob->soft->pointcache= BKE_ptcache_add();
+
+ for(psys=ob->particlesystem.first; psys; psys=psys->next) {
+ if(psys->soft && !psys->soft->pointcache)
+ psys->soft->pointcache= BKE_ptcache_add();
+ if(!psys->pointcache)
+ psys->pointcache= BKE_ptcache_add();
+ }
+
+ for(md=ob->modifiers.first; md; md=md->next) {
+ if(md->type==eModifierType_Cloth) {
+ ClothModifierData *clmd = (ClothModifierData*) md;
+ if(!clmd->point_cache)
+ clmd->point_cache= BKE_ptcache_add();
+ }
+ }
+ }
+
/* Copy over old per-level multires vertex data
into a single vertex array in struct Multires */
for(me = main->mesh.first; me; me=me->id.next) {
@@ -6942,6 +7411,54 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
}
}
+ for(wrld=main->world.first; wrld; wrld= wrld->id.next) {
+ if(wrld->ao_approx_error == 0.0f)
+ wrld->ao_approx_error= 0.25f;
+ }
+
+ for(sce= main->scene.first; sce; sce= sce->id.next) {
+ if(sce->nodetree)
+ ntree_version_245(fd, lib, sce->nodetree);
+
+ if(sce->r.simplify_shadowsamples == 0) {
+ sce->r.simplify_subsurf= 6;
+ sce->r.simplify_particles= 1.0f;
+ sce->r.simplify_shadowsamples= 16;
+ sce->r.simplify_aosss= 1.0f;
+ }
+
+ if(sce->r.cineongamma == 0) {
+ sce->r.cineonblack= 95;
+ sce->r.cineonwhite= 685;
+ sce->r.cineongamma= 1.7f;
+ }
+ }
+
+ for(ntree=main->nodetree.first; ntree; ntree= ntree->id.next)
+ ntree_version_245(fd, lib, ntree);
+
+ /* fix for temporary flag changes during 245 cycle */
+ for(ima= main->image.first; ima; ima= ima->id.next) {
+ if(ima->flag & IMA_OLD_PREMUL) {
+ ima->flag &= ~IMA_OLD_PREMUL;
+ ima->flag |= IMA_DO_PREMUL;
+ }
+ }
+
+ for(tex=main->tex.first; tex; tex=tex->id.next) {
+ if(tex->iuser.flag & IMA_OLD_PREMUL) {
+ tex->iuser.flag &= ~IMA_OLD_PREMUL;
+ tex->iuser.flag |= IMA_DO_PREMUL;
+
+ }
+
+ ima= newlibadr(fd, lib, tex->ima);
+ if(ima && (tex->iuser.flag & IMA_DO_PREMUL)) {
+ ima->flag &= ~IMA_OLD_PREMUL;
+ ima->flag |= IMA_DO_PREMUL;
+ }
+ }
+
if (main->versionfile < 245 || main->subversionfile < 12)
{
/* initialize skeleton generation toolsettings */
@@ -6964,6 +7481,24 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
}
}
}
+
+ /* sanity check for skgen
+ * */
+ {
+ Scene *sce;
+ for(sce=main->scene.first; sce; sce = sce->id.next)
+ {
+ if (sce->toolsettings->skgen_subdivisions[0] == sce->toolsettings->skgen_subdivisions[1] ||
+ sce->toolsettings->skgen_subdivisions[0] == sce->toolsettings->skgen_subdivisions[2] ||
+ sce->toolsettings->skgen_subdivisions[1] == sce->toolsettings->skgen_subdivisions[2])
+ {
+ sce->toolsettings->skgen_subdivisions[0] = SKGEN_SUB_CORRELATION;
+ sce->toolsettings->skgen_subdivisions[1] = SKGEN_SUB_LENGTH;
+ sce->toolsettings->skgen_subdivisions[2] = SKGEN_SUB_ANGLE;
+ }
+ }
+ }
+
if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 2)) {
Image *ima;
@@ -7092,62 +7627,6 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
sb->keys = NULL;
sb->totkey = 0;
- ob->softflag &= ~OB_SB_BAKESET;
- }
- }
- }
-
- if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 7)) {
- Object *ob;
- bPoseChannel *pchan;
- bConstraint *con;
- bConstraintTarget *ct;
-
- for(ob = main->object.first; ob; ob= ob->id.next) {
- if(ob->pose) {
- for(pchan=ob->pose->chanbase.first; pchan; pchan=pchan->next) {
- for(con=pchan->constraints.first; con; con=con->next) {
- if(con->type==CONSTRAINT_TYPE_PYTHON) {
- bPythonConstraint *data= (bPythonConstraint *)con->data;
- if (data->tar) {
- /* version patching needs to be done */
- ct= MEM_callocN(sizeof(bConstraintTarget), "PyConTarget");
-
- ct->tar = data->tar;
- strcpy(ct->subtarget, data->subtarget);
- ct->space = con->tarspace;
-
- BLI_addtail(&data->targets, ct);
- data->tarnum++;
-
- /* clear old targets to avoid problems */
- data->tar = NULL;
- strcpy(data->subtarget, "");
- }
- }
- }
- }
- }
-
- for(con=ob->constraints.first; con; con=con->next) {
- if(con->type==CONSTRAINT_TYPE_PYTHON) {
- bPythonConstraint *data= (bPythonConstraint *)con->data;
- if (data->tar) {
- /* version patching needs to be done */
- ct= MEM_callocN(sizeof(bConstraintTarget), "PyConTarget");
-
- ct->tar = data->tar;
- strcpy(ct->subtarget, data->subtarget);
- ct->space = con->tarspace;
-
- BLI_addtail(&data->targets, ct);
- data->tarnum++;
-
- /* clear old targets to avoid problems */
- data->tar = NULL;
- strcpy(data->subtarget, "");
- }
- }
}
}
}
@@ -7171,7 +7650,6 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
sb->keys = NULL;
sb->totkey = 0;
- ob->softflag &= ~OB_SB_BAKESET;
}
/* convert old particles to new system */
@@ -7183,17 +7661,19 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
/* create new particle system */
psys = MEM_callocN(sizeof(ParticleSystem), "particle_system");
+ psys->pointcache = BKE_ptcache_add();
part = psys->part = psys_new_settings("PSys", main);
/* needed for proper libdata lookup */
oldnewmap_insert(fd->libmap, psys->part, psys->part, 0);
+ part->id.lib= ob->id.lib;
part->id.us--;
part->id.flag |= (ob->id.flag & LIB_NEEDLINK);
psys->totpart=0;
- psys->flag=PSYS_ENABLED|PSYS_CURRENT;
+ psys->flag= PSYS_ENABLED|PSYS_CURRENT;
BLI_addtail(&ob->particlesystem, psys);
@@ -7217,6 +7697,9 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
part->eff_group = paf->group;
+ /* old system didn't interpolate between keypoints at render time */
+ part->draw_step = part->ren_step = 0;
+
/* physics */
part->normfac = paf->normfac * 25.0f;
part->obfac = paf->obfac;
@@ -7269,10 +7752,20 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
ob->transflag &= ~OB_DUPLIVERTS;
part->draw_as = PART_DRAW_OB;
+
+ /* needed for proper libdata lookup */
+ oldnewmap_insert(fd->libmap, dup, dup, 0);
}
}
}
+
+ {
+ FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
+ if(fluidmd && fluidmd->fss && fluidmd->fss->type == OB_FLUIDSIM_PARTICLE)
+ part->type = PART_FLUID;
+ }
+
free_effects(&ob->effect);
printf("Old particle system converted to new system.\n");
@@ -7340,17 +7833,259 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
strip->scale = length / (repeat * actlength);
if (strip->scale == 0.0f) strip->scale= 1.0f;
}
+ if(ob->soft){
+ ob->soft->inpush = ob->soft->inspring;
+ ob->soft->shearstiff = 1.0f;
+ }
}
}
+
+ if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 14)) {
+ Scene *sce= main->scene.first;
+ Sequence *seq;
+ Editing *ed;
+ while(sce) {
+ ed= sce->ed;
+ if(ed) {
+ WHILE_SEQ(&ed->seqbase) {
+ if (seq->blend_mode == 0) {
+ seq->blend_opacity = 100.0;
+ }
+ }
+ END_SEQ
+ }
+
+ sce= sce->id.next;
+ }
+ }
+
+ /*fix broken group lengths in id properties*/
+ if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 15)) {
+ idproperties_fix_group_lengths(main->scene);
+ idproperties_fix_group_lengths(main->library);
+ idproperties_fix_group_lengths(main->object);
+ idproperties_fix_group_lengths(main->mesh);
+ idproperties_fix_group_lengths(main->curve);
+ idproperties_fix_group_lengths(main->mball);
+ idproperties_fix_group_lengths(main->mat);
+ idproperties_fix_group_lengths(main->tex);
+ idproperties_fix_group_lengths(main->image);
+ idproperties_fix_group_lengths(main->wave);
+ idproperties_fix_group_lengths(main->latt);
+ idproperties_fix_group_lengths(main->lamp);
+ idproperties_fix_group_lengths(main->camera);
+ idproperties_fix_group_lengths(main->ipo);
+ idproperties_fix_group_lengths(main->key);
+ idproperties_fix_group_lengths(main->world);
+ idproperties_fix_group_lengths(main->screen);
+ idproperties_fix_group_lengths(main->script);
+ idproperties_fix_group_lengths(main->vfont);
+ idproperties_fix_group_lengths(main->text);
+ idproperties_fix_group_lengths(main->sound);
+ idproperties_fix_group_lengths(main->group);
+ idproperties_fix_group_lengths(main->armature);
+ idproperties_fix_group_lengths(main->action);
+ idproperties_fix_group_lengths(main->nodetree);
+ idproperties_fix_group_lengths(main->brush);
+ idproperties_fix_group_lengths(main->particle);
+ }
+
+ /* sun/sky */
+ if(main->versionfile < 246) {
+ Object *ob;
+ bActuator *act;
+
+ /* dRot actuator change direction in 2.46 */
+ for(ob = main->object.first; ob; ob= ob->id.next) {
+ for(act= ob->actuators.first; act; act= act->next) {
+ if (act->type == ACT_OBJECT) {
+ bObjectActuator *ba= act->data;
+
+ ba->drot[0] = -ba->drot[0];
+ ba->drot[1] = -ba->drot[1];
+ ba->drot[2] = -ba->drot[2];
+ }
+ }
+ }
+ }
+
+ // convert fluids to modifier
+ if(main->versionfile < 246 || (main->versionfile == 246 && main->subversionfile < 1))
+ {
+ Object *ob;
+ for(ob = main->object.first; ob; ob= ob->id.next) {
+ if(ob->fluidsimSettings)
+ {
+ FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifier_new(eModifierType_Fluidsim);
+ BLI_addhead(&ob->modifiers, (ModifierData *)fluidmd);
+
+ MEM_freeN(fluidmd->fss);
+ fluidmd->fss = MEM_dupallocN(ob->fluidsimSettings);
+ fluidmd->fss->ipo = newlibadr_us(fd, ob->id.lib, ob->fluidsimSettings->ipo);
+ MEM_freeN(ob->fluidsimSettings);
+
+ fluidmd->fss->lastgoodframe = INT_MAX;
+ fluidmd->fss->flag = 0;
+ }
+ }
+ }
+
+
+ if(main->versionfile < 246 || (main->versionfile == 246 && main->subversionfile < 1)) {
+ Mesh *me;
+
+ for(me=main->mesh.first; me; me= me->id.next)
+ alphasort_version_246(fd, lib, me);
+ }
+
+ if(main->versionfile < 246 || (main->versionfile == 246 && main->subversionfile < 1)){
+ Object *ob;
+ for(ob = main->object.first; ob; ob= ob->id.next) {
+ if(ob->pd && (ob->pd->forcefield == PFIELD_WIND))
+ ob->pd->f_noise = 0.0;
+ }
+ }
+
+ if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 2)){
+ Object *ob;
+ for(ob = main->object.first; ob; ob= ob->id.next) {
+ ob->gameflag |= OB_COLLISION;
+ ob->margin = 0.06;
+ }
+ }
+
+ if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 3)){
+ Object *ob;
+ for(ob = main->object.first; ob; ob= ob->id.next) {
+ // Starting from subversion 3, ACTOR is a separate feature.
+ // Before it was conditioning all the other dynamic flags
+ if (!(ob->gameflag & OB_ACTOR))
+ ob->gameflag &= ~(OB_GHOST|OB_DYNAMIC|OB_RIGID_BODY|OB_SOFT_BODY|OB_COLLISION_RESPONSE);
+ /* suitable default for older files */
+ }
+ }
+
+ if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 4)){
+ Scene *sce= main->scene.first;
+ while(sce) {
+ if(sce->frame_step==0)
+ sce->frame_step= 1;
+ sce= sce->id.next;
+ }
+ }
+
+ if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 5)) {
+ Lamp *la= main->lamp.first;
+ for(; la; la= la->id.next) {
+ la->skyblendtype= MA_RAMP_ADD;
+ la->skyblendfac= 1.0f;
+ }
+ }
+
+ /* set the curve radius interpolation to 2.47 default - easy */
+ if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 6)) {
+ Curve *cu;
+ Nurb *nu;
+
+ for(cu= main->curve.first; cu; cu= cu->id.next) {
+ for(nu= cu->nurb.first; nu; nu= nu->next) {
+ if (nu) {
+ nu->radius_interp = 3;
+
+ /* resolu and resolv are now used differently for surfaces
+ * rather then using the resolution to define the entire number of divisions,
+ * use it for the number of divisions per segment
+ */
+ if (nu->pntsv > 1) {
+ nu->resolu = MAX2( 1, (int)(((float)nu->resolu / (float)nu->pntsu)+0.5f) );
+ nu->resolv = MAX2( 1, (int)(((float)nu->resolv / (float)nu->pntsv)+0.5f) );
+ }
+ }
+ }
+ }
+ }
+ /* direction constraint actuators were always local in previous version */
+ if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 7)) {
+ bActuator *act;
+ Object *ob;
+
+ for(ob = main->object.first; ob; ob= ob->id.next) {
+ for(act= ob->actuators.first; act; act= act->next) {
+ if (act->type == ACT_CONSTRAINT) {
+ bConstraintActuator *coa = act->data;
+ if (coa->type == ACT_CONST_TYPE_DIST) {
+ coa->flag |= ACT_CONST_LOCAL;
+ }
+ }
+ }
+ }
+ }
+ /* autokey mode settings now used from scene, but need to be initialised off userprefs */
+ if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 8)) {
+ Scene *sce;
+
+ for (sce= main->scene.first; sce; sce= sce->id.next) {
+ if (sce->autokey_mode == 0)
+ sce->autokey_mode= U.autokey_mode;
+ }
+ }
+
+ if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 9)) {
+ Lamp *la= main->lamp.first;
+ for(; la; la= la->id.next) {
+ la->sky_exposure= 1.0f;
+ }
+ }
+
+ /* BGE message actuators needed OB prefix, very confusing */
+ if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 10)) {
+ bActuator *act;
+ Object *ob;
+
+ for(ob = main->object.first; ob; ob= ob->id.next) {
+ for(act= ob->actuators.first; act; act= act->next) {
+ if (act->type == ACT_MESSAGE) {
+ bMessageActuator *msgAct = (bMessageActuator *) act->data;
+ if (strlen(msgAct->toPropName) > 2) {
+ /* strip first 2 chars, would have only worked if these were OB anyway */
+ memmove( msgAct->toPropName, msgAct->toPropName+2, sizeof(msgAct->toPropName)-2 );
+ } else {
+ msgAct->toPropName[0] = '\0';
+ }
+ }
+ }
+ }
+ }
+
+ if (main->versionfile < 248) {
+ Lamp *la;
+
+ for(la=main->lamp.first; la; la= la->id.next) {
+ if(la->atm_turbidity == 0.0) {
+ la->sun_effect_type = 0;
+ la->horizon_brightness = 1.0;
+ la->spread = 1.0;
+ la->sun_brightness = 1.0;
+ la->sun_size = 1.0;
+ la->backscattered_light = 1.0;
+ la->atm_turbidity = 2.0;
+ la->atm_inscattering_factor = 1.0;
+ la->atm_extinction_factor = 1.0;
+ la->atm_distance_factor = 1.0;
+ la->sun_intensity = 1.0;
+ }
+ }
+ }
+
if (main->versionfile < 250) {
bScreen *screen;
for(screen= main->screen.first; screen; screen= screen->id.next)
do_versions_windowmanager_2_50(screen);
}
-
+
/* WATCH IT!!!: pointers from libdata have not been converted yet here! */
/* WATCH IT 2!: Userdef struct init has to be in src/usiblender.c! */
@@ -7461,13 +8196,14 @@ BlendFileData *blo_read_file_internal(FileData *fd, BlendReadError *error_r)
/* do before read_libraries, but skip undo case */
// if(fd->memfile==NULL) (the mesh shuffle hacks don't work yet? ton)
do_versions(fd, NULL, bfd->main);
-
+
read_libraries(fd, &fd->mainlist);
blo_join_main(&fd->mainlist);
lib_link_all(fd, bfd->main);
- lib_verify_nodetree(bfd->main);
+ lib_verify_nodetree(bfd->main, 1);
+ fix_relpaths_library(fd->filename, bfd->main); /* make all relative paths, relative to the open blend file */
link_global(fd, bfd); /* as last */
@@ -7476,6 +8212,43 @@ BlendFileData *blo_read_file_internal(FileData *fd, BlendReadError *error_r)
/* ************* APPEND LIBRARY ************** */
+struct bheadsort {
+ BHead *bhead;
+ void *old;
+};
+
+static int verg_bheadsort(const void *v1, const void *v2)
+{
+ const struct bheadsort *x1=v1, *x2=v2;
+
+ if( x1->old > x2->old) return 1;
+ else if( x1->old < x2->old) return -1;
+ return 0;
+}
+
+static void sort_bhead_old_map(FileData *fd)
+{
+ BHead *bhead;
+ struct bheadsort *bhs;
+ int tot= 0;
+
+ for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead))
+ tot++;
+
+ fd->tot_bheadmap= tot;
+ if(tot==0) return;
+
+ bhs= fd->bheadmap= MEM_mallocN(tot*sizeof(struct bheadsort), "bheadsort");
+
+ for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead), bhs++) {
+ bhs->bhead= bhead;
+ bhs->old= bhead->old;
+ }
+
+ qsort(fd->bheadmap, tot, sizeof(struct bheadsort), verg_bheadsort);
+
+}
+
static BHead *find_previous_lib(FileData *fd, BHead *bhead)
{
for (; bhead; bhead= blo_prevbhead(fd, bhead))
@@ -7487,14 +8260,28 @@ static BHead *find_previous_lib(FileData *fd, BHead *bhead)
static BHead *find_bhead(FileData *fd, void *old)
{
+#if 0
BHead *bhead;
-
+#endif
+ struct bheadsort *bhs, bhs_s;
+
if (!old)
return NULL;
+ if (fd->bheadmap==NULL)
+ sort_bhead_old_map(fd);
+
+ bhs_s.old= old;
+ bhs= bsearch(&bhs_s, fd->bheadmap, fd->tot_bheadmap, sizeof(struct bheadsort), verg_bheadsort);
+
+ if(bhs)
+ return bhs->bhead;
+
+#if 0
for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead))
if (bhead->old==old)
return bhead;
+#endif
return NULL;
}
@@ -7547,7 +8334,13 @@ static void expand_doit(FileData *fd, Main *mainvar, void *old)
ptr->curlib->parent= mainvar->curlib;
}
else {
- //oldnewmap_insert(fd->libmap, bhead->old, id, 1);
+ /* The line below was commented by Ton (I assume), when Hos did the merge from the orange branch. rev 6568
+ * This line is NEEDED, the case is that you have 3 blend files...
+ * user.blend, lib.blend and lib_indirect.blend - if user.blend alredy references a "tree" from
+ * lib_indirect.blend but lib.blend does too, linking in a Scene or Group from lib.blend can result in an
+ * empty without the dupli group referenced. Once you save and reload the group would appier. - Campbell */
+ /* This crashes files, must look further into it */
+ /*oldnewmap_insert(fd->libmap, bhead->old, id, 1);*/
change_idid_adr_fd(fd, bhead->old, id);
if(G.f & G_DEBUG) printf("expand_doit: already linked: %s lib: %s\n", id->name, lib->name);
@@ -7571,6 +8364,14 @@ static void expand_doit(FileData *fd, Main *mainvar, void *old)
}
}
+static void expand_particlesettings(FileData *fd, Main *mainvar, ParticleSettings *part)
+{
+ expand_doit(fd, mainvar, part->dup_ob);
+ expand_doit(fd, mainvar, part->dup_group);
+ expand_doit(fd, mainvar, part->eff_group);
+ expand_doit(fd, mainvar, part->bb_ob);
+}
+
static void expand_ipo(FileData *fd, Main *mainvar, Ipo *ipo)
{
IpoCurve *icu;
@@ -7841,6 +8642,12 @@ static void expand_constraints(FileData *fd, Main *mainvar, ListBase *lb)
expand_doit(fd, mainvar, data->tar);
}
break;
+ case CONSTRAINT_TYPE_DISTLIMIT:
+ {
+ bDistLimitConstraint *data = (bDistLimitConstraint*)curcon->data;
+ expand_doit(fd, mainvar, data->tar);
+ }
+ break;
default:
break;
}
@@ -7919,6 +8726,12 @@ static void expand_modifier(FileData *fd, Main *mainvar, ModifierData *md)
expand_doit(fd, mainvar, mmd->mirror_ob);
}
+ else if (md->type==eModifierType_Displace) {
+ DisplaceModifierData *dmd = (DisplaceModifierData*) md;
+
+ expand_doit(fd, mainvar, dmd->map_object);
+ expand_doit(fd, mainvar, dmd->texture);
+ }
}
static void expand_scriptlink(FileData *fd, Main *mainvar, ScriptLink *slink)
@@ -7945,6 +8758,7 @@ static void expand_object(FileData *fd, Main *mainvar, Object *ob)
expand_doit(fd, mainvar, ob->data);
expand_doit(fd, mainvar, ob->ipo);
expand_doit(fd, mainvar, ob->action);
+ expand_doit(fd, mainvar, ob->poselib);
for (md=ob->modifiers.first; md; md=md->next) {
expand_modifier(fd, mainvar, md);
@@ -7981,9 +8795,6 @@ static void expand_object(FileData *fd, Main *mainvar, Object *ob)
sens= ob->sensors.first;
while(sens) {
- for(a=0; a<sens->totlinks; a++) {
- sens->links[a]= newglobadr(fd, sens->links[a]);
- }
if(sens->type==SENS_TOUCH) {
bTouchSensor *ts= sens->data;
expand_doit(fd, mainvar, ts->ma);
@@ -7997,9 +8808,6 @@ static void expand_object(FileData *fd, Main *mainvar, Object *ob)
cont= ob->controllers.first;
while(cont) {
- for(a=0; a<cont->totlinks; a++) {
- cont->links[a]= newglobadr(fd, cont->links[a]);
- }
if(cont->type==CONT_PYTHON) {
bPythonCont *pc= cont->data;
expand_doit(fd, mainvar, pc->text);
@@ -8033,6 +8841,10 @@ static void expand_object(FileData *fd, Main *mainvar, Object *ob)
bActionActuator *aa= act->data;
expand_doit(fd, mainvar, aa->act);
}
+ else if(act->type==ACT_SHAPEACTION) {
+ bActionActuator *aa= act->data;
+ expand_doit(fd, mainvar, aa->act);
+ }
else if(act->type==ACT_PROPERTY) {
bPropertyActuator *pa= act->data;
expand_doit(fd, mainvar, pa->ob);
@@ -8043,6 +8855,9 @@ static void expand_object(FileData *fd, Main *mainvar, Object *ob)
}
act= act->next;
}
+
+ if(ob->pd && ob->pd->tex)
+ expand_doit(fd, mainvar, ob->pd->tex);
expand_scriptlink(fd, mainvar, &ob->scriptlink);
}
@@ -8156,6 +8971,8 @@ static void expand_main(FileData *fd, Main *mainvar)
case ID_IP:
expand_ipo(fd, mainvar, (Ipo *)id);
break;
+ case ID_PA:
+ expand_particlesettings(fd, mainvar, (ParticleSettings *)id);
}
doit= 1;
@@ -8179,34 +8996,42 @@ static int object_in_any_scene(Object *ob)
}
/* when *lib set, it also does objects that were in the appended group */
-static void give_base_to_objects(Scene *sce, ListBase *lb, Library *lib)
+static void give_base_to_objects(Scene *sce, ListBase *lb, Library *lib, int is_group_append)
{
Object *ob;
Base *base;
/* give all objects which are LIB_INDIRECT a base, or for a group when *lib has been set */
for(ob= lb->first; ob; ob= ob->id.next) {
-
+
if( ob->id.flag & LIB_INDIRECT ) {
- int do_it= 0;
- if(ob->id.us==0)
- do_it= 1;
- else if(ob->id.us==1 && lib)
- if(ob->id.lib==lib && (ob->flag & OB_FROMGROUP) && object_in_any_scene(ob)==0)
+ /* IF below is quite confusing!
+ if we are appending, but this object wasnt just added allong with a group,
+ then this is alredy used indirectly in the scene somewhere else and we didnt just append it.
+
+ (ob->id.flag & LIB_APPEND_TAG)==0 means that this is a newly appended object - Campbell */
+ if (is_group_append==0 || (ob->id.flag & LIB_APPEND_TAG)==0) {
+
+ int do_it= 0;
+
+ if(ob->id.us==0)
do_it= 1;
+ else if(ob->id.us==1 && lib)
+ if(ob->id.lib==lib && (ob->flag & OB_FROMGROUP) && object_in_any_scene(ob)==0)
+ do_it= 1;
+
+ if(do_it) {
+ base= MEM_callocN( sizeof(Base), "add_ext_base");
+ BLI_addtail(&(sce->base), base);
+ base->lay= ob->lay;
+ base->object= ob;
+ base->flag= ob->flag;
+ ob->id.us= 1;
- if(do_it) {
- base= MEM_callocN( sizeof(Base), "add_ext_base");
- BLI_addtail(&(sce->base), base);
- base->lay= ob->lay;
- base->object= ob;
- base->flag= ob->flag;
- ob->id.us= 1;
-
- ob->id.flag -= LIB_INDIRECT;
- ob->id.flag |= LIB_EXTERN;
-
+ ob->id.flag -= LIB_INDIRECT;
+ ob->id.flag |= LIB_EXTERN;
+ }
}
}
}
@@ -8295,38 +9120,38 @@ static void append_id_part(FileData *fd, Main *mainvar, ID *id, ID **id_r)
/* common routine to append/link something from a library */
static Library* library_append(Scene *scene, char* file, char *dir, int idcode,
- int totsel, FileData *fd, struct direntry* filelist, int totfile, short flag)
+ int totsel, FileData **fd, struct direntry* filelist, int totfile, short flag)
{
Main *mainl;
Library *curlib;
/* make mains */
- blo_split_main(&fd->mainlist, G.main);
+ blo_split_main(&(*fd)->mainlist, G.main);
/* which one do we need? */
- mainl = blo_find_main(fd, &fd->mainlist, dir, G.sce);
+ mainl = blo_find_main(*fd, &(*fd)->mainlist, dir, G.sce);
- mainl->versionfile= fd->fileversion; /* needed for do_version */
+ mainl->versionfile= (*fd)->fileversion; /* needed for do_version */
curlib= mainl->curlib;
if(totsel==0) {
- append_named_part(fd, mainl, scene, file, idcode, flag);
+ append_named_part(*fd, mainl, scene, file, idcode, flag);
}
else {
int a;
for(a=0; a<totfile; a++) {
if(filelist[a].flags & ACTIVE) {
- append_named_part(fd, mainl, scene, filelist[a].relname, idcode, flag);
+ append_named_part(*fd, mainl, scene, filelist[a].relname, idcode, flag);
}
}
}
/* make main consistant */
- expand_main(fd, mainl);
+ expand_main(*fd, mainl);
/* do this when expand found other libs */
- read_libraries(fd, &fd->mainlist);
+ read_libraries(*fd, &(*fd)->mainlist);
if(flag & FILE_STRINGCODE) {
@@ -8337,25 +9162,31 @@ static Library* library_append(Scene *scene, char* file, char *dir, int idcode,
BLI_makestringcode(G.sce, mainl->curlib->name);
}
- blo_join_main(&fd->mainlist);
- G.main= fd->mainlist.first;
+ blo_join_main(&(*fd)->mainlist);
+ G.main= (*fd)->mainlist.first;
- lib_link_all(fd, G.main);
- lib_verify_nodetree(G.main);
+ lib_link_all(*fd, G.main);
+ lib_verify_nodetree(G.main, 0);
+ fix_relpaths_library(G.sce, G.main); /* make all relative paths, relative to the open blend file */
/* give a base to loose objects. If group append, do it for objects too */
- if(idcode==ID_GR)
- give_base_to_objects(scene, &(G.main->object), (flag & FILE_LINK)?NULL:curlib);
- else
- give_base_to_objects(scene, &(G.main->object), NULL);
-
+ if(idcode==ID_GR) {
+ if (flag & FILE_LINK) {
+ give_base_to_objects(scene, &(G.main->object), NULL, 0);
+ } else {
+ give_base_to_objects(scene, &(G.main->object), curlib, 1);
+ }
+ } else {
+ give_base_to_objects(scene, &(G.main->object), NULL, 0);
+ }
/* has been removed... erm, why? s..ton) */
/* 20040907: looks like they are give base already in append_named_part(); -Nathan L */
/* 20041208: put back. It only linked direct, not indirect objects (ton) */
/* patch to prevent switch_endian happens twice */
- if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
- blo_freefiledata( fd );
+ if((*fd)->flags & FD_FLAGS_SWITCH_ENDIAN) {
+ blo_freefiledata( *fd );
+ *fd = NULL;
}
return curlib;
@@ -8366,11 +9197,11 @@ static Library* library_append(Scene *scene, char* file, char *dir, int idcode,
/* append to scene */
/* this should probably be moved into the Python code anyway */
-void BLO_script_library_append(BlendHandle *bh, char *dir, char *name,
+void BLO_script_library_append(BlendHandle **bh, char *dir, char *name,
int idcode, short flag, Scene *scene )
{
/* try to append the requested object */
- library_append(scene, name, dir, idcode, 0, (FileData *)bh, NULL, 0, flag );
+ library_append(scene, name, dir, idcode, 0, (FileData **)bh, NULL, 0, flag );
/* do we need to do this? */
DAG_scene_sort(scene);
@@ -8387,7 +9218,6 @@ void BLO_library_append(SpaceFile *sfile, char *dir, int idcode, Scene *scene)
void BLO_library_append_(BlendHandle** libfiledata, struct direntry* filelist, int totfile,
char *dir, char* file, short flag, int idcode, Scene *scene)
{
- FileData *fd= (FileData*) (*libfiledata);
Library *curlib;
Base *centerbase;
Object *ob;
@@ -8420,12 +9250,7 @@ void BLO_library_append_(BlendHandle** libfiledata, struct direntry* filelist, i
if(flag & FILE_AUTOSELECT) scene_deselect_all(scene);
- curlib = library_append(scene, file, dir, idcode, totsel, fd, filelist, totfile,flag );
-
- /* patch to prevent switch_endian happens twice */
- if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
- (*libfiledata)= 0;
- }
+ curlib = library_append(scene, file, dir, idcode, totsel, (FileData**) libfiledata, filelist, totfile,flag );
/* when not linking (appending)... */
if((flag & FILE_LINK)==0) {
@@ -8599,13 +9424,13 @@ static void read_libraries(FileData *basefd, ListBase *mainlist)
if(mainptr->curlib->filedata) blo_freefiledata(mainptr->curlib->filedata);
mainptr->curlib->filedata= NULL;
-
}
}
+
/* reading runtime */
-BlendFileData *blo_read_blendafterruntime(int file, int actualsize, BlendReadError *error_r)
+BlendFileData *blo_read_blendafterruntime(int file, char *name, int actualsize, BlendReadError *error_r)
{
BlendFileData *bfd = NULL;
FileData *fd = filedata_new();
@@ -8613,6 +9438,9 @@ BlendFileData *blo_read_blendafterruntime(int file, int actualsize, BlendReadErr
fd->buffersize = actualsize;
fd->read = fd_read_from_file;
+ /* needed for library_append and read_libraries */
+ BLI_strncpy(fd->filename, name, sizeof(fd->filename));
+
fd = blo_decode_and_check(fd, error_r);
if (!fd)
return NULL;
diff --git a/source/blender/blenloader/intern/readfile.h b/source/blender/blenloader/intern/readfile.h
index 51160a179fb..8547a4d9652 100644
--- a/source/blender/blenloader/intern/readfile.h
+++ b/source/blender/blenloader/intern/readfile.h
@@ -34,6 +34,7 @@
struct OldNewMap;
struct MemFile;
+struct bheadsort;
typedef struct FileData {
// linked list of BHeadN's
@@ -73,6 +74,9 @@ typedef struct FileData {
struct OldNewMap *libmap;
struct OldNewMap *imamap;
+ struct bheadsort *bheadmap;
+ int tot_bheadmap;
+
ListBase mainlist;
/* ick ick, used to return
@@ -108,6 +112,7 @@ FileData *blo_openblenderfile( char *name, BlendReadError *error_r);
FileData *blo_openblendermemory( void *buffer, int buffersize, BlendReadError *error_r);
FileData *blo_openblendermemfile(struct MemFile *memfile, BlendReadError *error_r);
+void blo_clear_proxy_pointers_from_lib(FileData *fd);
void blo_make_image_pointer_map(FileData *fd);
void blo_end_image_pointer_map(FileData *fd);
void blo_add_library_pointer_map(ListBase *mainlist, FileData *fd);
diff --git a/source/blender/blenloader/intern/writefile.c b/source/blender/blenloader/intern/writefile.c
index 383a732fbca..a4883087cfa 100644
--- a/source/blender/blenloader/intern/writefile.c
+++ b/source/blender/blenloader/intern/writefile.c
@@ -6,7 +6,7 @@
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
+ * of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -23,7 +23,7 @@
*
* Contributor(s): Blender Foundation
*
- * ***** END GPL/BL DUAL LICENSE BLOCK *****
+ * ***** END GPL LICENSE BLOCK *****
*/
/*
@@ -94,6 +94,7 @@ Any case: direct data is ALWAYS after the lib block
#include "DNA_actuator_types.h"
#include "DNA_brush_types.h"
#include "DNA_camera_types.h"
+#include "DNA_cloth_types.h"
#include "DNA_color_types.h"
#include "DNA_constraint_types.h"
#include "DNA_controller_types.h"
@@ -102,6 +103,7 @@ Any case: direct data is ALWAYS after the lib block
#include "DNA_effect_types.h"
#include "DNA_genfile.h"
#include "DNA_group_types.h"
+#include "DNA_gpencil_types.h"
#include "DNA_image_types.h"
#include "DNA_ipo_types.h"
#include "DNA_fileglobal_types.h"
@@ -143,6 +145,7 @@ Any case: direct data is ALWAYS after the lib block
#include "BKE_action.h"
#include "BKE_blender.h"
+#include "BKE_cloth.h"
#include "BKE_curve.h"
#include "BKE_customdata.h"
#include "BKE_constraint.h"
@@ -162,8 +165,6 @@ Any case: direct data is ALWAYS after the lib block
//XXX #include "BIF_verse.h"
#endif
-#include "GEN_messaging.h"
-
#include "BLO_writefile.h"
#include "BLO_readfile.h"
#include "BLO_undofile.h"
@@ -172,7 +173,10 @@ Any case: direct data is ALWAYS after the lib block
#include <errno.h>
-/* ********* my write, buffered writing with minimum 50k chunks ************ */
+/* ********* my write, buffered writing with minimum size chunks ************ */
+
+#define MYWRITE_BUFFER_SIZE 100000
+#define MYWRITE_MAX_CHUNK 32768
typedef struct {
struct SDNA *sdna;
@@ -198,7 +202,7 @@ static WriteData *writedata_new(int file)
wd->file= file;
- wd->buf= MEM_mallocN(100000, "wd->buf");
+ wd->buf= MEM_mallocN(MYWRITE_BUFFER_SIZE, "wd->buf");
return wd;
}
@@ -238,12 +242,13 @@ int mywfile;
* @warning Talks to other functions with global parameters
*/
-#define MYWRITE_FLUSH NULL
+#define MYWRITE_FLUSH NULL
static void mywrite( WriteData *wd, void *adr, int len)
{
if (wd->error) return;
+ /* flush helps compression for undo-save */
if(adr==MYWRITE_FLUSH) {
if(wd->count) {
writedata_do_write(wd, wd->buf, wd->count);
@@ -254,21 +259,33 @@ static void mywrite( WriteData *wd, void *adr, int len)
wd->tot+= len;
- if(len>50000) {
+ /* if we have a single big chunk, write existing data in
+ * buffer and write out big chunk in smaller pieces */
+ if(len>MYWRITE_MAX_CHUNK) {
if(wd->count) {
writedata_do_write(wd, wd->buf, wd->count);
wd->count= 0;
}
- writedata_do_write(wd, adr, len);
+
+ do {
+ int writelen= MIN2(len, MYWRITE_MAX_CHUNK);
+ writedata_do_write(wd, adr, writelen);
+ adr = (char*)adr + writelen;
+ len -= writelen;
+ } while(len > 0);
+
return;
}
- if(len+wd->count>99999) {
+
+ /* if data would overflow buffer, write out the buffer */
+ if(len+wd->count>MYWRITE_BUFFER_SIZE-1) {
writedata_do_write(wd, wd->buf, wd->count);
wd->count= 0;
}
+
+ /* append data at end of buffer */
memcpy(&wd->buf[wd->count], adr, len);
wd->count+= len;
-
}
/**
@@ -367,7 +384,7 @@ static void writedata(WriteData *wd, int filecode, int len, void *adr) /* do not
void IDP_WriteProperty_OnlyData(IDProperty *prop, void *wd);
void IDP_WriteProperty(IDProperty *prop, void *wd);
-void IDP_WriteArray(IDProperty *prop, void *wd)
+static void IDP_WriteArray(IDProperty *prop, void *wd)
{
/*REMEMBER to set totalen to len in the linking code!!*/
if (prop->data.pointer) {
@@ -375,13 +392,13 @@ void IDP_WriteArray(IDProperty *prop, void *wd)
}
}
-void IDP_WriteString(IDProperty *prop, void *wd)
+static void IDP_WriteString(IDProperty *prop, void *wd)
{
/*REMEMBER to set totalen to len in the linking code!!*/
writedata(wd, DATA, prop->len+1, prop->data.pointer);
}
-void IDP_WriteGroup(IDProperty *prop, void *wd)
+static void IDP_WriteGroup(IDProperty *prop, void *wd)
{
IDProperty *loop;
@@ -434,7 +451,7 @@ static void write_nodetree(WriteData *wd, bNodeTree *ntree)
writestruct(wd, DATA, "bNode", 1, node);
for(node= ntree->nodes.first; node; node= node->next) {
- if(node->storage) {
+ if(node->storage && node->type!=NODE_DYNAMIC) {
/* could be handlerized at some point, now only 1 exception still */
if(ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
write_curvemapping(wd, node->storage);
@@ -492,25 +509,6 @@ static void write_userdef(WriteData *wd)
}
}
-static void write_effects(WriteData *wd, ListBase *lb)
-{
- Effect *eff;
-
- eff= lb->first;
- while(eff) {
-
- switch(eff->type) {
- case EFF_PARTICLE:
- writestruct(wd, DATA, "PartEff", 1, eff);
- break;
- default:
- writedata(wd, DATA, MEM_allocN_len(eff), eff);
- }
-
- eff= eff->next;
- }
-}
-
static void write_particlesettings(WriteData *wd, ListBase *idbase)
{
ParticleSettings *part;
@@ -520,7 +518,9 @@ static void write_particlesettings(WriteData *wd, ListBase *idbase)
if(part->id.us>0 || wd->current) {
/* write LibData */
writestruct(wd, ID_PA, "ParticleSettings", 1, part);
+ if (part->id.properties) IDP_WriteProperty(part->id.properties, wd);
writestruct(wd, DATA, "PartDeflect", 1, part->pd);
+ writestruct(wd, DATA, "PartDeflect", 1, part->pd2);
}
part= part->id.next;
}
@@ -540,11 +540,13 @@ static void write_particlesystems(WriteData *wd, ListBase *particles)
ParticleData *pa = psys->particles;
for(a=0; a<psys->totpart; a++, pa++)
- writedata(wd, DATA, MEM_allocN_len(pa->hair),pa->hair);
+ writestruct(wd, DATA, "HairKey", pa->totkey, pa->hair);
}
}
if(psys->child) writestruct(wd, DATA, "ChildParticle", psys->totchild ,psys->child);
writestruct(wd, DATA, "SoftBody", 1, psys->soft);
+ if(psys->soft) writestruct(wd, DATA, "PointCache", 1, psys->soft->pointcache);
+ writestruct(wd, DATA, "PointCache", 1, psys->pointcache);
}
}
@@ -589,6 +591,12 @@ static void write_sensors(WriteData *wd, ListBase *lb)
case SENS_PROPERTY:
writestruct(wd, DATA, "bPropertySensor", 1, sens->data);
break;
+ case SENS_ACTUATOR:
+ writestruct(wd, DATA, "bActuatorSensor", 1, sens->data);
+ break;
+ case SENS_DELAY:
+ writestruct(wd, DATA, "bDelaySensor", 1, sens->data);
+ break;
case SENS_COLLISION:
writestruct(wd, DATA, "bCollisionSensor", 1, sens->data);
break;
@@ -650,6 +658,7 @@ static void write_actuators(WriteData *wd, ListBase *lb)
switch(act->type) {
case ACT_ACTION:
+ case ACT_SHAPEACTION:
writestruct(wd, DATA, "bActionActuator", 1, act->data);
break;
case ACT_SOUND:
@@ -694,6 +703,15 @@ static void write_actuators(WriteData *wd, ListBase *lb)
case ACT_VISIBILITY:
writestruct(wd, DATA, "bVisibilityActuator", 1, act->data);
break;
+ case ACT_2DFILTER:
+ writestruct(wd, DATA, "bTwoDFilterActuator", 1, act->data);
+ break;
+ case ACT_PARENT:
+ writestruct(wd, DATA, "bParentActuator", 1, act->data);
+ break;
+ case ACT_STATE:
+ writestruct(wd, DATA, "bStateActuator", 1, act->data);
+ break;
default:
; /* error: don't know how to write this file */
}
@@ -754,6 +772,7 @@ static void write_constraints(WriteData *wd, ListBase *conlist)
static void write_pose(WriteData *wd, bPose *pose)
{
bPoseChannel *chan;
+ bActionGroup *grp;
/* Write each channel */
if (!pose)
@@ -769,6 +788,10 @@ static void write_pose(WriteData *wd, bPose *pose)
writestruct(wd, DATA, "bPoseChannel", 1, chan);
}
+
+ /* Write groups */
+ for (grp=pose->agroups.first; grp; grp=grp->next)
+ writestruct(wd, DATA, "bActionGroup", 1, grp);
/* Write this pose */
writestruct(wd, DATA, "bPose", 1, pose);
@@ -807,6 +830,29 @@ static void write_modifiers(WriteData *wd, ListBase *modbase)
writedata(wd, DATA, sizeof(int)*hmd->totindex, hmd->indexar);
}
+ else if(md->type==eModifierType_Cloth) {
+ ClothModifierData *clmd = (ClothModifierData*) md;
+
+ writestruct(wd, DATA, "ClothSimSettings", 1, clmd->sim_parms);
+ writestruct(wd, DATA, "ClothCollSettings", 1, clmd->coll_parms);
+ writestruct(wd, DATA, "PointCache", 1, clmd->point_cache);
+ }
+ else if(md->type==eModifierType_Fluidsim) {
+ FluidsimModifierData *fluidmd = (FluidsimModifierData*) md;
+
+ writestruct(wd, DATA, "FluidsimSettings", 1, fluidmd->fss);
+ }
+ else if (md->type==eModifierType_Collision) {
+
+ /*
+ CollisionModifierData *collmd = (CollisionModifierData*) md;
+ // TODO: CollisionModifier should use pointcache
+ // + have proper reset events before enabling this
+ writestruct(wd, DATA, "MVert", collmd->numverts, collmd->x);
+ writestruct(wd, DATA, "MVert", collmd->numverts, collmd->xnew);
+ writestruct(wd, DATA, "MFace", collmd->numfaces, collmd->mfaces);
+ */
+ }
else if (md->type==eModifierType_MeshDeform) {
MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
int size = mmd->dyngridsize;
@@ -846,7 +892,7 @@ static void write_objects(WriteData *wd, ListBase *idbase)
/* direct data */
writedata(wd, DATA, sizeof(void *)*ob->totcol, ob->mat);
- write_effects(wd, &ob->effect);
+ /* write_effects(wd, &ob->effect); */ /* not used anymore */
write_properties(wd, &ob->prop);
write_sensors(wd, &ob->sensors);
write_controllers(wd, &ob->controllers);
@@ -860,7 +906,8 @@ static void write_objects(WriteData *wd, ListBase *idbase)
writestruct(wd, DATA, "PartDeflect", 1, ob->pd);
writestruct(wd, DATA, "SoftBody", 1, ob->soft);
- writestruct(wd, DATA, "FluidsimSettings", 1, ob->fluidsimSettings); // NT
+ if(ob->soft) writestruct(wd, DATA, "PointCache", 1, ob->soft->pointcache);
+ writestruct(wd, DATA, "BulletSoftBody", 1, ob->bsoft);
write_particlesystems(wd, &ob->particlesystem);
write_modifiers(wd, &ob->modifiers);
@@ -1004,7 +1051,7 @@ static void write_mballs(WriteData *wd, ListBase *idbase)
}
}
-int amount_of_chars(char *str)
+static int amount_of_chars(char *str)
{
// Since the data is saved as UTF-8 to the cu->str
// The cu->len is not same as the strlen(cu->str)
@@ -1385,6 +1432,7 @@ static void write_scenes(WriteData *wd, ListBase *scebase)
MetaStack *ms;
Strip *strip;
TimeMarker *marker;
+ TransformOrientation *ts;
SceneRenderLayer *srl;
int a;
@@ -1448,9 +1496,20 @@ static void write_scenes(WriteData *wd, ListBase *scebase)
strip= seq->strip;
writestruct(wd, DATA, "Strip", 1, strip);
-
+ if(seq->flag & SEQ_USE_CROP && strip->crop) {
+ writestruct(wd, DATA, "StripCrop", 1, strip->crop);
+ }
+ if(seq->flag & SEQ_USE_TRANSFORM && strip->transform) {
+ writestruct(wd, DATA, "StripTransform", 1, strip->transform);
+ }
+ if(seq->flag & SEQ_USE_PROXY && strip->proxy) {
+ writestruct(wd, DATA, "StripProxy", 1, strip->proxy);
+ }
+ if(seq->flag & SEQ_USE_COLOR_BALANCE && strip->color_balance) {
+ writestruct(wd, DATA, "StripColorBalance", 1, strip->color_balance);
+ }
if(seq->type==SEQ_IMAGE)
- writestruct(wd, DATA, "StripElem", strip->len, strip->stripdata);
+ writestruct(wd, DATA, "StripElem", MEM_allocN_len(strip->stripdata) / sizeof(struct StripElem), strip->stripdata);
else if(seq->type==SEQ_MOVIE || seq->type==SEQ_RAM_SOUND || seq->type == SEQ_HD_SOUND)
writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
@@ -1477,11 +1536,18 @@ static void write_scenes(WriteData *wd, ListBase *scebase)
writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
}
+ if (sce->r.ffcodecdata.properties) {
+ IDP_WriteProperty(sce->r.ffcodecdata.properties, wd);
+ }
/* writing dynamic list of TimeMarkers to the blend file */
for(marker= sce->markers.first; marker; marker= marker->next)
writestruct(wd, DATA, "TimeMarker", 1, marker);
+ /* writing dynamic list of TransformOrientations to the blend file */
+ for(ts = sce->transform_spaces.first; ts; ts = ts->next)
+ writestruct(wd, DATA, "TransformOrientation", 1, ts);
+
for(srl= sce->r.layers.first; srl; srl= srl->next)
writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
@@ -1496,6 +1562,32 @@ static void write_scenes(WriteData *wd, ListBase *scebase)
mywrite(wd, MYWRITE_FLUSH, 0);
}
+static void write_gpencil(WriteData *wd, bGPdata *gpd)
+{
+ bGPDlayer *gpl;
+ bGPDframe *gpf;
+ bGPDstroke *gps;
+
+ /* write gpd data block to file */
+ writestruct(wd, DATA, "bGPdata", 1, gpd);
+
+ /* write grease-pencil layers to file */
+ for (gpl= gpd->layers.first; gpl; gpl= gpl->next) {
+ writestruct(wd, DATA, "bGPDlayer", 1, gpl);
+
+ /* write this layer's frames to file */
+ for (gpf= gpl->frames.first; gpf; gpf= gpf->next) {
+ writestruct(wd, DATA, "bGPDframe", 1, gpf);
+
+ /* write strokes */
+ for (gps= gpf->strokes.first; gps; gps= gps->next) {
+ writestruct(wd, DATA, "bGPDstroke", 1, gps);
+ writestruct(wd, DATA, "bGPDspoint", gps->totpoints, gps->points);
+ }
+ }
+ }
+}
+
static void write_windowmanagers(WriteData *wd, ListBase *lb)
{
wmWindowManager *wm;
@@ -1550,11 +1642,12 @@ static void write_screens(WriteData *wd, ListBase *scrbase)
sl= sa->spacedata.first;
while(sl) {
if(sl->spacetype==SPACE_VIEW3D) {
- View3D *v3d= (View3D*) sl;
+ View3D *v3d= (View3D *) sl;
writestruct(wd, DATA, "View3D", 1, v3d);
if(v3d->bgpic) writestruct(wd, DATA, "BGpic", 1, v3d->bgpic);
if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
if(v3d->clipbb) writestruct(wd, DATA, "BoundBox", 1, v3d->clipbb);
+ if(v3d->gpd) write_gpencil(wd, v3d->gpd);
}
else if(sl->spacetype==SPACE_IPO) {
writestruct(wd, DATA, "SpaceIpo", 1, sl);
@@ -1566,7 +1659,9 @@ static void write_screens(WriteData *wd, ListBase *scrbase)
writestruct(wd, DATA, "SpaceFile", 1, sl);
}
else if(sl->spacetype==SPACE_SEQ) {
+ SpaceSeq *sseq= (SpaceSeq *)sl;
writestruct(wd, DATA, "SpaceSeq", 1, sl);
+ if(sseq->gpd) write_gpencil(wd, sseq->gpd);
}
else if(sl->spacetype==SPACE_OOPS) {
SpaceOops *so= (SpaceOops *)sl;
@@ -1603,7 +1698,9 @@ static void write_screens(WriteData *wd, ListBase *scrbase)
writestruct(wd, DATA, "SpaceImage", 1, sl);
if(sima->cumap)
- write_curvemapping(wd, sima->cumap);
+ write_curvemapping(wd, sima->cumap);
+ if(sima->gpd)
+ write_gpencil(wd, sima->gpd);
}
else if(sl->spacetype==SPACE_IMASEL) {
writestruct(wd, DATA, "SpaceImaSel", 1, sl);
@@ -1629,7 +1726,9 @@ static void write_screens(WriteData *wd, ListBase *scrbase)
writestruct(wd, DATA, "SpaceTime", 1, sl);
}
else if(sl->spacetype==SPACE_NODE){
+ SpaceNode *snode= (SpaceNode *)sl;
writestruct(wd, DATA, "SpaceNode", 1, sl);
+ if(snode->gpd) write_gpencil(wd, snode->gpd);
}
sl= sl->next;
}
@@ -1722,16 +1821,26 @@ static void write_actions(WriteData *wd, ListBase *idbase)
{
bAction *act;
bActionChannel *chan;
+ bActionGroup *grp;
+ TimeMarker *marker;
for(act=idbase->first; act; act= act->id.next) {
if (act->id.us>0 || wd->current) {
writestruct(wd, ID_AC, "bAction", 1, act);
if (act->id.properties) IDP_WriteProperty(act->id.properties, wd);
-
+
for (chan=act->chanbase.first; chan; chan=chan->next) {
writestruct(wd, DATA, "bActionChannel", 1, chan);
write_constraint_channels(wd, &chan->constraintChannels);
}
+
+ for (grp=act->groups.first; grp; grp=grp->next) {
+ writestruct(wd, DATA, "bActionGroup", 1, grp);
+ }
+
+ for (marker=act->markers.first; marker; marker=marker->next) {
+ writestruct(wd, DATA, "TimeMarker", 1, marker);
+ }
}
}
}
@@ -1740,6 +1849,7 @@ static void write_texts(WriteData *wd, ListBase *idbase)
{
Text *text;
TextLine *tmp;
+ TextMarker *mrk;
text= idbase->first;
while(text) {
@@ -1763,7 +1873,16 @@ static void write_texts(WriteData *wd, ListBase *idbase)
writedata(wd, DATA, tmp->len+1, tmp->line);
tmp= tmp->next;
}
+
+ /* write markers */
+ mrk= text->markers.first;
+ while (mrk) {
+ writestruct(wd, DATA, "TextMarker", 1, mrk);
+ mrk= mrk->next;
+ }
}
+
+
text= text->id.next;
}
@@ -1870,9 +1989,21 @@ static void write_brushes(WriteData *wd, ListBase *idbase)
}
}
+static void write_scripts(WriteData *wd, ListBase *idbase)
+{
+ Script *script;
+
+ for(script=idbase->first; script; script= script->id.next) {
+ if(script->id.us>0 || wd->current) {
+ writestruct(wd, ID_SCRIPT, "Script", 1, script);
+ if (script->id.properties) IDP_WriteProperty(script->id.properties, wd);
+ }
+ }
+}
+
/* context is usually defined by WM, two cases where no WM is available:
-/* - for forward compatibility, curscreen has to be saved */
-/* - for undofile, curscene needs to be saved */
+ * - for forward compatibility, curscreen has to be saved
+ * - for undofile, curscene needs to be saved */
/* XXX still remap G */
static void write_global(bContext *C, WriteData *wd)
{
@@ -1943,6 +2074,7 @@ static int write_file_handle(bContext *C, int handle, MemFile *compare, MemFile
write_particlesettings(wd, &G.main->particle);
write_nodetrees(wd, &G.main->nodetree);
write_brushes (wd, &G.main->brush);
+ write_scripts (wd, &G.main->script);
if(current==NULL)
write_libraries(wd, G.main->next); /* no library save in undo */
@@ -2003,7 +2135,7 @@ int BLO_write_file(bContext *C, char *dir, int write_flags, char **error_r)
}
}
else
- if(BLI_rename(tempname, dir) < 0) {
+ if(BLI_rename(tempname, dir) != 0) {
*error_r= "Can't change old file. File saved with @";
return 0;
}
@@ -2039,7 +2171,7 @@ int BLO_write_file_mem(bContext *C, MemFile *compare, MemFile *current, int writ
#define PATHSEPERATOR "/"
#endif
-static char *get_install_dir(void) {
+char *get_install_dir(void) {
extern char bprogname[];
char *tmpname = BLI_strdup(bprogname);
char *cut;
@@ -2167,7 +2299,7 @@ static int handle_append_runtime(int handle, char *exename, char **cause_r)
unsigned char buf[1024];
int count, progfd= -1;
- if (!runtime) {
+ if (!BLI_exists(runtime)) {
cause= "Unable to find runtime";
goto cleanup;
}
diff --git a/source/blender/blenpluginapi/SConscript b/source/blender/blenpluginapi/SConscript
index aa6e25532b8..4cf52a50e8c 100644
--- a/source/blender/blenpluginapi/SConscript
+++ b/source/blender/blenpluginapi/SConscript
@@ -7,8 +7,8 @@ incs = '. .. #/intern/guardedalloc ../blenlib ../imbuf ../makesdna'
defs = []
-if env['WITH_BF_QUICKTIME'] == 1:
+if env['WITH_BF_QUICKTIME']:
defs.append('WITH_QUICKTIME')
incs += ' ' + env['BF_QUICKTIME_INC']
-env.BlenderLib ( libname = 'bf_blenpluginapi', sources = sources, includes = Split(incs), defines = defs, libtype=['core', 'player'], priority = [90, 30] )
+env.BlenderLib ( libname = 'bf_blenpluginapi', sources = sources, includes = Split(incs), defines = defs, libtype=['core', 'player'], priority = [75, 35] )
diff --git a/source/blender/blenpluginapi/externdef.h b/source/blender/blenpluginapi/externdef.h
index 7322841e608..14a3115ce33 100644
--- a/source/blender/blenpluginapi/externdef.h
+++ b/source/blender/blenpluginapi/externdef.h
@@ -33,11 +33,14 @@
#ifdef WIN32
#ifdef PLUGIN_INTERN
#define LIBEXPORT __declspec(dllexport)
+ #define LIBIMPORT __declspec(dllexport)
#else
- #define LIBEXPORT extern __declspec(dllimport)
+ #define LIBEXPORT __declspec(dllexport)
+ #define LIBIMPORT extern __declspec(dllimport)
#endif
#elif !defined(WIN32)
#define LIBEXPORT extern
+ #define LIBIMPORT extern
#endif
#endif /* _EXTERNDEF_H */
diff --git a/source/blender/blenpluginapi/iff.h b/source/blender/blenpluginapi/iff.h
index 5eb52158a1a..92cbd7dd093 100644
--- a/source/blender/blenpluginapi/iff.h
+++ b/source/blender/blenpluginapi/iff.h
@@ -151,7 +151,7 @@ typedef struct ImBuf {
int userflags; /**< Used to set imbuf to Dirty and other stuff */
int *zbuf; /**< z buffer data, original zbuffer */
float *zbuf_float; /**< z buffer data, camera coordinates */
- void *userdata;
+ void *userdata; /**< temporary storage, only used by baking at the moment */
unsigned char *encodedbuffer; /**< Compressed image only used with png currently */
unsigned int encodedsize; /**< Size of data written to encodedbuffer */
unsigned int encodedbuffersize; /**< Size of encodedbuffer */
@@ -161,55 +161,56 @@ typedef struct ImBuf {
float dither; /**< random dither value, for conversion from float -> byte rect */
struct MEM_CacheLimiterHandle_s * c_handle; /**< handle for cache limiter */
+ struct ImgInfo * img_info;
int refcounter; /**< Refcounter for multiple users */
int index; /**< reference index for ImBuf lists */
struct ImBuf *mipmap[IB_MIPMAP_LEVELS]; /**< MipMap levels, a series of halved images */
} ImBuf;
-LIBEXPORT struct ImBuf *allocImBuf(short,short,uchar,uint,uchar);
-LIBEXPORT struct ImBuf *dupImBuf(struct ImBuf *);
-LIBEXPORT void freeImBuf(struct ImBuf*);
+LIBIMPORT struct ImBuf *allocImBuf(short,short,uchar,uint,uchar);
+LIBIMPORT struct ImBuf *dupImBuf(struct ImBuf *);
+LIBIMPORT void freeImBuf(struct ImBuf*);
-LIBEXPORT short converttocmap(struct ImBuf* ibuf);
+LIBIMPORT short converttocmap(struct ImBuf* ibuf);
-LIBEXPORT short saveiff(struct ImBuf *,char *,int);
+LIBIMPORT short saveiff(struct ImBuf *,char *,int);
-LIBEXPORT struct ImBuf *loadiffmem(int *,int);
-LIBEXPORT struct ImBuf *loadifffile(int,int);
-LIBEXPORT struct ImBuf *loadiffname(char *,int);
-LIBEXPORT struct ImBuf *testiffname(char *,int);
+LIBIMPORT struct ImBuf *loadiffmem(int *,int);
+LIBIMPORT struct ImBuf *loadifffile(int,int);
+LIBIMPORT struct ImBuf *loadiffname(char *,int);
+LIBIMPORT struct ImBuf *testiffname(char *,int);
-LIBEXPORT struct ImBuf *onehalf(struct ImBuf *);
-LIBEXPORT struct ImBuf *onethird(struct ImBuf *);
-LIBEXPORT struct ImBuf *halflace(struct ImBuf *);
-LIBEXPORT struct ImBuf *half_x(struct ImBuf *);
-LIBEXPORT struct ImBuf *half_y(struct ImBuf *);
-LIBEXPORT struct ImBuf *double_x(struct ImBuf *);
-LIBEXPORT struct ImBuf *double_y(struct ImBuf *);
-LIBEXPORT struct ImBuf *double_fast_x(struct ImBuf *);
-LIBEXPORT struct ImBuf *double_fast_y(struct ImBuf *);
+LIBIMPORT struct ImBuf *onehalf(struct ImBuf *);
+LIBIMPORT struct ImBuf *onethird(struct ImBuf *);
+LIBIMPORT struct ImBuf *halflace(struct ImBuf *);
+LIBIMPORT struct ImBuf *half_x(struct ImBuf *);
+LIBIMPORT struct ImBuf *half_y(struct ImBuf *);
+LIBIMPORT struct ImBuf *double_x(struct ImBuf *);
+LIBIMPORT struct ImBuf *double_y(struct ImBuf *);
+LIBIMPORT struct ImBuf *double_fast_x(struct ImBuf *);
+LIBIMPORT struct ImBuf *double_fast_y(struct ImBuf *);
-LIBEXPORT int ispic(char *);
+LIBIMPORT int ispic(char *);
-LIBEXPORT void dit2(struct ImBuf *, short, short);
-LIBEXPORT void dit0(struct ImBuf *, short, short);
+LIBIMPORT void dit2(struct ImBuf *, short, short);
+LIBIMPORT void dit0(struct ImBuf *, short, short);
-LIBEXPORT struct ImBuf *scaleImBuf(struct ImBuf *, short, short);
-LIBEXPORT struct ImBuf *scalefastImBuf(struct ImBuf *, short, short);
-LIBEXPORT struct ImBuf *scalefieldImBuf(struct ImBuf *, short, short);
-LIBEXPORT struct ImBuf *scalefastfieldImBuf(struct ImBuf *, short, short);
+LIBIMPORT struct ImBuf *scaleImBuf(struct ImBuf *, short, short);
+LIBIMPORT struct ImBuf *scalefastImBuf(struct ImBuf *, short, short);
+LIBIMPORT struct ImBuf *scalefieldImBuf(struct ImBuf *, short, short);
+LIBIMPORT struct ImBuf *scalefastfieldImBuf(struct ImBuf *, short, short);
-LIBEXPORT void de_interlace(struct ImBuf *ib);
-LIBEXPORT void interlace(struct ImBuf *ib);
-LIBEXPORT void gamwarp(struct ImBuf *ibuf, double gamma);
+LIBIMPORT void de_interlace(struct ImBuf *ib);
+LIBIMPORT void interlace(struct ImBuf *ib);
+LIBIMPORT void gamwarp(struct ImBuf *ibuf, double gamma);
-LIBEXPORT void IMB_rectcpy(struct ImBuf *dbuf, struct ImBuf *sbuf,
+LIBIMPORT void IMB_rectcpy(struct ImBuf *dbuf, struct ImBuf *sbuf,
int destx, int desty, int srcx, int srcy, int width, int height);
-LIBEXPORT void IMB_rectfill(struct ImBuf *drect, float col[4]);
-LIBEXPORT void IMB_rectfill_area(struct ImBuf *ibuf, float *col, int x1, int y1, int x2, int y2);
-LIBEXPORT void buf_rectfill_area(unsigned char *rect, float *rectf, int width, int height, float *col, int x1, int y1, int x2, int y2);
+LIBIMPORT void IMB_rectfill(struct ImBuf *drect, float col[4]);
+LIBIMPORT void IMB_rectfill_area(struct ImBuf *ibuf, float *col, int x1, int y1, int x2, int y2);
+LIBIMPORT void buf_rectfill_area(unsigned char *rect, float *rectf, int width, int height, float *col, int x1, int y1, int x2, int y2);
#endif /* IFF_H */
diff --git a/source/blender/blenpluginapi/intern/pluginapi.c b/source/blender/blenpluginapi/intern/pluginapi.c
index ee1ac8f0ae2..9c08a0b2f9d 100644
--- a/source/blender/blenpluginapi/intern/pluginapi.c
+++ b/source/blender/blenpluginapi/intern/pluginapi.c
@@ -50,9 +50,12 @@
#include "plugin.h"
#include "MEM_guardedalloc.h"
+#include "BLO_sys_types.h" // needed for intptr_t
+
#include "BLI_blenlib.h" /* util and noise functions */
#include "BLI_threads.h" /* For threadsfe guardedalloc malloc/calloc/free */
#include "IMB_imbuf.h" /* image buffer stuff */
+#define GET_INT_FROM_POINTER(i) ((int)(intptr_t)(i)) /* should use BKE_utildefines.h */
/* -------------------------------------------------------------------------- */
/* stuff from util.h */
@@ -321,42 +324,43 @@ int pluginapi_force_ref(void);
int pluginapi_force_ref(void)
{
- return (int) mallocN +
- (int) callocN +
- (int) freeN +
- (int) mallocT +
- (int) callocT +
- (int) freeT +
- (int) allocImBuf +
- (int) dupImBuf +
- (int) freeImBuf +
- (int) converttocmap +
- (int) saveiff +
- (int) loadiffmem +
- (int) loadifffile +
- (int) loadiffname +
- (int) testiffname +
- (int) onehalf +
- (int) onethird +
- (int) halflace +
- (int) half_x +
- (int) half_y +
- (int) double_x +
- (int) double_y +
- (int) double_fast_x +
- (int) double_fast_y +
- (int) ispic +
- (int) dit2 +
- (int) dit0 +
- (int) scaleImBuf +
- (int) scalefastImBuf +
- (int) scalefieldImBuf +
- (int) scalefastfieldImBuf +
- (int) hnoise +
- (int) hnoisep +
- (int) turbulence +
- (int) turbulence1 +
- (int) de_interlace +
- (int) interlace +
- (int) gamwarp;
+ return
+ GET_INT_FROM_POINTER( mallocN ) +
+ GET_INT_FROM_POINTER( callocN ) +
+ GET_INT_FROM_POINTER( freeN ) +
+ GET_INT_FROM_POINTER( mallocT ) +
+ GET_INT_FROM_POINTER( callocT ) +
+ GET_INT_FROM_POINTER( freeT ) +
+ GET_INT_FROM_POINTER( allocImBuf ) +
+ GET_INT_FROM_POINTER( dupImBuf ) +
+ GET_INT_FROM_POINTER( freeImBuf ) +
+ GET_INT_FROM_POINTER( converttocmap ) +
+ GET_INT_FROM_POINTER( saveiff ) +
+ GET_INT_FROM_POINTER( loadiffmem ) +
+ GET_INT_FROM_POINTER( loadifffile ) +
+ GET_INT_FROM_POINTER( loadiffname ) +
+ GET_INT_FROM_POINTER( testiffname ) +
+ GET_INT_FROM_POINTER( onehalf ) +
+ GET_INT_FROM_POINTER( onethird ) +
+ GET_INT_FROM_POINTER( halflace ) +
+ GET_INT_FROM_POINTER( half_x ) +
+ GET_INT_FROM_POINTER( half_y ) +
+ GET_INT_FROM_POINTER( double_x ) +
+ GET_INT_FROM_POINTER( double_y ) +
+ GET_INT_FROM_POINTER( double_fast_x ) +
+ GET_INT_FROM_POINTER( double_fast_y ) +
+ GET_INT_FROM_POINTER( ispic ) +
+ GET_INT_FROM_POINTER( dit2 ) +
+ GET_INT_FROM_POINTER( dit0 ) +
+ GET_INT_FROM_POINTER( scaleImBuf ) +
+ GET_INT_FROM_POINTER( scalefastImBuf ) +
+ GET_INT_FROM_POINTER( scalefieldImBuf ) +
+ GET_INT_FROM_POINTER( scalefastfieldImBuf ) +
+ GET_INT_FROM_POINTER( hnoise ) +
+ GET_INT_FROM_POINTER( hnoisep ) +
+ GET_INT_FROM_POINTER( turbulence ) +
+ GET_INT_FROM_POINTER( turbulence1 ) +
+ GET_INT_FROM_POINTER( de_interlace ) +
+ GET_INT_FROM_POINTER( interlace ) +
+ GET_INT_FROM_POINTER( gamwarp );
}
diff --git a/source/blender/blenpluginapi/plugin.h b/source/blender/blenpluginapi/plugin.h
index 1f6140130eb..da044cf7317 100644
--- a/source/blender/blenpluginapi/plugin.h
+++ b/source/blender/blenpluginapi/plugin.h
@@ -36,9 +36,10 @@
#include "util.h"
#include "floatpatch.h"
-#define B_PLUGIN_VERSION 5
+#define B_PLUGIN_VERSION 6
-typedef int (*TexDoit)(int, void*, float*, float*, float*);
+typedef int (*TexDoit)(int, void*, float*, float*, float*, float*);
+typedef int (*TexDoitold)(int, void*, float*, float*, float*);
typedef void (*SeqDoit)(void*, float, float, int, int, ImBuf*, ImBuf*, ImBuf*, ImBuf*);
typedef struct VarStruct {
@@ -66,9 +67,9 @@ typedef struct _PluginInfo {
void (*instance_init)(void *);
} PluginInfo;
-int plugin_tex_getversion(void);
-int plugin_seq_getversion(void);
-void plugin_getinfo(PluginInfo *);
+LIBEXPORT int plugin_tex_getversion(void);
+LIBEXPORT int plugin_seq_getversion(void);
+LIBEXPORT void plugin_getinfo(PluginInfo *);
/* *************** defines for button types ************** */
@@ -90,14 +91,14 @@ void plugin_getinfo(PluginInfo *);
/* *************** API functions ******************** */
/* derived from the famous Perlin noise */
-LIBEXPORT float hnoise(float noisesize, float x, float y, float z);
+LIBIMPORT float hnoise(float noisesize, float x, float y, float z);
/* the original Perlin noise */
-LIBEXPORT float hnoisep(float noisesize, float x, float y, float z);
+LIBIMPORT float hnoisep(float noisesize, float x, float y, float z);
/* soft turbulence */
-LIBEXPORT float turbulence(float noisesize, float x, float y, float z, int depth);
+LIBIMPORT float turbulence(float noisesize, float x, float y, float z, int depth);
/* hard turbulence */
-LIBEXPORT float turbulence1(float noisesize, float x, float y, float z, int depth);
+LIBIMPORT float turbulence1(float noisesize, float x, float y, float z, int depth);
#endif /* PLUGIN_H */
diff --git a/source/blender/editors/datafiles/SConscript b/source/blender/editors/datafiles/SConscript
index 88ac37b84c9..e69c8567ca0 100644
--- a/source/blender/editors/datafiles/SConscript
+++ b/source/blender/editors/datafiles/SConscript
@@ -6,4 +6,4 @@ sources = env.Glob('*.c')
incs = '../include ../../blenlib ../../blenkernel ../../makesdna ../../imbuf'
incs += ' #/intern/guardedalloc'
-env.BlenderLib ( 'bf_editor_datafiles', sources, Split(incs), [], libtype=['core','intern'], priority=[5, 25] )
+env.BlenderLib ( 'bf_editor_datafiles', sources, Split(incs), [], libtype=['core','intern'], priority=[50, 55] )
diff --git a/source/blender/editors/include/BIF_gl.h b/source/blender/editors/include/BIF_gl.h
index 244fd3bb78b..014201648c9 100644
--- a/source/blender/editors/include/BIF_gl.h
+++ b/source/blender/editors/include/BIF_gl.h
@@ -49,19 +49,13 @@
#endif
#endif
-#ifdef __APPLE__
-#include <OpenGL/gl.h>
-#include <OpenGL/glu.h>
-#else
-#include <GL/gl.h>
-#include <GL/glu.h>
-#endif
+#include "GL/glew.h"
+
/*
* these should be phased out. cpack should be replaced in
* code with calls to glColor3ub, lrectwrite probably should
* change to a function. - zr
*/
-
/*
*
* This define converts a numerical value to the equivalent 24-bit
@@ -75,5 +69,9 @@
#define lrectwrite(a, b, c, d, rect) {glRasterPos2i(a, b);glDrawPixels((c)-(a)+1, (d)-(b)+1, GL_RGBA, GL_UNSIGNED_BYTE, rect);}
+/* glStippleDefines, defined in glutil.c */
+extern GLubyte stipple_halftone[128];
+extern GLubyte stipple_quarttone[128];
+
#endif /* #ifdef BIF_GL_H */
diff --git a/source/blender/editors/include/BIF_interface_icons.h b/source/blender/editors/include/BIF_interface_icons.h
deleted file mode 100644
index e69de29bb2d..00000000000
--- a/source/blender/editors/include/BIF_interface_icons.h
+++ /dev/null
diff --git a/source/blender/editors/include/BIF_resources.h b/source/blender/editors/include/BIF_resources.h
deleted file mode 100644
index e69de29bb2d..00000000000
--- a/source/blender/editors/include/BIF_resources.h
+++ /dev/null
diff --git a/source/blender/editors/include/BIF_view2d.h b/source/blender/editors/include/BIF_view2d.h
deleted file mode 100644
index e69de29bb2d..00000000000
--- a/source/blender/editors/include/BIF_view2d.h
+++ /dev/null
diff --git a/source/blender/editors/interface/Makefile b/source/blender/editors/interface/Makefile
index 39bb651a616..fe223fabf2a 100644
--- a/source/blender/editors/interface/Makefile
+++ b/source/blender/editors/interface/Makefile
@@ -35,6 +35,7 @@ include nan_compile.mk
CFLAGS += $(LEVEL_1_C_WARNINGS)
+CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(OPENGL_HEADERS)
CPPFLAGS += -I$(NAN_BMFONT)/include
@@ -52,3 +53,8 @@ CPPFLAGS += -I../../ftfont
# own include
CPPFLAGS += -I../include
+
+ifeq ($(INTERNATIONAL), true)
+ CPPFLAGS += -DINTERNATIONAL
+endif
+
diff --git a/source/blender/editors/interface/SConscript b/source/blender/editors/interface/SConscript
index 0586d07d945..42e4db60edb 100644
--- a/source/blender/editors/interface/SConscript
+++ b/source/blender/editors/interface/SConscript
@@ -5,5 +5,13 @@ sources = env.Glob('*.c')
incs = '../include ../../blenlib ../../blenkernel ../../makesdna ../../imbuf'
incs += ' ../../makesrna ../../windowmanager #/intern/guardedalloc #intern/bmfont'
+incs += ' #/extern/glew/include'
-env.BlenderLib ( 'bf_editors_interface', sources, Split(incs), [], libtype=['core','intern'], priority=[40, 45] )
+defs = []
+
+if env['WITH_BF_INTERNATIONAL']:
+ incs += ' ../../ftfont'
+ defs.append('INTERNATIONAL')
+ defs.append('FTGL_STATIC_LIBRARY')
+
+env.BlenderLib ( 'bf_editors_interface', sources, Split(incs), Split(defs), libtype=['core','intern'], priority=[40, 45] )
diff --git a/source/blender/editors/screen/Makefile b/source/blender/editors/screen/Makefile
index 11cd8f264ad..b905d7c197b 100644
--- a/source/blender/editors/screen/Makefile
+++ b/source/blender/editors/screen/Makefile
@@ -35,6 +35,7 @@ include nan_compile.mk
CFLAGS += $(LEVEL_1_C_WARNINGS)
+CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(OPENGL_HEADERS)
# not very neat....
diff --git a/source/blender/editors/screen/SConscript b/source/blender/editors/screen/SConscript
index 8ca512fedc1..04a1d7f4388 100644
--- a/source/blender/editors/screen/SConscript
+++ b/source/blender/editors/screen/SConscript
@@ -5,6 +5,6 @@ sources = env.Glob('*.c')
incs = '../include ../../blenlib ../../blenkernel ../../makesdna ../../imbuf'
incs += ' ../../blenloader ../../windowmanager ../../python'
-incs += ' #/intern/guardedalloc'
+incs += ' #/intern/guardedalloc #/extern/glew/include'
env.BlenderLib ( 'bf_editors_screen', sources, Split(incs), [], libtype=['core','intern'], priority=[30, 35] )
diff --git a/source/blender/editors/screen/glutil.c b/source/blender/editors/screen/glutil.c
index 5b776fd7f49..08587ddb9a5 100644
--- a/source/blender/editors/screen/glutil.c
+++ b/source/blender/editors/screen/glutil.c
@@ -422,7 +422,6 @@ void glaDrawPixelsTex(float x, float y, int img_w, int img_h, int format, void *
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
}
-#define FTOCHAR(val) val<=0.0f?0: (val>=1.0f?255: (char)(255.0f*val))
void glaDrawPixelsSafe_to32(float fx, float fy, int img_w, int img_h, int row_w, float *rectf)
{
float *rf;
diff --git a/source/blender/editors/space_time/Makefile b/source/blender/editors/space_time/Makefile
index 72dca174dba..c64a81695bf 100644
--- a/source/blender/editors/space_time/Makefile
+++ b/source/blender/editors/space_time/Makefile
@@ -35,6 +35,7 @@ include nan_compile.mk
CFLAGS += $(LEVEL_1_C_WARNINGS)
+CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(OPENGL_HEADERS)
# not very neat....
diff --git a/source/blender/editors/space_time/SConscript b/source/blender/editors/space_time/SConscript
index 091218e0794..b83e79ff3e6 100644
--- a/source/blender/editors/space_time/SConscript
+++ b/source/blender/editors/space_time/SConscript
@@ -4,6 +4,6 @@ Import ('env')
sources = env.Glob('*.c')
incs = '../include ../../blenlib ../../blenkernel ../../makesdna ../../imbuf'
-incs += '../../windowmanager #/intern/guardedalloc'
+incs += '../../windowmanager #/intern/guardedalloc #/extern/glew/include'
env.BlenderLib ( 'bf_editors_space_time', sources, Split(incs), [], libtype=['core','intern'], priority=[35, 40] )
diff --git a/source/blender/editors/space_view3d/Makefile b/source/blender/editors/space_view3d/Makefile
index 0631cf010b8..45b6ca648d2 100644
--- a/source/blender/editors/space_view3d/Makefile
+++ b/source/blender/editors/space_view3d/Makefile
@@ -35,6 +35,7 @@ include nan_compile.mk
CFLAGS += $(LEVEL_1_C_WARNINGS)
+CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(OPENGL_HEADERS)
# not very neat....
diff --git a/source/blender/editors/space_view3d/SConscript b/source/blender/editors/space_view3d/SConscript
index 6e6c9fdc29d..99b620544cd 100644
--- a/source/blender/editors/space_view3d/SConscript
+++ b/source/blender/editors/space_view3d/SConscript
@@ -4,6 +4,6 @@ Import ('env')
sources = env.Glob('*.c')
incs = '../include ../../blenlib ../../blenkernel ../../makesdna ../../imbuf'
-incs += ' #/intern/guardedalloc'
+incs += ' #/intern/guardedalloc #/extern/glew/include'
env.BlenderLib ( 'bf_editors_space_view3d', sources, Split(incs), [], libtype=['core','intern'], priority=[35, 40] )
diff --git a/source/blender/ftfont/intern/FTF_TTFont.cpp b/source/blender/ftfont/intern/FTF_TTFont.cpp
index 77bfff5bd82..e8f2b82f970 100644
--- a/source/blender/ftfont/intern/FTF_TTFont.cpp
+++ b/source/blender/ftfont/intern/FTF_TTFont.cpp
@@ -31,6 +31,7 @@
#include <locale.h>
#include "libintl.h"
#include "BLI_blenlib.h"
+#include "BKE_font.h"
#include "../FTF_Settings.h"
@@ -48,49 +49,6 @@
#define FTF_MAX_STR_SIZE 512
-
-int utf8towchar(wchar_t *w, char *c)
-{
- int len=0;
- if(w==NULL || c==NULL) return(0);
- //printf("%s\n",c);
- while(*c)
- {
- //Converts Unicode to wchar:
-
- if(*c & 0x80)
- {
- if(*c & 0x40)
- {
- if(*c & 0x20)
- {
- if(*c & 0x10)
- {
- *w=(c[0] & 0x0f)<<18 | (c[1]&0x1f)<<12 | (c[2]&0x3f)<<6 | (c[3]&0x7f);
- c++;
- }
- else
- *w=(c[0] & 0x1f)<<12 | (c[1]&0x3f)<<6 | (c[2]&0x7f);
- c++;
- }
- else
- *w=(c[0] &0x3f)<<6 | c[1]&0x7f;
- c++;
- }
- else
- *w=(c[0] & 0x7f);
- }
- else
- *w=(c[0] & 0x7f);
-
- c++;
- w++;
- len++;
- }
- return len;
-}
-
-
FTF_TTFont::FTF_TTFont(void)
{
#ifdef __APPLE__
diff --git a/source/blender/gpu/CMakeLists.txt b/source/blender/gpu/CMakeLists.txt
new file mode 100644
index 00000000000..4d376f47d91
--- /dev/null
+++ b/source/blender/gpu/CMakeLists.txt
@@ -0,0 +1,34 @@
+# $Id: CMakeLists.txt 14444 2008-04-16 22:40:48Z hos $
+# ***** BEGIN GPL LICENSE BLOCK *****
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software Foundation,
+# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+# The Original Code is Copyright (C) 2006, Blender Foundation
+# All rights reserved.
+#
+# The Original Code is: all of this file.
+#
+# Contributor(s): Jacques Beaurain.
+#
+# ***** END GPL LICENSE BLOCK *****
+
+FILE(GLOB SRC intern/*.c)
+
+SET(INC
+ . ../blenlib ../blenkernel ../makesdna ../include
+ ../../../extern/glew/include ../../../intern/guardedalloc ../imbuf)
+
+BLENDERLIB(bf_gpu "${SRC}" "${INC}")
+
diff --git a/source/blender/gpu/GPU_draw.h b/source/blender/gpu/GPU_draw.h
new file mode 100644
index 00000000000..2399e7b6a8c
--- /dev/null
+++ b/source/blender/gpu/GPU_draw.h
@@ -0,0 +1,116 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This shader is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This shader is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this shader; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2005 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Brecht Van Lommel.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef GPU_GAME_H
+#define GPU_GAME_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct MTFace;
+struct Image;
+struct Scene;
+struct Object;
+
+/* OpenGL drawing functions related to shading. These are also
+ * shared with the game engine, where there were previously
+ * duplicates of some of these functions. */
+
+/* Initialize
+ * - sets the default Blender opengl state, if in doubt, check
+ * the contents of this function
+ * - this is called when starting Blender, for opengl rendering,
+ * and for switching back from the game engine for example. */
+
+void GPU_state_init(void);
+
+/* Material drawing
+ * - first the state is initialized by a particular object and
+ * it's materials
+ * - after this, materials can be quickly enabled by their number,
+ * GPU_enable_material returns 0 if drawing should be skipped
+ * - after drawing, the material must be disabled again */
+
+void GPU_set_object_materials(struct Scene *scene, struct Object *ob,
+ int glsl, int *do_alpha_pass);
+int GPU_enable_material(int nr, void *attribs);
+void GPU_disable_material(void);
+
+void GPU_set_material_blend_mode(int blendmode);
+int GPU_get_material_blend_mode(void);
+
+/* TexFace drawing
+ * - this is mutually exclusive with material drawing, a mesh should
+ * be drawn using one or the other
+ * - passing NULL clears the state again */
+
+int GPU_set_tpage(struct MTFace *tface);
+
+/* Lights
+ * - returns how many lights were enabled
+ * - this affects fixed functions materials and texface, not glsl */
+
+int GPU_default_lights(void);
+int GPU_scene_object_lights(struct Scene *scene, struct Object *ob,
+ int lay, float viewmat[][4]);
+
+/* Text render
+ * - based on moving uv coordinates */
+
+void GPU_render_text(struct MTFace *tface, int mode,
+ const char *textstr, int textlen, unsigned int *col,
+ float *v1, float *v2, float *v3, float *v4, int glattrib);
+
+/* Mipmap settings
+ * - these will free textures on changes */
+
+void GPU_set_mipmap(int mipmap);
+void GPU_set_linear_mipmap(int linear);
+void GPU_paint_set_mipmap(int mipmap);
+
+/* Image updates and free
+ * - these deal with images bound as opengl textures */
+
+void GPU_paint_update_image(struct Image *ima, int x, int y, int w, int h);
+void GPU_update_images_framechange(void);
+int GPU_update_image_time(struct Image *ima, double time);
+int GPU_verify_image(struct Image *ima, int tftile, int tfmode, int compare);
+void GPU_free_image(struct Image *ima);
+void GPU_free_images(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/source/blender/gpu/GPU_extensions.h b/source/blender/gpu/GPU_extensions.h
new file mode 100644
index 00000000000..66b19449419
--- /dev/null
+++ b/source/blender/gpu/GPU_extensions.h
@@ -0,0 +1,145 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This shader is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This shader is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this shader; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2005 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Brecht Van Lommel.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef GPU_EXTENSIONS_H
+#define GPU_EXTENSIONS_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* GPU extensions support */
+
+struct Image;
+struct ImageUser;
+
+struct GPUTexture;
+typedef struct GPUTexture GPUTexture;
+
+struct GPUFrameBuffer;
+typedef struct GPUFrameBuffer GPUFrameBuffer;
+
+struct GPUShader;
+typedef struct GPUShader GPUShader;
+
+void GPU_extensions_disable(void);
+void GPU_extensions_init(void); /* call this before running any of the functions below */
+void GPU_extensions_exit(void);
+int GPU_extensions_minimum_support(void);
+int GPU_print_error(char *str);
+
+/* GPU Texture
+ - always returns unsigned char RGBA textures
+ - if texture with non square dimensions is created, depending on the
+ graphics card capabilities the texture may actually be stored in a
+ larger texture with power of two dimensions. the actual dimensions
+ may be querd with GPU_texture_opengl_width/height. GPU_texture_coord_2f
+ calls glTexCoord2f with the coordinates adjust for this.
+ - can use reference counting:
+ - reference counter after GPU_texture_create is 1
+ - GPU_texture_ref increases by one
+ - GPU_texture_free decreases by one, and frees if 0
+ - if created with from_blender, will not free the texture
+*/
+
+GPUTexture *GPU_texture_create_1D(int w, float *pixels);
+GPUTexture *GPU_texture_create_2D(int w, int h, float *pixels);
+GPUTexture *GPU_texture_create_depth(int w, int h);
+GPUTexture *GPU_texture_from_blender(struct Image *ima,
+ struct ImageUser *iuser, double time);
+void GPU_texture_free(GPUTexture *tex);
+
+void GPU_texture_ref(GPUTexture *tex);
+
+void GPU_texture_bind(GPUTexture *tex, int number);
+void GPU_texture_unbind(GPUTexture *tex);
+
+GPUFrameBuffer *GPU_texture_framebuffer(GPUTexture *tex);
+
+int GPU_texture_target(GPUTexture *tex);
+int GPU_texture_opengl_width(GPUTexture *tex);
+int GPU_texture_opengl_height(GPUTexture *tex);
+
+/* GPU Framebuffer
+ - this is a wrapper for an OpenGL framebuffer object (FBO). in practice
+ multiple FBO's may be created, to get around limitations on the number
+ of attached textures and the dimension requirements.
+ - after any of the GPU_framebuffer_* functions, GPU_framebuffer_restore must
+ be called before rendering to the window framebuffer again */
+
+GPUFrameBuffer *GPU_framebuffer_create();
+int GPU_framebuffer_texture_attach(GPUFrameBuffer *fb, GPUTexture *tex);
+void GPU_framebuffer_texture_detach(GPUFrameBuffer *fb, GPUTexture *tex);
+void GPU_framebuffer_texture_bind(GPUFrameBuffer *fb, GPUTexture *tex);
+void GPU_framebuffer_texture_unbind(GPUFrameBuffer *fb, GPUTexture *tex);
+void GPU_framebuffer_free(GPUFrameBuffer *fb);
+
+void GPU_framebuffer_restore();
+
+/* GPU Shader
+ - only for fragment shaders now
+ - must call texture bind before setting a texture as uniform! */
+
+GPUShader *GPU_shader_create(const char *vertexcode, const char *fragcode, const char *libcode); /*GPUShader *lib);*/
+/*GPUShader *GPU_shader_create_lib(const char *code);*/
+void GPU_shader_free(GPUShader *shader);
+
+void GPU_shader_bind(GPUShader *shader);
+void GPU_shader_unbind();
+
+int GPU_shader_get_uniform(GPUShader *shader, char *name);
+void GPU_shader_uniform_vector(GPUShader *shader, int location, int length,
+ int arraysize, float *value);
+void GPU_shader_uniform_texture(GPUShader *shader, int location, GPUTexture *tex);
+
+int GPU_shader_get_attribute(GPUShader *shader, char *name);
+
+/* Vertex attributes for shaders */
+
+#define GPU_MAX_ATTRIB 32
+
+typedef struct GPUVertexAttribs {
+ struct {
+ int type;
+ int glindex;
+ char name[32];
+ } layer[GPU_MAX_ATTRIB];
+
+ int totlayer;
+} GPUVertexAttribs;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/source/blender/gpu/GPU_material.h b/source/blender/gpu/GPU_material.h
new file mode 100644
index 00000000000..ccc687858f4
--- /dev/null
+++ b/source/blender/gpu/GPU_material.h
@@ -0,0 +1,169 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This shader is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This shader is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this shader; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2005 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Brecht Van Lommel.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __GPU_MATERIAL__
+#define __GPU_MATERIAL__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct Image;
+struct ImageUser;
+struct Material;
+struct Object;
+struct Lamp;
+struct bNode;
+struct LinkNode;
+struct Scene;
+struct GPUVertexAttribs;
+struct GPUNode;
+struct GPUNodeLink;
+struct GPUNodeStack;
+struct GPUMaterial;
+struct GPUTexture;
+struct GPULamp;
+
+typedef struct GPUNode GPUNode;
+typedef struct GPUNodeLink GPUNodeLink;
+typedef struct GPUMaterial GPUMaterial;
+typedef struct GPULamp GPULamp;
+
+/* Functions to create GPU Materials nodes */
+
+typedef enum GPUType {
+ GPU_NONE = 0,
+ GPU_FLOAT = 1,
+ GPU_VEC2 = 2,
+ GPU_VEC3 = 3,
+ GPU_VEC4 = 4,
+ GPU_MAT3 = 9,
+ GPU_MAT4 = 16,
+ GPU_TEX1D = 1001,
+ GPU_TEX2D = 1002,
+ GPU_SHADOW2D = 1003,
+ GPU_ATTRIB = 3001
+} GPUType;
+
+typedef enum GPUBuiltin {
+ GPU_VIEW_MATRIX = 1,
+ GPU_OBJECT_MATRIX = 2,
+ GPU_INVERSE_VIEW_MATRIX = 4,
+ GPU_INVERSE_OBJECT_MATRIX = 8,
+ GPU_VIEW_POSITION = 16,
+ GPU_VIEW_NORMAL = 32,
+ GPU_OBCOLOR = 64
+} GPUBuiltin;
+
+typedef enum GPUBlendMode {
+ GPU_BLEND_SOLID = 0,
+ GPU_BLEND_ADD = 1,
+ GPU_BLEND_ALPHA = 2,
+ GPU_BLEND_CLIP = 4
+} GPUBlendMode;
+
+typedef struct GPUNodeStack {
+ GPUType type;
+ char *name;
+ float vec[4];
+ struct GPUNodeLink *link;
+ short hasinput;
+ short hasoutput;
+ short sockettype;
+} GPUNodeStack;
+
+GPUNodeLink *GPU_attribute(int type, char *name);
+GPUNodeLink *GPU_uniform(float *num);
+GPUNodeLink *GPU_dynamic_uniform(float *num);
+GPUNodeLink *GPU_image(struct Image *ima, struct ImageUser *iuser);
+GPUNodeLink *GPU_texture(int size, float *pixels);
+GPUNodeLink *GPU_dynamic_texture(struct GPUTexture *tex);
+GPUNodeLink *GPU_socket(GPUNodeStack *sock);
+GPUNodeLink *GPU_builtin(GPUBuiltin builtin);
+
+int GPU_link(GPUMaterial *mat, char *name, ...);
+int GPU_stack_link(GPUMaterial *mat, char *name, GPUNodeStack *in, GPUNodeStack *out, ...);
+
+void GPU_material_output_link(GPUMaterial *material, GPUNodeLink *link);
+void GPU_material_enable_alpha(GPUMaterial *material);
+GPUBlendMode GPU_material_blend_mode(GPUMaterial *material, float obcol[4]);
+
+/* High level functions to create and use GPU materials */
+
+GPUMaterial *GPU_material_from_blender(struct Scene *scene, struct Material *ma);
+void GPU_material_free(struct Material *ma);
+
+void GPU_materials_free();
+
+void GPU_material_bind(GPUMaterial *material, int oblay, int viewlay, double time);
+void GPU_material_bind_uniforms(GPUMaterial *material, float obmat[][4], float viewmat[][4], float viewinv[][4], float obcol[4]);
+void GPU_material_unbind(GPUMaterial *material);
+int GPU_material_bound(GPUMaterial *material);
+
+void GPU_material_vertex_attributes(GPUMaterial *material,
+ struct GPUVertexAttribs *attrib);
+
+/* Exported shading */
+
+typedef struct GPUShadeInput {
+ GPUMaterial *gpumat;
+ struct Material *mat;
+
+ GPUNodeLink *rgb, *specrgb, *vn, *view, *vcol, *ref;
+ GPUNodeLink *alpha, *refl, *spec, *emit, *har, *amb;
+} GPUShadeInput;
+
+typedef struct GPUShadeResult {
+ GPUNodeLink *diff, *spec, *combined, *alpha;
+} GPUShadeResult;
+
+void GPU_shadeinput_set(GPUMaterial *mat, struct Material *ma, GPUShadeInput *shi);
+void GPU_shaderesult_set(GPUShadeInput *shi, GPUShadeResult *shr);
+
+/* Lamps */
+
+GPULamp *GPU_lamp_from_blender(struct Scene *scene, struct Object *ob, struct Object *par);
+void GPU_lamp_free(struct Object *ob);
+
+int GPU_lamp_has_shadow_buffer(GPULamp *lamp);
+void GPU_lamp_shadow_buffer_bind(GPULamp *lamp, float viewmat[][4], int *winsize, float winmat[][4]);
+void GPU_lamp_shadow_buffer_unbind(GPULamp *lamp);
+
+void GPU_lamp_update(GPULamp *lamp, int lay, float obmat[][4]);
+int GPU_lamp_shadow_layer(GPULamp *lamp);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /*__GPU_MATERIAL__*/
+
diff --git a/source/blender/gpu/Makefile b/source/blender/gpu/Makefile
new file mode 100644
index 00000000000..b9bde147115
--- /dev/null
+++ b/source/blender/gpu/Makefile
@@ -0,0 +1,37 @@
+#
+# $Id$
+#
+# ***** BEGIN GPL/BL DUAL LICENSE BLOCK *****
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version. The Blender
+# Foundation also sells licenses for use in proprietary software under
+# the Blender License. See http://www.blender.org/BL/ for information
+# about this.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software Foundation,
+# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+# The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+# All rights reserved.
+#
+# The Original Code is: all of this file.
+#
+# Contributor(s): none yet.
+#
+# ***** END GPL/BL DUAL LICENSE BLOCK *****
+#
+# Makes module object directory and bounces make to subdirectories.
+
+SOURCEDIR = source/blender/gpu
+DIRS = intern
+
+include nan_subdirs.mk
diff --git a/source/blender/gpu/SConscript b/source/blender/gpu/SConscript
new file mode 100644
index 00000000000..8ccd4b7b24c
--- /dev/null
+++ b/source/blender/gpu/SConscript
@@ -0,0 +1,11 @@
+#!/usr/bin/python
+Import ('env')
+
+sources = env.Glob('intern/*.c')
+
+incs = '../blenlib ../blenkernel ../makesdna ../include'
+incs += ' #/extern/glew/include #intern/guardedalloc ../imbuf .'
+
+incs += ' ' + env['BF_OPENGL_INC']
+
+env.BlenderLib ( 'bf_gpu', sources, Split(incs), [], libtype=['core', 'player'], priority=[65, 20] )
diff --git a/source/blender/gpu/intern/Makefile b/source/blender/gpu/intern/Makefile
new file mode 100644
index 00000000000..733ee3f764c
--- /dev/null
+++ b/source/blender/gpu/intern/Makefile
@@ -0,0 +1,53 @@
+#
+# $Id$
+#
+# ***** BEGIN GPL/BL DUAL LICENSE BLOCK *****
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version. The Blender
+# Foundation also sells licenses for use in proprietary software under
+# the Blender License. See http://www.blender.org/BL/ for information
+# about this.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software Foundation,
+# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+# The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+# All rights reserved.
+#
+# The Original Code is: all of this file.
+#
+# Contributor(s): none yet.
+#
+# ***** END GPL/BL DUAL LICENSE BLOCK *****
+#
+
+LIBNAME = gpu
+DIR = $(OCGDIR)/blender/$(LIBNAME)
+
+include nan_compile.mk
+
+ifeq ($(OS),$(findstring $(OS), "beos darwin freebsd linux openbsd solaris windows"))
+ CFLAGS += -funsigned-char
+endif
+
+CFLAGS += $(LEVEL_1_C_WARNINGS)
+
+CPPFLAGS += -I$(OPENGL_HEADERS)
+
+CPPFLAGS += -I../../blenlib
+CPPFLAGS += -I../../makesdna
+CPPFLAGS += -I../../imbuf
+CPPFLAGS += -I../../blenkernel
+CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include
+CPPFLAGS += -I$(NAN_GLEW)/include
+CPPFLAGS += -I../
+
diff --git a/source/blender/gpu/intern/gpu_codegen.c b/source/blender/gpu/intern/gpu_codegen.c
new file mode 100644
index 00000000000..94c1910e3bc
--- /dev/null
+++ b/source/blender/gpu/intern/gpu_codegen.c
@@ -0,0 +1,1445 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2005 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Brecht Van Lommel.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "GL/glew.h"
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_customdata_types.h"
+#include "DNA_image_types.h"
+#include "DNA_listBase.h"
+#include "DNA_material_types.h"
+
+#include "BLI_dynstr.h"
+#include "BLI_blenlib.h"
+#include "BLI_ghash.h"
+#include "BLI_heap.h"
+
+#include "BKE_global.h"
+#include "BKE_utildefines.h"
+
+#include "GPU_material.h"
+#include "GPU_extensions.h"
+
+#include "BLO_sys_types.h" // for intptr_t support
+
+#include "gpu_codegen.h"
+
+#include <string.h>
+#include <stdarg.h>
+
+#ifdef _WIN32
+#ifndef vsnprintf
+#define vsnprintf _vsnprintf
+#endif
+#ifndef snprintf
+#define snprintf _snprintf
+#endif
+#endif
+
+extern char datatoc_gpu_shader_material_glsl[];
+extern char datatoc_gpu_shader_vertex_glsl[];
+
+/* structs and defines */
+
+typedef enum GPUDataSource {
+ GPU_SOURCE_VEC_UNIFORM,
+ GPU_SOURCE_BUILTIN,
+ GPU_SOURCE_TEX_PIXEL,
+ GPU_SOURCE_TEX,
+ GPU_SOURCE_ATTRIB
+} GPUDataSource;
+
+static char* GPU_DATATYPE_STR[17] = {"", "float", "vec2", "vec3", "vec4",
+ 0, 0, 0, 0, "mat3", 0, 0, 0, 0, 0, 0, "mat4"};
+
+struct GPUNode {
+ struct GPUNode *next, *prev;
+
+ char *name;
+ int tag;
+
+ ListBase inputs;
+ ListBase outputs;
+};
+
+struct GPUNodeLink {
+ GPUNodeStack *socket;
+
+ int attribtype;
+ char *attribname;
+
+ int image;
+
+ int texture;
+ int texturesize;
+
+ void *ptr1, *ptr2;
+
+ int dynamic;
+
+ int type;
+ int users;
+
+ GPUTexture *dynamictex;
+
+ GPUBuiltin builtin;
+
+ struct GPUOutput *output;
+};
+
+typedef struct GPUOutput {
+ struct GPUOutput *next, *prev;
+
+ GPUNode *node;
+ int type; /* data type = length of vector/matrix */
+ GPUNodeLink *link; /* output link */
+ int id; /* unique id as created by code generator */
+} GPUOutput;
+
+typedef struct GPUInput {
+ struct GPUInput *next, *prev;
+
+ GPUNode *node;
+
+ int type; /* datatype */
+ int source; /* data source */
+
+ int id; /* unique id as created by code generator */
+ int texid; /* number for multitexture */
+ int attribid; /* id for vertex attributes */
+ int bindtex; /* input is responsible for binding the texture? */
+ int definetex; /* input is responsible for defining the pixel? */
+ int textarget; /* GL_TEXTURE_* */
+ int textype; /* datatype */
+
+ struct Image *ima; /* image */
+ struct ImageUser *iuser;/* image user */
+ float *dynamicvec; /* vector data in case it is dynamic */
+ GPUTexture *tex; /* input texture, only set at runtime */
+ int shaderloc; /* id from opengl */
+ char shadername[32]; /* name in shader */
+
+ float vec[16]; /* vector data */
+ GPUNodeLink *link;
+ int dynamictex; /* dynamic? */
+ int attribtype; /* attribute type */
+ char attribname[32]; /* attribute name */
+ int attribfirst; /* this is the first one that is bound */
+ GPUBuiltin builtin; /* builtin uniform */
+} GPUInput;
+
+struct GPUPass {
+ struct GPUPass *next, *prev;
+
+ ListBase inputs;
+ struct GPUOutput *output;
+ struct GPUShader *shader;
+};
+
+/* Strings utility */
+
+static void BLI_dynstr_printf(DynStr *dynstr, const char *format, ...)
+{
+ va_list args;
+ int retval;
+ char str[2048];
+
+ va_start(args, format);
+ retval = vsnprintf(str, sizeof(str), format, args);
+ va_end(args);
+
+ if (retval >= sizeof(str))
+ fprintf(stderr, "BLI_dynstr_printf: limit exceeded\n");
+ else
+ BLI_dynstr_append(dynstr, str);
+}
+
+/* GLSL code parsing for finding function definitions.
+ * These are stored in a hash for lookup when creating a material. */
+
+static GHash *FUNCTION_HASH= NULL;
+/*static char *FUNCTION_PROTOTYPES= NULL;
+static GPUShader *FUNCTION_LIB= NULL;*/
+
+static int gpu_str_prefix(char *str, char *prefix)
+{
+ while(*str && *prefix) {
+ if(*str != *prefix)
+ return 0;
+
+ str++;
+ prefix++;
+ }
+
+ return (*prefix == '\0');
+}
+
+static char *gpu_str_skip_token(char *str, char *token, int max)
+{
+ int len = 0;
+
+ /* skip a variable/function name */
+ while(*str) {
+ if(ELEM6(*str, ' ', '(', ')', ',', '\t', '\n'))
+ break;
+ else {
+ if(token && len < max-1) {
+ *token= *str;
+ token++;
+ len++;
+ }
+ str++;
+ }
+ }
+
+ if(token)
+ *token= '\0';
+
+ /* skip the next special characters:
+ * note the missing ')' */
+ while(*str) {
+ if(ELEM5(*str, ' ', '(', ',', '\t', '\n'))
+ str++;
+ else
+ break;
+ }
+
+ return str;
+}
+
+static void gpu_parse_functions_string(GHash *hash, char *code)
+{
+ GPUFunction *function;
+ int i, type, qual;
+
+ while((code = strstr(code, "void "))) {
+ function = MEM_callocN(sizeof(GPUFunction), "GPUFunction");
+
+ code = gpu_str_skip_token(code, NULL, 0);
+ code = gpu_str_skip_token(code, function->name, MAX_FUNCTION_NAME);
+
+ /* get parameters */
+ while(*code && *code != ')') {
+ /* test if it's an input or output */
+ qual = FUNCTION_QUAL_IN;
+ if(gpu_str_prefix(code, "out "))
+ qual = FUNCTION_QUAL_OUT;
+ if(gpu_str_prefix(code, "inout "))
+ qual = FUNCTION_QUAL_INOUT;
+ if((qual != FUNCTION_QUAL_IN) || gpu_str_prefix(code, "in "))
+ code = gpu_str_skip_token(code, NULL, 0);
+
+ /* test for type */
+ type= 0;
+ for(i=1; i<=16; i++) {
+ if(GPU_DATATYPE_STR[i] && gpu_str_prefix(code, GPU_DATATYPE_STR[i])) {
+ type= i;
+ break;
+ }
+ }
+
+ if(!type && gpu_str_prefix(code, "sampler2DShadow"))
+ type= GPU_SHADOW2D;
+ if(!type && gpu_str_prefix(code, "sampler1D"))
+ type= GPU_TEX1D;
+ if(!type && gpu_str_prefix(code, "sampler2D"))
+ type= GPU_TEX2D;
+
+ if(type) {
+ /* add paramater */
+ code = gpu_str_skip_token(code, NULL, 0);
+ code = gpu_str_skip_token(code, NULL, 0);
+ function->paramqual[function->totparam]= qual;
+ function->paramtype[function->totparam]= type;
+ function->totparam++;
+ }
+ else {
+ fprintf(stderr, "GPU invalid function parameter in %s.\n", function->name);
+ break;
+ }
+ }
+
+ if(strlen(function->name) == 0 || function->totparam == 0) {
+ fprintf(stderr, "GPU functions parse error.\n");
+ MEM_freeN(function);
+ break;
+ }
+
+ BLI_ghash_insert(hash, function->name, function);
+ }
+}
+
+#if 0
+static char *gpu_generate_function_prototyps(GHash *hash)
+{
+ DynStr *ds = BLI_dynstr_new();
+ GHashIterator *ghi;
+ GPUFunction *function;
+ char *name, *prototypes;
+ int a;
+
+ /* automatically generate function prototypes to add to the top of the
+ * generated code, to avoid have to add the actual code & recompile all */
+ ghi = BLI_ghashIterator_new(hash);
+
+ for(; !BLI_ghashIterator_isDone(ghi); BLI_ghashIterator_step(ghi)) {
+ name = BLI_ghashIterator_getValue(ghi);
+ function = BLI_ghashIterator_getValue(ghi);
+
+ BLI_dynstr_printf(ds, "void %s(", name);
+ for(a=0; a<function->totparam; a++) {
+ if(function->paramqual[a] == FUNCTION_QUAL_OUT)
+ BLI_dynstr_append(ds, "out ");
+ else if(function->paramqual[a] == FUNCTION_QUAL_INOUT)
+ BLI_dynstr_append(ds, "inout ");
+
+ if(function->paramtype[a] == GPU_TEX1D)
+ BLI_dynstr_append(ds, "sampler1D");
+ else if(function->paramtype[a] == GPU_TEX2D)
+ BLI_dynstr_append(ds, "sampler2D");
+ else if(function->paramtype[a] == GPU_SHADOW2D)
+ BLI_dynstr_append(ds, "sampler2DShadow");
+ else
+ BLI_dynstr_append(ds, GPU_DATATYPE_STR[function->paramtype[a]]);
+
+ //BLI_dynstr_printf(ds, " param%d", a);
+
+ if(a != function->totparam-1)
+ BLI_dynstr_append(ds, ", ");
+ }
+ BLI_dynstr_append(ds, ");\n");
+ }
+
+ BLI_dynstr_append(ds, "\n");
+
+ prototypes = BLI_dynstr_get_cstring(ds);
+ BLI_dynstr_free(ds);
+
+ return prototypes;
+}
+#endif
+
+GPUFunction *GPU_lookup_function(char *name)
+{
+ if(!FUNCTION_HASH) {
+ FUNCTION_HASH = BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp);
+ gpu_parse_functions_string(FUNCTION_HASH, datatoc_gpu_shader_material_glsl);
+ /*FUNCTION_PROTOTYPES = gpu_generate_function_prototyps(FUNCTION_HASH);
+ FUNCTION_LIB = GPU_shader_create_lib(datatoc_gpu_shader_material_glsl);*/
+ }
+
+ return (GPUFunction*)BLI_ghash_lookup(FUNCTION_HASH, name);
+}
+
+void GPU_extensions_exit(void)
+{
+ extern Material defmaterial; // render module abuse...
+
+ if(defmaterial.gpumaterial.first)
+ GPU_material_free(&defmaterial);
+
+ if(FUNCTION_HASH) {
+ BLI_ghash_free(FUNCTION_HASH, NULL, (GHashValFreeFP)MEM_freeN);
+ FUNCTION_HASH = NULL;
+ }
+ /*if(FUNCTION_PROTOTYPES) {
+ MEM_freeN(FUNCTION_PROTOTYPES);
+ FUNCTION_PROTOTYPES = NULL;
+ }*/
+ /*if(FUNCTION_LIB) {
+ GPU_shader_free(FUNCTION_LIB);
+ FUNCTION_LIB = NULL;
+ }*/
+}
+
+/* GLSL code generation */
+
+static void codegen_convert_datatype(DynStr *ds, int from, int to, char *tmp, int id)
+{
+ char name[1024];
+
+ snprintf(name, sizeof(name), "%s%d", tmp, id);
+
+ if (from == to) {
+ BLI_dynstr_append(ds, name);
+ }
+ else if (to == GPU_FLOAT) {
+ if (from == GPU_VEC4)
+ BLI_dynstr_printf(ds, "dot(%s.rgb, vec3(0.35, 0.45, 0.2))", name);
+ else if (from == GPU_VEC3)
+ BLI_dynstr_printf(ds, "dot(%s, vec3(0.33))", name);
+ else if (from == GPU_VEC2)
+ BLI_dynstr_printf(ds, "%s.r", name);
+ }
+ else if (to == GPU_VEC2) {
+ if (from == GPU_VEC4)
+ BLI_dynstr_printf(ds, "vec2(dot(%s.rgb, vec3(0.35, 0.45, 0.2)), %s.a)", name, name);
+ else if (from == GPU_VEC3)
+ BLI_dynstr_printf(ds, "vec2(dot(%s.rgb, vec3(0.33)), 1.0)", name);
+ else if (from == GPU_FLOAT)
+ BLI_dynstr_printf(ds, "vec2(%s, 1.0)", name);
+ }
+ else if (to == GPU_VEC3) {
+ if (from == GPU_VEC4)
+ BLI_dynstr_printf(ds, "%s.rgb", name);
+ else if (from == GPU_VEC2)
+ BLI_dynstr_printf(ds, "vec3(%s.r, %s.r, %s.r)", name, name, name);
+ else if (from == GPU_FLOAT)
+ BLI_dynstr_printf(ds, "vec3(%s, %s, %s)", name, name, name);
+ }
+ else {
+ if (from == GPU_VEC3)
+ BLI_dynstr_printf(ds, "vec4(%s, 1.0)", name);
+ else if (from == GPU_VEC2)
+ BLI_dynstr_printf(ds, "vec4(%s.r, %s.r, %s.r, %s.g)", name, name, name, name);
+ else if (from == GPU_FLOAT)
+ BLI_dynstr_printf(ds, "vec4(%s, %s, %s, 1.0)", name, name, name);
+ }
+}
+
+static void codegen_print_datatype(DynStr *ds, int type, float *data)
+{
+ int i;
+
+ BLI_dynstr_printf(ds, "%s(", GPU_DATATYPE_STR[type]);
+
+ for(i=0; i<type; i++) {
+ BLI_dynstr_printf(ds, "%f", data[i]);
+ if(i == type-1)
+ BLI_dynstr_append(ds, ")");
+ else
+ BLI_dynstr_append(ds, ", ");
+ }
+}
+
+static int codegen_input_has_texture(GPUInput *input)
+{
+ if (input->link)
+ return 0;
+ else if(input->ima)
+ return 1;
+ else
+ return input->tex != 0;
+}
+
+char *GPU_builtin_name(GPUBuiltin builtin)
+{
+ if(builtin == GPU_VIEW_MATRIX)
+ return "unfviewmat";
+ else if(builtin == GPU_OBJECT_MATRIX)
+ return "unfobmat";
+ else if(builtin == GPU_INVERSE_VIEW_MATRIX)
+ return "unfinvviewmat";
+ else if(builtin == GPU_INVERSE_OBJECT_MATRIX)
+ return "unfinvobmat";
+ else if(builtin == GPU_VIEW_POSITION)
+ return "varposition";
+ else if(builtin == GPU_VIEW_NORMAL)
+ return "varnormal";
+ else if(builtin == GPU_OBCOLOR)
+ return "unfobcolor";
+ else
+ return "";
+}
+
+static void codegen_set_unique_ids(ListBase *nodes)
+{
+ GHash *bindhash, *definehash;
+ GPUNode *node;
+ GPUInput *input;
+ GPUOutput *output;
+ int id = 1, texid = 0;
+
+ bindhash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
+ definehash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
+
+ for (node=nodes->first; node; node=node->next) {
+ for (input=node->inputs.first; input; input=input->next) {
+ /* set id for unique names of uniform variables */
+ input->id = id++;
+ input->bindtex = 0;
+ input->definetex = 0;
+
+ /* set texid used for settings texture slot with multitexture */
+ if (codegen_input_has_texture(input) &&
+ ((input->source == GPU_SOURCE_TEX) || (input->source == GPU_SOURCE_TEX_PIXEL))) {
+ if (input->link) {
+ /* input is texture from buffer, assign only one texid per
+ buffer to avoid sampling the same texture twice */
+ if (!BLI_ghash_haskey(bindhash, input->link)) {
+ input->texid = texid++;
+ input->bindtex = 1;
+ BLI_ghash_insert(bindhash, input->link, SET_INT_IN_POINTER(input->texid));
+ }
+ else
+ input->texid = GET_INT_FROM_POINTER(BLI_ghash_lookup(bindhash, input->link));
+ }
+ else if(input->ima) {
+ /* input is texture from image, assign only one texid per
+ buffer to avoid sampling the same texture twice */
+ if (!BLI_ghash_haskey(bindhash, input->ima)) {
+ input->texid = texid++;
+ input->bindtex = 1;
+ BLI_ghash_insert(bindhash, input->ima, SET_INT_IN_POINTER(input->texid));
+ }
+ else
+ input->texid = GET_INT_FROM_POINTER(BLI_ghash_lookup(bindhash, input->ima));
+ }
+ else {
+ if (!BLI_ghash_haskey(bindhash, input->tex)) {
+ /* input is user created texture, check tex pointer */
+ input->texid = texid++;
+ input->bindtex = 1;
+ BLI_ghash_insert(bindhash, input->tex, SET_INT_IN_POINTER(input->texid));
+ }
+ else
+ input->texid = GET_INT_FROM_POINTER(BLI_ghash_lookup(bindhash, input->tex));
+ }
+
+ /* make sure this pixel is defined exactly once */
+ if (input->source == GPU_SOURCE_TEX_PIXEL) {
+ if(input->ima) {
+ if (!BLI_ghash_haskey(definehash, input->ima)) {
+ input->definetex = 1;
+ BLI_ghash_insert(definehash, input->ima, SET_INT_IN_POINTER(input->texid));
+ }
+ }
+ else {
+ if (!BLI_ghash_haskey(definehash, input->link)) {
+ input->definetex = 1;
+ BLI_ghash_insert(definehash, input->link, SET_INT_IN_POINTER(input->texid));
+ }
+ }
+ }
+ }
+ }
+
+ for (output=node->outputs.first; output; output=output->next)
+ /* set id for unique names of tmp variables storing output */
+ output->id = id++;
+ }
+
+ BLI_ghash_free(bindhash, NULL, NULL);
+ BLI_ghash_free(definehash, NULL, NULL);
+}
+
+static void codegen_print_uniforms_functions(DynStr *ds, ListBase *nodes)
+{
+ GPUNode *node;
+ GPUInput *input;
+ char *name;
+ int builtins = 0;
+
+ /* print uniforms */
+ for (node=nodes->first; node; node=node->next) {
+ for (input=node->inputs.first; input; input=input->next) {
+ if ((input->source == GPU_SOURCE_TEX) || (input->source == GPU_SOURCE_TEX_PIXEL)) {
+ /* create exactly one sampler for each texture */
+ if (codegen_input_has_texture(input) && input->bindtex)
+ BLI_dynstr_printf(ds, "uniform %s samp%d;\n",
+ (input->textype == GPU_TEX1D)? "sampler1D":
+ (input->textype == GPU_TEX2D)? "sampler2D": "sampler2DShadow",
+ input->texid);
+ }
+ else if(input->source == GPU_SOURCE_BUILTIN) {
+ /* only define each builting uniform/varying once */
+ if(!(builtins & input->builtin)) {
+ builtins |= input->builtin;
+ name = GPU_builtin_name(input->builtin);
+
+ if(gpu_str_prefix(name, "unf")) {
+ BLI_dynstr_printf(ds, "uniform %s %s;\n",
+ GPU_DATATYPE_STR[input->type], name);
+ }
+ else {
+ BLI_dynstr_printf(ds, "varying %s %s;\n",
+ GPU_DATATYPE_STR[input->type], name);
+ }
+ }
+ }
+ else if (input->source == GPU_SOURCE_VEC_UNIFORM) {
+ if(input->dynamicvec) {
+ /* only create uniforms for dynamic vectors */
+ BLI_dynstr_printf(ds, "uniform %s unf%d;\n",
+ GPU_DATATYPE_STR[input->type], input->id);
+ }
+ else {
+ /* for others use const so the compiler can do folding */
+ BLI_dynstr_printf(ds, "const %s cons%d = ",
+ GPU_DATATYPE_STR[input->type], input->id);
+ codegen_print_datatype(ds, input->type, input->vec);
+ BLI_dynstr_append(ds, ";\n");
+ }
+ }
+ else if (input->source == GPU_SOURCE_ATTRIB && input->attribfirst) {
+ BLI_dynstr_printf(ds, "varying %s var%d;\n",
+ GPU_DATATYPE_STR[input->type], input->attribid);
+ }
+ }
+ }
+
+ BLI_dynstr_append(ds, "\n");
+}
+
+static void codegen_declare_tmps(DynStr *ds, ListBase *nodes)
+{
+ GPUNode *node;
+ GPUInput *input;
+ GPUOutput *output;
+
+ for (node=nodes->first; node; node=node->next) {
+ /* load pixels from textures */
+ for (input=node->inputs.first; input; input=input->next) {
+ if (input->source == GPU_SOURCE_TEX_PIXEL) {
+ if (codegen_input_has_texture(input) && input->definetex) {
+ BLI_dynstr_printf(ds, "\tvec4 tex%d = texture2D(", input->texid);
+ BLI_dynstr_printf(ds, "samp%d, gl_TexCoord[%d].st);\n",
+ input->texid, input->texid);
+ }
+ }
+ }
+
+ /* declare temporary variables for node output storage */
+ for (output=node->outputs.first; output; output=output->next)
+ BLI_dynstr_printf(ds, "\t%s tmp%d;\n",
+ GPU_DATATYPE_STR[output->type], output->id);
+ }
+
+ BLI_dynstr_append(ds, "\n");
+}
+
+static void codegen_call_functions(DynStr *ds, ListBase *nodes, GPUOutput *finaloutput)
+{
+ GPUNode *node;
+ GPUInput *input;
+ GPUOutput *output;
+
+ for (node=nodes->first; node; node=node->next) {
+ BLI_dynstr_printf(ds, "\t%s(", node->name);
+
+ for (input=node->inputs.first; input; input=input->next) {
+ if (input->source == GPU_SOURCE_TEX) {
+ BLI_dynstr_printf(ds, "samp%d", input->texid);
+ if (input->link)
+ BLI_dynstr_printf(ds, ", gl_TexCoord[%d].st", input->texid);
+ }
+ else if (input->source == GPU_SOURCE_TEX_PIXEL) {
+ if (input->link && input->link->output)
+ codegen_convert_datatype(ds, input->link->output->type, input->type,
+ "tmp", input->link->output->id);
+ else
+ codegen_convert_datatype(ds, input->link->output->type, input->type,
+ "tex", input->texid);
+ }
+ else if(input->source == GPU_SOURCE_BUILTIN)
+ BLI_dynstr_printf(ds, "%s", GPU_builtin_name(input->builtin));
+ else if(input->source == GPU_SOURCE_VEC_UNIFORM) {
+ if(input->dynamicvec)
+ BLI_dynstr_printf(ds, "unf%d", input->id);
+ else
+ BLI_dynstr_printf(ds, "cons%d", input->id);
+ }
+ else if (input->source == GPU_SOURCE_ATTRIB)
+ BLI_dynstr_printf(ds, "var%d", input->attribid);
+
+ BLI_dynstr_append(ds, ", ");
+ }
+
+ for (output=node->outputs.first; output; output=output->next) {
+ BLI_dynstr_printf(ds, "tmp%d", output->id);
+ if (output->next)
+ BLI_dynstr_append(ds, ", ");
+ }
+
+ BLI_dynstr_append(ds, ");\n");
+ }
+
+ BLI_dynstr_append(ds, "\n\tgl_FragColor = ");
+ codegen_convert_datatype(ds, finaloutput->type, GPU_VEC4, "tmp", finaloutput->id);
+ BLI_dynstr_append(ds, ";\n");
+}
+
+static char *code_generate_fragment(ListBase *nodes, GPUOutput *output, const char *name)
+{
+ DynStr *ds = BLI_dynstr_new();
+ char *code;
+
+ /*BLI_dynstr_append(ds, FUNCTION_PROTOTYPES);*/
+
+ codegen_set_unique_ids(nodes);
+ codegen_print_uniforms_functions(ds, nodes);
+
+ //if(G.f & G_DEBUG)
+ // BLI_dynstr_printf(ds, "/* %s */\n", name);
+
+ BLI_dynstr_append(ds, "void main(void)\n");
+ BLI_dynstr_append(ds, "{\n");
+
+ codegen_declare_tmps(ds, nodes);
+ codegen_call_functions(ds, nodes, output);
+
+ BLI_dynstr_append(ds, "}\n");
+
+ /* create shader */
+ code = BLI_dynstr_get_cstring(ds);
+ BLI_dynstr_free(ds);
+
+ //if(G.f & G_DEBUG) printf("%s\n", code);
+
+ return code;
+}
+
+static char *code_generate_vertex(ListBase *nodes)
+{
+ DynStr *ds = BLI_dynstr_new();
+ GPUNode *node;
+ GPUInput *input;
+ char *code;
+
+ for (node=nodes->first; node; node=node->next) {
+ for (input=node->inputs.first; input; input=input->next) {
+ if (input->source == GPU_SOURCE_ATTRIB && input->attribfirst) {
+ BLI_dynstr_printf(ds, "attribute %s att%d;\n",
+ GPU_DATATYPE_STR[input->type], input->attribid);
+ BLI_dynstr_printf(ds, "varying %s var%d;\n",
+ GPU_DATATYPE_STR[input->type], input->attribid);
+ }
+ }
+ }
+
+ BLI_dynstr_append(ds, "\n");
+ BLI_dynstr_append(ds, datatoc_gpu_shader_vertex_glsl);
+
+ for (node=nodes->first; node; node=node->next)
+ for (input=node->inputs.first; input; input=input->next)
+ if (input->source == GPU_SOURCE_ATTRIB && input->attribfirst) {
+ if(input->attribtype == CD_TANGENT) /* silly exception */
+ BLI_dynstr_printf(ds, "\tvar%d = gl_NormalMatrix * ", input->attribid);
+ else
+ BLI_dynstr_printf(ds, "\tvar%d = ", input->attribid);
+
+ BLI_dynstr_printf(ds, "att%d;\n", input->attribid);
+ }
+
+ BLI_dynstr_append(ds, "}\n\n");
+
+ code = BLI_dynstr_get_cstring(ds);
+
+ BLI_dynstr_free(ds);
+
+ //if(G.f & G_DEBUG) printf("%s\n", code);
+
+ return code;
+}
+
+/* GPU pass binding/unbinding */
+
+GPUShader *GPU_pass_shader(GPUPass *pass)
+{
+ return pass->shader;
+}
+
+void GPU_nodes_extract_dynamic_inputs(GPUPass *pass, ListBase *nodes)
+{
+ GPUShader *shader = pass->shader;
+ GPUNode *node;
+ GPUInput *next, *input;
+ ListBase *inputs = &pass->inputs;
+ int extract, z;
+
+ memset(inputs, 0, sizeof(*inputs));
+
+ if(!shader)
+ return;
+
+ GPU_shader_bind(shader);
+
+ for (node=nodes->first; node; node=node->next) {
+ z = 0;
+ for (input=node->inputs.first; input; input=next, z++) {
+ next = input->next;
+
+ /* attributes don't need to be bound, they already have
+ * an id that the drawing functions will use */
+ if(input->source == GPU_SOURCE_ATTRIB ||
+ input->source == GPU_SOURCE_BUILTIN)
+ continue;
+
+ if (input->ima || input->tex)
+ snprintf(input->shadername, sizeof(input->shadername), "samp%d", input->texid);
+ else
+ snprintf(input->shadername, sizeof(input->shadername), "unf%d", input->id);
+
+ /* pass non-dynamic uniforms to opengl */
+ extract = 0;
+
+ if(input->ima || input->tex) {
+ if (input->bindtex)
+ extract = 1;
+ }
+ else if(input->dynamicvec)
+ extract = 1;
+
+ if(extract)
+ input->shaderloc = GPU_shader_get_uniform(shader, input->shadername);
+
+ /* extract nodes */
+ if(extract) {
+ BLI_remlink(&node->inputs, input);
+ BLI_addtail(inputs, input);
+ }
+ }
+ }
+
+ GPU_shader_unbind(shader);
+}
+
+void GPU_pass_bind(GPUPass *pass, double time)
+{
+ GPUInput *input;
+ GPUShader *shader = pass->shader;
+ ListBase *inputs = &pass->inputs;
+
+ if (!shader)
+ return;
+
+ GPU_shader_bind(shader);
+
+ /* now bind the textures */
+ for (input=inputs->first; input; input=input->next) {
+ if (input->ima)
+ input->tex = GPU_texture_from_blender(input->ima, input->iuser, time);
+
+ if(input->tex && input->bindtex) {
+ GPU_texture_bind(input->tex, input->texid);
+ GPU_shader_uniform_texture(shader, input->shaderloc, input->tex);
+ }
+ }
+}
+
+void GPU_pass_update_uniforms(GPUPass *pass)
+{
+ GPUInput *input;
+ GPUShader *shader = pass->shader;
+ ListBase *inputs = &pass->inputs;
+
+ if (!shader)
+ return;
+
+ /* pass dynamic inputs to opengl, others were removed */
+ for (input=inputs->first; input; input=input->next)
+ if(!(input->ima || input->tex))
+ GPU_shader_uniform_vector(shader, input->shaderloc, input->type, 1,
+ input->dynamicvec);
+}
+
+void GPU_pass_unbind(GPUPass *pass)
+{
+ GPUInput *input;
+ GPUShader *shader = pass->shader;
+ ListBase *inputs = &pass->inputs;
+
+ if (!shader)
+ return;
+
+ for (input=inputs->first; input; input=input->next) {
+ if(input->tex && input->bindtex)
+ GPU_texture_unbind(input->tex);
+
+ if (input->ima)
+ input->tex = 0;
+ }
+
+ GPU_shader_unbind(shader);
+}
+
+/* Node Link Functions */
+
+GPUNodeLink *GPU_node_link_create(int type)
+{
+ GPUNodeLink *link = MEM_callocN(sizeof(GPUNodeLink), "GPUNodeLink");
+ link->type = type;
+ link->users++;
+
+ return link;
+}
+
+void GPU_node_link_free(GPUNodeLink *link)
+{
+ link->users--;
+
+ if (link->users < 0)
+ fprintf(stderr, "GPU_node_link_free: negative refcount\n");
+
+ if (link->users == 0) {
+ if (link->output)
+ link->output->link = NULL;
+ MEM_freeN(link);
+ }
+}
+
+/* Node Functions */
+
+GPUNode *GPU_node_begin(char *name)
+{
+ GPUNode *node = MEM_callocN(sizeof(GPUNode), "GPUNode");
+
+ node->name = name;
+
+ return node;
+}
+
+void GPU_node_end(GPUNode *node)
+{
+ /* empty */
+}
+
+static void gpu_node_input_link(GPUNode *node, GPUNodeLink *link, int type)
+{
+ GPUInput *input;
+ GPUNode *outnode;
+ char *name;
+
+ if(link->output) {
+ outnode = link->output->node;
+ name = outnode->name;
+
+ if(strcmp(name, "set_value")==0 || strcmp(name, "set_rgb")==0) {
+ input = MEM_dupallocN(outnode->inputs.first);
+ input->type = type;
+ if(input->link)
+ input->link->users++;
+ BLI_addtail(&node->inputs, input);
+ return;
+ }
+ }
+
+ input = MEM_callocN(sizeof(GPUInput), "GPUInput");
+ input->node = node;
+
+ if(link->builtin) {
+ /* builtin uniform */
+ input->type = type;
+ input->source = GPU_SOURCE_BUILTIN;
+ input->builtin = link->builtin;
+
+ MEM_freeN(link);
+ }
+ else if(link->output) {
+ /* link to a node output */
+ input->type = type;
+ input->source = GPU_SOURCE_TEX_PIXEL;
+ input->link = link;
+ link->users++;
+ }
+ else if(link->dynamictex) {
+ /* dynamic texture, GPUTexture is updated/deleted externally */
+ input->type = type;
+ input->source = GPU_SOURCE_TEX;
+
+ input->tex = link->dynamictex;
+ input->textarget = GL_TEXTURE_2D;
+ input->textype = type;
+ input->dynamictex = 1;
+ MEM_freeN(link);
+ }
+ else if(link->texture) {
+ /* small texture created on the fly, like for colorbands */
+ input->type = GPU_VEC4;
+ input->source = GPU_SOURCE_TEX;
+ input->textype = type;
+
+ if (type == GPU_TEX1D) {
+ input->tex = GPU_texture_create_1D(link->texturesize, link->ptr1);
+ input->textarget = GL_TEXTURE_1D;
+ }
+ else {
+ input->tex = GPU_texture_create_2D(link->texturesize, link->texturesize, link->ptr2);
+ input->textarget = GL_TEXTURE_2D;
+ }
+
+ MEM_freeN(link->ptr1);
+ MEM_freeN(link);
+ }
+ else if(link->image) {
+ /* blender image */
+ input->type = GPU_VEC4;
+ input->source = GPU_SOURCE_TEX;
+
+ input->ima = link->ptr1;
+ input->textarget = GL_TEXTURE_2D;
+ input->textype = GPU_TEX2D;
+ MEM_freeN(link);
+ }
+ else if(link->attribtype) {
+ /* vertex attribute */
+ input->type = type;
+ input->source = GPU_SOURCE_ATTRIB;
+
+ input->attribtype = link->attribtype;
+ BLI_strncpy(input->attribname, link->attribname, sizeof(input->attribname));
+ MEM_freeN(link);
+ }
+ else {
+ /* uniform vector */
+ input->type = type;
+ input->source = GPU_SOURCE_VEC_UNIFORM;
+
+ memcpy(input->vec, link->ptr1, type*sizeof(float));
+ if(link->dynamic)
+ input->dynamicvec= link->ptr1;
+ MEM_freeN(link);
+ }
+
+ BLI_addtail(&node->inputs, input);
+}
+
+static void gpu_node_input_socket(GPUNode *node, GPUNodeStack *sock)
+{
+ GPUNodeLink *link;
+
+ if(sock->link) {
+ gpu_node_input_link(node, sock->link, sock->type);
+ }
+ else {
+ link = GPU_node_link_create(0);
+ link->ptr1 = sock->vec;
+ gpu_node_input_link(node, link, sock->type);
+ }
+}
+
+void GPU_node_output(GPUNode *node, int type, char *name, GPUNodeLink **link)
+{
+ GPUOutput *output = MEM_callocN(sizeof(GPUOutput), "GPUOutput");
+
+ output->type = type;
+ output->node = node;
+
+ if (link) {
+ *link = output->link = GPU_node_link_create(type);
+ output->link->output = output;
+
+ /* note: the caller owns the reference to the linkfer, GPUOutput
+ merely points to it, and if the node is destroyed it will
+ set that pointer to NULL */
+ }
+
+ BLI_addtail(&node->outputs, output);
+}
+
+void GPU_inputs_free(ListBase *inputs)
+{
+ GPUInput *input;
+
+ for(input=inputs->first; input; input=input->next) {
+ if(input->link)
+ GPU_node_link_free(input->link);
+ else if(input->tex && !input->dynamictex)
+ GPU_texture_free(input->tex);
+ }
+
+ BLI_freelistN(inputs);
+}
+
+void GPU_node_free(GPUNode *node)
+{
+ GPUOutput *output;
+
+ GPU_inputs_free(&node->inputs);
+
+ for (output=node->outputs.first; output; output=output->next)
+ if (output->link) {
+ output->link->output = NULL;
+ GPU_node_link_free(output->link);
+ }
+
+ BLI_freelistN(&node->outputs);
+ MEM_freeN(node);
+}
+
+void GPU_nodes_free(ListBase *nodes)
+{
+ GPUNode *node;
+
+ while (nodes->first) {
+ node = nodes->first;
+ BLI_remlink(nodes, node);
+ GPU_node_free(node);
+ }
+}
+
+/* vertex attributes */
+
+void gpu_nodes_get_vertex_attributes(ListBase *nodes, GPUVertexAttribs *attribs)
+{
+ GPUNode *node;
+ GPUInput *input;
+ int a;
+
+ /* convert attributes requested by node inputs to an array of layers,
+ * checking for duplicates and assigning id's starting from zero. */
+
+ memset(attribs, 0, sizeof(*attribs));
+
+ for(node=nodes->first; node; node=node->next) {
+ for(input=node->inputs.first; input; input=input->next) {
+ if(input->source == GPU_SOURCE_ATTRIB) {
+ for(a=0; a<attribs->totlayer; a++) {
+ if(attribs->layer[a].type == input->attribtype &&
+ strcmp(attribs->layer[a].name, input->attribname) == 0)
+ break;
+ }
+
+ if(a == attribs->totlayer && a < GPU_MAX_ATTRIB) {
+ input->attribid = attribs->totlayer++;
+ input->attribfirst = 1;
+
+ attribs->layer[a].type = input->attribtype;
+ attribs->layer[a].glindex = input->attribid;
+ BLI_strncpy(attribs->layer[a].name, input->attribname,
+ sizeof(attribs->layer[a].name));
+ }
+ else
+ input->attribid = attribs->layer[a].glindex;
+ }
+ }
+ }
+}
+
+void gpu_nodes_get_builtin_flag(ListBase *nodes, int *builtin)
+{
+ GPUNode *node;
+ GPUInput *input;
+
+ *builtin= 0;
+
+ for(node=nodes->first; node; node=node->next)
+ for(input=node->inputs.first; input; input=input->next)
+ if(input->source == GPU_SOURCE_BUILTIN)
+ *builtin |= input->builtin;
+}
+
+/* varargs linking */
+
+GPUNodeLink *GPU_attribute(int type, char *name)
+{
+ GPUNodeLink *link = GPU_node_link_create(0);
+
+ link->attribtype= type;
+ link->attribname= name;
+
+ return link;
+}
+
+GPUNodeLink *GPU_uniform(float *num)
+{
+ GPUNodeLink *link = GPU_node_link_create(0);
+
+ link->ptr1= num;
+ link->ptr2= NULL;
+
+ return link;
+}
+
+GPUNodeLink *GPU_dynamic_uniform(float *num)
+{
+ GPUNodeLink *link = GPU_node_link_create(0);
+
+ link->ptr1= num;
+ link->ptr2= NULL;
+ link->dynamic= 1;
+
+ return link;
+}
+
+GPUNodeLink *GPU_image(Image *ima, ImageUser *iuser)
+{
+ GPUNodeLink *link = GPU_node_link_create(0);
+
+ link->image= 1;
+ link->ptr1= ima;
+ link->ptr2= iuser;
+
+ return link;
+}
+
+GPUNodeLink *GPU_texture(int size, float *pixels)
+{
+ GPUNodeLink *link = GPU_node_link_create(0);
+
+ link->texture = 1;
+ link->texturesize = size;
+ link->ptr1= pixels;
+
+ return link;
+}
+
+GPUNodeLink *GPU_dynamic_texture(GPUTexture *tex)
+{
+ GPUNodeLink *link = GPU_node_link_create(0);
+
+ link->dynamic = 1;
+ link->dynamictex = tex;
+
+ return link;
+}
+
+GPUNodeLink *GPU_socket(GPUNodeStack *sock)
+{
+ GPUNodeLink *link = GPU_node_link_create(0);
+
+ link->socket= sock;
+
+ return link;
+}
+
+GPUNodeLink *GPU_builtin(GPUBuiltin builtin)
+{
+ GPUNodeLink *link = GPU_node_link_create(0);
+
+ link->builtin= builtin;
+
+ return link;
+}
+
+int GPU_link(GPUMaterial *mat, char *name, ...)
+{
+ GPUNode *node;
+ GPUFunction *function;
+ GPUNodeLink *link, **linkptr;
+ va_list params;
+ int i;
+
+ function = GPU_lookup_function(name);
+ if(!function) {
+ fprintf(stderr, "GPU failed to find function %s\n", name);
+ return 0;
+ }
+
+ node = GPU_node_begin(name);
+
+ va_start(params, name);
+ for(i=0; i<function->totparam; i++) {
+ if(function->paramqual[i] != FUNCTION_QUAL_IN) {
+ linkptr= va_arg(params, GPUNodeLink**);
+ GPU_node_output(node, function->paramtype[i], "", linkptr);
+ }
+ else {
+ link= va_arg(params, GPUNodeLink*);
+ gpu_node_input_link(node, link, function->paramtype[i]);
+ }
+ }
+ va_end(params);
+
+ GPU_node_end(node);
+
+ gpu_material_add_node(mat, node);
+
+ return 1;
+}
+
+int GPU_stack_link(GPUMaterial *mat, char *name, GPUNodeStack *in, GPUNodeStack *out, ...)
+{
+ GPUNode *node;
+ GPUFunction *function;
+ GPUNodeLink *link, **linkptr;
+ va_list params;
+ int i, totin, totout;
+
+ function = GPU_lookup_function(name);
+ if(!function) {
+ fprintf(stderr, "GPU failed to find function %s\n", name);
+ return 0;
+ }
+
+ node = GPU_node_begin(name);
+ totin = 0;
+ totout = 0;
+
+ if(in) {
+ for(i = 0; in[i].type != GPU_NONE; i++) {
+ gpu_node_input_socket(node, &in[i]);
+ totin++;
+ }
+ }
+
+ if(out) {
+ for(i = 0; out[i].type != GPU_NONE; i++) {
+ GPU_node_output(node, out[i].type, out[i].name, &out[i].link);
+ totout++;
+ }
+ }
+
+ va_start(params, out);
+ for(i=0; i<function->totparam; i++) {
+ if(function->paramqual[i] != FUNCTION_QUAL_IN) {
+ if(totout == 0) {
+ linkptr= va_arg(params, GPUNodeLink**);
+ GPU_node_output(node, function->paramtype[i], "", linkptr);
+ }
+ else
+ totout--;
+ }
+ else {
+ if(totin == 0) {
+ link= va_arg(params, GPUNodeLink*);
+ if(link->socket)
+ gpu_node_input_socket(node, link->socket);
+ else
+ gpu_node_input_link(node, link, function->paramtype[i]);
+ }
+ else
+ totin--;
+ }
+ }
+ va_end(params);
+
+ GPU_node_end(node);
+
+ gpu_material_add_node(mat, node);
+
+ return 1;
+}
+
+int GPU_link_changed(GPUNodeLink *link)
+{
+ GPUNode *node;
+ GPUInput *input;
+ char *name;
+
+ if(link->output) {
+ node = link->output->node;
+ name = node->name;
+
+ if(strcmp(name, "set_value")==0 || strcmp(name, "set_rgb")==0) {
+ input = node->inputs.first;
+ return (input->link != NULL);
+ }
+
+ return 1;
+ }
+ else
+ return 0;
+}
+
+/* Pass create/free */
+
+void gpu_nodes_tag(GPUNodeLink *link)
+{
+ GPUNode *node;
+ GPUInput *input;
+
+ if(!link->output)
+ return;
+
+ node = link->output->node;
+ if(node->tag)
+ return;
+
+ node->tag= 1;
+ for(input=node->inputs.first; input; input=input->next)
+ if(input->link)
+ gpu_nodes_tag(input->link);
+}
+
+void gpu_nodes_prune(ListBase *nodes, GPUNodeLink *outlink)
+{
+ GPUNode *node, *next;
+
+ for(node=nodes->first; node; node=node->next)
+ node->tag= 0;
+
+ gpu_nodes_tag(outlink);
+
+ for(node=nodes->first; node; node=next) {
+ next = node->next;
+
+ if(!node->tag) {
+ BLI_remlink(nodes, node);
+ GPU_node_free(node);
+ }
+ }
+}
+
+GPUPass *GPU_generate_pass(ListBase *nodes, GPUNodeLink *outlink, GPUVertexAttribs *attribs, int *builtins, const char *name)
+{
+ GPUShader *shader;
+ GPUPass *pass;
+ char *vertexcode, *fragmentcode;
+
+ /*if(!FUNCTION_LIB) {
+ GPU_nodes_free(nodes);
+ return NULL;
+ }*/
+
+ /* prune unused nodes */
+ gpu_nodes_prune(nodes, outlink);
+
+ gpu_nodes_get_vertex_attributes(nodes, attribs);
+ gpu_nodes_get_builtin_flag(nodes, builtins);
+
+ /* generate code and compile with opengl */
+ fragmentcode = code_generate_fragment(nodes, outlink->output, name);
+ vertexcode = code_generate_vertex(nodes);
+ shader = GPU_shader_create(vertexcode, fragmentcode, datatoc_gpu_shader_material_glsl); /*FUNCTION_LIB);*/
+ MEM_freeN(fragmentcode);
+ MEM_freeN(vertexcode);
+
+ /* failed? */
+ if (!shader) {
+ memset(attribs, 0, sizeof(*attribs));
+ memset(builtins, 0, sizeof(*builtins));
+ GPU_nodes_free(nodes);
+ return NULL;
+ }
+
+ /* create pass */
+ pass = MEM_callocN(sizeof(GPUPass), "GPUPass");
+
+ pass->output = outlink->output;
+ pass->shader = shader;
+
+ /* extract dynamic inputs and throw away nodes */
+ GPU_nodes_extract_dynamic_inputs(pass, nodes);
+ GPU_nodes_free(nodes);
+
+ return pass;
+}
+
+void GPU_pass_free(GPUPass *pass)
+{
+ GPU_shader_free(pass->shader);
+ GPU_inputs_free(&pass->inputs);
+ MEM_freeN(pass);
+}
+
diff --git a/source/blender/gpu/intern/gpu_codegen.h b/source/blender/gpu/intern/gpu_codegen.h
new file mode 100644
index 00000000000..53b52f24f16
--- /dev/null
+++ b/source/blender/gpu/intern/gpu_codegen.h
@@ -0,0 +1,87 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2005 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Brecht Van Lommel.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __GPU_CODEGEN_H__
+#define __GPU_CODEGEN_H__
+
+#include "DNA_listBase.h"
+
+struct ListBase;
+struct GPUShader;
+struct GPUOutput;
+struct GPUNode;
+struct GPUVertexAttribs;
+
+#define MAX_FUNCTION_NAME 64
+#define MAX_PARAMETER 32
+
+#define FUNCTION_QUAL_IN 0
+#define FUNCTION_QUAL_OUT 1
+#define FUNCTION_QUAL_INOUT 2
+
+typedef struct GPUFunction {
+ char name[MAX_FUNCTION_NAME];
+ int paramtype[MAX_PARAMETER];
+ int paramqual[MAX_PARAMETER];
+ int totparam;
+} GPUFunction;
+
+GPUFunction *GPU_lookup_function(char *name);
+
+/* Pass Generation
+ - Takes a list of nodes and a desired output, and makes a pass. This
+ will take ownership of the nodes and free them early if unused or
+ at the end if used.
+*/
+
+struct GPUPass;
+typedef struct GPUPass GPUPass;
+
+GPUPass *GPU_generate_pass(ListBase *nodes, struct GPUNodeLink *outlink,
+ struct GPUVertexAttribs *attribs, int *builtin, const char *name);
+
+struct GPUShader *GPU_pass_shader(GPUPass *pass);
+
+void GPU_pass_bind(GPUPass *pass, double time);
+void GPU_pass_update_uniforms(GPUPass *pass);
+void GPU_pass_unbind(GPUPass *pass);
+
+void GPU_pass_free(GPUPass *pass);
+
+/* Material calls */
+
+char *GPU_builtin_name(GPUBuiltin builtin);
+void gpu_material_add_node(struct GPUMaterial *material, struct GPUNode *node);
+int GPU_link_changed(struct GPUNodeLink *link);
+
+#endif
+
diff --git a/source/blender/gpu/intern/gpu_draw.c b/source/blender/gpu/intern/gpu_draw.c
new file mode 100644
index 00000000000..4025a12a867
--- /dev/null
+++ b/source/blender/gpu/intern/gpu_draw.c
@@ -0,0 +1,1185 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2005 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Brecht Van Lommel.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include <string.h>
+
+#include "GL/glew.h"
+
+#include "DNA_image_types.h"
+#include "DNA_lamp_types.h"
+#include "DNA_material_types.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_node_types.h"
+#include "DNA_object_types.h"
+#include "DNA_scene_types.h"
+#include "DNA_userdef_types.h"
+#include "DNA_view3d_types.h"
+
+#include "MEM_guardedalloc.h"
+
+#include "IMB_imbuf.h"
+#include "IMB_imbuf_types.h"
+
+#include "BKE_bmfont.h"
+#include "BKE_global.h"
+#include "BKE_image.h"
+#include "BKE_main.h"
+#include "BKE_material.h"
+#include "BKE_node.h"
+#include "BKE_object.h"
+#include "BKE_utildefines.h"
+
+#include "GPU_extensions.h"
+#include "GPU_material.h"
+#include "GPU_draw.h"
+
+/* These are some obscure rendering functions shared between the
+ * game engine and the blender, in this module to avoid duplicaten
+ * and abstract them away from the rest a bit */
+
+/* Text Rendering */
+
+static void gpu_mcol(unsigned int ucol)
+{
+ /* mcol order is swapped */
+ char *cp= (char *)&ucol;
+ glColor3ub(cp[3], cp[2], cp[1]);
+}
+
+void GPU_render_text(MTFace *tface, int mode,
+ const char *textstr, int textlen, unsigned int *col,
+ float *v1, float *v2, float *v3, float *v4, int glattrib)
+{
+ if (mode & TF_BMFONT) {
+ Image* ima;
+ int characters, index, character;
+ float centerx, centery, sizex, sizey, transx, transy, movex, movey, advance;
+
+ characters = textlen;
+
+ ima = (Image*)tface->tpage;
+ if (ima == NULL)
+ characters = 0;
+
+ // color has been set
+ if (tface->mode & TF_OBCOL)
+ col= NULL;
+ else if (!col)
+ glColor3f(1.0f, 1.0f, 1.0f);
+
+ glPushMatrix();
+ for (index = 0; index < characters; index++) {
+ float uv[4][2];
+
+ // lets calculate offset stuff
+ character = textstr[index];
+
+ // space starts at offset 1
+ // character = character - ' ' + 1;
+ matrixGlyph((ImBuf *)ima->ibufs.first, character, & centerx, &centery,
+ &sizex, &sizey, &transx, &transy, &movex, &movey, &advance);
+
+ uv[0][0] = (tface->uv[0][0] - centerx) * sizex + transx;
+ uv[0][1] = (tface->uv[0][1] - centery) * sizey + transy;
+ uv[1][0] = (tface->uv[1][0] - centerx) * sizex + transx;
+ uv[1][1] = (tface->uv[1][1] - centery) * sizey + transy;
+ uv[2][0] = (tface->uv[2][0] - centerx) * sizex + transx;
+ uv[2][1] = (tface->uv[2][1] - centery) * sizey + transy;
+
+ glBegin(GL_POLYGON);
+ if(glattrib >= 0) glVertexAttrib2fvARB(glattrib, uv[0]);
+ else glTexCoord2fv(uv[0]);
+ if(col) gpu_mcol(col[0]);
+ glVertex3f(sizex * v1[0] + movex, sizey * v1[1] + movey, v1[2]);
+
+ if(glattrib >= 0) glVertexAttrib2fvARB(glattrib, uv[1]);
+ else glTexCoord2fv(uv[1]);
+ if(col) gpu_mcol(col[1]);
+ glVertex3f(sizex * v2[0] + movex, sizey * v2[1] + movey, v2[2]);
+
+ if(glattrib >= 0) glVertexAttrib2fvARB(glattrib, uv[2]);
+ else glTexCoord2fv(uv[2]);
+ if(col) gpu_mcol(col[2]);
+ glVertex3f(sizex * v3[0] + movex, sizey * v3[1] + movey, v3[2]);
+
+ if(v4) {
+ uv[3][0] = (tface->uv[3][0] - centerx) * sizex + transx;
+ uv[3][1] = (tface->uv[3][1] - centery) * sizey + transy;
+
+ if(glattrib >= 0) glVertexAttrib2fvARB(glattrib, uv[3]);
+ else glTexCoord2fv(uv[3]);
+ if(col) gpu_mcol(col[3]);
+ glVertex3f(sizex * v4[0] + movex, sizey * v4[1] + movey, v4[2]);
+ }
+ glEnd();
+
+ glTranslatef(advance, 0.0, 0.0);
+ }
+ glPopMatrix();
+ }
+}
+
+/* Checking powers of two for images since opengl 1.x requires it */
+
+static int is_pow2(int num)
+{
+ /* (n&(n-1)) zeros the least significant bit of n */
+ return ((num)&(num-1))==0;
+}
+
+static int smaller_pow2(int num)
+{
+ while (!is_pow2(num))
+ num= num&(num-1);
+
+ return num;
+}
+
+static int is_pow2_limit(int num)
+{
+ /* take texture clamping into account */
+ if (U.glreslimit != 0 && num > U.glreslimit)
+ return 0;
+
+ return ((num)&(num-1))==0;
+}
+
+static int smaller_pow2_limit(int num)
+{
+ /* take texture clamping into account */
+ if (U.glreslimit != 0 && num > U.glreslimit)
+ return U.glreslimit;
+
+ return smaller_pow2(num);
+}
+
+/* Current OpenGL state caching for GPU_set_tpage */
+
+static struct GPUTextureState {
+ int curtile, tile;
+ int curtilemode, tilemode;
+ int curtileXRep, tileXRep;
+ int curtileYRep, tileYRep;
+ Image *ima, *curima;
+
+ int domipmap, linearmipmap;
+
+ int alphamode;
+ MTFace *lasttface;
+} GTS = {0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, 1, 0, -1, NULL};
+
+/* Mipmap settings */
+
+void GPU_set_mipmap(int mipmap)
+{
+ if (GTS.domipmap != (mipmap != 0)) {
+ GPU_free_images();
+ GTS.domipmap = mipmap != 0;
+ }
+}
+
+void GPU_set_linear_mipmap(int linear)
+{
+ if (GTS.linearmipmap != (linear != 0)) {
+ GPU_free_images();
+ GTS.linearmipmap = linear != 0;
+ }
+}
+
+static int gpu_get_mipmap(void)
+{
+ return GTS.domipmap && (!(G.f & G_TEXTUREPAINT));
+}
+
+static GLenum gpu_get_mipmap_filter(int mag)
+{
+ /* linearmipmap is off by default *when mipmapping is off,
+ * use unfiltered display */
+ if(mag) {
+ if(GTS.linearmipmap || GTS.domipmap)
+ return GL_LINEAR;
+ else
+ return GL_NEAREST;
+ }
+ else {
+ if(GTS.linearmipmap)
+ return GL_LINEAR_MIPMAP_LINEAR;
+ else if(GTS.domipmap)
+ return GL_LINEAR_MIPMAP_NEAREST;
+ else
+ return GL_NEAREST;
+ }
+}
+
+/* Set OpenGL state for an MTFace */
+
+static void gpu_make_repbind(Image *ima)
+{
+ ImBuf *ibuf;
+
+ ibuf = BKE_image_get_ibuf(ima, NULL);
+ if(ibuf==NULL)
+ return;
+
+ if(ima->repbind) {
+ glDeleteTextures(ima->totbind, (GLuint *)ima->repbind);
+ MEM_freeN(ima->repbind);
+ ima->repbind= 0;
+ ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
+ }
+
+ ima->totbind= ima->xrep*ima->yrep;
+
+ if(ima->totbind>1)
+ ima->repbind= MEM_callocN(sizeof(int)*ima->totbind, "repbind");
+}
+
+static void gpu_clear_tpage()
+{
+ if(GTS.lasttface==0)
+ return;
+
+ GTS.lasttface= 0;
+ GTS.curtile= 0;
+ GTS.curima= 0;
+ if(GTS.curtilemode!=0) {
+ glMatrixMode(GL_TEXTURE);
+ glLoadIdentity();
+ glMatrixMode(GL_MODELVIEW);
+ }
+ GTS.curtilemode= 0;
+ GTS.curtileXRep=0;
+ GTS.curtileYRep=0;
+ GTS.alphamode= -1;
+
+ glDisable(GL_BLEND);
+ glDisable(GL_TEXTURE_2D);
+ glDisable(GL_TEXTURE_GEN_S);
+ glDisable(GL_TEXTURE_GEN_T);
+ glDisable(GL_ALPHA_TEST);
+}
+
+static void gpu_set_blend_mode(GPUBlendMode blendmode)
+{
+ if(blendmode == GPU_BLEND_SOLID) {
+ glDisable(GL_BLEND);
+ glDisable(GL_ALPHA_TEST);
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ }
+ else if(blendmode==GPU_BLEND_ADD) {
+ glEnable(GL_BLEND);
+ glBlendFunc(GL_ONE, GL_ONE);
+ glDisable(GL_ALPHA_TEST);
+ }
+ else if(blendmode==GPU_BLEND_ALPHA) {
+ glEnable(GL_BLEND);
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+
+ /* if U.glalphaclip == 1.0, some cards go bonkers...
+ * turn off alpha test in this case */
+
+ /* added after 2.45 to clip alpha */
+ if(U.glalphaclip == 1.0) {
+ glDisable(GL_ALPHA_TEST);
+ }
+ else {
+ glEnable(GL_ALPHA_TEST);
+ glAlphaFunc(GL_GREATER, U.glalphaclip);
+ }
+ }
+ else if(blendmode==GPU_BLEND_CLIP) {
+ glDisable(GL_BLEND);
+ glEnable(GL_ALPHA_TEST);
+ glAlphaFunc(GL_GREATER, 0.5f);
+ }
+}
+
+static void gpu_verify_alpha_mode(MTFace *tface)
+{
+ /* verify alpha blending modes */
+ if(GTS.alphamode == tface->transp)
+ return;
+
+ gpu_set_blend_mode(tface->transp);
+ GTS.alphamode= tface->transp;
+}
+
+static void gpu_verify_reflection(Image *ima)
+{
+ if (ima && (ima->flag & IMA_REFLECT)) {
+ /* enable reflection mapping */
+ glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
+ glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
+
+ glEnable(GL_TEXTURE_GEN_S);
+ glEnable(GL_TEXTURE_GEN_T);
+ }
+ else {
+ /* disable reflection mapping */
+ glDisable(GL_TEXTURE_GEN_S);
+ glDisable(GL_TEXTURE_GEN_T);
+ }
+}
+
+int GPU_verify_image(Image *ima, int tftile, int tfmode, int compare)
+{
+ ImBuf *ibuf = NULL;
+ unsigned int *bind = NULL;
+ int rectw, recth, tpx=0, tpy=0, y;
+ unsigned int *rectrow, *tilerectrow;
+ unsigned int *tilerect= NULL, *scalerect= NULL, *rect= NULL;
+ short texwindx, texwindy, texwinsx, texwinsy;
+
+ /* initialize tile mode and number of repeats */
+ GTS.ima = ima;
+ GTS.tilemode= (tfmode & TF_TILES) || (ima && (ima->tpageflag & IMA_TWINANIM));
+ GTS.tileXRep = 0;
+ GTS.tileYRep = 0;
+
+ /* setting current tile according to frame */
+ if(ima && (ima->tpageflag & IMA_TWINANIM))
+ GTS.tile= ima->lastframe;
+ else
+ GTS.tile= tftile;
+
+ GTS.tile = MAX2(0, GTS.tile);
+
+ if(ima) {
+ GTS.tileXRep = ima->xrep;
+ GTS.tileYRep = ima->yrep;
+ }
+
+ /* if same image & tile, we're done */
+ if(compare && ima == GTS.curima && GTS.curtile == GTS.tile &&
+ GTS.tilemode == GTS.curtilemode && GTS.curtileXRep == GTS.tileXRep &&
+ GTS.curtileYRep == GTS.tileYRep)
+ return (ima!=0);
+
+ /* if tiling mode or repeat changed, change texture matrix to fit */
+ if(GTS.tilemode!=GTS.curtilemode || GTS.curtileXRep!=GTS.tileXRep ||
+ GTS.curtileYRep != GTS.tileYRep) {
+
+ glMatrixMode(GL_TEXTURE);
+ glLoadIdentity();
+
+ if((tfmode & TF_TILES) && ima!=NULL)
+ glScalef(ima->xrep, ima->yrep, 1.0);
+
+ glMatrixMode(GL_MODELVIEW);
+ }
+
+ /* check if we have a valid image */
+ if(ima==NULL || ima->ok==0)
+ return 0;
+
+ /* check if we have a valid image buffer */
+ ibuf= BKE_image_get_ibuf(ima, NULL);
+
+ if(ibuf==NULL)
+ return 0;
+
+ /* ensure we have a char buffer and not only float */
+ if ((ibuf->rect==NULL) && ibuf->rect_float)
+ IMB_rect_from_float(ibuf);
+
+ if(GTS.tilemode) {
+ /* tiled mode */
+ if(ima->repbind==0) gpu_make_repbind(ima);
+ if(GTS.tile>=ima->totbind) GTS.tile= 0;
+
+ /* this happens when you change repeat buttons */
+ if(ima->repbind) bind= &ima->repbind[GTS.tile];
+ else bind= &ima->bindcode;
+
+ if(*bind==0) {
+
+ texwindx= ibuf->x/ima->xrep;
+ texwindy= ibuf->y/ima->yrep;
+
+ if(GTS.tile>=ima->xrep*ima->yrep)
+ GTS.tile= ima->xrep*ima->yrep-1;
+
+ texwinsy= GTS.tile / ima->xrep;
+ texwinsx= GTS.tile - texwinsy*ima->xrep;
+
+ texwinsx*= texwindx;
+ texwinsy*= texwindy;
+
+ tpx= texwindx;
+ tpy= texwindy;
+
+ rect= ibuf->rect + texwinsy*ibuf->x + texwinsx;
+ }
+ }
+ else {
+ /* regular image mode */
+ bind= &ima->bindcode;
+
+ if(*bind==0) {
+ tpx= ibuf->x;
+ tpy= ibuf->y;
+ rect= ibuf->rect;
+ }
+ }
+
+ if(*bind != 0) {
+ /* enable opengl drawing with textures */
+ glBindTexture(GL_TEXTURE_2D, *bind);
+ return *bind;
+ }
+
+ rectw = tpx;
+ recth = tpy;
+
+ /* for tiles, copy only part of image into buffer */
+ if (GTS.tilemode) {
+ tilerect= MEM_mallocN(rectw*recth*sizeof(*tilerect), "tilerect");
+
+ for (y=0; y<recth; y++) {
+ rectrow= &rect[y*ibuf->x];
+ tilerectrow= &tilerect[y*rectw];
+
+ memcpy(tilerectrow, rectrow, tpx*sizeof(*rectrow));
+ }
+
+ rect= tilerect;
+ }
+
+ /* scale if not a power of two */
+ if (!is_pow2_limit(rectw) || !is_pow2_limit(recth)) {
+ rectw= smaller_pow2_limit(rectw);
+ recth= smaller_pow2_limit(recth);
+
+ scalerect= MEM_mallocN(rectw*recth*sizeof(*scalerect), "scalerect");
+ gluScaleImage(GL_RGBA, tpx, tpy, GL_UNSIGNED_BYTE, rect, rectw, recth, GL_UNSIGNED_BYTE, scalerect);
+ rect= scalerect;
+ }
+
+ /* create image */
+ glGenTextures(1, (GLuint *)bind);
+ glBindTexture( GL_TEXTURE_2D, *bind);
+
+ if (!gpu_get_mipmap()) {
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, rectw, recth, 0, GL_RGBA, GL_UNSIGNED_BYTE, rect);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
+ }
+ else {
+ gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, rectw, recth, GL_RGBA, GL_UNSIGNED_BYTE, rect);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gpu_get_mipmap_filter(0));
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
+
+ ima->tpageflag |= IMA_MIPMAP_COMPLETE;
+ }
+
+ /* set to modulate with vertex color */
+ glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
+
+ /* clean up */
+ if (tilerect)
+ MEM_freeN(tilerect);
+ if (scalerect)
+ MEM_freeN(scalerect);
+
+ return *bind;
+}
+
+static void gpu_verify_repeat(Image *ima)
+{
+ /* set either clamp or repeat in X/Y */
+ if (ima->tpageflag & IMA_CLAMP_U)
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ else
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+
+ if (ima->tpageflag & IMA_CLAMP_V)
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+ else
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
+}
+
+int GPU_set_tpage(MTFace *tface)
+{
+ Image *ima;
+
+ /* check if we need to clear the state */
+ if(tface==0) {
+ gpu_clear_tpage();
+ return 0;
+ }
+
+ ima= tface->tpage;
+ GTS.lasttface= tface;
+
+ gpu_verify_alpha_mode(tface);
+ gpu_verify_reflection(ima);
+
+ if(GPU_verify_image(ima, tface->tile, tface->mode, 1)) {
+ GTS.curtile= GTS.tile;
+ GTS.curima= GTS.ima;
+ GTS.curtilemode= GTS.tilemode;
+ GTS.curtileXRep = GTS.tileXRep;
+ GTS.curtileYRep = GTS.tileYRep;
+
+ glEnable(GL_TEXTURE_2D);
+ }
+ else {
+ glDisable(GL_TEXTURE_2D);
+
+ GTS.curtile= 0;
+ GTS.curima= 0;
+ GTS.curtilemode= 0;
+ GTS.curtileXRep = 0;
+ GTS.curtileYRep = 0;
+
+ return 0;
+ }
+
+ gpu_verify_repeat(ima);
+
+ /* Did this get lost in the image recode? */
+ /* tag_image_time(ima);*/
+
+ return 1;
+}
+
+/* these two functions are called on entering and exiting texture paint mode,
+ temporary disabling/enabling mipmapping on all images for quick texture
+ updates with glTexSubImage2D. images that didn't change don't have to be
+ re-uploaded to OpenGL */
+void GPU_paint_set_mipmap(int mipmap)
+{
+ Image* ima;
+
+ if(!GTS.domipmap)
+ return;
+
+ if(mipmap) {
+ for(ima=G.main->image.first; ima; ima=ima->id.next) {
+ if(ima->bindcode) {
+ if(ima->tpageflag & IMA_MIPMAP_COMPLETE) {
+ glBindTexture(GL_TEXTURE_2D, ima->bindcode);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gpu_get_mipmap_filter(0));
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
+ }
+ else
+ GPU_free_image(ima);
+ }
+ }
+
+ }
+ else {
+ for(ima=G.main->image.first; ima; ima=ima->id.next) {
+ if(ima->bindcode) {
+ glBindTexture(GL_TEXTURE_2D, ima->bindcode);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
+ }
+ }
+ }
+}
+
+void GPU_paint_update_image(Image *ima, int x, int y, int w, int h)
+{
+ ImBuf *ibuf;
+
+ ibuf = BKE_image_get_ibuf(ima, NULL);
+
+ if (ima->repbind || gpu_get_mipmap() || !ima->bindcode || !ibuf ||
+ (!is_pow2(ibuf->x) || !is_pow2(ibuf->y)) ||
+ (w == 0) || (h == 0)) {
+ /* these cases require full reload still */
+ GPU_free_image(ima);
+ }
+ else {
+ /* for the special case, we can do a partial update
+ * which is much quicker for painting */
+ GLint row_length, skip_pixels, skip_rows;
+
+ glGetIntegerv(GL_UNPACK_ROW_LENGTH, &row_length);
+ glGetIntegerv(GL_UNPACK_SKIP_PIXELS, &skip_pixels);
+ glGetIntegerv(GL_UNPACK_SKIP_ROWS, &skip_rows);
+
+ if ((ibuf->rect==NULL) && ibuf->rect_float)
+ IMB_rect_from_float(ibuf);
+
+ glBindTexture(GL_TEXTURE_2D, ima->bindcode);
+
+ glPixelStorei(GL_UNPACK_ROW_LENGTH, ibuf->x);
+ glPixelStorei(GL_UNPACK_SKIP_PIXELS, x);
+ glPixelStorei(GL_UNPACK_SKIP_ROWS, y);
+
+ glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA,
+ GL_UNSIGNED_BYTE, ibuf->rect);
+
+ glPixelStorei(GL_UNPACK_ROW_LENGTH, row_length);
+ glPixelStorei(GL_UNPACK_SKIP_PIXELS, skip_pixels);
+ glPixelStorei(GL_UNPACK_SKIP_ROWS, skip_rows);
+
+ if(ima->tpageflag & IMA_MIPMAP_COMPLETE)
+ ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
+ }
+}
+
+void GPU_update_images_framechange(void)
+{
+ Image *ima;
+
+ for(ima=G.main->image.first; ima; ima=ima->id.next) {
+ if(ima->tpageflag & IMA_TWINANIM) {
+ if(ima->twend >= ima->xrep*ima->yrep)
+ ima->twend= ima->xrep*ima->yrep-1;
+
+ /* check: is bindcode not in the array? free. (to do) */
+
+ ima->lastframe++;
+ if(ima->lastframe > ima->twend)
+ ima->lastframe= ima->twsta;
+ }
+ }
+}
+
+int GPU_update_image_time(Image *ima, double time)
+{
+ int inc = 0;
+ float diff;
+ int newframe;
+
+ if (!ima)
+ return 0;
+
+ if (ima->lastupdate<0)
+ ima->lastupdate = 0;
+
+ if (ima->lastupdate>time)
+ ima->lastupdate=(float)time;
+
+ if(ima->tpageflag & IMA_TWINANIM) {
+ if(ima->twend >= ima->xrep*ima->yrep) ima->twend= ima->xrep*ima->yrep-1;
+
+ /* check: is the bindcode not in the array? Then free. (still to do) */
+
+ diff = (float)(time-ima->lastupdate);
+ inc = (int)(diff*(float)ima->animspeed);
+
+ ima->lastupdate+=((float)inc/(float)ima->animspeed);
+
+ newframe = ima->lastframe+inc;
+
+ if(newframe > (int)ima->twend) {
+ if(ima->twend-ima->twsta != 0)
+ newframe = (int)ima->twsta-1 + (newframe-ima->twend)%(ima->twend-ima->twsta);
+ else
+ newframe = ima->twsta;
+ }
+
+ ima->lastframe = newframe;
+ }
+
+ return inc;
+}
+
+void GPU_free_image(Image *ima)
+{
+ /* free regular image binding */
+ if(ima->bindcode) {
+ glDeleteTextures(1, (GLuint *)&ima->bindcode);
+ ima->bindcode= 0;
+ ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
+ }
+
+ /* free glsl image binding */
+ if(ima->gputexture) {
+ GPU_texture_free(ima->gputexture);
+ ima->gputexture= NULL;
+ }
+
+ /* free repeated image binding */
+ if(ima->repbind) {
+ glDeleteTextures(ima->totbind, (GLuint *)ima->repbind);
+
+ MEM_freeN(ima->repbind);
+ ima->repbind= NULL;
+ ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
+ }
+}
+
+void GPU_free_images(void)
+{
+ Image* ima;
+
+ if(G.main)
+ for(ima=G.main->image.first; ima; ima=ima->id.next)
+ GPU_free_image(ima);
+}
+
+/* OpenGL Materials */
+
+/* materials start counting at # one.... */
+#define MAXMATBUF (MAXMAT+1)
+
+/* OpenGL state caching for materials */
+
+static struct GPUMaterialState {
+ float matbuf[MAXMATBUF][2][4];
+ int totmat;
+
+ Material *gmatbuf[MAXMATBUF];
+ Material *gboundmat;
+ Object *gob;
+ Scene *gscene;
+
+ GPUBlendMode blendmode[MAXMATBUF];
+ int alphapass;
+
+ int lastmatnr, lastretval;
+ GPUBlendMode lastblendmode;
+} GMS;
+
+Material *gpu_active_node_material(Material *ma)
+{
+ if(ma && ma->use_nodes && ma->nodetree) {
+ bNode *node= nodeGetActiveID(ma->nodetree, ID_MA);
+
+ if(node)
+ return (Material *)node->id;
+ else
+ return NULL;
+ }
+
+ return ma;
+}
+
+void GPU_set_object_materials(Scene *scene, Object *ob, int glsl, int *do_alpha_pass)
+{
+ extern Material defmaterial; /* from material.c */
+ Material *ma;
+ GPUMaterial *gpumat;
+ GPUBlendMode blendmode;
+ int a;
+
+ /* initialize state */
+ memset(&GMS, 0, sizeof(GMS));
+ GMS.lastmatnr = -1;
+ GMS.lastretval = -1;
+ GMS.lastblendmode = GPU_BLEND_SOLID;
+
+ GMS.gob = ob;
+ GMS.gscene = scene;
+ GMS.totmat= ob->totcol;
+
+ GMS.alphapass = (G.vd && G.vd->transp);
+ if(do_alpha_pass)
+ *do_alpha_pass = 0;
+
+ /* no materials assigned? */
+ if(ob->totcol==0) {
+ GMS.matbuf[0][0][0]= defmaterial.r;
+ GMS.matbuf[0][0][1]= defmaterial.g;
+ GMS.matbuf[0][0][2]= defmaterial.b;
+ GMS.matbuf[0][0][3]= 1.0;
+
+ GMS.matbuf[0][1][0]= defmaterial.specr;
+ GMS.matbuf[0][1][1]= defmaterial.specg;
+ GMS.matbuf[0][1][2]= defmaterial.specb;
+ GMS.matbuf[0][1][3]= 1.0;
+
+ /* do material 1 too, for displists! */
+ QUATCOPY(GMS.matbuf[1][0], GMS.matbuf[0][0]);
+ QUATCOPY(GMS.matbuf[1][1], GMS.matbuf[0][1]);
+
+ if(glsl) {
+ GMS.gmatbuf[0]= &defmaterial;
+ GPU_material_from_blender(GMS.gscene, &defmaterial);
+ }
+
+ GMS.blendmode[0]= GPU_BLEND_SOLID;
+ }
+
+ /* setup materials */
+ for(a=1; a<=ob->totcol; a++) {
+ /* find a suitable material */
+ ma= give_current_material(ob, a);
+ if(!glsl) ma= gpu_active_node_material(ma);
+ if(ma==NULL) ma= &defmaterial;
+
+ /* this shouldn't happen .. */
+ if(a>=MAXMATBUF)
+ continue;
+
+ /* create glsl material if requested */
+ gpumat = (glsl)? GPU_material_from_blender(GMS.gscene, ma): NULL;
+
+ if(gpumat) {
+ /* do glsl only if creating it succeed, else fallback */
+ GMS.gmatbuf[a]= ma;
+ blendmode = GPU_material_blend_mode(gpumat, ob->col);
+ }
+ else {
+ /* fixed function opengl materials */
+ if (ma->mode & MA_SHLESS) {
+ GMS.matbuf[a][0][0]= ma->r;
+ GMS.matbuf[a][0][1]= ma->g;
+ GMS.matbuf[a][0][2]= ma->b;
+ } else {
+ GMS.matbuf[a][0][0]= (ma->ref+ma->emit)*ma->r;
+ GMS.matbuf[a][0][1]= (ma->ref+ma->emit)*ma->g;
+ GMS.matbuf[a][0][2]= (ma->ref+ma->emit)*ma->b;
+
+ GMS.matbuf[a][1][0]= ma->spec*ma->specr;
+ GMS.matbuf[a][1][1]= ma->spec*ma->specg;
+ GMS.matbuf[a][1][2]= ma->spec*ma->specb;
+ GMS.matbuf[a][1][3]= 1.0;
+ }
+
+ blendmode = (ma->alpha == 1.0f)? GPU_BLEND_SOLID: GPU_BLEND_ALPHA;
+ if(do_alpha_pass && GMS.alphapass)
+ GMS.matbuf[a][0][3]= ma->alpha;
+ else
+ GMS.matbuf[a][0][3]= 1.0f;
+ }
+
+ /* setting do_alpha_pass = 1 indicates this object needs to be
+ * drawn in a second alpha pass for improved blending */
+ if(do_alpha_pass) {
+ GMS.blendmode[a]= blendmode;
+ if(ELEM(blendmode, GPU_BLEND_ALPHA, GPU_BLEND_ADD) && !GMS.alphapass)
+ *do_alpha_pass= 1;
+ }
+ }
+
+ /* let's start with a clean state */
+ GPU_disable_material();
+}
+
+int GPU_enable_material(int nr, void *attribs)
+{
+ GPUVertexAttribs *gattribs = attribs;
+ GPUMaterial *gpumat;
+ GPUBlendMode blendmode;
+
+ /* prevent index to use un-initialized array items */
+ if(nr>GMS.totmat)
+ nr= GMS.totmat;
+
+ if(gattribs)
+ memset(gattribs, 0, sizeof(*gattribs));
+
+ /* keep current material */
+ if(nr>=MAXMATBUF || nr==GMS.lastmatnr)
+ return GMS.lastretval;
+
+ /* unbind glsl material */
+ if(GMS.gboundmat) {
+ if(GMS.alphapass) glDepthMask(0);
+ GPU_material_unbind(GPU_material_from_blender(GMS.gscene, GMS.gboundmat));
+ GMS.gboundmat= NULL;
+ }
+
+ /* draw materials with alpha in alpha pass */
+ GMS.lastmatnr = nr;
+ GMS.lastretval = ELEM(GMS.blendmode[nr], GPU_BLEND_SOLID, GPU_BLEND_CLIP);
+ if(GMS.alphapass)
+ GMS.lastretval = !GMS.lastretval;
+
+ if(GMS.lastretval) {
+ if(gattribs && GMS.gmatbuf[nr]) {
+ /* bind glsl material and get attributes */
+ Material *mat = GMS.gmatbuf[nr];
+
+ gpumat = GPU_material_from_blender(GMS.gscene, mat);
+ GPU_material_vertex_attributes(gpumat, gattribs);
+ GPU_material_bind(gpumat, GMS.gob->lay, G.vd->lay, 1.0);
+ GPU_material_bind_uniforms(gpumat, GMS.gob->obmat, G.vd->viewmat, G.vd->viewinv, GMS.gob->col);
+ GMS.gboundmat= mat;
+
+ if(GMS.alphapass) glDepthMask(1);
+ }
+ else {
+ /* or do fixed function opengl material */
+ glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, GMS.matbuf[nr][0]);
+ glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, GMS.matbuf[nr][1]);
+ }
+
+ /* set (alpha) blending mode */
+ blendmode = (GMS.alphapass)? GPU_BLEND_ALPHA: GPU_BLEND_SOLID;
+ GPU_set_material_blend_mode(blendmode);
+ }
+
+ return GMS.lastretval;
+}
+
+void GPU_set_material_blend_mode(int blendmode)
+{
+ if(GMS.lastblendmode == blendmode)
+ return;
+
+ gpu_set_blend_mode(blendmode);
+ GMS.lastblendmode = blendmode;
+}
+
+int GPU_get_material_blend_mode(void)
+{
+ return GMS.lastblendmode;
+}
+
+void GPU_disable_material(void)
+{
+ GMS.lastmatnr= -1;
+ GMS.lastretval= 1;
+
+ if(GMS.gboundmat) {
+ if(GMS.alphapass) glDepthMask(0);
+ GPU_material_unbind(GPU_material_from_blender(GMS.gscene, GMS.gboundmat));
+ GMS.gboundmat= NULL;
+ }
+
+ GPU_set_material_blend_mode(GPU_BLEND_SOLID);
+}
+
+/* Lights */
+
+int GPU_default_lights(void)
+{
+ int a, count = 0;
+
+ /* initialize */
+ if(U.light[0].flag==0 && U.light[1].flag==0 && U.light[2].flag==0) {
+ U.light[0].flag= 1;
+ U.light[0].vec[0]= -0.3; U.light[0].vec[1]= 0.3; U.light[0].vec[2]= 0.9;
+ U.light[0].col[0]= 0.8; U.light[0].col[1]= 0.8; U.light[0].col[2]= 0.8;
+ U.light[0].spec[0]= 0.5; U.light[0].spec[1]= 0.5; U.light[0].spec[2]= 0.5;
+ U.light[0].spec[3]= 1.0;
+
+ U.light[1].flag= 0;
+ U.light[1].vec[0]= 0.5; U.light[1].vec[1]= 0.5; U.light[1].vec[2]= 0.1;
+ U.light[1].col[0]= 0.4; U.light[1].col[1]= 0.4; U.light[1].col[2]= 0.8;
+ U.light[1].spec[0]= 0.3; U.light[1].spec[1]= 0.3; U.light[1].spec[2]= 0.5;
+ U.light[1].spec[3]= 1.0;
+
+ U.light[2].flag= 0;
+ U.light[2].vec[0]= 0.3; U.light[2].vec[1]= -0.3; U.light[2].vec[2]= -0.2;
+ U.light[2].col[0]= 0.8; U.light[2].col[1]= 0.5; U.light[2].col[2]= 0.4;
+ U.light[2].spec[0]= 0.5; U.light[2].spec[1]= 0.4; U.light[2].spec[2]= 0.3;
+ U.light[2].spec[3]= 1.0;
+ }
+
+ glLightfv(GL_LIGHT0, GL_POSITION, U.light[0].vec);
+ glLightfv(GL_LIGHT0, GL_DIFFUSE, U.light[0].col);
+ glLightfv(GL_LIGHT0, GL_SPECULAR, U.light[0].spec);
+
+ glLightfv(GL_LIGHT1, GL_POSITION, U.light[1].vec);
+ glLightfv(GL_LIGHT1, GL_DIFFUSE, U.light[1].col);
+ glLightfv(GL_LIGHT1, GL_SPECULAR, U.light[1].spec);
+
+ glLightfv(GL_LIGHT2, GL_POSITION, U.light[2].vec);
+ glLightfv(GL_LIGHT2, GL_DIFFUSE, U.light[2].col);
+ glLightfv(GL_LIGHT2, GL_SPECULAR, U.light[2].spec);
+
+ for(a=0; a<8; a++) {
+ if(a<3) {
+ if(U.light[a].flag) {
+ glEnable(GL_LIGHT0+a);
+ count++;
+ }
+ else
+ glDisable(GL_LIGHT0+a);
+
+ // clear stuff from other opengl lamp usage
+ glLightf(GL_LIGHT0+a, GL_SPOT_CUTOFF, 180.0);
+ glLightf(GL_LIGHT0+a, GL_CONSTANT_ATTENUATION, 1.0);
+ glLightf(GL_LIGHT0+a, GL_LINEAR_ATTENUATION, 0.0);
+ }
+ else
+ glDisable(GL_LIGHT0+a);
+ }
+
+ glDisable(GL_LIGHTING);
+
+ glDisable(GL_COLOR_MATERIAL);
+
+ return count;
+}
+
+int GPU_scene_object_lights(Scene *scene, Object *ob, int lay, float viewmat[][4])
+{
+ Base *base;
+ Lamp *la;
+ int count;
+ float position[4], direction[4], energy[4];
+
+ /* disable all lights */
+ for(count=0; count<8; count++)
+ glDisable(GL_LIGHT0+count);
+
+ count= 0;
+
+ for(base=scene->base.first; base; base=base->next) {
+ if(base->object->type!=OB_LAMP)
+ continue;
+
+ if(!(base->lay & lay) || !(base->lay & ob->lay))
+ continue;
+
+ la= base->object->data;
+
+ /* setup lamp transform */
+ glPushMatrix();
+ glLoadMatrixf((float *)viewmat);
+
+ where_is_object_simul(base->object);
+
+ if(la->type==LA_SUN) {
+ /* sun lamp */
+ VECCOPY(direction, base->object->obmat[2]);
+ direction[3]= 0.0;
+
+ glLightfv(GL_LIGHT0+count, GL_POSITION, direction);
+ }
+ else {
+ /* other lamps with attenuation */
+ VECCOPY(position, base->object->obmat[3]);
+ position[3]= 1.0f;
+
+ glLightfv(GL_LIGHT0+count, GL_POSITION, position);
+ glLightf(GL_LIGHT0+count, GL_CONSTANT_ATTENUATION, 1.0);
+ glLightf(GL_LIGHT0+count, GL_LINEAR_ATTENUATION, la->att1/la->dist);
+ glLightf(GL_LIGHT0+count, GL_QUADRATIC_ATTENUATION, la->att2/(la->dist*la->dist));
+
+ if(la->type==LA_SPOT) {
+ /* spot lamp */
+ direction[0]= -base->object->obmat[2][0];
+ direction[1]= -base->object->obmat[2][1];
+ direction[2]= -base->object->obmat[2][2];
+ glLightfv(GL_LIGHT0+count, GL_SPOT_DIRECTION, direction);
+ glLightf(GL_LIGHT0+count, GL_SPOT_CUTOFF, la->spotsize/2.0);
+ glLightf(GL_LIGHT0+count, GL_SPOT_EXPONENT, 128.0*la->spotblend);
+ }
+ else
+ glLightf(GL_LIGHT0+count, GL_SPOT_CUTOFF, 180.0);
+ }
+
+ /* setup energy */
+ energy[0]= la->energy*la->r;
+ energy[1]= la->energy*la->g;
+ energy[2]= la->energy*la->b;
+ energy[3]= 1.0;
+
+ glLightfv(GL_LIGHT0+count, GL_DIFFUSE, energy);
+ glLightfv(GL_LIGHT0+count, GL_SPECULAR, energy);
+ glEnable(GL_LIGHT0+count);
+
+ glPopMatrix();
+
+ count++;
+ if(count==8)
+ break;
+ }
+
+ return count;
+}
+
+/* Default OpenGL State */
+
+void GPU_state_init(void)
+{
+ /* also called when doing opengl rendering and in the game engine */
+ float mat_ambient[] = { 0.0, 0.0, 0.0, 0.0 };
+ float mat_specular[] = { 0.5, 0.5, 0.5, 1.0 };
+ float mat_shininess[] = { 35.0 };
+ int a, x, y;
+ GLubyte pat[32*32];
+ const GLubyte *patc= pat;
+
+ glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambient);
+ glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_specular);
+ glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
+ glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess);
+
+ GPU_default_lights();
+
+ /* no local viewer, looks ugly in ortho mode */
+ /* glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, &one); */
+
+ glDepthFunc(GL_LEQUAL);
+ /* scaling matrices */
+ glEnable(GL_NORMALIZE);
+
+ glShadeModel(GL_FLAT);
+
+ glDisable(GL_ALPHA_TEST);
+ glDisable(GL_BLEND);
+ glDisable(GL_DEPTH_TEST);
+ glDisable(GL_FOG);
+ glDisable(GL_LIGHTING);
+ glDisable(GL_LOGIC_OP);
+ glDisable(GL_STENCIL_TEST);
+ glDisable(GL_TEXTURE_1D);
+ glDisable(GL_TEXTURE_2D);
+
+ /* default on, disable/enable should be local per function */
+ glEnableClientState(GL_VERTEX_ARRAY);
+ glEnableClientState(GL_NORMAL_ARRAY);
+
+ glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
+ glPixelTransferi(GL_RED_SCALE, 1);
+ glPixelTransferi(GL_RED_BIAS, 0);
+ glPixelTransferi(GL_GREEN_SCALE, 1);
+ glPixelTransferi(GL_GREEN_BIAS, 0);
+ glPixelTransferi(GL_BLUE_SCALE, 1);
+ glPixelTransferi(GL_BLUE_BIAS, 0);
+ glPixelTransferi(GL_ALPHA_SCALE, 1);
+ glPixelTransferi(GL_ALPHA_BIAS, 0);
+
+ glPixelTransferi(GL_DEPTH_BIAS, 0);
+ glPixelTransferi(GL_DEPTH_SCALE, 1);
+ glDepthRange(0.0, 1.0);
+
+ a= 0;
+ for(x=0; x<32; x++) {
+ for(y=0; y<4; y++) {
+ if( (x) & 1) pat[a++]= 0x88;
+ else pat[a++]= 0x22;
+ }
+ }
+
+ glPolygonStipple(patc);
+
+ glMatrixMode(GL_TEXTURE);
+ glLoadIdentity();
+ glMatrixMode(GL_MODELVIEW);
+
+ glFrontFace(GL_CCW);
+ glCullFace(GL_BACK);
+ glDisable(GL_CULL_FACE);
+}
+
diff --git a/source/blender/gpu/intern/gpu_extensions.c b/source/blender/gpu/intern/gpu_extensions.c
new file mode 100644
index 00000000000..7654c67419b
--- /dev/null
+++ b/source/blender/gpu/intern/gpu_extensions.c
@@ -0,0 +1,998 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2005 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Brecht Van Lommel.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "GL/glew.h"
+
+#include "DNA_listBase.h"
+#include "DNA_image_types.h"
+#include "DNA_userdef_types.h"
+
+#include "MEM_guardedalloc.h"
+
+#include "BKE_image.h"
+#include "BKE_global.h"
+#include "BKE_utildefines.h"
+
+#include "IMB_imbuf.h"
+#include "IMB_imbuf_types.h"
+
+#include "BLI_blenlib.h"
+
+#include "GPU_draw.h"
+#include "GPU_extensions.h"
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+/* Extensions support */
+
+/* extensions used:
+ - texture border clamp: 1.3 core
+ - fragement shader: 2.0 core
+ - framebuffer object: ext specification
+ - multitexture 1.3 core
+ - arb non power of two: 2.0 core
+ - pixel buffer objects? 2.1 core
+ - arb draw buffers? 2.0 core
+*/
+
+static struct GPUGlobal {
+ GLint maxtextures;
+ GLuint currentfb;
+ int minimumsupport;
+ int extdisabled;
+} GG = {1, 0, 0, 0};
+
+void GPU_extensions_disable()
+{
+ GG.extdisabled = 1;
+}
+
+void GPU_extensions_init()
+{
+ glewInit();
+
+ /* glewIsSupported("GL_VERSION_2_0") */
+
+ if (GLEW_ARB_multitexture)
+ glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS_ARB, &GG.maxtextures);
+
+ GG.minimumsupport = 1;
+ if (!GLEW_ARB_multitexture) GG.minimumsupport = 0;
+ if (!GLEW_ARB_vertex_shader) GG.minimumsupport = 0;
+ if (!GLEW_ARB_fragment_shader) GG.minimumsupport = 0;
+}
+
+int GPU_extensions_minimum_support()
+{
+ return !GG.extdisabled && GG.minimumsupport;
+}
+
+int GPU_print_error(char *str)
+{
+ GLenum errCode;
+
+ if (G.f & G_DEBUG) {
+ if ((errCode = glGetError()) != GL_NO_ERROR) {
+ fprintf(stderr, "%s opengl error: %s\n", str, gluErrorString(errCode));
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+static void GPU_print_framebuffer_error(GLenum status)
+{
+ fprintf(stderr, "GPUFrameBuffer: framebuffer incomplete error %d\n",
+ (int)status);
+
+ switch(status) {
+ case GL_FRAMEBUFFER_COMPLETE_EXT:
+ break;
+ case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
+ fprintf(stderr, "Incomplete attachment.\n");
+ break;
+ case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
+ fprintf(stderr, "Unsupported framebuffer format.\n");
+ break;
+ case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT:
+ fprintf(stderr, "Missing attachment.\n");
+ break;
+ case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
+ fprintf(stderr, "Attached images must have same dimensions.\n");
+ break;
+ case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT:
+ fprintf(stderr, "Attached images must have same format.\n");
+ break;
+ case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT:
+ fprintf(stderr, "Missing draw buffer.\n");
+ break;
+ case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT:
+ fprintf(stderr, "Missing read buffer.\n");
+ break;
+ default:
+ fprintf(stderr, "Unknown.\n");
+ break;
+ }
+}
+
+/* GPUTexture */
+
+struct GPUTexture {
+ int w, h; /* width/height */
+ int number; /* number for multitexture binding */
+ int refcount; /* reference count */
+ GLenum target; /* GL_TEXTURE_* */
+ GLuint bindcode; /* opengl identifier for texture */
+ int fromblender; /* we got the texture from Blender */
+
+ GPUFrameBuffer *fb; /* GPUFramebuffer this texture is attached to */
+ int depth; /* is a depth texture? */
+};
+
+static unsigned char *GPU_texture_convert_pixels(int length, float *fpixels)
+{
+ unsigned char *pixels, *p;
+ float *fp;
+ int a, len;
+
+ len = 4*length;
+ fp = fpixels;
+ p = pixels = MEM_callocN(sizeof(unsigned char)*len, "GPUTexturePixels");
+
+ for (a=0; a<len; a++, p++, fp++)
+ *p = FTOCHAR((*fp));
+
+ return pixels;
+}
+
+static int is_pow2(int n)
+{
+ return ((n)&(n-1))==0;
+}
+
+static int larger_pow2(int n)
+{
+ if (is_pow2(n))
+ return n;
+
+ while(!is_pow2(n))
+ n= n&(n-1);
+
+ return n*2;
+}
+
+static void GPU_glTexSubImageEmpty(GLenum target, GLenum format, int x, int y, int w, int h)
+{
+ void *pixels = MEM_callocN(sizeof(char)*4*w*h, "GPUTextureEmptyPixels");
+
+ if (target == GL_TEXTURE_1D)
+ glTexSubImage1D(target, 0, x, w, format, GL_UNSIGNED_BYTE, pixels);
+ else
+ glTexSubImage2D(target, 0, x, y, w, h, format, GL_UNSIGNED_BYTE, pixels);
+
+ MEM_freeN(pixels);
+}
+
+static GPUTexture *GPU_texture_create_nD(int w, int h, int n, float *fpixels, int depth)
+{
+ GPUTexture *tex;
+ GLenum type, format, internalformat;
+ void *pixels = NULL;
+
+ if(depth && !GLEW_ARB_depth_texture)
+ return NULL;
+
+ tex = MEM_callocN(sizeof(GPUTexture), "GPUTexture");
+ tex->w = w;
+ tex->h = h;
+ tex->number = -1;
+ tex->refcount = 1;
+ tex->target = (n == 1)? GL_TEXTURE_1D: GL_TEXTURE_2D;
+ tex->depth = depth;
+
+ glGenTextures(1, &tex->bindcode);
+
+ if (!tex->bindcode) {
+ fprintf(stderr, "GPUTexture: texture create failed: %d\n",
+ (int)glGetError());
+ GPU_texture_free(tex);
+ return NULL;
+ }
+
+ if (!GLEW_ARB_texture_non_power_of_two) {
+ tex->w = larger_pow2(tex->w);
+ tex->h = larger_pow2(tex->h);
+ }
+
+ tex->number = 0;
+ glBindTexture(tex->target, tex->bindcode);
+
+ if(depth) {
+ type = GL_UNSIGNED_BYTE;
+ format = GL_DEPTH_COMPONENT;
+ internalformat = GL_DEPTH_COMPONENT;
+ }
+ else {
+ type = GL_UNSIGNED_BYTE;
+ format = GL_RGBA;
+ internalformat = GL_RGBA8;
+
+ if (fpixels)
+ pixels = GPU_texture_convert_pixels(w*h, fpixels);
+ }
+
+ if (tex->target == GL_TEXTURE_1D) {
+ glTexImage1D(tex->target, 0, internalformat, tex->w, 0, format, type, 0);
+
+ if (fpixels) {
+ glTexSubImage1D(tex->target, 0, 0, w, format, type,
+ pixels? pixels: fpixels);
+
+ if (tex->w > w)
+ GPU_glTexSubImageEmpty(tex->target, format, w, 0,
+ tex->w-w, 1);
+ }
+ }
+ else {
+ glTexImage2D(tex->target, 0, internalformat, tex->w, tex->h, 0,
+ format, type, 0);
+
+ if (fpixels) {
+ glTexSubImage2D(tex->target, 0, 0, 0, w, h,
+ format, type, pixels? pixels: fpixels);
+
+ if (tex->w > w)
+ GPU_glTexSubImageEmpty(tex->target, format, w, 0, tex->w-w, tex->h);
+ if (tex->h > h)
+ GPU_glTexSubImageEmpty(tex->target, format, 0, h, w, tex->h-h);
+ }
+ }
+
+ if (pixels)
+ MEM_freeN(pixels);
+
+ if(depth) {
+ glTexParameteri(tex->target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+ glTexParameteri(tex->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ glTexParameteri(tex->target, GL_TEXTURE_COMPARE_MODE_ARB, GL_COMPARE_R_TO_TEXTURE);
+ glTexParameteri(tex->target, GL_TEXTURE_COMPARE_FUNC_ARB, GL_LEQUAL);
+ glTexParameteri(tex->target, GL_DEPTH_TEXTURE_MODE_ARB, GL_INTENSITY);
+ }
+ else {
+ glTexParameteri(tex->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ glTexParameteri(tex->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ }
+
+ if (tex->target != GL_TEXTURE_1D) {
+ /* CLAMP_TO_BORDER is an OpenGL 1.3 core feature */
+ GLenum wrapmode = (depth)? GL_CLAMP_TO_EDGE: GL_CLAMP_TO_BORDER;
+ glTexParameteri(tex->target, GL_TEXTURE_WRAP_S, wrapmode);
+ glTexParameteri(tex->target, GL_TEXTURE_WRAP_T, wrapmode);
+
+#if 0
+ float borderColor[] = { 1.0f, 1.0f, 1.0f, 1.0f };
+ glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor);
+#endif
+ }
+ else
+ glTexParameteri(tex->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+
+ return tex;
+}
+
+GPUTexture *GPU_texture_from_blender(Image *ima, ImageUser *iuser, double time)
+{
+ GPUTexture *tex;
+ GLint w, h, border, lastbindcode, bindcode;
+
+ glGetIntegerv(GL_TEXTURE_BINDING_2D, &lastbindcode);
+
+ GPU_update_image_time(ima, time);
+ bindcode = GPU_verify_image(ima, 0, 0, 0);
+
+ if(ima->gputexture) {
+ ima->gputexture->bindcode = bindcode;
+ glBindTexture(GL_TEXTURE_2D, lastbindcode);
+ return ima->gputexture;
+ }
+
+ if(!bindcode) {
+ glBindTexture(GL_TEXTURE_2D, lastbindcode);
+ return NULL;
+ }
+
+ tex = MEM_callocN(sizeof(GPUTexture), "GPUTexture");
+ tex->bindcode = bindcode;
+ tex->number = -1;
+ tex->refcount = 1;
+ tex->target = GL_TEXTURE_2D;
+ tex->fromblender = 1;
+
+ ima->gputexture= tex;
+
+ if (!glIsTexture(tex->bindcode)) {
+ GPU_print_error("Blender Texture");
+ }
+ else {
+ glBindTexture(GL_TEXTURE_2D, tex->bindcode);
+ glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &w);
+ glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &h);
+ glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_BORDER, &border);
+
+ tex->w = w - border;
+ tex->h = h - border;
+ }
+
+ glBindTexture(GL_TEXTURE_2D, lastbindcode);
+
+ return tex;
+}
+
+GPUTexture *GPU_texture_create_1D(int w, float *fpixels)
+{
+ GPUTexture *tex = GPU_texture_create_nD(w, 1, 1, fpixels, 0);
+
+ if (tex)
+ GPU_texture_unbind(tex);
+
+ return tex;
+}
+
+GPUTexture *GPU_texture_create_2D(int w, int h, float *fpixels)
+{
+ GPUTexture *tex = GPU_texture_create_nD(w, h, 2, fpixels, 0);
+
+ if (tex)
+ GPU_texture_unbind(tex);
+
+ return tex;
+}
+
+GPUTexture *GPU_texture_create_depth(int w, int h)
+{
+ GPUTexture *tex = GPU_texture_create_nD(w, h, 2, NULL, 1);
+
+ if (tex)
+ GPU_texture_unbind(tex);
+
+ return tex;
+}
+
+void GPU_texture_bind(GPUTexture *tex, int number)
+{
+ GLenum arbnumber;
+
+ if (number >= GG.maxtextures) {
+ GPU_print_error("Not enough texture slots.");
+ return;
+ }
+
+ if(number == -1)
+ return;
+
+ GPU_print_error("Pre Texture Bind");
+
+ arbnumber = (GLenum)((GLuint)GL_TEXTURE0_ARB + number);
+ if (number != 0) glActiveTextureARB(arbnumber);
+ glBindTexture(tex->target, tex->bindcode);
+ glEnable(tex->target);
+ if (number != 0) glActiveTextureARB(GL_TEXTURE0_ARB);
+
+ tex->number = number;
+
+ GPU_print_error("Post Texture Bind");
+}
+
+void GPU_texture_unbind(GPUTexture *tex)
+{
+ GLenum arbnumber;
+
+ if (tex->number >= GG.maxtextures) {
+ GPU_print_error("Not enough texture slots.");
+ return;
+ }
+
+ if(tex->number == -1)
+ return;
+
+ GPU_print_error("Pre Texture Unbind");
+
+ arbnumber = (GLenum)((GLuint)GL_TEXTURE0_ARB + tex->number);
+ if (tex->number != 0) glActiveTextureARB(arbnumber);
+ glBindTexture(tex->target, 0);
+ glDisable(tex->target);
+ if (tex->number != 0) glActiveTextureARB(GL_TEXTURE0_ARB);
+
+ tex->number = -1;
+
+ GPU_print_error("Post Texture Unbind");
+}
+
+void GPU_texture_free(GPUTexture *tex)
+{
+ tex->refcount--;
+
+ if (tex->refcount < 0)
+ fprintf(stderr, "GPUTexture: negative refcount\n");
+
+ if (tex->refcount == 0) {
+ if (tex->fb)
+ GPU_framebuffer_texture_detach(tex->fb, tex);
+ if (tex->bindcode && !tex->fromblender)
+ glDeleteTextures(1, &tex->bindcode);
+
+ MEM_freeN(tex);
+ }
+}
+
+void GPU_texture_ref(GPUTexture *tex)
+{
+ tex->refcount++;
+}
+
+int GPU_texture_target(GPUTexture *tex)
+{
+ return tex->target;
+}
+
+int GPU_texture_opengl_width(GPUTexture *tex)
+{
+ return tex->w;
+}
+
+int GPU_texture_opengl_height(GPUTexture *tex)
+{
+ return tex->h;
+}
+
+GPUFrameBuffer *GPU_texture_framebuffer(GPUTexture *tex)
+{
+ return tex->fb;
+}
+
+/* GPUFrameBuffer */
+
+struct GPUFrameBuffer {
+ GLuint object;
+ GPUTexture *colortex;
+ GPUTexture *depthtex;
+};
+
+GPUFrameBuffer *GPU_framebuffer_create()
+{
+ GPUFrameBuffer *fb;
+
+ if (!GLEW_EXT_framebuffer_object)
+ return NULL;
+
+ fb= MEM_callocN(sizeof(GPUFrameBuffer), "GPUFrameBuffer");
+ glGenFramebuffersEXT(1, &fb->object);
+
+ if (!fb->object) {
+ fprintf(stderr, "GPUFFrameBuffer: framebuffer gen failed. %d\n",
+ (int)glGetError());
+ GPU_framebuffer_free(fb);
+ return NULL;
+ }
+
+ return fb;
+}
+
+int GPU_framebuffer_texture_attach(GPUFrameBuffer *fb, GPUTexture *tex)
+{
+ GLenum status;
+ GLenum attachment;
+
+ if(tex->depth)
+ attachment = GL_DEPTH_ATTACHMENT_EXT;
+ else
+ attachment = GL_COLOR_ATTACHMENT0_EXT;
+
+ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb->object);
+ GG.currentfb = fb->object;
+
+ glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, attachment,
+ tex->target, tex->bindcode, 0);
+
+ if(tex->depth) {
+ glDrawBuffer(GL_NONE);
+ glReadBuffer(GL_NONE);
+ }
+ else {
+ glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
+ glReadBuffer(GL_NONE);
+ }
+
+ status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
+
+ if (status != GL_FRAMEBUFFER_COMPLETE_EXT) {
+ GPU_framebuffer_restore();
+ GPU_print_framebuffer_error(status);
+ return 0;
+ }
+
+ if(tex->depth)
+ fb->depthtex = tex;
+ else
+ fb->colortex = tex;
+
+ tex->fb= fb;
+
+ return 1;
+}
+
+void GPU_framebuffer_texture_detach(GPUFrameBuffer *fb, GPUTexture *tex)
+{
+ GLenum attachment;
+
+ if(!tex->fb)
+ return;
+
+ if(GG.currentfb != tex->fb->object) {
+ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, tex->fb->object);
+ GG.currentfb = tex->fb->object;
+ }
+
+ if(tex->depth) {
+ fb->depthtex = NULL;
+ attachment = GL_DEPTH_ATTACHMENT_EXT;
+ }
+ else {
+ fb->colortex = NULL;
+ attachment = GL_COLOR_ATTACHMENT0_EXT;
+ }
+
+ glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, attachment,
+ tex->target, 0, 0);
+
+ tex->fb = NULL;
+}
+
+void GPU_framebuffer_texture_bind(GPUFrameBuffer *fb, GPUTexture *tex)
+{
+ /* push attributes */
+ glPushAttrib(GL_ENABLE_BIT);
+ glPushAttrib(GL_VIEWPORT_BIT);
+ glDisable(GL_SCISSOR_TEST);
+
+ /* bind framebuffer */
+ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, tex->fb->object);
+
+ /* push matrices and set default viewport and matrix */
+ glViewport(0, 0, tex->w, tex->h);
+ GG.currentfb = tex->fb->object;
+
+ glMatrixMode(GL_PROJECTION);
+ glPushMatrix();
+ glLoadIdentity();
+ glMatrixMode(GL_MODELVIEW);
+ glPushMatrix();
+ glLoadIdentity();
+}
+
+void GPU_framebuffer_texture_unbind(GPUFrameBuffer *fb, GPUTexture *tex)
+{
+ /* restore matrix */
+ glMatrixMode(GL_PROJECTION);
+ glPopMatrix();
+ glMatrixMode(GL_MODELVIEW);
+ glPopMatrix();
+
+ /* restore attributes */
+ glPopAttrib();
+ glPopAttrib();
+ glEnable(GL_SCISSOR_TEST);
+}
+
+void GPU_framebuffer_free(GPUFrameBuffer *fb)
+{
+ if(fb->depthtex)
+ GPU_framebuffer_texture_detach(fb, fb->depthtex);
+ if(fb->colortex)
+ GPU_framebuffer_texture_detach(fb, fb->colortex);
+
+ if(fb->object) {
+ glDeleteFramebuffersEXT(1, &fb->object);
+
+ if (GG.currentfb == fb->object) {
+ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
+ GG.currentfb = 0;
+ }
+ }
+
+ MEM_freeN(fb);
+}
+
+void GPU_framebuffer_restore()
+{
+ if (GG.currentfb != 0) {
+ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
+ GG.currentfb = 0;
+ }
+}
+
+/* GPUShader */
+
+struct GPUShader {
+ GLhandleARB object; /* handle for full shader */
+ GLhandleARB vertex; /* handle for vertex shader */
+ GLhandleARB fragment; /* handle for fragment shader */
+ GLhandleARB lib; /* handle for libment shader */
+ int totattrib; /* total number of attributes */
+};
+
+static void shader_print_errors(char *task, char *log, const char *code)
+{
+ const char *c, *pos, *end = code + strlen(code);
+ int line = 1;
+
+ fprintf(stderr, "GPUShader: %s error:\n", task);
+
+ if(G.f & G_DEBUG) {
+ c = code;
+ while ((c < end) && (pos = strchr(c, '\n'))) {
+ fprintf(stderr, "%2d ", line);
+ fwrite(c, (pos+1)-c, 1, stderr);
+ c = pos+1;
+ line++;
+ }
+
+ fprintf(stderr, "%s", c);
+ }
+
+ fprintf(stderr, "%s\n", log);
+}
+
+GPUShader *GPU_shader_create(const char *vertexcode, const char *fragcode, /*GPUShader *lib,*/ const char *libcode)
+{
+ GLint status;
+ GLcharARB log[5000];
+ const char *fragsource[2];
+ GLsizei length = 0;
+ GLint count;
+ GPUShader *shader;
+
+ if (!GLEW_ARB_vertex_shader || !GLEW_ARB_fragment_shader)
+ return NULL;
+
+ shader = MEM_callocN(sizeof(GPUShader), "GPUShader");
+
+ if(vertexcode)
+ shader->vertex = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
+ if(fragcode)
+ shader->fragment = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
+ shader->object = glCreateProgramObjectARB();
+
+ if (!shader->object ||
+ (vertexcode && !shader->vertex) ||
+ (fragcode && !shader->fragment)) {
+ fprintf(stderr, "GPUShader, object creation failed.\n");
+ GPU_shader_free(shader);
+ return NULL;
+ }
+
+ if(vertexcode) {
+ glAttachObjectARB(shader->object, shader->vertex);
+ glShaderSourceARB(shader->vertex, 1, (const char**)&vertexcode, NULL);
+
+ glCompileShaderARB(shader->vertex);
+ glGetObjectParameterivARB(shader->vertex, GL_OBJECT_COMPILE_STATUS_ARB, &status);
+
+ if (!status) {
+ glGetInfoLogARB(shader->vertex, sizeof(log), &length, log);
+ shader_print_errors("compile", log, vertexcode);
+
+ GPU_shader_free(shader);
+ return NULL;
+ }
+ }
+
+ if(fragcode) {
+ count = 0;
+ if(libcode) fragsource[count++] = libcode;
+ if(fragcode) fragsource[count++] = fragcode;
+
+ glAttachObjectARB(shader->object, shader->fragment);
+ glShaderSourceARB(shader->fragment, count, fragsource, NULL);
+
+ glCompileShaderARB(shader->fragment);
+ glGetObjectParameterivARB(shader->fragment, GL_OBJECT_COMPILE_STATUS_ARB, &status);
+
+ if (!status) {
+ glGetInfoLogARB(shader->fragment, sizeof(log), &length, log);
+ shader_print_errors("compile", log, fragcode);
+
+ GPU_shader_free(shader);
+ return NULL;
+ }
+ }
+
+ /*if(lib && lib->lib)
+ glAttachObjectARB(shader->object, lib->lib);*/
+
+ glLinkProgramARB(shader->object);
+ glGetObjectParameterivARB(shader->object, GL_OBJECT_LINK_STATUS_ARB, &status);
+ if (!status) {
+ glGetInfoLogARB(shader->object, sizeof(log), &length, log);
+ shader_print_errors("linking", log, fragcode);
+
+ GPU_shader_free(shader);
+ return NULL;
+ }
+
+ return shader;
+}
+
+#if 0
+GPUShader *GPU_shader_create_lib(const char *code)
+{
+ GLint status;
+ GLcharARB log[5000];
+ GLsizei length = 0;
+ GPUShader *shader;
+
+ if (!GLEW_ARB_vertex_shader || !GLEW_ARB_fragment_shader)
+ return NULL;
+
+ shader = MEM_callocN(sizeof(GPUShader), "GPUShader");
+
+ shader->lib = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
+
+ if (!shader->lib) {
+ fprintf(stderr, "GPUShader, object creation failed.\n");
+ GPU_shader_free(shader);
+ return NULL;
+ }
+
+ glShaderSourceARB(shader->lib, 1, (const char**)&code, NULL);
+
+ glCompileShaderARB(shader->lib);
+ glGetObjectParameterivARB(shader->lib, GL_OBJECT_COMPILE_STATUS_ARB, &status);
+
+ if (!status) {
+ glGetInfoLogARB(shader->lib, sizeof(log), &length, log);
+ shader_print_errors("compile", log, code);
+
+ GPU_shader_free(shader);
+ return NULL;
+ }
+
+ return shader;
+}
+#endif
+
+void GPU_shader_bind(GPUShader *shader)
+{
+ GPU_print_error("Pre Shader Bind");
+ glUseProgramObjectARB(shader->object);
+ GPU_print_error("Post Shader Bind");
+}
+
+void GPU_shader_unbind()
+{
+ GPU_print_error("Pre Shader Unbind");
+ glUseProgramObjectARB(0);
+ GPU_print_error("Post Shader Unbind");
+}
+
+void GPU_shader_free(GPUShader *shader)
+{
+ if (shader->lib)
+ glDeleteObjectARB(shader->lib);
+ if (shader->vertex)
+ glDeleteObjectARB(shader->vertex);
+ if (shader->fragment)
+ glDeleteObjectARB(shader->fragment);
+ if (shader->object)
+ glDeleteObjectARB(shader->object);
+ MEM_freeN(shader);
+}
+
+int GPU_shader_get_uniform(GPUShader *shader, char *name)
+{
+ return glGetUniformLocationARB(shader->object, name);
+}
+
+void GPU_shader_uniform_vector(GPUShader *shader, int location, int length, int arraysize, float *value)
+{
+ if(location == -1)
+ return;
+
+ GPU_print_error("Pre Uniform Vector");
+
+ if (length == 1) glUniform1fvARB(location, arraysize, value);
+ else if (length == 2) glUniform2fvARB(location, arraysize, value);
+ else if (length == 3) glUniform3fvARB(location, arraysize, value);
+ else if (length == 4) glUniform4fvARB(location, arraysize, value);
+ else if (length == 9) glUniformMatrix3fvARB(location, arraysize, 0, value);
+ else if (length == 16) glUniformMatrix4fvARB(location, arraysize, 0, value);
+
+ GPU_print_error("Post Uniform Vector");
+}
+
+void GPU_shader_uniform_texture(GPUShader *shader, int location, GPUTexture *tex)
+{
+ GLenum arbnumber;
+
+ if (tex->number >= GG.maxtextures) {
+ GPU_print_error("Not enough texture slots.");
+ return;
+ }
+
+ if(tex->number == -1)
+ return;
+
+ if(location == -1)
+ return;
+
+ GPU_print_error("Pre Uniform Texture");
+
+ arbnumber = (GLenum)((GLuint)GL_TEXTURE0_ARB + tex->number);
+
+ if (tex->number != 0) glActiveTextureARB(arbnumber);
+ glBindTexture(tex->target, tex->bindcode);
+ glUniform1iARB(location, tex->number);
+ glEnable(tex->target);
+ if (tex->number != 0) glActiveTextureARB(GL_TEXTURE0_ARB);
+
+ GPU_print_error("Post Uniform Texture");
+}
+
+int GPU_shader_get_attribute(GPUShader *shader, char *name)
+{
+ int index;
+
+ GPU_print_error("Pre Get Attribute");
+
+ index = glGetAttribLocationARB(shader->object, name);
+
+ GPU_print_error("Post Get Attribute");
+
+ return index;
+}
+
+#if 0
+/* GPUPixelBuffer */
+
+typedef struct GPUPixelBuffer {
+ GLuint bindcode[2];
+ GLuint current;
+ int datasize;
+ int numbuffers;
+ int halffloat;
+} GPUPixelBuffer;
+
+void GPU_pixelbuffer_free(GPUPixelBuffer *pb)
+{
+ if (pb->bindcode[0])
+ glDeleteBuffersARB(pb->numbuffers, pb->bindcode);
+ MEM_freeN(pb);
+}
+
+GPUPixelBuffer *gpu_pixelbuffer_create(int x, int y, int halffloat, int numbuffers)
+{
+ GPUPixelBuffer *pb;
+
+ if (!GLEW_ARB_multitexture || !GLEW_EXT_pixel_buffer_object)
+ return NULL;
+
+ pb = MEM_callocN(sizeof(GPUPixelBuffer), "GPUPBO");
+ pb->datasize = x*y*4*((halffloat)? 16: 8);
+ pb->numbuffers = numbuffers;
+ pb->halffloat = halffloat;
+
+ glGenBuffersARB(pb->numbuffers, pb->bindcode);
+
+ if (!pb->bindcode[0]) {
+ fprintf(stderr, "GPUPixelBuffer allocation failed\n");
+ GPU_pixelbuffer_free(pb);
+ return NULL;
+ }
+
+ return pb;
+}
+
+void GPU_pixelbuffer_texture(GPUTexture *tex, GPUPixelBuffer *pb)
+{
+ void *pixels;
+ int i;
+
+ glBindTexture(GL_TEXTURE_RECTANGLE_EXT, tex->bindcode);
+
+ for (i = 0; i < pb->numbuffers; i++) {
+ glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT, pb->bindcode[pb->current]);
+ glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_EXT, pb->datasize, NULL,
+ GL_STREAM_DRAW_ARB);
+
+ pixels = glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT, GL_WRITE_ONLY);
+ /*memcpy(pixels, _oImage.data(), pb->datasize);*/
+
+ if (!glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT)) {
+ fprintf(stderr, "Could not unmap opengl PBO\n");
+ break;
+ }
+ }
+
+ glBindTexture(GL_TEXTURE_RECTANGLE_EXT, 0);
+}
+
+static int pixelbuffer_map_into_gpu(GLuint bindcode)
+{
+ void *pixels;
+
+ glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT, bindcode);
+ pixels = glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT, GL_WRITE_ONLY);
+
+ /* do stuff in pixels */
+
+ if (!glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT)) {
+ fprintf(stderr, "Could not unmap opengl PBO\n");
+ return 0;
+ }
+
+ return 1;
+}
+
+static void pixelbuffer_copy_to_texture(GPUTexture *tex, GPUPixelBuffer *pb, GLuint bindcode)
+{
+ GLenum type = (pb->halffloat)? GL_HALF_FLOAT_NV: GL_UNSIGNED_BYTE;
+ glBindTexture(GL_TEXTURE_RECTANGLE_EXT, tex->bindcode);
+ glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT, bindcode);
+
+ glTexSubImage2D(GL_TEXTURE_RECTANGLE_EXT, 0, 0, 0, tex->w, tex->h,
+ GL_RGBA, type, NULL);
+
+ glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT, 0);
+ glBindTexture(GL_TEXTURE_RECTANGLE_EXT, 0);
+}
+
+void GPU_pixelbuffer_async_to_gpu(GPUTexture *tex, GPUPixelBuffer *pb)
+{
+ int newbuffer;
+
+ if (pb->numbuffers == 1) {
+ pixelbuffer_copy_to_texture(tex, pb, pb->bindcode[0]);
+ pixelbuffer_map_into_gpu(pb->bindcode[0]);
+ }
+ else {
+ pb->current = (pb->current+1)%pb->numbuffers;
+ newbuffer = (pb->current+1)%pb->numbuffers;
+
+ pixelbuffer_map_into_gpu(pb->bindcode[newbuffer]);
+ pixelbuffer_copy_to_texture(tex, pb, pb->bindcode[pb->current]);
+ }
+}
+#endif
+
diff --git a/source/blender/gpu/intern/gpu_material.c b/source/blender/gpu/intern/gpu_material.c
new file mode 100644
index 00000000000..46df003cbbc
--- /dev/null
+++ b/source/blender/gpu/intern/gpu_material.c
@@ -0,0 +1,1502 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2006 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Brecht Van Lommel.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include <math.h>
+#include <string.h>
+
+#include "GL/glew.h"
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_image_types.h"
+#include "DNA_lamp_types.h"
+#include "DNA_listBase.h"
+#include "DNA_material_types.h"
+#include "DNA_object_types.h"
+#include "DNA_scene_types.h"
+#include "DNA_texture_types.h"
+#include "DNA_view3d_types.h"
+#include "DNA_world_types.h"
+
+#include "BKE_anim.h"
+#include "BKE_colortools.h"
+#include "BKE_DerivedMesh.h"
+#include "BKE_global.h"
+#include "BKE_main.h"
+#include "BKE_node.h"
+#include "BKE_scene.h"
+#include "BKE_texture.h"
+#include "BKE_utildefines.h"
+
+#include "BLI_arithb.h"
+#include "BLI_blenlib.h"
+
+#include "GPU_extensions.h"
+#include "GPU_material.h"
+
+#include "gpu_codegen.h"
+
+#include <string.h>
+
+/* Structs */
+
+typedef enum DynMatProperty {
+ DYN_LAMP_CO = 1,
+ DYN_LAMP_VEC = 2,
+ DYN_LAMP_IMAT = 4,
+ DYN_LAMP_PERSMAT = 8,
+} DynMatProperty;
+
+struct GPUMaterial {
+ Scene *scene;
+ Material *ma;
+
+ /* for creating the material */
+ ListBase nodes;
+ GPUNodeLink *outlink;
+
+ /* for binding the material */
+ GPUPass *pass;
+ GPUVertexAttribs attribs;
+ int bound;
+ int builtins;
+ int alpha, obcolalpha;
+ int dynproperty;
+
+ /* for passing uniforms */
+ int viewmatloc, invviewmatloc;
+ int obmatloc, invobmatloc;
+ int obcolloc;
+
+ ListBase lamps;
+};
+
+struct GPULamp {
+ Scene *scene;
+ Object *ob;
+ Object *par;
+ Lamp *la;
+
+ int type, mode, lay;
+
+ float dynenergy, dyncol[3];
+ float energy, col[3];
+
+ float co[3], vec[3];
+ float dynco[3], dynvec[3];
+ float obmat[4][4];
+ float imat[4][4];
+ float dynimat[4][4];
+
+ float spotsi, spotbl, k;
+ float dist, att1, att2;
+
+ float bias, d, clipend;
+ int size;
+
+ int falloff_type;
+ struct CurveMapping *curfalloff;
+
+ float winmat[4][4];
+ float viewmat[4][4];
+ float persmat[4][4];
+ float dynpersmat[4][4];
+
+ GPUFrameBuffer *fb;
+ GPUTexture *tex;
+
+ ListBase materials;
+};
+
+/* Functions */
+
+static GPUMaterial *GPU_material_construct_begin(Material *ma)
+{
+ GPUMaterial *material = MEM_callocN(sizeof(GPUMaterial), "GPUMaterial");
+
+ material->ma= ma;
+
+ return material;
+}
+
+static void gpu_material_set_attrib_id(GPUMaterial *material)
+{
+ GPUVertexAttribs *attribs;
+ GPUShader *shader;
+ GPUPass *pass;
+ char name[32];
+ int a, b;
+
+ attribs= &material->attribs;
+ pass= material->pass;
+ if(!pass) {
+ attribs->totlayer = 0;
+ return;
+ }
+
+ shader= GPU_pass_shader(pass);
+ if(!shader) {
+ attribs->totlayer = 0;
+ return;
+ }
+
+ /* convert from attribute number to the actual id assigned by opengl,
+ * in case the attrib does not get a valid index back, it was probably
+ * removed by the glsl compiler by dead code elimination */
+
+ for(a=0, b=0; a<attribs->totlayer; a++) {
+ sprintf(name, "att%d", attribs->layer[a].glindex);
+ attribs->layer[a].glindex = GPU_shader_get_attribute(shader, name);
+
+ if(attribs->layer[a].glindex >= 0) {
+ attribs->layer[b] = attribs->layer[a];
+ b++;
+ }
+ }
+
+ attribs->totlayer = b;
+}
+
+static int GPU_material_construct_end(GPUMaterial *material)
+{
+ if (material->outlink) {
+ GPUNodeLink *outlink;
+ GPUShader *shader;
+
+ outlink = material->outlink;
+ material->pass = GPU_generate_pass(&material->nodes, outlink,
+ &material->attribs, &material->builtins, material->ma->id.name);
+
+ if(!material->pass)
+ return 0;
+
+ gpu_material_set_attrib_id(material);
+
+ shader = GPU_pass_shader(material->pass);
+
+ if(material->builtins & GPU_VIEW_MATRIX)
+ material->viewmatloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_VIEW_MATRIX));
+ if(material->builtins & GPU_INVERSE_VIEW_MATRIX)
+ material->invviewmatloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_INVERSE_VIEW_MATRIX));
+ if(material->builtins & GPU_OBJECT_MATRIX)
+ material->obmatloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_OBJECT_MATRIX));
+ if(material->builtins & GPU_INVERSE_OBJECT_MATRIX)
+ material->invobmatloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_INVERSE_OBJECT_MATRIX));
+ if(material->builtins & GPU_OBCOLOR)
+ material->obcolloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_OBCOLOR));
+
+ return 1;
+ }
+
+ return 0;
+}
+
+void GPU_material_free(Material *ma)
+{
+ LinkData *link;
+ LinkData *nlink, *mlink, *next;
+
+ for(link=ma->gpumaterial.first; link; link=link->next) {
+ GPUMaterial *material = link->data;
+
+ if(material->pass)
+ GPU_pass_free(material->pass);
+
+ for(nlink=material->lamps.first; nlink; nlink=nlink->next) {
+ GPULamp *lamp = nlink->data;
+
+ for(mlink=lamp->materials.first; mlink; mlink=next) {
+ next = mlink->next;
+ if(mlink->data == ma)
+ BLI_freelinkN(&lamp->materials, mlink);
+ }
+ }
+
+ BLI_freelistN(&material->lamps);
+
+ MEM_freeN(material);
+ }
+
+ BLI_freelistN(&ma->gpumaterial);
+}
+
+void GPU_material_bind(GPUMaterial *material, int oblay, int viewlay, double time)
+{
+ if(material->pass) {
+ LinkData *nlink;
+ GPULamp *lamp;
+
+ /* handle layer lamps */
+ for(nlink=material->lamps.first; nlink; nlink=nlink->next) {
+ lamp= nlink->data;
+
+ if((lamp->lay & viewlay) && (!(lamp->mode & LA_LAYER) || (lamp->lay & oblay))) {
+ lamp->dynenergy = lamp->energy;
+ VECCOPY(lamp->dyncol, lamp->col);
+ }
+ else {
+ lamp->dynenergy = 0.0f;
+ lamp->dyncol[0]= lamp->dyncol[1]= lamp->dyncol[2] = 0.0f;
+ }
+ }
+
+ GPU_pass_bind(material->pass, time);
+ material->bound = 1;
+ }
+}
+
+void GPU_material_bind_uniforms(GPUMaterial *material, float obmat[][4], float viewmat[][4], float viewinv[][4], float obcol[4])
+{
+ if(material->pass) {
+ GPUShader *shader = GPU_pass_shader(material->pass);
+ LinkData *nlink;
+ GPULamp *lamp;
+ float invmat[4][4], col[4];
+
+ /* handle builtins */
+ if(material->builtins & GPU_VIEW_MATRIX) {
+ GPU_shader_uniform_vector(shader, material->viewmatloc, 16, 1, (float*)viewmat);
+ }
+ if(material->builtins & GPU_INVERSE_VIEW_MATRIX) {
+ GPU_shader_uniform_vector(shader, material->invviewmatloc, 16, 1, (float*)viewinv);
+ }
+ if(material->builtins & GPU_OBJECT_MATRIX) {
+ GPU_shader_uniform_vector(shader, material->obmatloc, 16, 1, (float*)obmat);
+ }
+ if(material->builtins & GPU_INVERSE_OBJECT_MATRIX) {
+ Mat4Invert(invmat, obmat);
+ GPU_shader_uniform_vector(shader, material->invobmatloc, 16, 1, (float*)invmat);
+ }
+ if(material->builtins & GPU_OBCOLOR) {
+ QUATCOPY(col, obcol);
+ CLAMP(col[3], 0.0f, 1.0f);
+ GPU_shader_uniform_vector(shader, material->obcolloc, 4, 1, col);
+ }
+
+ /* update lamps */
+ for(nlink=material->lamps.first; nlink; nlink=nlink->next) {
+ lamp= nlink->data;
+
+ if(material->dynproperty & DYN_LAMP_VEC) {
+ VECCOPY(lamp->dynvec, lamp->vec);
+ Normalize(lamp->dynvec);
+ VecMulf(lamp->dynvec, -1.0f);
+ Mat4Mul3Vecfl(viewmat, lamp->dynvec);
+ }
+
+ if(material->dynproperty & DYN_LAMP_CO) {
+ VECCOPY(lamp->dynco, lamp->co);
+ Mat4MulVecfl(viewmat, lamp->dynco);
+ }
+
+ if(material->dynproperty & DYN_LAMP_IMAT)
+ Mat4MulMat4(lamp->dynimat, viewinv, lamp->imat);
+ if(material->dynproperty & DYN_LAMP_PERSMAT)
+ Mat4MulMat4(lamp->dynpersmat, viewinv, lamp->persmat);
+ }
+
+ GPU_pass_update_uniforms(material->pass);
+ }
+}
+
+void GPU_material_unbind(GPUMaterial *material)
+{
+ if (material->pass) {
+ material->bound = 0;
+ GPU_pass_unbind(material->pass);
+ }
+}
+
+int GPU_material_bound(GPUMaterial *material)
+{
+ return material->bound;
+}
+
+void GPU_material_vertex_attributes(GPUMaterial *material, GPUVertexAttribs *attribs)
+{
+ *attribs = material->attribs;
+}
+
+void GPU_material_output_link(GPUMaterial *material, GPUNodeLink *link)
+{
+ if(!material->outlink)
+ material->outlink= link;
+}
+
+void GPU_material_enable_alpha(GPUMaterial *material)
+{
+ material->alpha= 1;
+}
+
+GPUBlendMode GPU_material_blend_mode(GPUMaterial *material, float obcol[3])
+{
+ if(material->alpha || (material->obcolalpha && obcol[3] < 1.0f))
+ return GPU_BLEND_ALPHA;
+ else
+ return GPU_BLEND_SOLID;
+}
+
+void gpu_material_add_node(GPUMaterial *material, GPUNode *node)
+{
+ BLI_addtail(&material->nodes, node);
+}
+
+/* Code generation */
+
+static GPUNodeLink *lamp_get_visibility(GPUMaterial *mat, GPULamp *lamp, GPUNodeLink **lv, GPUNodeLink **dist)
+{
+ GPUNodeLink *visifac, *inpr;
+
+ /* from get_lamp_visibility */
+ if(lamp->type==LA_SUN || lamp->type==LA_HEMI) {
+ mat->dynproperty |= DYN_LAMP_VEC;
+ GPU_link(mat, "lamp_visibility_sun_hemi", GPU_dynamic_uniform(lamp->dynvec), lv, dist, &visifac);
+ return visifac;
+ }
+ else {
+ mat->dynproperty |= DYN_LAMP_CO;
+ GPU_link(mat, "lamp_visibility_other", GPU_builtin(GPU_VIEW_POSITION), GPU_dynamic_uniform(lamp->dynco), lv, dist, &visifac);
+
+ if(lamp->type==LA_AREA)
+ return visifac;
+
+ switch(lamp->falloff_type)
+ {
+ case LA_FALLOFF_CONSTANT:
+ break;
+ case LA_FALLOFF_INVLINEAR:
+ GPU_link(mat, "lamp_falloff_invlinear", GPU_uniform(&lamp->dist), *dist, &visifac);
+ break;
+ case LA_FALLOFF_INVSQUARE:
+ GPU_link(mat, "lamp_falloff_invsquare", GPU_uniform(&lamp->dist), *dist, &visifac);
+ break;
+ case LA_FALLOFF_SLIDERS:
+ GPU_link(mat, "lamp_falloff_sliders", GPU_uniform(&lamp->dist), GPU_uniform(&lamp->att1), GPU_uniform(&lamp->att2), *dist, &visifac);
+ break;
+ case LA_FALLOFF_CURVE:
+ {
+ float *array;
+ int size;
+
+ curvemapping_table_RGBA(lamp->curfalloff, &array, &size);
+ GPU_link(mat, "lamp_falloff_curve", GPU_uniform(&lamp->dist), GPU_texture(size, array), *dist, &visifac);
+ }
+ break;
+ }
+
+ if(lamp->mode & LA_SPHERE)
+ GPU_link(mat, "lamp_visibility_sphere", GPU_uniform(&lamp->dist), *dist, visifac, &visifac);
+
+ if(lamp->type == LA_SPOT) {
+ if(lamp->mode & LA_SQUARE) {
+ mat->dynproperty |= DYN_LAMP_VEC|DYN_LAMP_IMAT;
+ GPU_link(mat, "lamp_visibility_spot_square", GPU_dynamic_uniform(lamp->dynvec), GPU_dynamic_uniform((float*)lamp->dynimat), *lv, &inpr);
+ }
+ else {
+ mat->dynproperty |= DYN_LAMP_VEC;
+ GPU_link(mat, "lamp_visibility_spot_circle", GPU_dynamic_uniform(lamp->dynvec), *lv, &inpr);
+ }
+
+ GPU_link(mat, "lamp_visibility_spot", GPU_uniform(&lamp->spotsi), GPU_uniform(&lamp->spotbl), inpr, visifac, &visifac);
+ }
+
+ GPU_link(mat, "lamp_visibility_clamp", visifac, &visifac);
+
+ return visifac;
+ }
+}
+
+#if 0
+static void area_lamp_vectors(LampRen *lar)
+{
+ float xsize= 0.5*lar->area_size, ysize= 0.5*lar->area_sizey, multifac;
+
+ /* make it smaller, so area light can be multisampled */
+ multifac= 1.0f/sqrt((float)lar->ray_totsamp);
+ xsize *= multifac;
+ ysize *= multifac;
+
+ /* corner vectors */
+ lar->area[0][0]= lar->co[0] - xsize*lar->mat[0][0] - ysize*lar->mat[1][0];
+ lar->area[0][1]= lar->co[1] - xsize*lar->mat[0][1] - ysize*lar->mat[1][1];
+ lar->area[0][2]= lar->co[2] - xsize*lar->mat[0][2] - ysize*lar->mat[1][2];
+
+ /* corner vectors */
+ lar->area[1][0]= lar->co[0] - xsize*lar->mat[0][0] + ysize*lar->mat[1][0];
+ lar->area[1][1]= lar->co[1] - xsize*lar->mat[0][1] + ysize*lar->mat[1][1];
+ lar->area[1][2]= lar->co[2] - xsize*lar->mat[0][2] + ysize*lar->mat[1][2];
+
+ /* corner vectors */
+ lar->area[2][0]= lar->co[0] + xsize*lar->mat[0][0] + ysize*lar->mat[1][0];
+ lar->area[2][1]= lar->co[1] + xsize*lar->mat[0][1] + ysize*lar->mat[1][1];
+ lar->area[2][2]= lar->co[2] + xsize*lar->mat[0][2] + ysize*lar->mat[1][2];
+
+ /* corner vectors */
+ lar->area[3][0]= lar->co[0] + xsize*lar->mat[0][0] - ysize*lar->mat[1][0];
+ lar->area[3][1]= lar->co[1] + xsize*lar->mat[0][1] - ysize*lar->mat[1][1];
+ lar->area[3][2]= lar->co[2] + xsize*lar->mat[0][2] - ysize*lar->mat[1][2];
+ /* only for correction button size, matrix size works on energy */
+ lar->areasize= lar->dist*lar->dist/(4.0*xsize*ysize);
+}
+#endif
+
+static void ramp_blend(GPUMaterial *mat, GPUNodeLink *fac, GPUNodeLink *col1, GPUNodeLink *col2, int type, GPUNodeLink **outcol)
+{
+ static char *names[] = {"mix_blend", "mix_add", "mix_mult", "mix_sub",
+ "mix_screen", "mix_div", "mix_diff", "mix_dark", "mix_light",
+ "mix_overlay", "mix_dodge", "mix_burn", "mix_hue", "mix_sat",
+ "mix_val", "mix_color"};
+
+ GPU_link(mat, names[type], fac, col1, col2, outcol);
+}
+
+static void do_colorband_blend(GPUMaterial *mat, ColorBand *coba, GPUNodeLink *fac, float rampfac, int type, GPUNodeLink *incol, GPUNodeLink **outcol)
+{
+ GPUNodeLink *tmp, *alpha, *col;
+ float *array;
+ int size;
+
+ /* do colorband */
+ colorband_table_RGBA(coba, &array, &size);
+ GPU_link(mat, "valtorgb", fac, GPU_texture(size, array), &col, &tmp);
+
+ /* use alpha in fac */
+ GPU_link(mat, "mtex_alpha_from_col", col, &alpha);
+ GPU_link(mat, "math_multiply", alpha, GPU_uniform(&rampfac), &fac);
+
+ /* blending method */
+ ramp_blend(mat, fac, incol, col, type, outcol);
+}
+
+static void ramp_diffuse_result(GPUShadeInput *shi, GPUNodeLink **diff)
+{
+ Material *ma= shi->mat;
+ GPUMaterial *mat= shi->gpumat;
+ GPUNodeLink *fac;
+
+ if(!(G.fileflags & G_FILE_GLSL_NO_RAMPS)) {
+ if(ma->ramp_col) {
+ if(ma->rampin_col==MA_RAMP_IN_RESULT) {
+ GPU_link(mat, "ramp_rgbtobw", *diff, &fac);
+
+ /* colorband + blend */
+ do_colorband_blend(mat, ma->ramp_col, fac, ma->rampfac_col, ma->rampblend_col, *diff, diff);
+ }
+ }
+ }
+}
+
+static void add_to_diffuse(GPUMaterial *mat, Material *ma, GPUShadeInput *shi, GPUNodeLink *is, GPUNodeLink *rgb, GPUNodeLink **diff)
+{
+ GPUNodeLink *fac, *tmp, *addcol;
+
+ if(!(G.fileflags & G_FILE_GLSL_NO_RAMPS) &&
+ ma->ramp_col && (ma->mode & MA_RAMP_COL)) {
+ /* MA_RAMP_IN_RESULT is exceptional */
+ if(ma->rampin_col==MA_RAMP_IN_RESULT) {
+ addcol = shi->rgb;
+ }
+ else {
+ /* input */
+ switch(ma->rampin_col) {
+ case MA_RAMP_IN_ENERGY:
+ GPU_link(mat, "ramp_rgbtobw", rgb, &fac);
+ break;
+ case MA_RAMP_IN_SHADER:
+ fac= is;
+ break;
+ case MA_RAMP_IN_NOR:
+ GPU_link(mat, "vec_math_dot", shi->view, shi->vn, &tmp, &fac);
+ break;
+ default:
+ GPU_link(mat, "set_value_zero", &fac);
+ break;
+ }
+
+ /* colorband + blend */
+ do_colorband_blend(mat, ma->ramp_col, fac, ma->rampfac_col, ma->rampblend_col, shi->rgb, &addcol);
+ }
+ }
+ else
+ addcol = shi->rgb;
+
+ /* output to */
+ GPU_link(mat, "shade_madd", *diff, rgb, addcol, diff);
+}
+
+static void ramp_spec_result(GPUShadeInput *shi, GPUNodeLink **spec)
+{
+ Material *ma= shi->mat;
+ GPUMaterial *mat= shi->gpumat;
+ GPUNodeLink *fac;
+
+ if(!(G.fileflags & G_FILE_GLSL_NO_RAMPS) &&
+ ma->ramp_spec && ma->rampin_spec==MA_RAMP_IN_RESULT) {
+ GPU_link(mat, "ramp_rgbtobw", *spec, &fac);
+
+ /* colorband + blend */
+ do_colorband_blend(mat, ma->ramp_spec, fac, ma->rampfac_spec, ma->rampblend_spec, *spec, spec);
+ }
+}
+
+static void do_specular_ramp(GPUShadeInput *shi, GPUNodeLink *is, GPUNodeLink *t, GPUNodeLink **spec)
+{
+ Material *ma= shi->mat;
+ GPUMaterial *mat= shi->gpumat;
+ GPUNodeLink *fac, *tmp;
+
+ *spec = shi->specrgb;
+
+ /* MA_RAMP_IN_RESULT is exception */
+ if(ma->ramp_spec && (ma->rampin_spec!=MA_RAMP_IN_RESULT)) {
+
+ /* input */
+ switch(ma->rampin_spec) {
+ case MA_RAMP_IN_ENERGY:
+ fac = t;
+ break;
+ case MA_RAMP_IN_SHADER:
+ fac = is;
+ break;
+ case MA_RAMP_IN_NOR:
+ GPU_link(mat, "vec_math_dot", shi->view, shi->vn, &tmp, &fac);
+ break;
+ default:
+ GPU_link(mat, "set_value_zero", &fac);
+ break;
+ }
+
+ /* colorband + blend */
+ do_colorband_blend(mat, ma->ramp_spec, fac, ma->rampfac_spec, ma->rampblend_spec, *spec, spec);
+ }
+}
+
+void add_user_list(ListBase *list, void *data)
+{
+ LinkData *link = MEM_callocN(sizeof(LinkData), "GPULinkData");
+ link->data = data;
+ BLI_addtail(list, link);
+}
+
+static void shade_one_light(GPUShadeInput *shi, GPUShadeResult *shr, GPULamp *lamp)
+{
+ Material *ma= shi->mat;
+ GPUMaterial *mat= shi->gpumat;
+ GPUNodeLink *lv, *dist, *visifac, *is, *inp, *i, *vn, *view;
+ GPUNodeLink *outcol, *specfac, *t, *shadfac;
+ float one = 1.0f;
+
+ if((lamp->mode & LA_ONLYSHADOW) && !(ma->mode & MA_SHADOW))
+ return;
+
+ vn= shi->vn;
+ view= shi->view;
+
+ visifac= lamp_get_visibility(mat, lamp, &lv, &dist);
+
+ /*if(ma->mode & MA_TANGENT_V)
+ GPU_link(mat, "shade_tangent_v", lv, GPU_attribute(CD_TANGENT, ""), &vn);*/
+
+ GPU_link(mat, "shade_inp", vn, lv, &inp);
+
+ if(lamp->mode & LA_NO_DIFF) {
+ GPU_link(mat, "shade_is_no_diffuse", &is);
+ }
+ else if(lamp->type == LA_HEMI) {
+ GPU_link(mat, "shade_is_hemi", inp, &is);
+ }
+ else {
+ if(lamp->type == LA_AREA) {
+ float area[4][4], areasize;
+
+ memset(&area, 0, sizeof(area));
+ memset(&areasize, 0, sizeof(areasize));
+ mat->dynproperty |= DYN_LAMP_VEC|DYN_LAMP_CO;
+ GPU_link(mat, "shade_inp_area", GPU_builtin(GPU_VIEW_POSITION), GPU_dynamic_uniform(lamp->dynco), GPU_dynamic_uniform(lamp->dynvec), vn, GPU_uniform((float*)area),
+ GPU_uniform(&areasize), GPU_uniform(&lamp->k), &inp);
+ }
+
+ is= inp; /* Lambert */
+
+ if(!(G.fileflags & G_FILE_GLSL_NO_SHADERS)) {
+ if(ma->diff_shader==MA_DIFF_ORENNAYAR)
+ GPU_link(mat, "shade_diffuse_oren_nayer", inp, vn, lv, view, GPU_uniform(&ma->roughness), &is);
+ else if(ma->diff_shader==MA_DIFF_TOON)
+ GPU_link(mat, "shade_diffuse_toon", vn, lv, view, GPU_uniform(&ma->param[0]), GPU_uniform(&ma->param[1]), &is);
+ else if(ma->diff_shader==MA_DIFF_MINNAERT)
+ GPU_link(mat, "shade_diffuse_minnaert", inp, vn, view, GPU_uniform(&ma->darkness), &is);
+ else if(ma->diff_shader==MA_DIFF_FRESNEL)
+ GPU_link(mat, "shade_diffuse_fresnel", vn, lv, view, GPU_uniform(&ma->param[0]), GPU_uniform(&ma->param[1]), &is);
+ }
+ }
+
+ if(!(G.fileflags & G_FILE_GLSL_NO_SHADERS))
+ if(ma->shade_flag & MA_CUBIC)
+ GPU_link(mat, "shade_cubic", is, &is);
+
+ i = is;
+ GPU_link(mat, "shade_visifac", i, visifac, shi->refl, &i);
+
+ vn = shi->vn;
+ /*if(ma->mode & MA_TANGENT_VN)
+ GPU_link(mat, "shade_tangent_v_spec", GPU_attribute(CD_TANGENT, ""), &vn);*/
+
+ /* this replaces if(i > 0.0) conditional until that is supported */
+ // done in shade_visifac now, GPU_link(mat, "mtex_value_clamp_positive", i, &i);
+
+ if((ma->mode & MA_SHADOW) && GPU_lamp_has_shadow_buffer(lamp)) {
+ if(!(G.fileflags & G_FILE_GLSL_NO_SHADOWS)) {
+ mat->dynproperty |= DYN_LAMP_PERSMAT;
+
+ GPU_link(mat, "test_shadowbuf",
+ GPU_builtin(GPU_VIEW_POSITION),
+ GPU_dynamic_texture(lamp->tex),
+ GPU_dynamic_uniform((float*)lamp->dynpersmat),
+ GPU_uniform(&lamp->bias), inp, &shadfac);
+
+ if(lamp->mode & LA_ONLYSHADOW) {
+ GPU_link(mat, "shade_only_shadow", i, shadfac,
+ GPU_dynamic_uniform(&lamp->dynenergy), &shadfac);
+
+ if(!(lamp->mode & LA_NO_DIFF))
+ GPU_link(mat, "shade_only_shadow_diffuse", shadfac, shi->rgb,
+ shr->diff, &shr->diff);
+
+ if(!(lamp->mode & LA_NO_SPEC))
+ GPU_link(mat, "shade_only_shadow_specular", shadfac, shi->specrgb,
+ shr->spec, &shr->spec);
+
+ add_user_list(&mat->lamps, lamp);
+ add_user_list(&lamp->materials, shi->gpumat->ma);
+ return;
+ }
+
+ GPU_link(mat, "math_multiply", i, shadfac, &i);
+ }
+ }
+ else if((G.fileflags & G_FILE_GLSL_NO_SHADOWS) && (lamp->mode & LA_ONLYSHADOW)) {
+ add_user_list(&mat->lamps, lamp);
+ add_user_list(&lamp->materials, shi->gpumat->ma);
+ return;
+ }
+ else
+ GPU_link(mat, "set_value", GPU_uniform(&one), &shadfac);
+
+ if(GPU_link_changed(shi->refl) || ma->ref != 0.0f) {
+ if(!(lamp->mode & LA_NO_DIFF)) {
+ GPUNodeLink *rgb;
+ GPU_link(mat, "shade_mul_value", i, GPU_dynamic_uniform(lamp->dyncol), &rgb);
+ add_to_diffuse(mat, ma, shi, is, rgb, &shr->diff);
+ }
+ }
+
+ if(G.fileflags & G_FILE_GLSL_NO_SHADERS);
+ else if(!(lamp->mode & LA_NO_SPEC) && !(lamp->mode & LA_ONLYSHADOW) &&
+ (GPU_link_changed(shi->spec) || ma->spec != 0.0f)) {
+ if(lamp->type == LA_HEMI) {
+ GPU_link(mat, "shade_hemi_spec", vn, lv, view, GPU_uniform(&ma->spec), shi->har, visifac, &t);
+ GPU_link(mat, "shade_add_spec", t, GPU_dynamic_uniform(lamp->dyncol), shi->specrgb, &outcol);
+ GPU_link(mat, "shade_add", shr->spec, outcol, &shr->spec);
+ }
+ else {
+ if(ma->spec_shader==MA_SPEC_PHONG)
+ GPU_link(mat, "shade_phong_spec", vn, lv, view, shi->har, &specfac);
+ else if(ma->spec_shader==MA_SPEC_COOKTORR)
+ GPU_link(mat, "shade_cooktorr_spec", vn, lv, view, shi->har, &specfac);
+ else if(ma->spec_shader==MA_SPEC_BLINN)
+ GPU_link(mat, "shade_blinn_spec", vn, lv, view, GPU_uniform(&ma->refrac), shi->har, &specfac);
+ else if(ma->spec_shader==MA_SPEC_WARDISO)
+ GPU_link(mat, "shade_wardiso_spec", vn, lv, view, GPU_uniform(&ma->rms), &specfac);
+ else
+ GPU_link(mat, "shade_toon_spec", vn, lv, view, GPU_uniform(&ma->param[2]), GPU_uniform(&ma->param[3]), &specfac);
+
+ if(lamp->type==LA_AREA)
+ GPU_link(mat, "shade_spec_area_inp", specfac, inp, &specfac);
+
+ GPU_link(mat, "shade_spec_t", shadfac, shi->spec, visifac, specfac, &t);
+
+ if(ma->mode & MA_RAMP_SPEC) {
+ GPUNodeLink *spec;
+ do_specular_ramp(shi, specfac, t, &spec);
+ GPU_link(mat, "shade_add_spec", t, GPU_dynamic_uniform(lamp->dyncol), spec, &outcol);
+ GPU_link(mat, "shade_add", shr->spec, outcol, &shr->spec);
+ }
+ else {
+ GPU_link(mat, "shade_add_spec", t, GPU_dynamic_uniform(lamp->dyncol), shi->specrgb, &outcol);
+ GPU_link(mat, "shade_add", shr->spec, outcol, &shr->spec);
+ }
+ }
+ }
+
+ add_user_list(&mat->lamps, lamp);
+ add_user_list(&lamp->materials, shi->gpumat->ma);
+}
+
+static void material_lights(GPUShadeInput *shi, GPUShadeResult *shr)
+{
+ Base *base;
+ Object *ob;
+ Scene *sce;
+ GPULamp *lamp;
+
+ for(SETLOOPER(shi->gpumat->scene, base)) {
+ ob= base->object;
+
+ if(ob->type==OB_LAMP) {
+ lamp = GPU_lamp_from_blender(shi->gpumat->scene, ob, NULL);
+ if(lamp)
+ shade_one_light(shi, shr, lamp);
+ }
+
+ if (ob->transflag & OB_DUPLI) {
+ DupliObject *dob;
+ ListBase *lb = object_duplilist(shi->gpumat->scene, ob);
+
+ for(dob=lb->first; dob; dob=dob->next) {
+ Object *ob = dob->ob;
+
+ if(ob->type==OB_LAMP) {
+ Mat4CpyMat4(ob->obmat, dob->mat);
+
+ lamp = GPU_lamp_from_blender(shi->gpumat->scene, ob, base->object);
+ if(lamp)
+ shade_one_light(shi, shr, lamp);
+ }
+ }
+
+ free_object_duplilist(lb);
+ }
+ }
+}
+
+static void texture_rgb_blend(GPUMaterial *mat, GPUNodeLink *tex, GPUNodeLink *out, GPUNodeLink *fact, GPUNodeLink *facg, int blendtype, GPUNodeLink **in)
+{
+ switch(blendtype) {
+ case MTEX_BLEND:
+ GPU_link(mat, "mtex_rgb_blend", out, tex, fact, facg, in);
+ break;
+ case MTEX_MUL:
+ GPU_link(mat, "mtex_rgb_mul", out, tex, fact, facg, in);
+ break;
+ case MTEX_SCREEN:
+ GPU_link(mat, "mtex_rgb_screen", out, tex, fact, facg, in);
+ break;
+ case MTEX_OVERLAY:
+ GPU_link(mat, "mtex_rgb_overlay", out, tex, fact, facg, in);
+ break;
+ case MTEX_SUB:
+ GPU_link(mat, "mtex_rgb_sub", out, tex, fact, facg, in);
+ break;
+ case MTEX_ADD:
+ GPU_link(mat, "mtex_rgb_add", out, tex, fact, facg, in);
+ break;
+ case MTEX_DIV:
+ GPU_link(mat, "mtex_rgb_div", out, tex, fact, facg, in);
+ break;
+ case MTEX_DIFF:
+ GPU_link(mat, "mtex_rgb_diff", out, tex, fact, facg, in);
+ break;
+ case MTEX_DARK:
+ GPU_link(mat, "mtex_rgb_dark", out, tex, fact, facg, in);
+ break;
+ case MTEX_LIGHT:
+ GPU_link(mat, "mtex_rgb_light", out, tex, fact, facg, in);
+ break;
+ case MTEX_BLEND_HUE:
+ GPU_link(mat, "mtex_rgb_hue", out, tex, fact, facg, in);
+ break;
+ case MTEX_BLEND_SAT:
+ GPU_link(mat, "mtex_rgb_sat", out, tex, fact, facg, in);
+ break;
+ case MTEX_BLEND_VAL:
+ GPU_link(mat, "mtex_rgb_val", out, tex, fact, facg, in);
+ break;
+ case MTEX_BLEND_COLOR:
+ GPU_link(mat, "mtex_rgb_color", out, tex, fact, facg, in);
+ break;
+ default:
+ GPU_link(mat, "set_rgb_zero", &in);
+ break;
+ }
+}
+
+static void texture_value_blend(GPUMaterial *mat, GPUNodeLink *tex, GPUNodeLink *out, GPUNodeLink *fact, GPUNodeLink *facg, int blendtype, int flip, GPUNodeLink **in)
+{
+ float flipf = (flip)? 1.0f: 0.0;
+
+ switch(blendtype) {
+ case MTEX_BLEND:
+ GPU_link(mat, "mtex_value_blend", out, tex, fact, facg, GPU_uniform(&flipf), in);
+ break;
+ case MTEX_MUL:
+ GPU_link(mat, "mtex_value_mul", out, tex, fact, facg, GPU_uniform(&flipf), in);
+ break;
+ case MTEX_SCREEN:
+ GPU_link(mat, "mtex_value_screen", out, tex, fact, facg, GPU_uniform(&flipf), in);
+ break;
+ case MTEX_SUB:
+ GPU_link(mat, "mtex_value_sub", out, tex, fact, facg, GPU_uniform(&flipf), in);
+ break;
+ case MTEX_ADD:
+ GPU_link(mat, "mtex_value_add", out, tex, fact, facg, GPU_uniform(&flipf), in);
+ break;
+ case MTEX_DIV:
+ GPU_link(mat, "mtex_value_div", out, tex, fact, facg, GPU_uniform(&flipf), in);
+ break;
+ case MTEX_DIFF:
+ GPU_link(mat, "mtex_value_diff", out, tex, fact, facg, GPU_uniform(&flipf), in);
+ break;
+ case MTEX_DARK:
+ GPU_link(mat, "mtex_value_dark", out, tex, fact, facg, GPU_uniform(&flipf), in);
+ break;
+ case MTEX_LIGHT:
+ GPU_link(mat, "mtex_value_light", out, tex, fact, facg, GPU_uniform(&flipf), in);
+ break;
+ default:
+ GPU_link(mat, "set_value_zero", &in);
+ break;
+ }
+}
+
+static void do_material_tex(GPUShadeInput *shi)
+{
+ Material *ma= shi->mat;
+ GPUMaterial *mat= shi->gpumat;
+ MTex *mtex;
+ Tex *tex;
+ GPUNodeLink *texco, *tin, *trgb, *tnor, *tcol, *stencil, *tnorfac;
+ GPUNodeLink *texco_norm, *texco_orco, *texco_object, *texco_tangent;
+ GPUNodeLink *texco_global, *texco_uv = NULL;
+ GPUNodeLink *colfac, *newnor, *varfac, *orn;
+ char *lastuvname = NULL;
+ float one = 1.0f, norfac, ofs[3];
+ int tex_nr, rgbnor, talpha;
+
+ GPU_link(mat, "set_value", GPU_uniform(&one), &stencil);
+
+ GPU_link(mat, "texco_norm", GPU_builtin(GPU_VIEW_NORMAL), &texco_norm);
+ GPU_link(mat, "texco_orco", GPU_attribute(CD_ORCO, ""), &texco_orco);
+ GPU_link(mat, "texco_object", GPU_builtin(GPU_INVERSE_VIEW_MATRIX),
+ GPU_builtin(GPU_INVERSE_OBJECT_MATRIX),
+ GPU_builtin(GPU_VIEW_POSITION), &texco_object);
+ GPU_link(mat, "texco_tangent", GPU_attribute(CD_TANGENT, ""), &texco_tangent);
+ GPU_link(mat, "texco_global", GPU_builtin(GPU_INVERSE_VIEW_MATRIX),
+ GPU_builtin(GPU_VIEW_POSITION), &texco_global);
+
+ orn= texco_norm;
+
+ /* go over texture slots */
+ for(tex_nr=0; tex_nr<MAX_MTEX; tex_nr++) {
+ /* separate tex switching */
+ if(ma->septex & (1<<tex_nr)) continue;
+
+ if(ma->mtex[tex_nr]) {
+ mtex= ma->mtex[tex_nr];
+
+ tex= mtex->tex;
+ if(tex==0) continue;
+
+ /* which coords */
+ if(mtex->texco==TEXCO_ORCO)
+ texco= texco_orco;
+ else if(mtex->texco==TEXCO_OBJECT)
+ texco= texco_object;
+ else if(mtex->texco==TEXCO_NORM)
+ texco= orn;
+ else if(mtex->texco==TEXCO_TANGENT)
+ texco= texco_object;
+ else if(mtex->texco==TEXCO_GLOB)
+ texco= texco_global;
+ else if(mtex->texco==TEXCO_REFL)
+ texco= shi->ref;
+ else if(mtex->texco==TEXCO_UV) {
+ if(1) { //!(texco_uv && strcmp(mtex->uvname, lastuvname) == 0)) {
+ GPU_link(mat, "texco_uv", GPU_attribute(CD_MTFACE, mtex->uvname), &texco_uv);
+ lastuvname = mtex->uvname;
+ }
+ texco= texco_uv;
+ }
+ else
+ continue;
+
+ /* in case of uv, this would just undo a multiplication in texco_uv */
+ if(mtex->texco != TEXCO_UV)
+ GPU_link(mat, "mtex_2d_mapping", texco, &texco);
+
+ if(mtex->size[0] != 1.0f || mtex->size[1] != 1.0f || mtex->size[2] != 1.0f)
+ GPU_link(mat, "mtex_mapping_size", texco, GPU_uniform(mtex->size), &texco);
+
+ ofs[0] = mtex->ofs[0] + 0.5f - 0.5f*mtex->size[0];
+ ofs[1] = mtex->ofs[1] + 0.5f - 0.5f*mtex->size[1];
+ ofs[2] = 0.0f;
+ if(ofs[0] != 0.0f || ofs[1] != 0.0f || ofs[2] != 0.0f)
+ GPU_link(mat, "mtex_mapping_ofs", texco, GPU_uniform(ofs), &texco);
+
+ talpha = 0;
+ rgbnor = 0;
+
+ if(tex && tex->type == TEX_IMAGE && tex->ima) {
+ GPU_link(mat, "mtex_image", texco, GPU_image(tex->ima, NULL), &tin, &trgb, &tnor);
+ rgbnor= TEX_RGB;
+
+ if(tex->imaflag & TEX_USEALPHA)
+ talpha= 1;
+ }
+ else continue;
+
+ /* texture output */
+ if((rgbnor & TEX_RGB) && (mtex->texflag & MTEX_RGBTOINT)) {
+ GPU_link(mat, "mtex_rgbtoint", trgb, &tin);
+ rgbnor -= TEX_RGB;
+ }
+
+ if(mtex->texflag & MTEX_NEGATIVE) {
+ if(rgbnor & TEX_RGB)
+ GPU_link(mat, "mtex_rgb_invert", trgb, &trgb);
+ else
+ GPU_link(mat, "mtex_value_invert", tin, &tin);
+ }
+
+ if(mtex->texflag & MTEX_STENCIL) {
+ if(rgbnor & TEX_RGB)
+ GPU_link(mat, "mtex_rgb_stencil", stencil, trgb, &stencil, &trgb);
+ else
+ GPU_link(mat, "mtex_value_stencil", stencil, tin, &stencil, &tin);
+ }
+
+ /* mapping */
+ if(mtex->mapto & (MAP_COL+MAP_COLSPEC)) {
+ /* stencil maps on the texture control slider, not texture intensity value */
+ if(mtex->colfac == 1.0f)
+ colfac = stencil;
+ else
+ GPU_link(mat, "math_multiply", GPU_uniform(&mtex->colfac), stencil, &colfac);
+
+ if((rgbnor & TEX_RGB)==0) {
+ GPU_link(mat, "set_rgb", GPU_uniform(&mtex->r), &tcol);
+ }
+ else {
+ GPU_link(mat, "set_rgba", trgb, &tcol);
+
+ if(mtex->mapto & MAP_ALPHA)
+ GPU_link(mat, "set_value", stencil, &tin);
+ else if(talpha)
+ GPU_link(mat, "mtex_alpha_from_col", trgb, &tin);
+ else
+ GPU_link(mat, "set_value_one", &tin);
+ }
+
+ if(mtex->mapto & MAP_COL)
+ texture_rgb_blend(mat, tcol, shi->rgb, tin, colfac, mtex->blendtype, &shi->rgb);
+
+ if(!(G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX) && (mtex->mapto & MAP_COLSPEC))
+ texture_rgb_blend(mat, tcol, shi->specrgb, tin, colfac, mtex->blendtype, &shi->specrgb);
+ }
+
+ if(!(G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX) && (mtex->mapto & MAP_NORM)) {
+ if(mtex->maptoneg & MAP_NORM) tex->norfac= -mtex->norfac;
+ else tex->norfac= mtex->norfac;
+
+ if((tex->type==TEX_IMAGE) && (tex->imaflag & TEX_NORMALMAP)) {
+ tex->norfac = mtex->norfac;
+
+ if(mtex->maptoneg & MAP_NORM)
+ GPU_link(mat, "mtex_negate_texnormal", tnor, &tnor);
+
+ if(mtex->normapspace == MTEX_NSPACE_TANGENT)
+ GPU_link(mat, "mtex_nspace_tangent", GPU_attribute(CD_TANGENT, ""), shi->vn, tnor, &newnor);
+ else
+ newnor = tnor;
+
+ norfac = MIN2(mtex->norfac, 1.0);
+ if(norfac == 1.0f && !GPU_link_changed(stencil)) {
+ shi->vn = newnor;
+ }
+ else {
+ tnorfac = GPU_uniform(&norfac);
+
+ if(GPU_link_changed(stencil))
+ GPU_link(mat, "math_multiply", tnorfac, stencil, &tnorfac);
+
+ GPU_link(mat, "mtex_blend_normal", tnorfac, shi->vn, newnor, &shi->vn);
+ }
+ }
+
+ GPU_link(mat, "vec_math_negate", shi->vn, &orn);
+ GPU_link(mat, "texco_refl", shi->vn, shi->view, &shi->ref);
+ }
+
+ if((mtex->mapto & MAP_VARS)) {
+ if(mtex->varfac == 1.0f)
+ varfac = stencil;
+ else
+ GPU_link(mat, "math_multiply", GPU_uniform(&mtex->varfac), stencil, &varfac);
+
+ if(rgbnor & TEX_RGB) {
+ if(talpha)
+ GPU_link(mat, "mtex_alpha_from_col", trgb, &tin);
+ else
+ GPU_link(mat, "mtex_rgbtoint", trgb, &tin);
+ }
+
+ if(!(G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_REF) {
+ int flip= mtex->maptoneg & MAP_REF;
+ texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->refl, tin, varfac, mtex->blendtype, flip, &shi->refl);
+ GPU_link(mat, "mtex_value_clamp_positive", shi->refl, &shi->refl);
+ }
+ if(!(G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_SPEC) {
+ int flip= mtex->maptoneg & MAP_SPEC;
+ texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->spec, tin, varfac, mtex->blendtype, flip, &shi->spec);
+ GPU_link(mat, "mtex_value_clamp_positive", shi->spec, &shi->spec);
+ }
+ if(!(G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_EMIT) {
+ int flip= mtex->maptoneg & MAP_EMIT;
+ texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->emit, tin, varfac, mtex->blendtype, flip, &shi->emit);
+ GPU_link(mat, "mtex_value_clamp_positive", shi->emit, &shi->emit);
+ }
+ if(!(G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_HAR) {
+ int flip= mtex->maptoneg & MAP_HAR;
+ GPU_link(mat, "mtex_har_divide", shi->har, &shi->har);
+ texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->har, tin, varfac, mtex->blendtype, flip, &shi->har);
+ GPU_link(mat, "mtex_har_multiply_clamp", shi->har, &shi->har);
+ }
+ if(mtex->mapto & MAP_ALPHA) {
+ int flip= mtex->maptoneg & MAP_ALPHA;
+ texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->alpha, tin, varfac, mtex->blendtype, flip, &shi->alpha);
+ GPU_link(mat, "mtex_value_clamp", shi->alpha, &shi->alpha);
+ }
+ if(!(G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_AMB) {
+ int flip= mtex->maptoneg & MAP_AMB;
+ texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->amb, tin, varfac, mtex->blendtype, flip, &shi->amb);
+ GPU_link(mat, "mtex_value_clamp", shi->amb, &shi->amb);
+ }
+ }
+ }
+ }
+}
+
+void GPU_shadeinput_set(GPUMaterial *mat, Material *ma, GPUShadeInput *shi)
+{
+ float hard = ma->har;
+
+ memset(shi, 0, sizeof(*shi));
+
+ shi->gpumat = mat;
+ shi->mat = ma;
+
+ GPU_link(mat, "set_rgb", GPU_uniform(&ma->r), &shi->rgb);
+ GPU_link(mat, "set_rgb", GPU_uniform(&ma->specr), &shi->specrgb);
+ GPU_link(mat, "shade_norm", GPU_builtin(GPU_VIEW_NORMAL), &shi->vn);
+ GPU_link(mat, "set_value", GPU_uniform(&ma->alpha), &shi->alpha);
+ GPU_link(mat, "set_value", GPU_uniform(&ma->ref), &shi->refl);
+ GPU_link(mat, "set_value", GPU_uniform(&ma->spec), &shi->spec);
+ GPU_link(mat, "set_value", GPU_uniform(&ma->emit), &shi->emit);
+ GPU_link(mat, "set_value", GPU_uniform(&hard), &shi->har);
+ GPU_link(mat, "set_value", GPU_uniform(&ma->amb), &shi->amb);
+ GPU_link(mat, "shade_view", GPU_builtin(GPU_VIEW_POSITION), &shi->view);
+ GPU_link(mat, "vcol_attribute", GPU_attribute(CD_MCOL, ""), &shi->vcol);
+ GPU_link(mat, "texco_refl", shi->vn, shi->view, &shi->ref);
+}
+
+void GPU_shaderesult_set(GPUShadeInput *shi, GPUShadeResult *shr)
+{
+ GPUMaterial *mat= shi->gpumat;
+ GPUNodeLink *emit, *ulinfac, *ulogfac, *mistfac;
+ Material *ma= shi->mat;
+ World *world= mat->scene->world;
+ float linfac, logfac, misttype;
+
+ memset(shr, 0, sizeof(*shr));
+
+ if(ma->mode & MA_VERTEXCOLP)
+ shi->rgb = shi->vcol;
+
+ do_material_tex(shi);
+
+ if(ma->mode & MA_ZTRA)
+ GPU_material_enable_alpha(mat);
+
+ if((G.fileflags & G_FILE_GLSL_NO_LIGHTS) || (ma->mode & MA_SHLESS)) {
+ shr->combined = shi->rgb;
+ shr->alpha = shi->alpha;
+ GPU_link(mat, "set_rgb", shi->rgb, &shr->diff);
+ GPU_link(mat, "set_rgb_zero", &shr->spec);
+ }
+ else {
+ if(GPU_link_changed(shi->emit) || ma->emit != 0.0f) {
+ if((ma->mode & (MA_VERTEXCOL|MA_VERTEXCOLP))== MA_VERTEXCOL) {
+ GPU_link(mat, "shade_add", shi->emit, shi->vcol, &emit);
+ GPU_link(mat, "shade_mul", emit, shi->rgb, &shr->diff);
+ }
+ else
+ GPU_link(mat, "shade_mul_value", shi->emit, shi->rgb, &shr->diff);
+ }
+ else
+ GPU_link(mat, "set_rgb_zero", &shr->diff);
+
+ GPU_link(mat, "set_rgb_zero", &shr->spec);
+
+ material_lights(shi, shr);
+
+ shr->combined = shr->diff;
+ shr->alpha = shi->alpha;
+
+ if(world) {
+ /* exposure correction */
+ if(world->exp!=0.0f || world->range!=1.0f) {
+ linfac= 1.0 + pow((2.0*world->exp + 0.5), -10);
+ logfac= log((linfac-1.0)/linfac)/world->range;
+
+ GPU_link(mat, "set_value", GPU_uniform(&linfac), &ulinfac);
+ GPU_link(mat, "set_value", GPU_uniform(&logfac), &ulogfac);
+
+ GPU_link(mat, "shade_exposure_correct", shr->combined,
+ ulinfac, ulogfac, &shr->combined);
+ GPU_link(mat, "shade_exposure_correct", shr->spec,
+ ulinfac, ulogfac, &shr->spec);
+ }
+
+ /* ambient color */
+ if(world->ambr!=0.0f || world->ambg!=0.0f || world->ambb!=0.0f) {
+ if(GPU_link_changed(shi->amb) || ma->amb != 0.0f)
+ GPU_link(mat, "shade_maddf", shr->combined, GPU_uniform(&ma->amb),
+ GPU_uniform(&world->ambr), &shr->combined);
+ }
+ }
+
+ if(ma->mode & MA_RAMP_COL) ramp_diffuse_result(shi, &shr->combined);
+ if(ma->mode & MA_RAMP_SPEC) ramp_spec_result(shi, &shr->spec);
+
+ if(GPU_link_changed(shi->spec) || ma->spec != 0.0f)
+ GPU_link(mat, "shade_add", shr->combined, shr->spec, &shr->combined);
+ }
+
+ GPU_link(mat, "mtex_alpha_to_col", shr->combined, shr->alpha, &shr->combined);
+
+ if(ma->shade_flag & MA_OBCOLOR)
+ GPU_link(mat, "shade_obcolor", shr->combined, GPU_builtin(GPU_OBCOLOR), &shr->combined);
+
+ if(world && (world->mode & WO_MIST) && !(ma->mode & MA_NOMIST)) {
+ misttype = world->mistype;
+
+ GPU_link(mat, "shade_mist_factor", GPU_builtin(GPU_VIEW_POSITION),
+ GPU_uniform(&world->miststa), GPU_uniform(&world->mistdist),
+ GPU_uniform(&misttype), GPU_uniform(&world->misi), &mistfac);
+
+ GPU_link(mat, "mix_blend", mistfac, shr->combined,
+ GPU_uniform(&world->horr), &shr->combined);
+ }
+
+ if(!(ma->mode & MA_ZTRA)) {
+ if(world && (GPU_link_changed(shr->alpha) || ma->alpha != 1.0f))
+ GPU_link(mat, "shade_world_mix", GPU_uniform(&world->horr),
+ shr->combined, &shr->combined);
+
+ GPU_link(mat, "shade_alpha_opaque", shr->combined, &shr->combined);
+ }
+
+ if(ma->shade_flag & MA_OBCOLOR) {
+ mat->obcolalpha = 1;
+ GPU_link(mat, "shade_alpha_obcolor", shr->combined, GPU_builtin(GPU_OBCOLOR), &shr->combined);
+ }
+}
+
+GPUNodeLink *GPU_blender_material(GPUMaterial *mat, Material *ma)
+{
+ GPUShadeInput shi;
+ GPUShadeResult shr;
+
+ GPU_shadeinput_set(mat, ma, &shi);
+ GPU_shaderesult_set(&shi, &shr);
+
+ return shr.combined;
+}
+
+GPUMaterial *GPU_material_from_blender(Scene *scene, Material *ma)
+{
+ GPUMaterial *mat;
+ GPUNodeLink *outlink;
+ LinkData *link;
+
+ for(link=ma->gpumaterial.first; link; link=link->next)
+ if(((GPUMaterial*)link->data)->scene == scene)
+ return link->data;
+
+ mat = GPU_material_construct_begin(ma);
+ mat->scene = scene;
+
+ if(!(G.fileflags & G_FILE_GLSL_NO_NODES) && ma->nodetree && ma->use_nodes) {
+ ntreeGPUMaterialNodes(ma->nodetree, mat);
+ }
+ else {
+ outlink = GPU_blender_material(mat, ma);
+ GPU_material_output_link(mat, outlink);
+ }
+
+ /*if(!GPU_material_construct_end(mat)) {
+ GPU_material_free(mat);
+ mat= NULL;
+ return 0;
+ }*/
+
+ GPU_material_construct_end(mat);
+
+ link = MEM_callocN(sizeof(LinkData), "GPUMaterialLink");
+ link->data = mat;
+ BLI_addtail(&ma->gpumaterial, link);
+
+ return mat;
+}
+
+void GPU_materials_free()
+{
+ Object *ob;
+ Material *ma;
+ extern Material defmaterial;
+
+ for(ma=G.main->mat.first; ma; ma=ma->id.next)
+ GPU_material_free(ma);
+
+ GPU_material_free(&defmaterial);
+
+ for(ob=G.main->object.first; ma; ma=ma->id.next)
+ GPU_lamp_free(ob);
+}
+
+/* Lamps and shadow buffers */
+
+void GPU_lamp_update(GPULamp *lamp, int lay, float obmat[][4])
+{
+ float mat[4][4];
+
+ lamp->lay = lay;
+
+ Mat4CpyMat4(mat, obmat);
+ Mat4Ortho(mat);
+
+ VECCOPY(lamp->vec, mat[2]);
+ VECCOPY(lamp->co, mat[3]);
+ Mat4CpyMat4(lamp->obmat, mat);
+ Mat4Invert(lamp->imat, mat);
+}
+
+static void gpu_lamp_from_blender(Scene *scene, Object *ob, Object *par, Lamp *la, GPULamp *lamp)
+{
+ float temp, angle, pixsize, wsize;
+
+ lamp->scene = scene;
+ lamp->ob = ob;
+ lamp->par = par;
+ lamp->la = la;
+
+ /* add_render_lamp */
+ lamp->mode = la->mode;
+ lamp->type = la->type;
+
+ lamp->energy = la->energy;
+ if(lamp->mode & LA_NEG) lamp->energy= -lamp->energy;
+
+ lamp->col[0]= la->r*lamp->energy;
+ lamp->col[1]= la->g*lamp->energy;
+ lamp->col[2]= la->b*lamp->energy;
+
+ GPU_lamp_update(lamp, ob->lay, ob->obmat);
+
+ lamp->spotsi= la->spotsize;
+ if(lamp->mode & LA_HALO)
+ if(lamp->spotsi > 170.0)
+ lamp->spotsi = 170.0;
+ lamp->spotsi= cos(M_PI*lamp->spotsi/360.0);
+ lamp->spotbl= (1.0 - lamp->spotsi)*la->spotblend;
+ lamp->k= la->k;
+
+ lamp->dist= la->dist;
+ lamp->falloff_type= la->falloff_type;
+ lamp->att1= la->att1;
+ lamp->att2= la->att2;
+ lamp->curfalloff= la->curfalloff;
+
+ /* initshadowbuf */
+ lamp->bias = 0.02f*la->bias;
+ lamp->size = la->bufsize;
+ lamp->d= la->clipsta;
+ lamp->clipend= la->clipend;
+
+ /* arbitrary correction for the fact we do no soft transition */
+ lamp->bias *= 0.25f;
+
+ /* makeshadowbuf */
+ angle= saacos(lamp->spotsi);
+ temp= 0.5f*lamp->size*cos(angle)/sin(angle);
+ pixsize= (lamp->d)/temp;
+ wsize= pixsize*0.5f*lamp->size;
+
+ i_window(-wsize, wsize, -wsize, wsize, lamp->d, lamp->clipend, lamp->winmat);
+}
+
+static void gpu_lamp_shadow_free(GPULamp *lamp)
+{
+ if(lamp->tex) {
+ GPU_texture_free(lamp->tex);
+ lamp->tex= NULL;
+ }
+ if(lamp->fb) {
+ GPU_framebuffer_free(lamp->fb);
+ lamp->fb= NULL;
+ }
+}
+
+GPULamp *GPU_lamp_from_blender(Scene *scene, Object *ob, Object *par)
+{
+ Lamp *la;
+ GPULamp *lamp;
+ LinkData *link;
+
+ for(link=ob->gpulamp.first; link; link=link->next) {
+ lamp = (GPULamp*)link->data;
+
+ if(lamp->par == par && lamp->scene == scene)
+ return link->data;
+ }
+
+ lamp = MEM_callocN(sizeof(GPULamp), "GPULamp");
+
+ link = MEM_callocN(sizeof(LinkData), "GPULampLink");
+ link->data = lamp;
+ BLI_addtail(&ob->gpulamp, link);
+
+ la = ob->data;
+ gpu_lamp_from_blender(scene, ob, par, la, lamp);
+
+ if(la->type==LA_SPOT && (la->mode & LA_SHAD_BUF)) {
+ /* opengl */
+ lamp->fb = GPU_framebuffer_create();
+ if(!lamp->fb) {
+ gpu_lamp_shadow_free(lamp);
+ return lamp;
+ }
+
+ lamp->tex = GPU_texture_create_depth(lamp->size, lamp->size);
+ if(!lamp->tex) {
+ gpu_lamp_shadow_free(lamp);
+ return lamp;
+ }
+
+ if(!GPU_framebuffer_texture_attach(lamp->fb, lamp->tex)) {
+ gpu_lamp_shadow_free(lamp);
+ return lamp;
+ }
+
+ GPU_framebuffer_restore();
+ }
+
+ return lamp;
+}
+
+void GPU_lamp_free(Object *ob)
+{
+ GPULamp *lamp;
+ LinkData *link;
+ LinkData *nlink;
+ Material *ma;
+
+ for(link=ob->gpulamp.first; link; link=link->next) {
+ lamp = link->data;
+
+ while(lamp->materials.first) {
+ nlink = lamp->materials.first;
+ ma = nlink->data;
+ BLI_freelinkN(&lamp->materials, nlink);
+
+ if(ma->gpumaterial.first)
+ GPU_material_free(ma);
+ }
+
+ gpu_lamp_shadow_free(lamp);
+
+ MEM_freeN(lamp);
+ }
+
+ BLI_freelistN(&ob->gpulamp);
+}
+
+int GPU_lamp_has_shadow_buffer(GPULamp *lamp)
+{
+ return (!(G.fileflags & G_FILE_GLSL_NO_SHADOWS) &&
+ !(G.fileflags & G_FILE_GLSL_NO_LIGHTS) &&
+ lamp->tex && lamp->fb);
+}
+
+void GPU_lamp_shadow_buffer_bind(GPULamp *lamp, float viewmat[][4], int *winsize, float winmat[][4])
+{
+ float rangemat[4][4], persmat[4][4];
+
+ /* initshadowbuf */
+ Mat4Invert(lamp->viewmat, lamp->obmat);
+ Normalize(lamp->viewmat[0]);
+ Normalize(lamp->viewmat[1]);
+ Normalize(lamp->viewmat[2]);
+
+ /* makeshadowbuf */
+ Mat4MulMat4(persmat, lamp->viewmat, lamp->winmat);
+
+ /* opengl depth buffer is range 0.0..1.0 instead of -1.0..1.0 in blender */
+ Mat4One(rangemat);
+ rangemat[0][0] = 0.5f;
+ rangemat[1][1] = 0.5f;
+ rangemat[2][2] = 0.5f;
+ rangemat[3][0] = 0.5f;
+ rangemat[3][1] = 0.5f;
+ rangemat[3][2] = 0.5f;
+
+ Mat4MulMat4(lamp->persmat, persmat, rangemat);
+
+ /* opengl */
+ GPU_framebuffer_texture_bind(lamp->fb, lamp->tex);
+
+ /* set matrices */
+ Mat4CpyMat4(viewmat, lamp->viewmat);
+ Mat4CpyMat4(winmat, lamp->winmat);
+ *winsize = lamp->size;
+}
+
+void GPU_lamp_shadow_buffer_unbind(GPULamp *lamp)
+{
+ GPU_framebuffer_texture_unbind(lamp->fb, lamp->tex);
+ GPU_framebuffer_restore();
+}
+
+int GPU_lamp_shadow_layer(GPULamp *lamp)
+{
+ if(lamp->fb && lamp->tex && (lamp->mode & (LA_LAYER|LA_LAYER_SHADOW)))
+ return lamp->lay;
+ else
+ return -1;
+}
+
diff --git a/source/blender/gpu/intern/gpu_shader_material.glsl b/source/blender/gpu/intern/gpu_shader_material.glsl
new file mode 100644
index 00000000000..16ed38cb47d
--- /dev/null
+++ b/source/blender/gpu/intern/gpu_shader_material.glsl
@@ -0,0 +1,1555 @@
+
+float exp_blender(float f)
+{
+ return pow(2.71828182846, f);
+}
+
+void rgb_to_hsv(vec4 rgb, out vec4 outcol)
+{
+ float cmax, cmin, h, s, v, cdelta;
+ vec3 c;
+
+ cmax = max(rgb[0], max(rgb[1], rgb[2]));
+ cmin = min(rgb[0], min(rgb[1], rgb[2]));
+ cdelta = cmax-cmin;
+
+ v = cmax;
+ if (cmax!=0.0)
+ s = cdelta/cmax;
+ else {
+ s = 0.0;
+ h = 0.0;
+ }
+
+ if (s == 0.0) {
+ h = 0.0;
+ }
+ else {
+ c = (vec3(cmax, cmax, cmax) - rgb.xyz)/cdelta;
+
+ if (rgb.x==cmax) h = c[2] - c[1];
+ else if (rgb.y==cmax) h = 2.0 + c[0] - c[2];
+ else h = 4.0 + c[1] - c[0];
+
+ h /= 6.0;
+
+ if (h<0.0)
+ h += 1.0;
+ }
+
+ outcol = vec4(h, s, v, rgb.w);
+}
+
+void hsv_to_rgb(vec4 hsv, out vec4 outcol)
+{
+ float i, f, p, q, t, h, s, v;
+ vec3 rgb;
+
+ h = hsv[0];
+ s = hsv[1];
+ v = hsv[2];
+
+ if(s==0.0) {
+ rgb = vec3(v, v, v);
+ }
+ else {
+ if(h==1.0)
+ h = 0.0;
+
+ h *= 6.0;
+ i = floor(h);
+ f = h - i;
+ rgb = vec3(f, f, f);
+ p = v*(1.0-s);
+ q = v*(1.0-(s*f));
+ t = v*(1.0-(s*(1.0-f)));
+
+ if (i == 0.0) rgb = vec3(v, t, p);
+ else if (i == 1.0) rgb = vec3(q, v, p);
+ else if (i == 2.0) rgb = vec3(p, v, t);
+ else if (i == 3.0) rgb = vec3(p, q, v);
+ else if (i == 4.0) rgb = vec3(t, p, v);
+ else rgb = vec3(v, p, q);
+ }
+
+ outcol = vec4(rgb, hsv.w);
+}
+
+#define M_PI 3.14159265358979323846
+
+/*********** SHADER NODES ***************/
+
+void vcol_attribute(vec4 attvcol, out vec4 vcol)
+{
+ vcol = vec4(attvcol.x/255.0, attvcol.y/255.0, attvcol.z/255.0, 1.0);
+}
+
+void uv_attribute(vec2 attuv, out vec3 uv)
+{
+ uv = vec3(attuv*2.0 - vec2(1.0, 1.0), 0.0);
+}
+
+void geom(vec3 co, vec3 nor, mat4 viewinvmat, vec3 attorco, vec2 attuv, vec4 attvcol, out vec3 global, out vec3 local, out vec3 view, out vec3 orco, out vec3 uv, out vec3 normal, out vec4 vcol, out float frontback)
+{
+ local = co;
+ view = normalize(local);
+ global = (viewinvmat*vec4(local, 1.0)).xyz;
+ orco = attorco;
+ uv_attribute(attuv, uv);
+ normal = -normalize(nor); /* blender render normal is negated */
+ vcol_attribute(attvcol, vcol);
+ frontback = 1.0;
+}
+
+void mapping(vec3 vec, mat4 mat, vec3 minvec, vec3 maxvec, float domin, float domax, out vec3 outvec)
+{
+ outvec = (mat * vec4(vec, 1.0)).xyz;
+ if(domin == 1.0)
+ outvec = max(outvec, minvec);
+ if(domax == 1.0)
+ outvec = min(outvec, maxvec);
+}
+
+void camera(vec3 co, out vec3 outview, out float outdepth, out float outdist)
+{
+ outdepth = abs(co.z);
+ outdist = length(co);
+ outview = normalize(co);
+}
+
+void math_add(float val1, float val2, out float outval)
+{
+ outval = val1 + val2;
+}
+
+void math_subtract(float val1, float val2, out float outval)
+{
+ outval = val1 - val2;
+}
+
+void math_multiply(float val1, float val2, out float outval)
+{
+ outval = val1 * val2;
+}
+
+void math_divide(float val1, float val2, out float outval)
+{
+ if (val2 == 0.0)
+ outval = 0.0;
+ else
+ outval = val1 / val2;
+}
+
+void math_sine(float val, out float outval)
+{
+ outval = sin(val);
+}
+
+void math_cosine(float val, out float outval)
+{
+ outval = cos(val);
+}
+
+void math_tangent(float val, out float outval)
+{
+ outval = tan(val);
+}
+
+void math_asin(float val, out float outval)
+{
+ if (val <= 1.0 && val >= -1.0)
+ outval = asin(val);
+ else
+ outval = 0.0;
+}
+
+void math_acos(float val, out float outval)
+{
+ if (val <= 1.0 && val >= -1.0)
+ outval = acos(val);
+ else
+ outval = 0.0;
+}
+
+void math_atan(float val, out float outval)
+{
+ outval = atan(val);
+}
+
+void math_pow(float val1, float val2, out float outval)
+{
+ if (val1 >= 0.0)
+ outval = pow(val1, val2);
+ else
+ outval = 0.0;
+}
+
+void math_log(float val1, float val2, out float outval)
+{
+ if(val1 > 0.0 && val2 > 0.0)
+ outval= log2(val1) / log2(val2);
+ else
+ outval= 0.0;
+}
+
+void math_max(float val1, float val2, out float outval)
+{
+ outval = max(val1, val2);
+}
+
+void math_min(float val1, float val2, out float outval)
+{
+ outval = min(val1, val2);
+}
+
+void math_round(float val, out float outval)
+{
+ outval= floor(val + 0.5);
+}
+
+void math_less_than(float val1, float val2, out float outval)
+{
+ if(val1 < val2)
+ outval = 1.0;
+ else
+ outval = 0.0;
+}
+
+void math_greater_than(float val1, float val2, out float outval)
+{
+ if(val1 > val2)
+ outval = 1.0;
+ else
+ outval = 0.0;
+}
+
+void squeeze(float val, float width, float center, out float outval)
+{
+ outval = 1.0/(1.0 + pow(2.71828183, -((val-center)*width)));
+}
+
+void vec_math_add(vec3 v1, vec3 v2, out vec3 outvec, out float outval)
+{
+ outvec = v1 + v2;
+ outval = (abs(outvec[0]) + abs(outvec[1]) + abs(outvec[2]))/3.0;
+}
+
+void vec_math_sub(vec3 v1, vec3 v2, out vec3 outvec, out float outval)
+{
+ outvec = v1 - v2;
+ outval = (abs(outvec[0]) + abs(outvec[1]) + abs(outvec[2]))/3.0;
+}
+
+void vec_math_average(vec3 v1, vec3 v2, out vec3 outvec, out float outval)
+{
+ outvec = v1 + v2;
+ outval = length(outvec);
+ outvec = normalize(outvec);
+}
+
+void vec_math_dot(vec3 v1, vec3 v2, out vec3 outvec, out float outval)
+{
+ outvec = vec3(0, 0, 0);
+ outval = dot(v1, v2);
+}
+
+void vec_math_cross(vec3 v1, vec3 v2, out vec3 outvec, out float outval)
+{
+ outvec = cross(v1, v2);
+ outval = length(outvec);
+}
+
+void vec_math_normalize(vec3 v, out vec3 outvec, out float outval)
+{
+ outval = length(v);
+ outvec = normalize(v);
+}
+
+void vec_math_negate(vec3 v, out vec3 outv)
+{
+ outv = -v;
+}
+
+void normal(vec3 dir, vec3 nor, out vec3 outnor, out float outdot)
+{
+ outnor = dir;
+ outdot = -dot(dir, nor);
+}
+
+void curves_vec(vec3 vec, sampler1D curvemap, out vec3 outvec)
+{
+ outvec.x = texture1D(curvemap, (vec.x + 1.0)*0.5).x;
+ outvec.y = texture1D(curvemap, (vec.y + 1.0)*0.5).y;
+ outvec.z = texture1D(curvemap, (vec.z + 1.0)*0.5).z;
+}
+
+void curves_rgb(vec4 col, sampler1D curvemap, out vec4 outcol)
+{
+ outcol.r = texture1D(curvemap, texture1D(curvemap, col.r).a).r;
+ outcol.g = texture1D(curvemap, texture1D(curvemap, col.g).a).g;
+ outcol.b = texture1D(curvemap, texture1D(curvemap, col.b).a).b;
+ outcol.a = col.a;
+}
+
+void set_value(float val, out float outval)
+{
+ outval = val;
+}
+
+void set_rgb(vec3 col, out vec3 outcol)
+{
+ outcol = col;
+}
+
+void set_rgba(vec4 col, out vec4 outcol)
+{
+ outcol = col;
+}
+
+void set_value_zero(out float outval)
+{
+ outval = 0.0;
+}
+
+void set_value_one(out float outval)
+{
+ outval = 1.0;
+}
+
+void set_rgb_zero(out vec3 outval)
+{
+ outval = vec3(0.0);
+}
+
+void set_rgba_zero(out vec4 outval)
+{
+ outval = vec4(0.0);
+}
+
+void mix_blend(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ outcol = mix(col1, col2, fac);
+ outcol.a = col1.a;
+}
+
+void mix_add(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ outcol = mix(col1, col1 + col2, fac);
+ outcol.a = col1.a;
+}
+
+void mix_mult(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ outcol = mix(col1, col1 * col2, fac);
+ outcol.a = col1.a;
+}
+
+void mix_screen(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ float facm = 1.0 - fac;
+
+ outcol = vec4(1.0) - (vec4(facm) + fac*(vec4(1.0) - col2))*(vec4(1.0) - col1);
+ outcol.a = col1.a;
+}
+
+void mix_overlay(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ float facm = 1.0 - fac;
+
+ outcol = col1;
+
+ if(outcol.r < 0.5)
+ outcol.r *= facm + 2.0*fac*col2.r;
+ else
+ outcol.r = 1.0 - (facm + 2.0*fac*(1.0 - col2.r))*(1.0 - outcol.r);
+
+ if(outcol.g < 0.5)
+ outcol.g *= facm + 2.0*fac*col2.g;
+ else
+ outcol.g = 1.0 - (facm + 2.0*fac*(1.0 - col2.g))*(1.0 - outcol.g);
+
+ if(outcol.b < 0.5)
+ outcol.b *= facm + 2.0*fac*col2.b;
+ else
+ outcol.b = 1.0 - (facm + 2.0*fac*(1.0 - col2.b))*(1.0 - outcol.b);
+}
+
+void mix_sub(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ outcol = mix(col1, col1 - col2, fac);
+ outcol.a = col1.a;
+}
+
+void mix_div(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ float facm = 1.0 - fac;
+
+ outcol = col1;
+
+ if(col2.r != 0.0) outcol.r = facm*outcol.r + fac*outcol.r/col2.r;
+ if(col2.g != 0.0) outcol.g = facm*outcol.g + fac*outcol.g/col2.g;
+ if(col2.b != 0.0) outcol.b = facm*outcol.b + fac*outcol.b/col2.b;
+}
+
+void mix_diff(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ outcol = mix(col1, abs(col1 - col2), fac);
+ outcol.a = col1.a;
+}
+
+void mix_dark(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ outcol.rgb = min(col1.rgb, col2.rgb*fac);
+ outcol.a = col1.a;
+}
+
+void mix_light(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ outcol.rgb = max(col1.rgb, col2.rgb*fac);
+ outcol.a = col1.a;
+}
+
+void mix_dodge(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ outcol = col1;
+
+ if(outcol.r != 0.0) {
+ float tmp = 1.0 - fac*col2.r;
+ if(tmp <= 0.0)
+ outcol.r = 1.0;
+ else if((tmp = outcol.r/tmp) > 1.0)
+ outcol.r = 1.0;
+ else
+ outcol.r = tmp;
+ }
+ if(outcol.g != 0.0) {
+ float tmp = 1.0 - fac*col2.g;
+ if(tmp <= 0.0)
+ outcol.g = 1.0;
+ else if((tmp = outcol.g/tmp) > 1.0)
+ outcol.g = 1.0;
+ else
+ outcol.g = tmp;
+ }
+ if(outcol.b != 0.0) {
+ float tmp = 1.0 - fac*col2.b;
+ if(tmp <= 0.0)
+ outcol.b = 1.0;
+ else if((tmp = outcol.b/tmp) > 1.0)
+ outcol.b = 1.0;
+ else
+ outcol.b = tmp;
+ }
+}
+
+void mix_burn(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ float tmp, facm = 1.0 - fac;
+
+ outcol = col1;
+
+ tmp = facm + fac*col2.r;
+ if(tmp <= 0.0)
+ outcol.r = 0.0;
+ else if((tmp = (1.0 - (1.0 - outcol.r)/tmp)) < 0.0)
+ outcol.r = 0.0;
+ else if(tmp > 1.0)
+ outcol.r = 1.0;
+ else
+ outcol.r = tmp;
+
+ tmp = facm + fac*col2.g;
+ if(tmp <= 0.0)
+ outcol.g = 0.0;
+ else if((tmp = (1.0 - (1.0 - outcol.g)/tmp)) < 0.0)
+ outcol.g = 0.0;
+ else if(tmp > 1.0)
+ outcol.g = 1.0;
+ else
+ outcol.g = tmp;
+
+ tmp = facm + fac*col2.b;
+ if(tmp <= 0.0)
+ outcol.b = 0.0;
+ else if((tmp = (1.0 - (1.0 - outcol.b)/tmp)) < 0.0)
+ outcol.b = 0.0;
+ else if(tmp > 1.0)
+ outcol.b = 1.0;
+ else
+ outcol.b = tmp;
+}
+
+void mix_hue(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ float facm = 1.0 - fac;
+
+ outcol = col1;
+
+ vec4 hsv, hsv2, tmp;
+ rgb_to_hsv(col2, hsv2);
+
+ if(hsv2.y != 0.0) {
+ rgb_to_hsv(outcol, hsv);
+ hsv.x = hsv2.x;
+ hsv_to_rgb(hsv, tmp);
+
+ outcol = mix(outcol, tmp, fac);
+ outcol.a = col1.a;
+ }
+}
+
+void mix_sat(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ float facm = 1.0 - fac;
+
+ outcol = col1;
+
+ vec4 hsv, hsv2;
+ rgb_to_hsv(outcol, hsv);
+
+ if(hsv.y != 0.0) {
+ rgb_to_hsv(col2, hsv2);
+
+ hsv.y = facm*hsv.y + fac*hsv2.y;
+ hsv_to_rgb(hsv, outcol);
+ }
+}
+
+void mix_val(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ float facm = 1.0 - fac;
+
+ vec4 hsv, hsv2;
+ rgb_to_hsv(col1, hsv);
+ rgb_to_hsv(col2, hsv2);
+
+ hsv.z = facm*hsv.z + fac*hsv2.z;
+ hsv_to_rgb(hsv, outcol);
+}
+
+void mix_color(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ float facm = 1.0 - fac;
+
+ outcol = col1;
+
+ vec4 hsv, hsv2, tmp;
+ rgb_to_hsv(col2, hsv2);
+
+ if(hsv2.y != 0.0) {
+ rgb_to_hsv(outcol, hsv);
+ hsv.x = hsv2.x;
+ hsv.y = hsv2.y;
+ hsv_to_rgb(hsv, tmp);
+
+ outcol = mix(outcol, tmp, fac);
+ outcol.a = col1.a;
+ }
+}
+
+void valtorgb(float fac, sampler1D colormap, out vec4 outcol, out float outalpha)
+{
+ outcol = texture1D(colormap, fac);
+ outalpha = outcol.a;
+}
+
+void rgbtobw(vec4 color, out float outval)
+{
+ outval = color.r*0.35 + color.g*0.45 + color.b*0.2;
+}
+
+void invert(float fac, vec4 col, out vec4 outcol)
+{
+ outcol.xyz = mix(col.xyz, vec3(1.0, 1.0, 1.0) - col.xyz, fac);
+ outcol.w = col.w;
+}
+
+void hue_sat(float hue, float sat, float value, float fac, vec4 col, out vec4 outcol)
+{
+ vec4 hsv;
+
+ rgb_to_hsv(col, hsv);
+
+ hsv[0] += (hue - 0.5);
+ if(hsv[0]>1.0) hsv[0]-=1.0; else if(hsv[0]<0.0) hsv[0]+= 1.0;
+ hsv[1] *= sat;
+ if(hsv[1]>1.0) hsv[1]= 1.0; else if(hsv[1]<0.0) hsv[1]= 0.0;
+ hsv[2] *= value;
+ if(hsv[2]>1.0) hsv[2]= 1.0; else if(hsv[2]<0.0) hsv[2]= 0.0;
+
+ hsv_to_rgb(hsv, outcol);
+
+ outcol = mix(col, outcol, fac);
+}
+
+void separate_rgb(vec4 col, out float r, out float g, out float b)
+{
+ r = col.r;
+ g = col.g;
+ b = col.b;
+}
+
+void combine_rgb(float r, float g, float b, out vec4 col)
+{
+ col = vec4(r, g, b, 1.0);
+}
+
+void output_node(vec4 rgb, float alpha, out vec4 outrgb)
+{
+ outrgb = vec4(rgb.rgb, alpha);
+}
+
+/*********** TEXTURES ***************/
+
+void texture_flip_blend(vec3 vec, out vec3 outvec)
+{
+ outvec = vec.yxz;
+}
+
+void texture_blend_lin(vec3 vec, out float outval)
+{
+ outval = (1.0+vec.x)/2.0;
+}
+
+void texture_blend_quad(vec3 vec, out float outval)
+{
+ outval = max((1.0+vec.x)/2.0, 0.0);
+ outval *= outval;
+}
+
+void texture_wood_sin(vec3 vec, out float value, out vec4 color, out vec3 normal)
+{
+ float a = sqrt(vec.x*vec.x + vec.y*vec.y + vec.z*vec.z)*20.0;
+ float wi = 0.5 + 0.5*sin(a);
+
+ value = wi;
+ color = vec4(wi, wi, wi, 1.0);
+ normal = vec3(0.0, 0.0, 0.0);
+}
+
+void texture_image(vec3 vec, sampler2D ima, out float value, out vec4 color, out vec3 normal)
+{
+ color = texture2D(ima, (vec.xy + vec2(1.0, 1.0))*0.5);
+ value = 1.0;
+
+ normal.x = 2.0*(color.r - 0.5);
+ normal.y = 2.0*(0.5 - color.g);
+ normal.z = 2.0*(color.b - 0.5);
+}
+
+/************* MTEX *****************/
+
+void texco_orco(vec3 attorco, out vec3 orco)
+{
+ orco = attorco;
+}
+
+void texco_uv(vec2 attuv, out vec3 uv)
+{
+ /* disabled for now, works together with leaving out mtex_2d_mapping
+ uv = vec3(attuv*2.0 - vec2(1.0, 1.0), 0.0); */
+ uv = vec3(attuv, 0.0);
+}
+
+void texco_norm(vec3 normal, out vec3 outnormal)
+{
+ /* corresponds to shi->orn, which is negated so cancels
+ out blender normal negation */
+ outnormal = normalize(normal);
+}
+
+void texco_tangent(vec3 tangent, out vec3 outtangent)
+{
+ outtangent = normalize(tangent);
+}
+
+void texco_global(mat4 viewinvmat, vec3 co, out vec3 global)
+{
+ global = (viewinvmat*vec4(co, 1.0)).xyz;
+}
+
+void texco_object(mat4 viewinvmat, mat4 obinvmat, vec3 co, out vec3 object)
+{
+ object = (obinvmat*(viewinvmat*vec4(co, 1.0))).xyz;
+}
+
+void texco_refl(vec3 vn, vec3 view, out vec3 ref)
+{
+ ref = view - 2.0*dot(vn, view)*vn;
+}
+
+void shade_norm(vec3 normal, out vec3 outnormal)
+{
+ /* blender render normal is negated */
+ outnormal = -normalize(normal);
+}
+
+void mtex_rgb_blend(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ float facm;
+
+ fact *= facg;
+ facm = 1.0-fact;
+
+ incol = fact*texcol + facm*outcol;
+}
+
+void mtex_rgb_mul(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ float facm;
+
+ fact *= facg;
+ facm = 1.0-facg;
+
+ incol = (facm + fact*texcol)*outcol;
+}
+
+void mtex_rgb_screen(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ float facm;
+
+ fact *= facg;
+ facm = 1.0-facg;
+
+ incol = vec3(1.0) - (vec3(facm) + fact*(vec3(1.0) - texcol))*(vec3(1.0) - outcol);
+}
+
+void mtex_rgb_overlay(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ float facm;
+
+ fact *= facg;
+ facm = 1.0-facg;
+
+ if(outcol.r < 0.5)
+ incol.r = outcol.r*(facm + 2.0*fact*texcol.r);
+ else
+ incol.r = 1.0 - (facm + 2.0*fact*(1.0 - texcol.r))*(1.0 - outcol.r);
+
+ if(outcol.g < 0.5)
+ incol.g = outcol.g*(facm + 2.0*fact*texcol.g);
+ else
+ incol.g = 1.0 - (facm + 2.0*fact*(1.0 - texcol.g))*(1.0 - outcol.g);
+
+ if(outcol.b < 0.5)
+ incol.b = outcol.b*(facm + 2.0*fact*texcol.b);
+ else
+ incol.b = 1.0 - (facm + 2.0*fact*(1.0 - texcol.b))*(1.0 - outcol.b);
+}
+
+void mtex_rgb_sub(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ incol = -fact*facg*texcol + outcol;
+}
+
+void mtex_rgb_add(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ incol = fact*facg*texcol + outcol;
+}
+
+void mtex_rgb_div(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ float facm;
+
+ fact *= facg;
+ facm = 1.0-fact;
+
+ if(texcol.r != 0.0) incol.r = facm*outcol.r + fact*outcol.r/texcol.r;
+ if(texcol.g != 0.0) incol.g = facm*outcol.g + fact*outcol.g/texcol.g;
+ if(texcol.b != 0.0) incol.b = facm*outcol.b + fact*outcol.b/texcol.b;
+}
+
+void mtex_rgb_diff(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ float facm;
+
+ fact *= facg;
+ facm = 1.0-fact;
+
+ incol = facm*outcol + fact*abs(texcol - outcol);
+}
+
+void mtex_rgb_dark(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ float facm, col;
+
+ fact *= facg;
+ facm = 1.0-fact;
+
+ col = fact*texcol.r;
+ if(col < outcol.r) incol.r = col; else incol.r = outcol.r;
+ col = fact*texcol.g;
+ if(col < outcol.g) incol.g = col; else incol.g = outcol.g;
+ col = fact*texcol.b;
+ if(col < outcol.b) incol.b = col; else incol.b = outcol.b;
+}
+
+void mtex_rgb_light(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ float facm, col;
+
+ fact *= facg;
+ facm = 1.0-fact;
+
+ col = fact*texcol.r;
+ if(col > outcol.r) incol.r = col; else incol.r = outcol.r;
+ col = fact*texcol.g;
+ if(col > outcol.g) incol.g = col; else incol.g = outcol.g;
+ col = fact*texcol.b;
+ if(col > outcol.b) incol.b = col; else incol.b = outcol.b;
+}
+
+void mtex_rgb_hue(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ vec4 col;
+
+ mix_hue(fact*facg, vec4(outcol, 1.0), vec4(texcol, 1.0), col);
+ incol.rgb = col.rgb;
+}
+
+void mtex_rgb_sat(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ vec4 col;
+
+ mix_sat(fact*facg, vec4(outcol, 1.0), vec4(texcol, 1.0), col);
+ incol.rgb = col.rgb;
+}
+
+void mtex_rgb_val(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ vec4 col;
+
+ mix_val(fact*facg, vec4(outcol, 1.0), vec4(texcol, 1.0), col);
+ incol.rgb = col.rgb;
+}
+
+void mtex_rgb_color(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ vec4 col;
+
+ mix_color(fact*facg, vec4(outcol, 1.0), vec4(texcol, 1.0), col);
+ incol.rgb = col.rgb;
+}
+
+void mtex_value_vars(inout float fact, float facg, out float facm, float flip)
+{
+ fact *= facg;
+ facm = 1.0-fact;
+
+ if(flip != 0.0) {
+ float tmp = fact;
+ fact = facm;
+ facm = tmp;
+ }
+}
+
+void mtex_value_blend(float outcol, float texcol, float fact, float facg, float flip, out float incol)
+{
+ float facm;
+ mtex_value_vars(fact, facg, facm, flip);
+
+ incol = fact*texcol + facm*outcol;
+}
+
+void mtex_value_mul(float outcol, float texcol, float fact, float facg, float flip, out float incol)
+{
+ float facm;
+ mtex_value_vars(fact, facg, facm, flip);
+
+ facm = 1.0 - facg;
+ incol = (facm + fact*texcol)*outcol;
+}
+
+void mtex_value_screen(float outcol, float texcol, float fact, float facg, float flip, out float incol)
+{
+ float facm;
+ mtex_value_vars(fact, facg, facm, flip);
+
+ facm = 1.0 - facg;
+ incol = 1.0 - (facm + fact*(1.0 - texcol))*(1.0 - outcol);
+}
+
+void mtex_value_sub(float outcol, float texcol, float fact, float facg, float flip, out float incol)
+{
+ float facm;
+ mtex_value_vars(fact, facg, facm, flip);
+
+ fact = -fact;
+ incol = fact*texcol + outcol;
+}
+
+void mtex_value_add(float outcol, float texcol, float fact, float facg, float flip, out float incol)
+{
+ float facm;
+ mtex_value_vars(fact, facg, facm, flip);
+
+ fact = fact;
+ incol = fact*texcol + outcol;
+}
+
+void mtex_value_div(float outcol, float texcol, float fact, float facg, float flip, out float incol)
+{
+ float facm;
+ mtex_value_vars(fact, facg, facm, flip);
+
+ if(texcol != 0.0)
+ incol = facm*outcol + fact*outcol/texcol;
+ else
+ incol = 0.0;
+}
+
+void mtex_value_diff(float outcol, float texcol, float fact, float facg, float flip, out float incol)
+{
+ float facm;
+ mtex_value_vars(fact, facg, facm, flip);
+
+ incol = facm*outcol + fact*abs(texcol - outcol);
+}
+
+void mtex_value_dark(float outcol, float texcol, float fact, float facg, float flip, out float incol)
+{
+ float facm;
+ mtex_value_vars(fact, facg, facm, flip);
+
+ float col = fact*texcol;
+ if(col < outcol) incol = col; else incol = outcol;
+}
+
+void mtex_value_light(float outcol, float texcol, float fact, float facg, float flip, out float incol)
+{
+ float facm;
+ mtex_value_vars(fact, facg, facm, flip);
+
+ float col = fact*texcol;
+ if(col > outcol) incol = col; else incol = outcol;
+}
+
+void mtex_value_clamp_positive(float fac, out float outfac)
+{
+ outfac = max(fac, 0.0);
+}
+
+void mtex_value_clamp(float fac, out float outfac)
+{
+ outfac = clamp(fac, 0.0, 1.0);
+}
+
+void mtex_har_divide(float har, out float outhar)
+{
+ outhar = har/128.0;
+}
+
+void mtex_har_multiply_clamp(float har, out float outhar)
+{
+ har *= 128.0;
+
+ if(har < 1.0) outhar = 1.0;
+ else if(har > 511.0) outhar = 511.0;
+ else outhar = har;
+}
+
+void mtex_alpha_from_col(vec4 col, out float alpha)
+{
+ alpha = col.a;
+}
+
+void mtex_alpha_to_col(vec4 col, float alpha, out vec4 outcol)
+{
+ outcol = vec4(col.rgb, alpha);
+}
+
+void mtex_rgbtoint(vec4 rgb, out float intensity)
+{
+ intensity = dot(vec3(0.35, 0.45, 0.2), rgb.rgb);
+}
+
+void mtex_value_invert(float invalue, out float outvalue)
+{
+ outvalue = 1.0 - invalue;
+}
+
+void mtex_rgb_invert(vec4 inrgb, out vec4 outrgb)
+{
+ outrgb = vec4(vec3(1.0) - inrgb.rgb, inrgb.a);
+}
+
+void mtex_value_stencil(float stencil, float intensity, out float outstencil, out float outintensity)
+{
+ float fact = intensity;
+ outintensity = intensity*stencil;
+ outstencil = stencil*fact;
+}
+
+void mtex_rgb_stencil(float stencil, vec4 rgb, out float outstencil, out vec4 outrgb)
+{
+ float fact = rgb.a;
+ outrgb = vec4(rgb.rgb, rgb.a*stencil);
+ outstencil = stencil*fact;
+}
+
+void mtex_mapping_ofs(vec3 texco, vec3 ofs, out vec3 outtexco)
+{
+ outtexco = texco + ofs;
+}
+
+void mtex_mapping_size(vec3 texco, vec3 size, out vec3 outtexco)
+{
+ outtexco = size*texco;
+}
+
+void mtex_2d_mapping(vec3 vec, out vec3 outvec)
+{
+ outvec = vec3(vec.xy*0.5 + vec2(0.5, 0.5), vec.z);
+}
+
+void mtex_image(vec3 vec, sampler2D ima, out float value, out vec4 color, out vec3 normal)
+{
+ color = texture2D(ima, vec.xy);
+ value = 1.0;
+
+ normal = 2.0*(vec3(color.r, -color.g, color.b) - vec3(0.5, -0.5, 0.5));
+}
+
+void mtex_negate_texnormal(vec3 normal, out vec3 outnormal)
+{
+ outnormal = vec3(-normal.x, -normal.y, normal.z);
+}
+
+void mtex_nspace_tangent(vec3 tangent, vec3 normal, vec3 texnormal, out vec3 outnormal)
+{
+ tangent = normalize(tangent);
+ vec3 B = cross(normal, tangent);
+
+ outnormal = texnormal.x*tangent + texnormal.y*B + texnormal.z*normal;
+ outnormal = normalize(outnormal);
+}
+
+void mtex_blend_normal(float norfac, vec3 normal, vec3 newnormal, out vec3 outnormal)
+{
+ outnormal = (1.0 - norfac)*normal + norfac*newnormal;
+ outnormal = normalize(outnormal);
+}
+
+/******* MATERIAL *********/
+
+void lamp_visibility_sun_hemi(vec3 lampvec, out vec3 lv, out float dist, out float visifac)
+{
+ lv = lampvec;
+ dist = 1.0;
+ visifac = 1.0;
+}
+
+void lamp_visibility_other(vec3 co, vec3 lampco, out vec3 lv, out float dist, out float visifac)
+{
+ lv = co - lampco;
+ dist = length(lv);
+ lv = normalize(lv);
+ visifac = 1.0;
+}
+
+void lamp_falloff_invlinear(float lampdist, float dist, out float visifac)
+{
+ visifac = lampdist/(lampdist + dist);
+}
+
+void lamp_falloff_invsquare(float lampdist, float dist, out float visifac)
+{
+ visifac = lampdist/(lampdist + dist*dist);
+}
+
+void lamp_falloff_sliders(float lampdist, float ld1, float ld2, float dist, out float visifac)
+{
+ float lampdistkw = lampdist*lampdist;
+
+ visifac = lampdist/(lampdist + ld1*dist);
+ visifac *= lampdistkw/(lampdistkw + ld2*dist*dist);
+}
+
+void lamp_falloff_curve(float lampdist, sampler1D curvemap, float dist, out float visifac)
+{
+ visifac = texture1D(curvemap, dist/lampdist).x;
+}
+
+void lamp_visibility_sphere(float lampdist, float dist, float visifac, out float outvisifac)
+{
+ float t= lampdist - dist;
+
+ outvisifac= visifac*max(t, 0.0)/lampdist;
+}
+
+void lamp_visibility_spot_square(vec3 lampvec, mat4 lampimat, vec3 lv, out float inpr)
+{
+ if(dot(lv, lampvec) > 0.0) {
+ vec3 lvrot = (lampimat*vec4(lv, 0.0)).xyz;
+ float x = max(abs(lvrot.x/lvrot.z), abs(lvrot.y/lvrot.z));
+
+ inpr = 1.0/sqrt(1.0 + x*x);
+ }
+ else
+ inpr = 0.0;
+}
+
+void lamp_visibility_spot_circle(vec3 lampvec, vec3 lv, out float inpr)
+{
+ inpr = dot(lv, lampvec);
+}
+
+void lamp_visibility_spot(float spotsi, float spotbl, float inpr, float visifac, out float outvisifac)
+{
+ float t = spotsi;
+
+ if(inpr <= t) {
+ outvisifac = 0.0;
+ }
+ else {
+ t = inpr - t;
+
+ /* soft area */
+ if(spotbl != 0.0)
+ inpr *= smoothstep(0.0, 1.0, t/spotbl);
+
+ outvisifac = visifac*inpr;
+ }
+}
+
+void lamp_visibility_clamp(float visifac, out float outvisifac)
+{
+ outvisifac = (visifac < 0.001)? 0.0: visifac;
+}
+
+void shade_view(vec3 co, out vec3 view)
+{
+ /* handle perspective/orthographic */
+ view = (gl_ProjectionMatrix[3][3] == 0.0)? normalize(co): vec3(0.0, 0.0, -1.0);
+}
+
+void shade_tangent_v(vec3 lv, vec3 tang, out vec3 vn)
+{
+ vec3 c = cross(lv, tang);
+ vec3 vnor = cross(c, tang);
+
+ vn = -normalize(vnor);
+}
+
+void shade_inp(vec3 vn, vec3 lv, out float inp)
+{
+ inp = dot(vn, lv);
+}
+
+void shade_is_no_diffuse(out float is)
+{
+ is = 0.0;
+}
+
+void shade_is_hemi(float inp, out float is)
+{
+ is = 0.5*inp + 0.5;
+}
+
+float area_lamp_energy(mat4 area, vec3 co, vec3 vn)
+{
+ vec3 vec[4], c[4];
+ float rad[4], fac;
+
+ vec[0] = normalize(co - area[0].xyz);
+ vec[1] = normalize(co - area[1].xyz);
+ vec[2] = normalize(co - area[2].xyz);
+ vec[3] = normalize(co - area[3].xyz);
+
+ c[0] = normalize(cross(vec[0], vec[1]));
+ c[1] = normalize(cross(vec[1], vec[2]));
+ c[2] = normalize(cross(vec[2], vec[3]));
+ c[3] = normalize(cross(vec[3], vec[0]));
+
+ rad[0] = acos(dot(vec[0], vec[1]));
+ rad[1] = acos(dot(vec[1], vec[2]));
+ rad[2] = acos(dot(vec[2], vec[3]));
+ rad[3] = acos(dot(vec[3], vec[0]));
+
+ fac= rad[0]*dot(vn, c[0]);
+ fac+= rad[1]*dot(vn, c[1]);
+ fac+= rad[2]*dot(vn, c[2]);
+ fac+= rad[3]*dot(vn, c[3]);
+
+ return max(fac, 0.0);
+}
+
+void shade_inp_area(vec3 position, vec3 lampco, vec3 lampvec, vec3 vn, mat4 area, float areasize, float k, out float inp)
+{
+ vec3 co = position;
+ vec3 vec = co - lampco;
+
+ if(dot(vec, lampvec) < 0.0) {
+ inp = 0.0;
+ }
+ else {
+ float intens = area_lamp_energy(area, co, vn);
+
+ inp = pow(intens*areasize, k);
+ }
+}
+
+void shade_diffuse_oren_nayer(float nl, vec3 n, vec3 l, vec3 v, float rough, out float is)
+{
+ vec3 h = normalize(v + l);
+ float nh = max(dot(n, h), 0.0);
+ float nv = max(dot(n, v), 0.0);
+ float realnl = dot(n, l);
+
+ if(realnl < 0.0) {
+ is = 0.0;
+ }
+ else if(nl < 0.0) {
+ is = 0.0;
+ }
+ else {
+ float vh = max(dot(v, h), 0.0);
+ float Lit_A = acos(realnl);
+ float View_A = acos(nv);
+
+ vec3 Lit_B = normalize(l - realnl*n);
+ vec3 View_B = normalize(v - nv*n);
+
+ float t = max(dot(Lit_B, View_B), 0.0);
+
+ float a, b;
+
+ if(Lit_A > View_A) {
+ a = Lit_A;
+ b = View_A;
+ }
+ else {
+ a = View_A;
+ b = Lit_A;
+ }
+
+ float A = 1.0 - (0.5*((rough*rough)/((rough*rough) + 0.33)));
+ float B = 0.45*((rough*rough)/((rough*rough) + 0.09));
+
+ b *= 0.95;
+ is = nl*(A + (B * t * sin(a) * tan(b)));
+ }
+}
+
+void shade_diffuse_toon(vec3 n, vec3 l, vec3 v, float size, float tsmooth, out float is)
+{
+ float rslt = dot(n, l);
+ float ang = acos(rslt);
+
+ if(ang < size) is = 1.0;
+ else if(ang > (size + tsmooth) || tsmooth == 0.0) is = 0.0;
+ else is = 1.0 - ((ang - size)/tsmooth);
+}
+
+void shade_diffuse_minnaert(float nl, vec3 n, vec3 v, float darkness, out float is)
+{
+ if(nl <= 0.0) {
+ is = 0.0;
+ }
+ else {
+ float nv = max(dot(n, v), 0.0);
+
+ if(darkness <= 1.0)
+ is = nl*pow(max(nv*nl, 0.1), darkness - 1.0);
+ else
+ is = nl*pow(1.0001 - nv, darkness - 1.0);
+ }
+}
+
+float fresnel_fac(vec3 view, vec3 vn, float grad, float fac)
+{
+ float t1, t2;
+ float ffac;
+
+ if(fac==0.0) {
+ ffac = 1.0;
+ }
+ else {
+ t1= dot(view, vn);
+ if(t1>0.0) t2= 1.0+t1;
+ else t2= 1.0-t1;
+
+ t2= grad + (1.0-grad)*pow(t2, fac);
+
+ if(t2<0.0) ffac = 0.0;
+ else if(t2>1.0) ffac = 1.0;
+ else ffac = t2;
+ }
+
+ return ffac;
+}
+
+void shade_diffuse_fresnel(vec3 vn, vec3 lv, vec3 view, float fac_i, float fac, out float is)
+{
+ is = fresnel_fac(lv, vn, fac_i, fac);
+}
+
+void shade_cubic(float is, out float outis)
+{
+ if(is>0.0 && is<1.0)
+ outis= smoothstep(0.0, 1.0, is);
+ else
+ outis= is;
+}
+
+void shade_visifac(float i, float visifac, float refl, out float outi)
+{
+ /*if(i > 0.0)*/
+ outi = max(i*visifac*refl, 0.0);
+ /*else
+ outi = i;*/
+}
+
+void shade_tangent_v_spec(vec3 tang, out vec3 vn)
+{
+ vn = tang;
+}
+
+void shade_add_to_diffuse(float i, vec3 lampcol, vec3 col, out vec3 outcol)
+{
+ if(i > 0.0)
+ outcol = i*lampcol*col;
+ else
+ outcol = vec3(0.0, 0.0, 0.0);
+}
+
+void shade_hemi_spec(vec3 vn, vec3 lv, vec3 view, float spec, float hard, float visifac, out float t)
+{
+ lv += view;
+ lv = normalize(lv);
+
+ t = dot(vn, lv);
+ t = 0.5*t + 0.5;
+
+ t = visifac*spec*pow(t, hard);
+}
+
+void shade_phong_spec(vec3 n, vec3 l, vec3 v, float hard, out float specfac)
+{
+ vec3 h = normalize(l + v);
+ float rslt = max(dot(h, n), 0.0);
+
+ specfac = pow(rslt, hard);
+}
+
+void shade_cooktorr_spec(vec3 n, vec3 l, vec3 v, float hard, out float specfac)
+{
+ vec3 h = normalize(v + l);
+ float nh = dot(n, h);
+
+ if(nh < 0.0) {
+ specfac = 0.0;
+ }
+ else {
+ float nv = max(dot(n, v), 0.0);
+ float i = pow(nh, hard);
+
+ i = i/(0.1+nv);
+ specfac = i;
+ }
+}
+
+void shade_blinn_spec(vec3 n, vec3 l, vec3 v, float refrac, float spec_power, out float specfac)
+{
+ if(refrac < 1.0) {
+ specfac = 0.0;
+ }
+ else if(spec_power == 0.0) {
+ specfac = 0.0;
+ }
+ else {
+ if(spec_power<100.0)
+ spec_power= sqrt(1.0/spec_power);
+ else
+ spec_power= 10.0/spec_power;
+
+ vec3 h = normalize(v + l);
+ float nh = dot(n, h);
+ if(nh < 0.0) {
+ specfac = 0.0;
+ }
+ else {
+ float nv = max(dot(n, v), 0.01);
+ float nl = dot(n, l);
+ if(nl <= 0.01) {
+ specfac = 0.0;
+ }
+ else {
+ float vh = max(dot(v, h), 0.01);
+
+ float a = 1.0;
+ float b = (2.0*nh*nv)/vh;
+ float c = (2.0*nh*nl)/vh;
+
+ float g = 0.0;
+
+ if(a < b && a < c) g = a;
+ else if(b < a && b < c) g = b;
+ else if(c < a && c < b) g = c;
+
+ float p = sqrt(((refrac * refrac)+(vh*vh)-1.0));
+ float f = (((p-vh)*(p-vh))/((p+vh)*(p+vh)))*(1.0+((((vh*(p+vh))-1.0)*((vh*(p+vh))-1.0))/(((vh*(p-vh))+1.0)*((vh*(p-vh))+1.0))));
+ float ang = acos(nh);
+
+ specfac = max(f*g*exp_blender((-(ang*ang)/(2.0*spec_power*spec_power))), 0.0);
+ }
+ }
+ }
+}
+
+void shade_wardiso_spec(vec3 n, vec3 l, vec3 v, float rms, out float specfac)
+{
+ vec3 h = normalize(l + v);
+ float nh = max(dot(n, h), 0.001);
+ float nv = max(dot(n, v), 0.001);
+ float nl = max(dot(n, l), 0.001);
+ float angle = tan(acos(nh));
+ float alpha = max(rms, 0.001);
+
+ specfac= nl * (1.0/(4.0*M_PI*alpha*alpha))*(exp_blender(-(angle*angle)/(alpha*alpha))/(sqrt(nv*nl)));
+}
+
+void shade_toon_spec(vec3 n, vec3 l, vec3 v, float size, float tsmooth, out float specfac)
+{
+ vec3 h = normalize(l + v);
+ float rslt = dot(h, n);
+ float ang = acos(rslt);
+
+ if(ang < size) rslt = 1.0;
+ else if(ang >= (size + tsmooth) || tsmooth == 0.0) rslt = 0.0;
+ else rslt = 1.0 - ((ang - size)/tsmooth);
+
+ specfac = rslt;
+}
+
+void shade_spec_area_inp(float specfac, float inp, out float outspecfac)
+{
+ outspecfac = specfac*inp;
+}
+
+void shade_spec_t(float shadfac, float spec, float visifac, float specfac, out float t)
+{
+ t = shadfac*spec*visifac*specfac;
+}
+
+void shade_add_spec(float t, vec3 lampcol, vec3 speccol, out vec3 outcol)
+{
+ outcol = t*lampcol*speccol;
+}
+
+void shade_add(vec4 col1, vec4 col2, out vec4 outcol)
+{
+ outcol = col1 + col2;
+}
+
+void shade_madd(vec4 col, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ outcol = col + col1*col2;
+}
+
+void shade_maddf(vec4 col, float f, vec4 col1, out vec4 outcol)
+{
+ outcol = col + f*col1;
+}
+
+void shade_mul(vec4 col1, vec4 col2, out vec4 outcol)
+{
+ outcol = col1*col2;
+}
+
+void shade_mul_value(float fac, vec4 col, out vec4 outcol)
+{
+ outcol = col*fac;
+}
+
+void shade_obcolor(vec4 col, vec4 obcol, out vec4 outcol)
+{
+ outcol = vec4(col.rgb*obcol.rgb, col.a);
+}
+
+void ramp_rgbtobw(vec3 color, out float outval)
+{
+ outval = color.r*0.3 + color.g*0.58 + color.b*0.12;
+}
+
+void shade_only_shadow(float i, float shadfac, float energy, out float outshadfac)
+{
+ outshadfac = i*energy*(1.0 - shadfac);
+}
+
+void shade_only_shadow_diffuse(float shadfac, vec3 rgb, vec4 diff, out vec4 outdiff)
+{
+ outdiff = diff - vec4(rgb*shadfac, 0.0);
+}
+
+void shade_only_shadow_specular(float shadfac, vec3 specrgb, vec4 spec, out vec4 outspec)
+{
+ outspec = spec - vec4(specrgb*shadfac, 0.0);
+}
+
+void test_shadowbuf(vec3 rco, sampler2DShadow shadowmap, mat4 shadowpersmat, float shadowbias, float inp, out float result)
+{
+ if(inp <= 0.0) {
+ result = 0.0;
+ }
+ else {
+ vec4 co = shadowpersmat*vec4(rco, 1.0);
+
+ //float bias = (1.5 - inp*inp)*shadowbias;
+ co.z -= shadowbias*co.w;
+
+ result = shadow2DProj(shadowmap, co).x;
+ }
+}
+
+void shade_exposure_correct(vec3 col, float linfac, float logfac, out vec3 outcol)
+{
+ outcol = linfac*(1.0 - exp(col*logfac));
+}
+
+void shade_mist_factor(vec3 co, float miststa, float mistdist, float misttype, float misi, out float outfac)
+{
+ float fac, zcor;
+
+ zcor = (gl_ProjectionMatrix[3][3] == 0.0)? length(co): -co[2];
+
+ fac = clamp((zcor-miststa)/mistdist, 0.0, 1.0);
+ if(misttype == 0.0) fac *= fac;
+ else if(misttype == 1.0);
+ else fac = sqrt(fac);
+
+ outfac = 1.0 - (1.0-fac)*(1.0-misi);
+}
+
+void shade_world_mix(vec3 hor, vec4 col, out vec4 outcol)
+{
+ float fac = clamp(col.a, 0.0, 1.0);
+ outcol = vec4(mix(hor, col.rgb, fac), col.a);
+}
+
+void shade_alpha_opaque(vec4 col, out vec4 outcol)
+{
+ outcol = vec4(col.rgb, 1.0);
+}
+
+void shade_alpha_obcolor(vec4 col, vec4 obcol, out vec4 outcol)
+{
+ outcol = vec4(col.rgb, col.a*obcol.a);
+}
+
diff --git a/source/blender/gpu/intern/gpu_shader_material.glsl.c b/source/blender/gpu/intern/gpu_shader_material.glsl.c
new file mode 100644
index 00000000000..8287efe84ea
--- /dev/null
+++ b/source/blender/gpu/intern/gpu_shader_material.glsl.c
@@ -0,0 +1,1032 @@
+/* DataToC output of file <gpu_shader_material_glsl> */
+
+int datatoc_gpu_shader_material_glsl_size= 32828;
+char datatoc_gpu_shader_material_glsl[]= {
+ 10,102,108,111, 97,116, 32,101,120,112, 95, 98,108,101,110,100,101,114, 40,102,108,111, 97,116, 32,102, 41, 10,
+123, 10, 9,114,101,116,117,114,110, 32,112,111,119, 40, 50, 46, 55, 49, 56, 50, 56, 49, 56, 50, 56, 52, 54, 44, 32,102, 41, 59,
+ 10,125, 10, 10,118,111,105,100, 32,114,103, 98, 95,116,111, 95,104,115,118, 40,118,101, 99, 52, 32,114,103, 98, 44, 32,111,117,
+116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32, 99,109, 97,120, 44, 32, 99,109,
+105,110, 44, 32,104, 44, 32,115, 44, 32,118, 44, 32, 99,100,101,108,116, 97, 59, 10, 9,118,101, 99, 51, 32, 99, 59, 10, 10, 9,
+ 99,109, 97,120, 32, 61, 32,109, 97,120, 40,114,103, 98, 91, 48, 93, 44, 32,109, 97,120, 40,114,103, 98, 91, 49, 93, 44, 32,114,
+103, 98, 91, 50, 93, 41, 41, 59, 10, 9, 99,109,105,110, 32, 61, 32,109,105,110, 40,114,103, 98, 91, 48, 93, 44, 32,109,105,110,
+ 40,114,103, 98, 91, 49, 93, 44, 32,114,103, 98, 91, 50, 93, 41, 41, 59, 10, 9, 99,100,101,108,116, 97, 32, 61, 32, 99,109, 97,
+120, 45, 99,109,105,110, 59, 10, 10, 9,118, 32, 61, 32, 99,109, 97,120, 59, 10, 9,105,102, 32, 40, 99,109, 97,120, 33, 61, 48,
+ 46, 48, 41, 10, 9, 9,115, 32, 61, 32, 99,100,101,108,116, 97, 47, 99,109, 97,120, 59, 10, 9,101,108,115,101, 32,123, 10, 9,
+ 9,115, 32, 61, 32, 48, 46, 48, 59, 10, 9, 9,104, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 10, 9,105,102, 32, 40,115, 32,
+ 61, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,104, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, 10,
+ 9, 9, 99, 32, 61, 32, 40,118,101, 99, 51, 40, 99,109, 97,120, 44, 32, 99,109, 97,120, 44, 32, 99,109, 97,120, 41, 32, 45, 32,
+114,103, 98, 46,120,121,122, 41, 47, 99,100,101,108,116, 97, 59, 10, 10, 9, 9,105,102, 32, 40,114,103, 98, 46,120, 61, 61, 99,
+109, 97,120, 41, 32,104, 32, 61, 32, 99, 91, 50, 93, 32, 45, 32, 99, 91, 49, 93, 59, 10, 9, 9,101,108,115,101, 32,105,102, 32,
+ 40,114,103, 98, 46,121, 61, 61, 99,109, 97,120, 41, 32,104, 32, 61, 32, 50, 46, 48, 32, 43, 32, 99, 91, 48, 93, 32, 45, 32, 32,
+ 99, 91, 50, 93, 59, 10, 9, 9,101,108,115,101, 32,104, 32, 61, 32, 52, 46, 48, 32, 43, 32, 99, 91, 49, 93, 32, 45, 32, 99, 91,
+ 48, 93, 59, 10, 10, 9, 9,104, 32, 47, 61, 32, 54, 46, 48, 59, 10, 10, 9, 9,105,102, 32, 40,104, 60, 48, 46, 48, 41, 10, 9,
+ 9, 9,104, 32, 43, 61, 32, 49, 46, 48, 59, 10, 9,125, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32,118,101, 99, 52, 40,104,
+ 44, 32,115, 44, 32,118, 44, 32,114,103, 98, 46,119, 41, 59, 10,125, 10, 10,118,111,105,100, 32,104,115,118, 95,116,111, 95,114,
+103, 98, 40,118,101, 99, 52, 32,104,115,118, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10,
+ 9,102,108,111, 97,116, 32,105, 44, 32,102, 44, 32,112, 44, 32,113, 44, 32,116, 44, 32,104, 44, 32,115, 44, 32,118, 59, 10, 9,
+118,101, 99, 51, 32,114,103, 98, 59, 10, 10, 9,104, 32, 61, 32,104,115,118, 91, 48, 93, 59, 10, 9,115, 32, 61, 32,104,115,118,
+ 91, 49, 93, 59, 10, 9,118, 32, 61, 32,104,115,118, 91, 50, 93, 59, 10, 10, 9,105,102, 40,115, 61, 61, 48, 46, 48, 41, 32,123,
+ 10, 9, 9,114,103, 98, 32, 61, 32,118,101, 99, 51, 40,118, 44, 32,118, 44, 32,118, 41, 59, 10, 9,125, 10, 9,101,108,115,101,
+ 32,123, 10, 9, 9,105,102, 40,104, 61, 61, 49, 46, 48, 41, 10, 9, 9, 9,104, 32, 61, 32, 48, 46, 48, 59, 10, 9, 9, 10, 9,
+ 9,104, 32, 42, 61, 32, 54, 46, 48, 59, 10, 9, 9,105, 32, 61, 32,102,108,111,111,114, 40,104, 41, 59, 10, 9, 9,102, 32, 61,
+ 32,104, 32, 45, 32,105, 59, 10, 9, 9,114,103, 98, 32, 61, 32,118,101, 99, 51, 40,102, 44, 32,102, 44, 32,102, 41, 59, 10, 9,
+ 9,112, 32, 61, 32,118, 42, 40, 49, 46, 48, 45,115, 41, 59, 10, 9, 9,113, 32, 61, 32,118, 42, 40, 49, 46, 48, 45, 40,115, 42,
+102, 41, 41, 59, 10, 9, 9,116, 32, 61, 32,118, 42, 40, 49, 46, 48, 45, 40,115, 42, 40, 49, 46, 48, 45,102, 41, 41, 41, 59, 10,
+ 9, 9, 10, 9, 9,105,102, 32, 40,105, 32, 61, 61, 32, 48, 46, 48, 41, 32,114,103, 98, 32, 61, 32,118,101, 99, 51, 40,118, 44,
+ 32,116, 44, 32,112, 41, 59, 10, 9, 9,101,108,115,101, 32,105,102, 32, 40,105, 32, 61, 61, 32, 49, 46, 48, 41, 32,114,103, 98,
+ 32, 61, 32,118,101, 99, 51, 40,113, 44, 32,118, 44, 32,112, 41, 59, 10, 9, 9,101,108,115,101, 32,105,102, 32, 40,105, 32, 61,
+ 61, 32, 50, 46, 48, 41, 32,114,103, 98, 32, 61, 32,118,101, 99, 51, 40,112, 44, 32,118, 44, 32,116, 41, 59, 10, 9, 9,101,108,
+115,101, 32,105,102, 32, 40,105, 32, 61, 61, 32, 51, 46, 48, 41, 32,114,103, 98, 32, 61, 32,118,101, 99, 51, 40,112, 44, 32,113,
+ 44, 32,118, 41, 59, 10, 9, 9,101,108,115,101, 32,105,102, 32, 40,105, 32, 61, 61, 32, 52, 46, 48, 41, 32,114,103, 98, 32, 61,
+ 32,118,101, 99, 51, 40,116, 44, 32,112, 44, 32,118, 41, 59, 10, 9, 9,101,108,115,101, 32,114,103, 98, 32, 61, 32,118,101, 99,
+ 51, 40,118, 44, 32,112, 44, 32,113, 41, 59, 10, 9,125, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32,118,101, 99, 52, 40,114,
+103, 98, 44, 32,104,115,118, 46,119, 41, 59, 10,125, 10, 10, 35,100,101,102,105,110,101, 32, 77, 95, 80, 73, 32, 51, 46, 49, 52,
+ 49, 53, 57, 50, 54, 53, 51, 53, 56, 57, 55, 57, 51, 50, 51, 56, 52, 54, 10, 10, 47, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42,
+ 32, 83, 72, 65, 68, 69, 82, 32, 78, 79, 68, 69, 83, 32, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 47, 10, 10,
+118,111,105,100, 32,118, 99,111,108, 95, 97,116,116,114,105, 98,117,116,101, 40,118,101, 99, 52, 32, 97,116,116,118, 99,111,108,
+ 44, 32,111,117,116, 32,118,101, 99, 52, 32,118, 99,111,108, 41, 10,123, 10, 9,118, 99,111,108, 32, 61, 32,118,101, 99, 52, 40,
+ 97,116,116,118, 99,111,108, 46,120, 47, 50, 53, 53, 46, 48, 44, 32, 97,116,116,118, 99,111,108, 46,121, 47, 50, 53, 53, 46, 48,
+ 44, 32, 97,116,116,118, 99,111,108, 46,122, 47, 50, 53, 53, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100,
+ 32,117,118, 95, 97,116,116,114,105, 98,117,116,101, 40,118,101, 99, 50, 32, 97,116,116,117,118, 44, 32,111,117,116, 32,118,101,
+ 99, 51, 32,117,118, 41, 10,123, 10, 9,117,118, 32, 61, 32,118,101, 99, 51, 40, 97,116,116,117,118, 42, 50, 46, 48, 32, 45, 32,
+118,101, 99, 50, 40, 49, 46, 48, 44, 32, 49, 46, 48, 41, 44, 32, 48, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,103,101,
+111,109, 40,118,101, 99, 51, 32, 99,111, 44, 32,118,101, 99, 51, 32,110,111,114, 44, 32,109, 97,116, 52, 32,118,105,101,119,105,
+110,118,109, 97,116, 44, 32,118,101, 99, 51, 32, 97,116,116,111,114, 99,111, 44, 32,118,101, 99, 50, 32, 97,116,116,117,118, 44,
+ 32,118,101, 99, 52, 32, 97,116,116,118, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,103,108,111, 98, 97,108, 44, 32,
+111,117,116, 32,118,101, 99, 51, 32,108,111, 99, 97,108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,118,105,101,119, 44, 32,111,
+117,116, 32,118,101, 99, 51, 32,111,114, 99,111, 44, 32,111,117,116, 32,118,101, 99, 51, 32,117,118, 44, 32,111,117,116, 32,118,
+101, 99, 51, 32,110,111,114,109, 97,108, 44, 32,111,117,116, 32,118,101, 99, 52, 32,118, 99,111,108, 44, 32,111,117,116, 32,102,
+108,111, 97,116, 32,102,114,111,110,116, 98, 97, 99,107, 41, 10,123, 10, 9,108,111, 99, 97,108, 32, 61, 32, 99,111, 59, 10, 9,
+118,105,101,119, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,108,111, 99, 97,108, 41, 59, 10, 9,103,108,111, 98, 97,108,
+ 32, 61, 32, 40,118,105,101,119,105,110,118,109, 97,116, 42,118,101, 99, 52, 40,108,111, 99, 97,108, 44, 32, 49, 46, 48, 41, 41,
+ 46,120,121,122, 59, 10, 9,111,114, 99,111, 32, 61, 32, 97,116,116,111,114, 99,111, 59, 10, 9,117,118, 95, 97,116,116,114,105,
+ 98,117,116,101, 40, 97,116,116,117,118, 44, 32,117,118, 41, 59, 10, 9,110,111,114,109, 97,108, 32, 61, 32, 45,110,111,114,109,
+ 97,108,105,122,101, 40,110,111,114, 41, 59, 9, 47, 42, 32, 98,108,101,110,100,101,114, 32,114,101,110,100,101,114, 32,110,111,
+114,109, 97,108, 32,105,115, 32,110,101,103, 97,116,101,100, 32, 42, 47, 10, 9,118, 99,111,108, 95, 97,116,116,114,105, 98,117,
+116,101, 40, 97,116,116,118, 99,111,108, 44, 32,118, 99,111,108, 41, 59, 10, 9,102,114,111,110,116, 98, 97, 99,107, 32, 61, 32,
+ 49, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,112,112,105,110,103, 40,118,101, 99, 51, 32,118,101, 99, 44, 32,109,
+ 97,116, 52, 32,109, 97,116, 44, 32,118,101, 99, 51, 32,109,105,110,118,101, 99, 44, 32,118,101, 99, 51, 32,109, 97,120,118,101,
+ 99, 44, 32,102,108,111, 97,116, 32,100,111,109,105,110, 44, 32,102,108,111, 97,116, 32,100,111,109, 97,120, 44, 32,111,117,116,
+ 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32, 40,109, 97,116, 32, 42,
+ 32,118,101, 99, 52, 40,118,101, 99, 44, 32, 49, 46, 48, 41, 41, 46,120,121,122, 59, 10, 9,105,102, 40,100,111,109,105,110, 32,
+ 61, 61, 32, 49, 46, 48, 41, 10, 9, 9,111,117,116,118,101, 99, 32, 61, 32,109, 97,120, 40,111,117,116,118,101, 99, 44, 32,109,
+105,110,118,101, 99, 41, 59, 10, 9,105,102, 40,100,111,109, 97,120, 32, 61, 61, 32, 49, 46, 48, 41, 10, 9, 9,111,117,116,118,
+101, 99, 32, 61, 32,109,105,110, 40,111,117,116,118,101, 99, 44, 32,109, 97,120,118,101, 99, 41, 59, 10,125, 10, 10,118,111,105,
+100, 32, 99, 97,109,101,114, 97, 40,118,101, 99, 51, 32, 99,111, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,105,
+101,119, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,100,101,112,116,104, 44, 32,111,117,116, 32,102,108,111, 97,
+116, 32,111,117,116,100,105,115,116, 41, 10,123, 10, 9,111,117,116,100,101,112,116,104, 32, 61, 32, 97, 98,115, 40, 99,111, 46,
+122, 41, 59, 10, 9,111,117,116,100,105,115,116, 32, 61, 32,108,101,110,103,116,104, 40, 99,111, 41, 59, 10, 9,111,117,116,118,
+105,101,119, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40, 99,111, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,
+104, 95, 97,100,100, 40,102,108,111, 97,116, 32,118, 97,108, 49, 44, 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,
+116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,118, 97,108, 49,
+ 32, 43, 32,118, 97,108, 50, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95,115,117, 98,116,114, 97, 99,116, 40,102,
+108,111, 97,116, 32,118, 97,108, 49, 44, 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116,
+ 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,118, 97,108, 49, 32, 45, 32,118, 97,108, 50,
+ 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95,109,117,108,116,105,112,108,121, 40,102,108,111, 97,116, 32,118, 97,
+108, 49, 44, 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108,
+ 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,118, 97,108, 49, 32, 42, 32,118, 97,108, 50, 59, 10,125, 10, 10,118,111,
+105,100, 32,109, 97,116,104, 95,100,105,118,105,100,101, 40,102,108,111, 97,116, 32,118, 97,108, 49, 44, 32,102,108,111, 97,116,
+ 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,105,102, 32, 40,
+118, 97,108, 50, 32, 61, 61, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116,118, 97,108, 32, 61, 32, 48, 46, 48, 59, 10, 9,101,108,
+115,101, 10, 9, 9,111,117,116,118, 97,108, 32, 61, 32,118, 97,108, 49, 32, 47, 32,118, 97,108, 50, 59, 10,125, 10, 10,118,111,
+105,100, 32,109, 97,116,104, 95,115,105,110,101, 40,102,108,111, 97,116, 32,118, 97,108, 44, 32,111,117,116, 32,102,108,111, 97,
+116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,115,105,110, 40,118, 97,108, 41, 59, 10,
+125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95, 99,111,115,105,110,101, 40,102,108,111, 97,116, 32,118, 97,108, 44, 32,111,
+117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32, 99,111,115,
+ 40,118, 97,108, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95,116, 97,110,103,101,110,116, 40,102,108,111, 97,
+116, 32,118, 97,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118,
+ 97,108, 32, 61, 32,116, 97,110, 40,118, 97,108, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95, 97,115,105,110,
+ 40,102,108,111, 97,116, 32,118, 97,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10,
+ 9,105,102, 32, 40,118, 97,108, 32, 60, 61, 32, 49, 46, 48, 32, 38, 38, 32,118, 97,108, 32, 62, 61, 32, 45, 49, 46, 48, 41, 10,
+ 9, 9,111,117,116,118, 97,108, 32, 61, 32, 97,115,105,110, 40,118, 97,108, 41, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,
+116,118, 97,108, 32, 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95, 97, 99,111,115, 40,102,108,
+111, 97,116, 32,118, 97,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,105,102,
+ 32, 40,118, 97,108, 32, 60, 61, 32, 49, 46, 48, 32, 38, 38, 32,118, 97,108, 32, 62, 61, 32, 45, 49, 46, 48, 41, 10, 9, 9,111,
+117,116,118, 97,108, 32, 61, 32, 97, 99,111,115, 40,118, 97,108, 41, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116,118, 97,
+108, 32, 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95, 97,116, 97,110, 40,102,108,111, 97,116,
+ 32,118, 97,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,
+108, 32, 61, 32, 97,116, 97,110, 40,118, 97,108, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95,112,111,119, 40,
+102,108,111, 97,116, 32,118, 97,108, 49, 44, 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,
+116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,105,102, 32, 40,118, 97,108, 49, 32, 62, 61, 32, 48, 46, 48, 41, 10, 9, 9,
+111,117,116,118, 97,108, 32, 61, 32,112,111,119, 40,118, 97,108, 49, 44, 32,118, 97,108, 50, 41, 59, 10, 9,101,108,115,101, 10,
+ 9, 9,111,117,116,118, 97,108, 32, 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95,108,111,103,
+ 40,102,108,111, 97,116, 32,118, 97,108, 49, 44, 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111,
+ 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,105,102, 40,118, 97,108, 49, 32, 62, 32, 48, 46, 48, 32, 32, 38, 38, 32,
+118, 97,108, 50, 32, 62, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116,118, 97,108, 61, 32,108,111,103, 50, 40,118, 97,108, 49, 41,
+ 32, 47, 32,108,111,103, 50, 40,118, 97,108, 50, 41, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116,118, 97,108, 61, 32, 48,
+ 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95,109, 97,120, 40,102,108,111, 97,116, 32,118, 97,108, 49, 44,
+ 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123,
+ 10, 9,111,117,116,118, 97,108, 32, 61, 32,109, 97,120, 40,118, 97,108, 49, 44, 32,118, 97,108, 50, 41, 59, 10,125, 10, 10,118,
+111,105,100, 32,109, 97,116,104, 95,109,105,110, 40,102,108,111, 97,116, 32,118, 97,108, 49, 44, 32,102,108,111, 97,116, 32,118,
+ 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108,
+ 32, 61, 32,109,105,110, 40,118, 97,108, 49, 44, 32,118, 97,108, 50, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104,
+ 95,114,111,117,110,100, 40,102,108,111, 97,116, 32,118, 97,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118,
+ 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 61, 32,102,108,111,111,114, 40,118, 97,108, 32, 43, 32, 48, 46, 53, 41, 59,
+ 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95,108,101,115,115, 95,116,104, 97,110, 40,102,108,111, 97,116, 32,118, 97,
+108, 49, 44, 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108,
+ 41, 10,123, 10, 9,105,102, 40,118, 97,108, 49, 32, 60, 32,118, 97,108, 50, 41, 10, 9, 9,111,117,116,118, 97,108, 32, 61, 32,
+ 49, 46, 48, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116,118, 97,108, 32, 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,
+105,100, 32,109, 97,116,104, 95,103,114,101, 97,116,101,114, 95,116,104, 97,110, 40,102,108,111, 97,116, 32,118, 97,108, 49, 44,
+ 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123,
+ 10, 9,105,102, 40,118, 97,108, 49, 32, 62, 32,118, 97,108, 50, 41, 10, 9, 9,111,117,116,118, 97,108, 32, 61, 32, 49, 46, 48,
+ 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116,118, 97,108, 32, 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,
+115,113,117,101,101,122,101, 40,102,108,111, 97,116, 32,118, 97,108, 44, 32,102,108,111, 97,116, 32,119,105,100,116,104, 44, 32,
+102,108,111, 97,116, 32, 99,101,110,116,101,114, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,
+123, 10, 9,111,117,116,118, 97,108, 32, 61, 32, 49, 46, 48, 47, 40, 49, 46, 48, 32, 43, 32,112,111,119, 40, 50, 46, 55, 49, 56,
+ 50, 56, 49, 56, 51, 44, 32, 45, 40, 40,118, 97,108, 45, 99,101,110,116,101,114, 41, 42,119,105,100,116,104, 41, 41, 41, 59, 10,
+125, 10, 10,118,111,105,100, 32,118,101, 99, 95,109, 97,116,104, 95, 97,100,100, 40,118,101, 99, 51, 32,118, 49, 44, 32,118,101,
+ 99, 51, 32,118, 50, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 44, 32,111,117,116, 32,102,108,111, 97,
+116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32,118, 49, 32, 43, 32,118, 50, 59, 10, 9,
+111,117,116,118, 97,108, 32, 61, 32, 40, 97, 98,115, 40,111,117,116,118,101, 99, 91, 48, 93, 41, 32, 43, 32, 97, 98,115, 40,111,
+117,116,118,101, 99, 91, 49, 93, 41, 32, 43, 32, 97, 98,115, 40,111,117,116,118,101, 99, 91, 50, 93, 41, 41, 47, 51, 46, 48, 59,
+ 10,125, 10, 10,118,111,105,100, 32,118,101, 99, 95,109, 97,116,104, 95,115,117, 98, 40,118,101, 99, 51, 32,118, 49, 44, 32,118,
+101, 99, 51, 32,118, 50, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 44, 32,111,117,116, 32,102,108,111,
+ 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32,118, 49, 32, 45, 32,118, 50, 59, 10,
+ 9,111,117,116,118, 97,108, 32, 61, 32, 40, 97, 98,115, 40,111,117,116,118,101, 99, 91, 48, 93, 41, 32, 43, 32, 97, 98,115, 40,
+111,117,116,118,101, 99, 91, 49, 93, 41, 32, 43, 32, 97, 98,115, 40,111,117,116,118,101, 99, 91, 50, 93, 41, 41, 47, 51, 46, 48,
+ 59, 10,125, 10, 10,118,111,105,100, 32,118,101, 99, 95,109, 97,116,104, 95, 97,118,101,114, 97,103,101, 40,118,101, 99, 51, 32,
+118, 49, 44, 32,118,101, 99, 51, 32,118, 50, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 44, 32,111,117,
+116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32,118, 49, 32, 43,
+ 32,118, 50, 59, 10, 9,111,117,116,118, 97,108, 32, 61, 32,108,101,110,103,116,104, 40,111,117,116,118,101, 99, 41, 59, 10, 9,
+111,117,116,118,101, 99, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,111,117,116,118,101, 99, 41, 59, 10,125, 10, 10,118,
+111,105,100, 32,118,101, 99, 95,109, 97,116,104, 95,100,111,116, 40,118,101, 99, 51, 32,118, 49, 44, 32,118,101, 99, 51, 32,118,
+ 50, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,
+116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32,118,101, 99, 51, 40, 48, 44, 32, 48, 44, 32, 48, 41, 59,
+ 10, 9,111,117,116,118, 97,108, 32, 61, 32,100,111,116, 40,118, 49, 44, 32,118, 50, 41, 59, 10,125, 10, 10,118,111,105,100, 32,
+118,101, 99, 95,109, 97,116,104, 95, 99,114,111,115,115, 40,118,101, 99, 51, 32,118, 49, 44, 32,118,101, 99, 51, 32,118, 50, 44,
+ 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118,
+ 97,108, 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32, 99,114,111,115,115, 40,118, 49, 44, 32,118, 50, 41, 59, 10, 9,
+111,117,116,118, 97,108, 32, 61, 32,108,101,110,103,116,104, 40,111,117,116,118,101, 99, 41, 59, 10,125, 10, 10,118,111,105,100,
+ 32,118,101, 99, 95,109, 97,116,104, 95,110,111,114,109, 97,108,105,122,101, 40,118,101, 99, 51, 32,118, 44, 32,111,117,116, 32,
+118,101, 99, 51, 32,111,117,116,118,101, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123,
+ 10, 9,111,117,116,118, 97,108, 32, 61, 32,108,101,110,103,116,104, 40,118, 41, 59, 10, 9,111,117,116,118,101, 99, 32, 61, 32,
+110,111,114,109, 97,108,105,122,101, 40,118, 41, 59, 10,125, 10, 10,118,111,105,100, 32,118,101, 99, 95,109, 97,116,104, 95,110,
+101,103, 97,116,101, 40,118,101, 99, 51, 32,118, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118, 41, 10,123, 10, 9,
+111,117,116,118, 32, 61, 32, 45,118, 59, 10,125, 10, 10,118,111,105,100, 32,110,111,114,109, 97,108, 40,118,101, 99, 51, 32,100,
+105,114, 44, 32,118,101, 99, 51, 32,110,111,114, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,110,111,114, 44, 32,111,
+117,116, 32,102,108,111, 97,116, 32,111,117,116,100,111,116, 41, 10,123, 10, 9,111,117,116,110,111,114, 32, 61, 32,100,105,114,
+ 59, 10, 9,111,117,116,100,111,116, 32, 61, 32, 45,100,111,116, 40,100,105,114, 44, 32,110,111,114, 41, 59, 10,125, 10, 10,118,
+111,105,100, 32, 99,117,114,118,101,115, 95,118,101, 99, 40,118,101, 99, 51, 32,118,101, 99, 44, 32,115, 97,109,112,108,101,114,
+ 49, 68, 32, 99,117,114,118,101,109, 97,112, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 41, 10,123, 10,
+ 9,111,117,116,118,101, 99, 46,120, 32, 61, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,118,101,109, 97,112, 44, 32,
+ 40,118,101, 99, 46,120, 32, 43, 32, 49, 46, 48, 41, 42, 48, 46, 53, 41, 46,120, 59, 10, 9,111,117,116,118,101, 99, 46,121, 32,
+ 61, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,118,101,109, 97,112, 44, 32, 40,118,101, 99, 46,121, 32, 43, 32, 49,
+ 46, 48, 41, 42, 48, 46, 53, 41, 46,121, 59, 10, 9,111,117,116,118,101, 99, 46,122, 32, 61, 32,116,101,120,116,117,114,101, 49,
+ 68, 40, 99,117,114,118,101,109, 97,112, 44, 32, 40,118,101, 99, 46,122, 32, 43, 32, 49, 46, 48, 41, 42, 48, 46, 53, 41, 46,122,
+ 59, 10,125, 10, 10,118,111,105,100, 32, 99,117,114,118,101,115, 95,114,103, 98, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,115,
+ 97,109,112,108,101,114, 49, 68, 32, 99,117,114,118,101,109, 97,112, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,
+111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 46,114, 32, 61, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,118,
+101,109, 97,112, 44, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,118,101,109, 97,112, 44, 32, 99,111,108, 46,114, 41,
+ 46, 97, 41, 46,114, 59, 10, 9,111,117,116, 99,111,108, 46,103, 32, 61, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,
+118,101,109, 97,112, 44, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,118,101,109, 97,112, 44, 32, 99,111,108, 46,103,
+ 41, 46, 97, 41, 46,103, 59, 10, 9,111,117,116, 99,111,108, 46, 98, 32, 61, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,
+114,118,101,109, 97,112, 44, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,118,101,109, 97,112, 44, 32, 99,111,108, 46,
+ 98, 41, 46, 97, 41, 46, 98, 59, 10, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 46, 97, 59, 10,125, 10, 10,118,
+111,105,100, 32,115,101,116, 95,118, 97,108,117,101, 40,102,108,111, 97,116, 32,118, 97,108, 44, 32,111,117,116, 32,102,108,111,
+ 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,118, 97,108, 59, 10,125, 10, 10,118,
+111,105,100, 32,115,101,116, 95,114,103, 98, 40,118,101, 99, 51, 32, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,
+117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,
+115,101,116, 95,114,103, 98, 97, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,
+111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,115,101,116,
+ 95,118, 97,108,117,101, 95,122,101,114,111, 40,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10,
+ 9,111,117,116,118, 97,108, 32, 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,115,101,116, 95,118, 97,108,117,101,
+ 95,111,110,101, 40,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108,
+ 32, 61, 32, 49, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,115,101,116, 95,114,103, 98, 95,122,101,114,111, 40,111,117,116,
+ 32,118,101, 99, 51, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,118,101, 99, 51, 40, 48,
+ 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,101,116, 95,114,103, 98, 97, 95,122,101,114,111, 40,111,117,116, 32,118,
+101, 99, 52, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,118,101, 99, 52, 40, 48, 46, 48,
+ 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95, 98,108,101,110,100, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,
+118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,
+117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32,
+ 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 32, 61, 32,109,105,120, 40, 99,111,108, 49, 44, 32, 99,111,108, 50, 44, 32,
+102, 97, 99, 41, 59, 10, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105,
+100, 32,109,105,120, 95, 97,100,100, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,
+118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102,
+ 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,
+111,108, 32, 61, 32,109,105,120, 40, 99,111,108, 49, 44, 32, 99,111,108, 49, 32, 43, 32, 99,111,108, 50, 44, 32,102, 97, 99, 41,
+ 59, 10, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,
+120, 95,109,117,108,116, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99,
+ 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32,
+ 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 32,
+ 61, 32,109,105,120, 40, 99,111,108, 49, 44, 32, 99,111,108, 49, 32, 42, 32, 99,111,108, 50, 44, 32,102, 97, 99, 41, 59, 10, 9,
+111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,115,
+ 99,114,101,101,110, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52,
+ 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61,
+ 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,102,108,111, 97,116, 32,102, 97,
+ 99,109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 59, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32,118,101, 99, 52, 40,
+ 49, 46, 48, 41, 32, 45, 32, 40,118,101, 99, 52, 40,102, 97, 99,109, 41, 32, 43, 32,102, 97, 99, 42, 40,118,101, 99, 52, 40, 49,
+ 46, 48, 41, 32, 45, 32, 99,111,108, 50, 41, 41, 42, 40,118,101, 99, 52, 40, 49, 46, 48, 41, 32, 45, 32, 99,111,108, 49, 41, 59,
+ 10, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120,
+ 95,111,118,101,114,108, 97,121, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,
+101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97,
+ 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,102,108,111, 97,116,
+ 32,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 59, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,
+108, 49, 59, 10, 10, 9,105,102, 40,111,117,116, 99,111,108, 46,114, 32, 60, 32, 48, 46, 53, 41, 10, 9, 9,111,117,116, 99,111,
+108, 46,114, 32, 42, 61, 32,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99, 42, 99,111,108, 50, 46,114, 59, 10, 9,101,
+108,115,101, 10, 9, 9,111,117,116, 99,111,108, 46,114, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40,102, 97, 99,109, 32, 43, 32, 50,
+ 46, 48, 42,102, 97, 99, 42, 40, 49, 46, 48, 32, 45, 32, 99,111,108, 50, 46,114, 41, 41, 42, 40, 49, 46, 48, 32, 45, 32,111,117,
+116, 99,111,108, 46,114, 41, 59, 10, 10, 9,105,102, 40,111,117,116, 99,111,108, 46,103, 32, 60, 32, 48, 46, 53, 41, 10, 9, 9,
+111,117,116, 99,111,108, 46,103, 32, 42, 61, 32,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99, 42, 99,111,108, 50, 46,
+103, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116, 99,111,108, 46,103, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40,102, 97, 99,
+109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99, 42, 40, 49, 46, 48, 32, 45, 32, 99,111,108, 50, 46,103, 41, 41, 42, 40, 49, 46, 48,
+ 32, 45, 32,111,117,116, 99,111,108, 46,103, 41, 59, 10, 10, 9,105,102, 40,111,117,116, 99,111,108, 46, 98, 32, 60, 32, 48, 46,
+ 53, 41, 10, 9, 9,111,117,116, 99,111,108, 46, 98, 32, 42, 61, 32,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99, 42,
+ 99,111,108, 50, 46, 98, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116, 99,111,108, 46, 98, 32, 61, 32, 49, 46, 48, 32, 45,
+ 32, 40,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99, 42, 40, 49, 46, 48, 32, 45, 32, 99,111,108, 50, 46, 98, 41, 41,
+ 42, 40, 49, 46, 48, 32, 45, 32,111,117,116, 99,111,108, 46, 98, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,115,
+117, 98, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,
+108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108,
+ 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 32, 61, 32,109,105,
+120, 40, 99,111,108, 49, 44, 32, 99,111,108, 49, 32, 45, 32, 99,111,108, 50, 44, 32,102, 97, 99, 41, 59, 10, 9,111,117,116, 99,
+111,108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,100,105,118, 40,102,
+108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,
+111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,
+102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 32, 61, 32, 49, 46,
+ 48, 32, 45, 32,102, 97, 99, 59, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 49, 59, 10, 10, 9,105,102, 40, 99,
+111,108, 50, 46,114, 32, 33, 61, 32, 48, 46, 48, 41, 32,111,117,116, 99,111,108, 46,114, 32, 61, 32,102, 97, 99,109, 42,111,117,
+116, 99,111,108, 46,114, 32, 43, 32,102, 97, 99, 42,111,117,116, 99,111,108, 46,114, 47, 99,111,108, 50, 46,114, 59, 10, 9,105,
+102, 40, 99,111,108, 50, 46,103, 32, 33, 61, 32, 48, 46, 48, 41, 32,111,117,116, 99,111,108, 46,103, 32, 61, 32,102, 97, 99,109,
+ 42,111,117,116, 99,111,108, 46,103, 32, 43, 32,102, 97, 99, 42,111,117,116, 99,111,108, 46,103, 47, 99,111,108, 50, 46,103, 59,
+ 10, 9,105,102, 40, 99,111,108, 50, 46, 98, 32, 33, 61, 32, 48, 46, 48, 41, 32,111,117,116, 99,111,108, 46, 98, 32, 61, 32,102,
+ 97, 99,109, 42,111,117,116, 99,111,108, 46, 98, 32, 43, 32,102, 97, 99, 42,111,117,116, 99,111,108, 46, 98, 47, 99,111,108, 50,
+ 46, 98, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,100,105,102,102, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,
+118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,
+117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32,
+ 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 32, 61, 32,109,105,120, 40, 99,111,108, 49, 44, 32, 97, 98,115, 40, 99,111,
+108, 49, 32, 45, 32, 99,111,108, 50, 41, 44, 32,102, 97, 99, 41, 59, 10, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,
+108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,100, 97,114,107, 40,102,108,111, 97,116, 32,102, 97, 99,
+ 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52,
+ 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48,
+ 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 46,114,103, 98, 32, 61, 32,109,105,110, 40, 99,111,108, 49, 46,114,
+103, 98, 44, 32, 99,111,108, 50, 46,114,103, 98, 42,102, 97, 99, 41, 59, 10, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,
+111,108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,108,105,103,104,116, 40,102,108,111, 97,116, 32,102,
+ 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101,
+ 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48,
+ 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 46,114,103, 98, 32, 61, 32,109, 97,120, 40, 99,111,108, 49,
+ 46,114,103, 98, 44, 32, 99,111,108, 50, 46,114,103, 98, 42,102, 97, 99, 41, 59, 10, 9,111,117,116, 99,111,108, 46, 97, 32, 61,
+ 32, 99,111,108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,100,111,100,103,101, 40,102,108,111, 97,116,
+ 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,
+118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44,
+ 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 49, 59, 10, 10, 9,105,102,
+ 40,111,117,116, 99,111,108, 46,114, 32, 33, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,102,108,111, 97,116, 32,116,109,112, 32,
+ 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 42, 99,111,108, 50, 46,114, 59, 10, 9, 9,105,102, 40,116,109,112, 32, 60, 61, 32,
+ 48, 46, 48, 41, 10, 9, 9, 9,111,117,116, 99,111,108, 46,114, 32, 61, 32, 49, 46, 48, 59, 10, 9, 9,101,108,115,101, 32,105,
+102, 40, 40,116,109,112, 32, 61, 32,111,117,116, 99,111,108, 46,114, 47,116,109,112, 41, 32, 62, 32, 49, 46, 48, 41, 10, 9, 9,
+ 9,111,117,116, 99,111,108, 46,114, 32, 61, 32, 49, 46, 48, 59, 10, 9, 9,101,108,115,101, 10, 9, 9, 9,111,117,116, 99,111,
+108, 46,114, 32, 61, 32,116,109,112, 59, 10, 9,125, 10, 9,105,102, 40,111,117,116, 99,111,108, 46,103, 32, 33, 61, 32, 48, 46,
+ 48, 41, 32,123, 10, 9, 9,102,108,111, 97,116, 32,116,109,112, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 42, 99,111,108,
+ 50, 46,103, 59, 10, 9, 9,105,102, 40,116,109,112, 32, 60, 61, 32, 48, 46, 48, 41, 10, 9, 9, 9,111,117,116, 99,111,108, 46,
+103, 32, 61, 32, 49, 46, 48, 59, 10, 9, 9,101,108,115,101, 32,105,102, 40, 40,116,109,112, 32, 61, 32,111,117,116, 99,111,108,
+ 46,103, 47,116,109,112, 41, 32, 62, 32, 49, 46, 48, 41, 10, 9, 9, 9,111,117,116, 99,111,108, 46,103, 32, 61, 32, 49, 46, 48,
+ 59, 10, 9, 9,101,108,115,101, 10, 9, 9, 9,111,117,116, 99,111,108, 46,103, 32, 61, 32,116,109,112, 59, 10, 9,125, 10, 9,
+105,102, 40,111,117,116, 99,111,108, 46, 98, 32, 33, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,102,108,111, 97,116, 32,116,109,
+112, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 42, 99,111,108, 50, 46, 98, 59, 10, 9, 9,105,102, 40,116,109,112, 32, 60,
+ 61, 32, 48, 46, 48, 41, 10, 9, 9, 9,111,117,116, 99,111,108, 46, 98, 32, 61, 32, 49, 46, 48, 59, 10, 9, 9,101,108,115,101,
+ 32,105,102, 40, 40,116,109,112, 32, 61, 32,111,117,116, 99,111,108, 46, 98, 47,116,109,112, 41, 32, 62, 32, 49, 46, 48, 41, 10,
+ 9, 9, 9,111,117,116, 99,111,108, 46, 98, 32, 61, 32, 49, 46, 48, 59, 10, 9, 9,101,108,115,101, 10, 9, 9, 9,111,117,116,
+ 99,111,108, 46, 98, 32, 61, 32,116,109,112, 59, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95, 98,117,114,110,
+ 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50,
+ 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,
+112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,102,108,111, 97,116, 32,116,109,112, 44, 32,102, 97,
+ 99,109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 59, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 49, 59,
+ 10, 10, 9,116,109,112, 32, 61, 32,102, 97, 99,109, 32, 43, 32,102, 97, 99, 42, 99,111,108, 50, 46,114, 59, 10, 9,105,102, 40,
+116,109,112, 32, 60, 61, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116, 99,111,108, 46,114, 32, 61, 32, 48, 46, 48, 59, 10, 9,101,
+108,115,101, 32,105,102, 40, 40,116,109,112, 32, 61, 32, 40, 49, 46, 48, 32, 45, 32, 40, 49, 46, 48, 32, 45, 32,111,117,116, 99,
+111,108, 46,114, 41, 47,116,109,112, 41, 41, 32, 60, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116, 99,111,108, 46,114, 32, 61, 32,
+ 48, 46, 48, 59, 10, 9,101,108,115,101, 32,105,102, 40,116,109,112, 32, 62, 32, 49, 46, 48, 41, 10, 9, 9,111,117,116, 99,111,
+108, 46,114, 32, 61, 32, 49, 46, 48, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116, 99,111,108, 46,114, 32, 61, 32,116,109,
+112, 59, 10, 10, 9,116,109,112, 32, 61, 32,102, 97, 99,109, 32, 43, 32,102, 97, 99, 42, 99,111,108, 50, 46,103, 59, 10, 9,105,
+102, 40,116,109,112, 32, 60, 61, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116, 99,111,108, 46,103, 32, 61, 32, 48, 46, 48, 59, 10,
+ 9,101,108,115,101, 32,105,102, 40, 40,116,109,112, 32, 61, 32, 40, 49, 46, 48, 32, 45, 32, 40, 49, 46, 48, 32, 45, 32,111,117,
+116, 99,111,108, 46,103, 41, 47,116,109,112, 41, 41, 32, 60, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116, 99,111,108, 46,103, 32,
+ 61, 32, 48, 46, 48, 59, 10, 9,101,108,115,101, 32,105,102, 40,116,109,112, 32, 62, 32, 49, 46, 48, 41, 10, 9, 9,111,117,116,
+ 99,111,108, 46,103, 32, 61, 32, 49, 46, 48, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116, 99,111,108, 46,103, 32, 61, 32,
+116,109,112, 59, 10, 10, 9,116,109,112, 32, 61, 32,102, 97, 99,109, 32, 43, 32,102, 97, 99, 42, 99,111,108, 50, 46, 98, 59, 10,
+ 9,105,102, 40,116,109,112, 32, 60, 61, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116, 99,111,108, 46, 98, 32, 61, 32, 48, 46, 48,
+ 59, 10, 9,101,108,115,101, 32,105,102, 40, 40,116,109,112, 32, 61, 32, 40, 49, 46, 48, 32, 45, 32, 40, 49, 46, 48, 32, 45, 32,
+111,117,116, 99,111,108, 46, 98, 41, 47,116,109,112, 41, 41, 32, 60, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116, 99,111,108, 46,
+ 98, 32, 61, 32, 48, 46, 48, 59, 10, 9,101,108,115,101, 32,105,102, 40,116,109,112, 32, 62, 32, 49, 46, 48, 41, 10, 9, 9,111,
+117,116, 99,111,108, 46, 98, 32, 61, 32, 49, 46, 48, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116, 99,111,108, 46, 98, 32,
+ 61, 32,116,109,112, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,104,117,101, 40,102,108,111, 97,116, 32,102, 97, 99,
+ 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52,
+ 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48,
+ 44, 32, 49, 46, 48, 41, 59, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 59,
+ 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 49, 59, 10, 10, 9,118,101, 99, 52, 32,104,115,118, 44, 32,104,115,
+118, 50, 44, 32,116,109,112, 59, 10, 9,114,103, 98, 95,116,111, 95,104,115,118, 40, 99,111,108, 50, 44, 32,104,115,118, 50, 41,
+ 59, 10, 10, 9,105,102, 40,104,115,118, 50, 46,121, 32, 33, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,114,103, 98, 95,116,111,
+ 95,104,115,118, 40,111,117,116, 99,111,108, 44, 32,104,115,118, 41, 59, 10, 9, 9,104,115,118, 46,120, 32, 61, 32,104,115,118,
+ 50, 46,120, 59, 10, 9, 9,104,115,118, 95,116,111, 95,114,103, 98, 40,104,115,118, 44, 32,116,109,112, 41, 59, 32, 10, 10, 9,
+ 9,111,117,116, 99,111,108, 32, 61, 32,109,105,120, 40,111,117,116, 99,111,108, 44, 32,116,109,112, 44, 32,102, 97, 99, 41, 59,
+ 10, 9, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10, 9,125, 10,125, 10, 10,118,111,105,100,
+ 32,109,105,120, 95,115, 97,116, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,
+101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97,
+ 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,102,108,111, 97,116,
+ 32,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 59, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,
+108, 49, 59, 10, 10, 9,118,101, 99, 52, 32,104,115,118, 44, 32,104,115,118, 50, 59, 10, 9,114,103, 98, 95,116,111, 95,104,115,
+118, 40,111,117,116, 99,111,108, 44, 32,104,115,118, 41, 59, 10, 10, 9,105,102, 40,104,115,118, 46,121, 32, 33, 61, 32, 48, 46,
+ 48, 41, 32,123, 10, 9, 9,114,103, 98, 95,116,111, 95,104,115,118, 40, 99,111,108, 50, 44, 32,104,115,118, 50, 41, 59, 10, 10,
+ 9, 9,104,115,118, 46,121, 32, 61, 32,102, 97, 99,109, 42,104,115,118, 46,121, 32, 43, 32,102, 97, 99, 42,104,115,118, 50, 46,
+121, 59, 10, 9, 9,104,115,118, 95,116,111, 95,114,103, 98, 40,104,115,118, 44, 32,111,117,116, 99,111,108, 41, 59, 10, 9,125,
+ 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,118, 97,108, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52,
+ 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,
+108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41,
+ 59, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 59, 10, 10, 9,118,101, 99,
+ 52, 32,104,115,118, 44, 32,104,115,118, 50, 59, 10, 9,114,103, 98, 95,116,111, 95,104,115,118, 40, 99,111,108, 49, 44, 32,104,
+115,118, 41, 59, 10, 9,114,103, 98, 95,116,111, 95,104,115,118, 40, 99,111,108, 50, 44, 32,104,115,118, 50, 41, 59, 10, 10, 9,
+104,115,118, 46,122, 32, 61, 32,102, 97, 99,109, 42,104,115,118, 46,122, 32, 43, 32,102, 97, 99, 42,104,115,118, 50, 46,122, 59,
+ 10, 9,104,115,118, 95,116,111, 95,114,103, 98, 40,104,115,118, 44, 32,111,117,116, 99,111,108, 41, 59, 10,125, 10, 10,118,111,
+105,100, 32,109,105,120, 95, 99,111,108,111,114, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108,
+ 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123,
+ 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,102,
+108,111, 97,116, 32,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 59, 10, 10, 9,111,117,116, 99,111,108, 32,
+ 61, 32, 99,111,108, 49, 59, 10, 10, 9,118,101, 99, 52, 32,104,115,118, 44, 32,104,115,118, 50, 44, 32,116,109,112, 59, 10, 9,
+114,103, 98, 95,116,111, 95,104,115,118, 40, 99,111,108, 50, 44, 32,104,115,118, 50, 41, 59, 10, 10, 9,105,102, 40,104,115,118,
+ 50, 46,121, 32, 33, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,114,103, 98, 95,116,111, 95,104,115,118, 40,111,117,116, 99,111,
+108, 44, 32,104,115,118, 41, 59, 10, 9, 9,104,115,118, 46,120, 32, 61, 32,104,115,118, 50, 46,120, 59, 10, 9, 9,104,115,118,
+ 46,121, 32, 61, 32,104,115,118, 50, 46,121, 59, 10, 9, 9,104,115,118, 95,116,111, 95,114,103, 98, 40,104,115,118, 44, 32,116,
+109,112, 41, 59, 32, 10, 10, 9, 9,111,117,116, 99,111,108, 32, 61, 32,109,105,120, 40,111,117,116, 99,111,108, 44, 32,116,109,
+112, 44, 32,102, 97, 99, 41, 59, 10, 9, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10, 9,125,
+ 10,125, 10, 10,118,111,105,100, 32,118, 97,108,116,111,114,103, 98, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,115, 97,109,
+112,108,101,114, 49, 68, 32, 99,111,108,111,114,109, 97,112, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108,
+ 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116, 97,108,112,104, 97, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32,
+ 61, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,111,108,111,114,109, 97,112, 44, 32,102, 97, 99, 41, 59, 10, 9,111,117,116,
+ 97,108,112,104, 97, 32, 61, 32,111,117,116, 99,111,108, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,114,103, 98,116,111, 98,
+119, 40,118,101, 99, 52, 32, 99,111,108,111,114, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,
+123, 10, 9,111,117,116,118, 97,108, 32, 61, 32, 99,111,108,111,114, 46,114, 42, 48, 46, 51, 53, 32, 43, 32, 99,111,108,111,114,
+ 46,103, 42, 48, 46, 52, 53, 32, 43, 32, 99,111,108,111,114, 46, 98, 42, 48, 46, 50, 59, 10,125, 10, 10,118,111,105,100, 32,105,
+110,118,101,114,116, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 44, 32,111,117,116, 32,118,
+101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 46,120,121,122, 32, 61, 32,109,105,120, 40,
+ 99,111,108, 46,120,121,122, 44, 32,118,101, 99, 51, 40, 49, 46, 48, 44, 32, 49, 46, 48, 44, 32, 49, 46, 48, 41, 32, 45, 32, 99,
+111,108, 46,120,121,122, 44, 32,102, 97, 99, 41, 59, 10, 9,111,117,116, 99,111,108, 46,119, 32, 61, 32, 99,111,108, 46,119, 59,
+ 10,125, 10, 10,118,111,105,100, 32,104,117,101, 95,115, 97,116, 40,102,108,111, 97,116, 32,104,117,101, 44, 32,102,108,111, 97,
+116, 32,115, 97,116, 44, 32,102,108,111, 97,116, 32,118, 97,108,117,101, 44, 32,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,
+101, 99, 52, 32, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,118,101, 99,
+ 52, 32,104,115,118, 59, 10, 10, 9,114,103, 98, 95,116,111, 95,104,115,118, 40, 99,111,108, 44, 32,104,115,118, 41, 59, 10, 10,
+ 9,104,115,118, 91, 48, 93, 32, 43, 61, 32, 40,104,117,101, 32, 45, 32, 48, 46, 53, 41, 59, 10, 9,105,102, 40,104,115,118, 91,
+ 48, 93, 62, 49, 46, 48, 41, 32,104,115,118, 91, 48, 93, 45, 61, 49, 46, 48, 59, 32,101,108,115,101, 32,105,102, 40,104,115,118,
+ 91, 48, 93, 60, 48, 46, 48, 41, 32,104,115,118, 91, 48, 93, 43, 61, 32, 49, 46, 48, 59, 10, 9,104,115,118, 91, 49, 93, 32, 42,
+ 61, 32,115, 97,116, 59, 10, 9,105,102, 40,104,115,118, 91, 49, 93, 62, 49, 46, 48, 41, 32,104,115,118, 91, 49, 93, 61, 32, 49,
+ 46, 48, 59, 32,101,108,115,101, 32,105,102, 40,104,115,118, 91, 49, 93, 60, 48, 46, 48, 41, 32,104,115,118, 91, 49, 93, 61, 32,
+ 48, 46, 48, 59, 10, 9,104,115,118, 91, 50, 93, 32, 42, 61, 32,118, 97,108,117,101, 59, 10, 9,105,102, 40,104,115,118, 91, 50,
+ 93, 62, 49, 46, 48, 41, 32,104,115,118, 91, 50, 93, 61, 32, 49, 46, 48, 59, 32,101,108,115,101, 32,105,102, 40,104,115,118, 91,
+ 50, 93, 60, 48, 46, 48, 41, 32,104,115,118, 91, 50, 93, 61, 32, 48, 46, 48, 59, 10, 10, 9,104,115,118, 95,116,111, 95,114,103,
+ 98, 40,104,115,118, 44, 32,111,117,116, 99,111,108, 41, 59, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32,109,105,120, 40, 99,
+111,108, 44, 32,111,117,116, 99,111,108, 44, 32,102, 97, 99, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,101,112, 97,114, 97,
+116,101, 95,114,103, 98, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,114, 44, 32,111,117,
+116, 32,102,108,111, 97,116, 32,103, 44, 32,111,117,116, 32,102,108,111, 97,116, 32, 98, 41, 10,123, 10, 9,114, 32, 61, 32, 99,
+111,108, 46,114, 59, 10, 9,103, 32, 61, 32, 99,111,108, 46,103, 59, 10, 9, 98, 32, 61, 32, 99,111,108, 46, 98, 59, 10,125, 10,
+ 10,118,111,105,100, 32, 99,111,109, 98,105,110,101, 95,114,103, 98, 40,102,108,111, 97,116, 32,114, 44, 32,102,108,111, 97,116,
+ 32,103, 44, 32,102,108,111, 97,116, 32, 98, 44, 32,111,117,116, 32,118,101, 99, 52, 32, 99,111,108, 41, 10,123, 10, 9, 99,111,
+108, 32, 61, 32,118,101, 99, 52, 40,114, 44, 32,103, 44, 32, 98, 44, 32, 49, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,
+111,117,116,112,117,116, 95,110,111,100,101, 40,118,101, 99, 52, 32,114,103, 98, 44, 32,102,108,111, 97,116, 32, 97,108,112,104,
+ 97, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116,114,103, 98, 41, 10,123, 10, 9,111,117,116,114,103, 98, 32, 61, 32,
+118,101, 99, 52, 40,114,103, 98, 46,114,103, 98, 44, 32, 97,108,112,104, 97, 41, 59, 10,125, 10, 10, 47, 42, 42, 42, 42, 42, 42,
+ 42, 42, 42, 42, 42, 32, 84, 69, 88, 84, 85, 82, 69, 83, 32, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 47, 10,
+ 10,118,111,105,100, 32,116,101,120,116,117,114,101, 95,102,108,105,112, 95, 98,108,101,110,100, 40,118,101, 99, 51, 32,118,101,
+ 99, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32,
+118,101, 99, 46,121,120,122, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120,116,117,114,101, 95, 98,108,101,110,100, 95,108,
+105,110, 40,118,101, 99, 51, 32,118,101, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123,
+ 10, 9,111,117,116,118, 97,108, 32, 61, 32, 40, 49, 46, 48, 43,118,101, 99, 46,120, 41, 47, 50, 46, 48, 59, 10,125, 10, 10,118,
+111,105,100, 32,116,101,120,116,117,114,101, 95, 98,108,101,110,100, 95,113,117, 97,100, 40,118,101, 99, 51, 32,118,101, 99, 44,
+ 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,109,
+ 97,120, 40, 40, 49, 46, 48, 43,118,101, 99, 46,120, 41, 47, 50, 46, 48, 44, 32, 48, 46, 48, 41, 59, 10, 9,111,117,116,118, 97,
+108, 32, 42, 61, 32,111,117,116,118, 97,108, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120,116,117,114,101, 95,119,111,111,
+100, 95,115,105,110, 40,118,101, 99, 51, 32,118,101, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,118, 97,108,117,101, 44,
+ 32,111,117,116, 32,118,101, 99, 52, 32, 99,111,108,111,114, 44, 32,111,117,116, 32,118,101, 99, 51, 32,110,111,114,109, 97,108,
+ 41, 10,123, 10, 9,102,108,111, 97,116, 32, 97, 32, 61, 32,115,113,114,116, 40,118,101, 99, 46,120, 42,118,101, 99, 46,120, 32,
+ 43, 32,118,101, 99, 46,121, 42,118,101, 99, 46,121, 32, 43, 32,118,101, 99, 46,122, 42,118,101, 99, 46,122, 41, 42, 50, 48, 46,
+ 48, 59, 10, 9,102,108,111, 97,116, 32,119,105, 32, 61, 32, 48, 46, 53, 32, 43, 32, 48, 46, 53, 42,115,105,110, 40, 97, 41, 59,
+ 10, 10, 9,118, 97,108,117,101, 32, 61, 32,119,105, 59, 10, 9, 99,111,108,111,114, 32, 61, 32,118,101, 99, 52, 40,119,105, 44,
+ 32,119,105, 44, 32,119,105, 44, 32, 49, 46, 48, 41, 59, 10, 9,110,111,114,109, 97,108, 32, 61, 32,118,101, 99, 51, 40, 48, 46,
+ 48, 44, 32, 48, 46, 48, 44, 32, 48, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120,116,117,114,101, 95,105,109,
+ 97,103,101, 40,118,101, 99, 51, 32,118,101, 99, 44, 32,115, 97,109,112,108,101,114, 50, 68, 32,105,109, 97, 44, 32,111,117,116,
+ 32,102,108,111, 97,116, 32,118, 97,108,117,101, 44, 32,111,117,116, 32,118,101, 99, 52, 32, 99,111,108,111,114, 44, 32,111,117,
+116, 32,118,101, 99, 51, 32,110,111,114,109, 97,108, 41, 10,123, 10, 9, 99,111,108,111,114, 32, 61, 32,116,101,120,116,117,114,
+101, 50, 68, 40,105,109, 97, 44, 32, 40,118,101, 99, 46,120,121, 32, 43, 32,118,101, 99, 50, 40, 49, 46, 48, 44, 32, 49, 46, 48,
+ 41, 41, 42, 48, 46, 53, 41, 59, 10, 9,118, 97,108,117,101, 32, 61, 32, 49, 46, 48, 59, 10, 10, 9,110,111,114,109, 97,108, 46,
+120, 32, 61, 32, 50, 46, 48, 42, 40, 99,111,108,111,114, 46,114, 32, 45, 32, 48, 46, 53, 41, 59, 10, 9,110,111,114,109, 97,108,
+ 46,121, 32, 61, 32, 50, 46, 48, 42, 40, 48, 46, 53, 32, 45, 32, 99,111,108,111,114, 46,103, 41, 59, 10, 9,110,111,114,109, 97,
+108, 46,122, 32, 61, 32, 50, 46, 48, 42, 40, 99,111,108,111,114, 46, 98, 32, 45, 32, 48, 46, 53, 41, 59, 10,125, 10, 10, 47, 42,
+ 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 32, 77, 84, 69, 88, 32, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42,
+ 42, 42, 42, 47, 10, 10,118,111,105,100, 32,116,101,120, 99,111, 95,111,114, 99,111, 40,118,101, 99, 51, 32, 97,116,116,111,114,
+ 99,111, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,114, 99,111, 41, 10,123, 10, 9,111,114, 99,111, 32, 61, 32, 97,116,116,
+111,114, 99,111, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120, 99,111, 95,117,118, 40,118,101, 99, 50, 32, 97,116,116,117,
+118, 44, 32,111,117,116, 32,118,101, 99, 51, 32,117,118, 41, 10,123, 10, 9, 47, 42, 32,100,105,115, 97, 98,108,101,100, 32,102,
+111,114, 32,110,111,119, 44, 32,119,111,114,107,115, 32,116,111,103,101,116,104,101,114, 32,119,105,116,104, 32,108,101, 97,118,
+105,110,103, 32,111,117,116, 32,109,116,101,120, 95, 50,100, 95,109, 97,112,112,105,110,103, 10, 9, 32, 32, 32,117,118, 32, 61,
+ 32,118,101, 99, 51, 40, 97,116,116,117,118, 42, 50, 46, 48, 32, 45, 32,118,101, 99, 50, 40, 49, 46, 48, 44, 32, 49, 46, 48, 41,
+ 44, 32, 48, 46, 48, 41, 59, 32, 42, 47, 10, 9,117,118, 32, 61, 32,118,101, 99, 51, 40, 97,116,116,117,118, 44, 32, 48, 46, 48,
+ 41, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120, 99,111, 95,110,111,114,109, 40,118,101, 99, 51, 32,110,111,114,109, 97,
+108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,110,111,114,109, 97,108, 41, 10,123, 10, 9, 47, 42, 32, 99,111,114,
+114,101,115,112,111,110,100,115, 32,116,111, 32,115,104,105, 45, 62,111,114,110, 44, 32,119,104,105, 99,104, 32,105,115, 32,110,
+101,103, 97,116,101,100, 32,115,111, 32, 99, 97,110, 99,101,108,115, 10, 9, 32, 32, 32,111,117,116, 32, 98,108,101,110,100,101,
+114, 32,110,111,114,109, 97,108, 32,110,101,103, 97,116,105,111,110, 32, 42, 47, 10, 9,111,117,116,110,111,114,109, 97,108, 32,
+ 61, 32,110,111,114,109, 97,108,105,122,101, 40,110,111,114,109, 97,108, 41, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120,
+ 99,111, 95,116, 97,110,103,101,110,116, 40,118,101, 99, 51, 32,116, 97,110,103,101,110,116, 44, 32,111,117,116, 32,118,101, 99,
+ 51, 32,111,117,116,116, 97,110,103,101,110,116, 41, 10,123, 10, 9,111,117,116,116, 97,110,103,101,110,116, 32, 61, 32,110,111,
+114,109, 97,108,105,122,101, 40,116, 97,110,103,101,110,116, 41, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120, 99,111, 95,
+103,108,111, 98, 97,108, 40,109, 97,116, 52, 32,118,105,101,119,105,110,118,109, 97,116, 44, 32,118,101, 99, 51, 32, 99,111, 44,
+ 32,111,117,116, 32,118,101, 99, 51, 32,103,108,111, 98, 97,108, 41, 10,123, 10, 9,103,108,111, 98, 97,108, 32, 61, 32, 40,118,
+105,101,119,105,110,118,109, 97,116, 42,118,101, 99, 52, 40, 99,111, 44, 32, 49, 46, 48, 41, 41, 46,120,121,122, 59, 10,125, 10,
+ 10,118,111,105,100, 32,116,101,120, 99,111, 95,111, 98,106,101, 99,116, 40,109, 97,116, 52, 32,118,105,101,119,105,110,118,109,
+ 97,116, 44, 32,109, 97,116, 52, 32,111, 98,105,110,118,109, 97,116, 44, 32,118,101, 99, 51, 32, 99,111, 44, 32,111,117,116, 32,
+118,101, 99, 51, 32,111, 98,106,101, 99,116, 41, 10,123, 10, 9,111, 98,106,101, 99,116, 32, 61, 32, 40,111, 98,105,110,118,109,
+ 97,116, 42, 40,118,105,101,119,105,110,118,109, 97,116, 42,118,101, 99, 52, 40, 99,111, 44, 32, 49, 46, 48, 41, 41, 41, 46,120,
+121,122, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120, 99,111, 95,114,101,102,108, 40,118,101, 99, 51, 32,118,110, 44, 32,
+118,101, 99, 51, 32,118,105,101,119, 44, 32,111,117,116, 32,118,101, 99, 51, 32,114,101,102, 41, 10,123, 10, 9,114,101,102, 32,
+ 61, 32,118,105,101,119, 32, 45, 32, 50, 46, 48, 42,100,111,116, 40,118,110, 44, 32,118,105,101,119, 41, 42,118,110, 59, 10,125,
+ 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,110,111,114,109, 40,118,101, 99, 51, 32,110,111,114,109, 97,108, 44, 32,111,
+117,116, 32,118,101, 99, 51, 32,111,117,116,110,111,114,109, 97,108, 41, 10,123, 10, 9, 47, 42, 32, 98,108,101,110,100,101,114,
+ 32,114,101,110,100,101,114, 32,110,111,114,109, 97,108, 32,105,115, 32,110,101,103, 97,116,101,100, 32, 42, 47, 10, 9,111,117,
+116,110,111,114,109, 97,108, 32, 61, 32, 45,110,111,114,109, 97,108,105,122,101, 40,110,111,114,109, 97,108, 41, 59, 10,125, 10,
+ 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95, 98,108,101,110,100, 40,118,101, 99, 51, 32,111,117,116, 99,111,108,
+ 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116,
+ 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,
+102, 97, 99,109, 59, 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, 61, 32, 49, 46,
+ 48, 45,102, 97, 99,116, 59, 10, 10, 9,105,110, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 32, 43, 32,
+102, 97, 99,109, 42,111,117,116, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,109,117,
+108, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,
+116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,
+111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,
+103, 59, 10, 9,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 45,102, 97, 99,103, 59, 10, 10, 9,105,110, 99,111,108, 32, 61, 32, 40,
+102, 97, 99,109, 32, 43, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 41, 42,111,117,116, 99,111,108, 59, 10,125, 10, 10,118,
+111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,115, 99,114,101,101,110, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44,
+ 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,
+102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102,
+ 97, 99,109, 59, 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, 61, 32, 49, 46, 48,
+ 45,102, 97, 99,103, 59, 10, 10, 9,105,110, 99,111,108, 32, 61, 32,118,101, 99, 51, 40, 49, 46, 48, 41, 32, 45, 32, 40,118,101,
+ 99, 51, 40,102, 97, 99,109, 41, 32, 43, 32,102, 97, 99,116, 42, 40,118,101, 99, 51, 40, 49, 46, 48, 41, 32, 45, 32,116,101,120,
+ 99,111,108, 41, 41, 42, 40,118,101, 99, 51, 40, 49, 46, 48, 41, 32, 45, 32,111,117,116, 99,111,108, 41, 59, 10,125, 10, 10,118,
+111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,111,118,101,114,108, 97,121, 40,118,101, 99, 51, 32,111,117,116, 99,111,108,
+ 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116,
+ 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,
+102, 97, 99,109, 59, 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, 61, 32, 49, 46,
+ 48, 45,102, 97, 99,103, 59, 10, 10, 9,105,102, 40,111,117,116, 99,111,108, 46,114, 32, 60, 32, 48, 46, 53, 41, 10, 9, 9,105,
+110, 99,111,108, 46,114, 32, 61, 32,111,117,116, 99,111,108, 46,114, 42, 40,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97,
+ 99,116, 42,116,101,120, 99,111,108, 46,114, 41, 59, 10, 9,101,108,115,101, 10, 9, 9,105,110, 99,111,108, 46,114, 32, 61, 32,
+ 49, 46, 48, 32, 45, 32, 40,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99,116, 42, 40, 49, 46, 48, 32, 45, 32,116,101,
+120, 99,111,108, 46,114, 41, 41, 42, 40, 49, 46, 48, 32, 45, 32,111,117,116, 99,111,108, 46,114, 41, 59, 10, 10, 9,105,102, 40,
+111,117,116, 99,111,108, 46,103, 32, 60, 32, 48, 46, 53, 41, 10, 9, 9,105,110, 99,111,108, 46,103, 32, 61, 32,111,117,116, 99,
+111,108, 46,103, 42, 40,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99,116, 42,116,101,120, 99,111,108, 46,103, 41, 59,
+ 10, 9,101,108,115,101, 10, 9, 9,105,110, 99,111,108, 46,103, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40,102, 97, 99,109, 32, 43,
+ 32, 50, 46, 48, 42,102, 97, 99,116, 42, 40, 49, 46, 48, 32, 45, 32,116,101,120, 99,111,108, 46,103, 41, 41, 42, 40, 49, 46, 48,
+ 32, 45, 32,111,117,116, 99,111,108, 46,103, 41, 59, 10, 10, 9,105,102, 40,111,117,116, 99,111,108, 46, 98, 32, 60, 32, 48, 46,
+ 53, 41, 10, 9, 9,105,110, 99,111,108, 46, 98, 32, 61, 32,111,117,116, 99,111,108, 46, 98, 42, 40,102, 97, 99,109, 32, 43, 32,
+ 50, 46, 48, 42,102, 97, 99,116, 42,116,101,120, 99,111,108, 46, 98, 41, 59, 10, 9,101,108,115,101, 10, 9, 9,105,110, 99,111,
+108, 46, 98, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99,116, 42, 40, 49, 46,
+ 48, 32, 45, 32,116,101,120, 99,111,108, 46, 98, 41, 41, 42, 40, 49, 46, 48, 32, 45, 32,111,117,116, 99,111,108, 46, 98, 41, 59,
+ 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,115,117, 98, 40,118,101, 99, 51, 32,111,117,116, 99,111,
+108, 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,
+116, 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,105,110, 99,111,108,
+ 32, 61, 32, 45,102, 97, 99,116, 42,102, 97, 99,103, 42,116,101,120, 99,111,108, 32, 43, 32,111,117,116, 99,111,108, 59, 10,125,
+ 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95, 97,100,100, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44,
+ 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,
+102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,105,110, 99,111,108, 32, 61,
+ 32,102, 97, 99,116, 42,102, 97, 99,103, 42,116,101,120, 99,111,108, 32, 43, 32,111,117,116, 99,111,108, 59, 10,125, 10, 10,118,
+111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,100,105,118, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44, 32,118,101,
+ 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,
+103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109,
+ 59, 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 45,102, 97,
+ 99,116, 59, 10, 10, 9,105,102, 40,116,101,120, 99,111,108, 46,114, 32, 33, 61, 32, 48, 46, 48, 41, 32,105,110, 99,111,108, 46,
+114, 32, 61, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 46,114, 32, 43, 32,102, 97, 99,116, 42,111,117,116, 99,111,108, 46,
+114, 47,116,101,120, 99,111,108, 46,114, 59, 10, 9,105,102, 40,116,101,120, 99,111,108, 46,103, 32, 33, 61, 32, 48, 46, 48, 41,
+ 32,105,110, 99,111,108, 46,103, 32, 61, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 46,103, 32, 43, 32,102, 97, 99,116, 42,
+111,117,116, 99,111,108, 46,103, 47,116,101,120, 99,111,108, 46,103, 59, 10, 9,105,102, 40,116,101,120, 99,111,108, 46, 98, 32,
+ 33, 61, 32, 48, 46, 48, 41, 32,105,110, 99,111,108, 46, 98, 32, 61, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 46, 98, 32,
+ 43, 32,102, 97, 99,116, 42,111,117,116, 99,111,108, 46, 98, 47,116,101,120, 99,111,108, 46, 98, 59, 10,125, 10, 10,118,111,105,
+100, 32,109,116,101,120, 95,114,103, 98, 95,100,105,102,102, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44, 32,118,101, 99,
+ 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103,
+ 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 59,
+ 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 45,102, 97, 99,
+116, 59, 10, 10, 9,105,110, 99,111,108, 32, 61, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 32, 43, 32,102, 97, 99,116, 42,
+ 97, 98,115, 40,116,101,120, 99,111,108, 32, 45, 32,111,117,116, 99,111,108, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,
+101,120, 95,114,103, 98, 95,100, 97,114,107, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44, 32,118,101, 99, 51, 32,116,101,
+120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,111,117,
+116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 44, 32, 99,111,108,
+ 59, 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 45,102, 97,
+ 99,116, 59, 10, 10, 9, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 46,114, 59, 10, 9,105,102, 40, 99,
+111,108, 32, 60, 32,111,117,116, 99,111,108, 46,114, 41, 32,105,110, 99,111,108, 46,114, 32, 61, 32, 99,111,108, 59, 32,101,108,
+115,101, 32,105,110, 99,111,108, 46,114, 32, 61, 32,111,117,116, 99,111,108, 46,114, 59, 10, 9, 99,111,108, 32, 61, 32,102, 97,
+ 99,116, 42,116,101,120, 99,111,108, 46,103, 59, 10, 9,105,102, 40, 99,111,108, 32, 60, 32,111,117,116, 99,111,108, 46,103, 41,
+ 32,105,110, 99,111,108, 46,103, 32, 61, 32, 99,111,108, 59, 32,101,108,115,101, 32,105,110, 99,111,108, 46,103, 32, 61, 32,111,
+117,116, 99,111,108, 46,103, 59, 10, 9, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 46, 98, 59, 10, 9,
+105,102, 40, 99,111,108, 32, 60, 32,111,117,116, 99,111,108, 46, 98, 41, 32,105,110, 99,111,108, 46, 98, 32, 61, 32, 99,111,108,
+ 59, 32,101,108,115,101, 32,105,110, 99,111,108, 46, 98, 32, 61, 32,111,117,116, 99,111,108, 46, 98, 59, 10,125, 10, 10,118,111,
+105,100, 32,109,116,101,120, 95,114,103, 98, 95,108,105,103,104,116, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44, 32,118,
+101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97,
+ 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,
+109, 44, 32, 99,111,108, 59, 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, 61, 32,
+ 49, 46, 48, 45,102, 97, 99,116, 59, 10, 10, 9, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 46,114, 59,
+ 10, 9,105,102, 40, 99,111,108, 32, 62, 32,111,117,116, 99,111,108, 46,114, 41, 32,105,110, 99,111,108, 46,114, 32, 61, 32, 99,
+111,108, 59, 32,101,108,115,101, 32,105,110, 99,111,108, 46,114, 32, 61, 32,111,117,116, 99,111,108, 46,114, 59, 10, 9, 99,111,
+108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 46,103, 59, 10, 9,105,102, 40, 99,111,108, 32, 62, 32,111,117,116,
+ 99,111,108, 46,103, 41, 32,105,110, 99,111,108, 46,103, 32, 61, 32, 99,111,108, 59, 32,101,108,115,101, 32,105,110, 99,111,108,
+ 46,103, 32, 61, 32,111,117,116, 99,111,108, 46,103, 59, 10, 9, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,
+108, 46, 98, 59, 10, 9,105,102, 40, 99,111,108, 32, 62, 32,111,117,116, 99,111,108, 46, 98, 41, 32,105,110, 99,111,108, 46, 98,
+ 32, 61, 32, 99,111,108, 59, 32,101,108,115,101, 32,105,110, 99,111,108, 46, 98, 32, 61, 32,111,117,116, 99,111,108, 46, 98, 59,
+ 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,104,117,101, 40,118,101, 99, 51, 32,111,117,116, 99,111,
+108, 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,
+116, 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,118,101, 99, 52, 32,
+ 99,111,108, 59, 10, 10, 9,109,105,120, 95,104,117,101, 40,102, 97, 99,116, 42,102, 97, 99,103, 44, 32,118,101, 99, 52, 40,111,
+117,116, 99,111,108, 44, 32, 49, 46, 48, 41, 44, 32,118,101, 99, 52, 40,116,101,120, 99,111,108, 44, 32, 49, 46, 48, 41, 44, 32,
+ 99,111,108, 41, 59, 10, 9,105,110, 99,111,108, 46,114,103, 98, 32, 61, 32, 99,111,108, 46,114,103, 98, 59, 10,125, 10, 10,118,
+111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,115, 97,116, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44, 32,118,101,
+ 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,
+103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,118,101, 99, 52, 32, 99,111,108, 59, 10,
+ 10, 9,109,105,120, 95,115, 97,116, 40,102, 97, 99,116, 42,102, 97, 99,103, 44, 32,118,101, 99, 52, 40,111,117,116, 99,111,108,
+ 44, 32, 49, 46, 48, 41, 44, 32,118,101, 99, 52, 40,116,101,120, 99,111,108, 44, 32, 49, 46, 48, 41, 44, 32, 99,111,108, 41, 59,
+ 10, 9,105,110, 99,111,108, 46,114,103, 98, 32, 61, 32, 99,111,108, 46,114,103, 98, 59, 10,125, 10, 10,118,111,105,100, 32,109,
+116,101,120, 95,114,103, 98, 95,118, 97,108, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44, 32,118,101, 99, 51, 32,116,101,
+120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,111,117,
+116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,118,101, 99, 52, 32, 99,111,108, 59, 10, 10, 9,109,105,120,
+ 95,118, 97,108, 40,102, 97, 99,116, 42,102, 97, 99,103, 44, 32,118,101, 99, 52, 40,111,117,116, 99,111,108, 44, 32, 49, 46, 48,
+ 41, 44, 32,118,101, 99, 52, 40,116,101,120, 99,111,108, 44, 32, 49, 46, 48, 41, 44, 32, 99,111,108, 41, 59, 10, 9,105,110, 99,
+111,108, 46,114,103, 98, 32, 61, 32, 99,111,108, 46,114,103, 98, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,
+103, 98, 95, 99,111,108,111,114, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,
+108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,
+101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,118,101, 99, 52, 32, 99,111,108, 59, 10, 10, 9,109,105,120, 95, 99,111,
+108,111,114, 40,102, 97, 99,116, 42,102, 97, 99,103, 44, 32,118,101, 99, 52, 40,111,117,116, 99,111,108, 44, 32, 49, 46, 48, 41,
+ 44, 32,118,101, 99, 52, 40,116,101,120, 99,111,108, 44, 32, 49, 46, 48, 41, 44, 32, 99,111,108, 41, 59, 10, 9,105,110, 99,111,
+108, 46,114,103, 98, 32, 61, 32, 99,111,108, 46,114,103, 98, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,
+108,117,101, 95,118, 97,114,115, 40,105,110,111,117,116, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116,
+ 32,102, 97, 99,103, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,102, 97, 99,109, 44, 32,102,108,111, 97,116, 32,102,108,105,
+112, 41, 10,123, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 45,
+102, 97, 99,116, 59, 10, 10, 9,105,102, 40,102,108,105,112, 32, 33, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,102,108,111, 97,
+116, 32,116,109,112, 32, 61, 32,102, 97, 99,116, 59, 10, 9, 9,102, 97, 99,116, 32, 61, 32,102, 97, 99,109, 59, 10, 9, 9,102,
+ 97, 99,109, 32, 61, 32,116,109,112, 59, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,108,117,101,
+ 95, 98,108,101,110,100, 40,102,108,111, 97,116, 32,111,117,116, 99,111,108, 44, 32,102,108,111, 97,116, 32,116,101,120, 99,111,
+108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,102,108,111, 97,116,
+ 32,102,108,105,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116,
+ 32,102, 97, 99,109, 59, 10, 9,109,116,101,120, 95,118, 97,108,117,101, 95,118, 97,114,115, 40,102, 97, 99,116, 44, 32,102, 97,
+ 99,103, 44, 32,102, 97, 99,109, 44, 32,102,108,105,112, 41, 59, 10, 10, 9,105,110, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,
+116,101,120, 99,111,108, 32, 43, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,
+101,120, 95,118, 97,108,117,101, 95,109,117,108, 40,102,108,111, 97,116, 32,111,117,116, 99,111,108, 44, 32,102,108,111, 97,116,
+ 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44,
+ 32,102,108,111, 97,116, 32,102,108,105,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110, 99,111,108, 41, 10,123, 10,
+ 9,102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 9,109,116,101,120, 95,118, 97,108,117,101, 95,118, 97,114,115, 40,102, 97,
+ 99,116, 44, 32,102, 97, 99,103, 44, 32,102, 97, 99,109, 44, 32,102,108,105,112, 41, 59, 10, 10, 9,102, 97, 99,109, 32, 61, 32,
+ 49, 46, 48, 32, 45, 32,102, 97, 99,103, 59, 10, 9,105,110, 99,111,108, 32, 61, 32, 40,102, 97, 99,109, 32, 43, 32,102, 97, 99,
+116, 42,116,101,120, 99,111,108, 41, 42,111,117,116, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118,
+ 97,108,117,101, 95,115, 99,114,101,101,110, 40,102,108,111, 97,116, 32,111,117,116, 99,111,108, 44, 32,102,108,111, 97,116, 32,
+116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,
+102,108,111, 97,116, 32,102,108,105,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110, 99,111,108, 41, 10,123, 10, 9,
+102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 9,109,116,101,120, 95,118, 97,108,117,101, 95,118, 97,114,115, 40,102, 97, 99,
+116, 44, 32,102, 97, 99,103, 44, 32,102, 97, 99,109, 44, 32,102,108,105,112, 41, 59, 10, 10, 9,102, 97, 99,109, 32, 61, 32, 49,
+ 46, 48, 32, 45, 32,102, 97, 99,103, 59, 10, 9,105,110, 99,111,108, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40,102, 97, 99,109, 32,
+ 43, 32,102, 97, 99,116, 42, 40, 49, 46, 48, 32, 45, 32,116,101,120, 99,111,108, 41, 41, 42, 40, 49, 46, 48, 32, 45, 32,111,117,
+116, 99,111,108, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,108,117,101, 95,115,117, 98, 40,102,108,
+111, 97,116, 32,111,117,116, 99,111,108, 44, 32,102,108,111, 97,116, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,
+102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,102,108,111, 97,116, 32,102,108,105,112, 44, 32,111,117,
+116, 32,102,108,111, 97,116, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 9,109,
+116,101,120, 95,118, 97,108,117,101, 95,118, 97,114,115, 40,102, 97, 99,116, 44, 32,102, 97, 99,103, 44, 32,102, 97, 99,109, 44,
+ 32,102,108,105,112, 41, 59, 10, 10, 9,102, 97, 99,116, 32, 61, 32, 45,102, 97, 99,116, 59, 10, 9,105,110, 99,111,108, 32, 61,
+ 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 32, 43, 32,111,117,116, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,109,
+116,101,120, 95,118, 97,108,117,101, 95, 97,100,100, 40,102,108,111, 97,116, 32,111,117,116, 99,111,108, 44, 32,102,108,111, 97,
+116, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103,
+ 44, 32,102,108,111, 97,116, 32,102,108,105,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110, 99,111,108, 41, 10,123,
+ 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 9,109,116,101,120, 95,118, 97,108,117,101, 95,118, 97,114,115, 40,102,
+ 97, 99,116, 44, 32,102, 97, 99,103, 44, 32,102, 97, 99,109, 44, 32,102,108,105,112, 41, 59, 10, 10, 9,102, 97, 99,116, 32, 61,
+ 32,102, 97, 99,116, 59, 10, 9,105,110, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 32, 43, 32,111,117,
+116, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,108,117,101, 95,100,105,118, 40,102,108,111,
+ 97,116, 32,111,117,116, 99,111,108, 44, 32,102,108,111, 97,116, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102,
+ 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,102,108,111, 97,116, 32,102,108,105,112, 44, 32,111,117,116,
+ 32,102,108,111, 97,116, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 9,109,116,
+101,120, 95,118, 97,108,117,101, 95,118, 97,114,115, 40,102, 97, 99,116, 44, 32,102, 97, 99,103, 44, 32,102, 97, 99,109, 44, 32,
+102,108,105,112, 41, 59, 10, 10, 9,105,102, 40,116,101,120, 99,111,108, 32, 33, 61, 32, 48, 46, 48, 41, 10, 9, 9,105,110, 99,
+111,108, 32, 61, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 32, 43, 32,102, 97, 99,116, 42,111,117,116, 99,111,108, 47,116,
+101,120, 99,111,108, 59, 10, 9,101,108,115,101, 10, 9, 9,105,110, 99,111,108, 32, 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,
+111,105,100, 32,109,116,101,120, 95,118, 97,108,117,101, 95,100,105,102,102, 40,102,108,111, 97,116, 32,111,117,116, 99,111,108,
+ 44, 32,102,108,111, 97,116, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,
+116, 32,102, 97, 99,103, 44, 32,102,108,111, 97,116, 32,102,108,105,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110,
+ 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 9,109,116,101,120, 95,118, 97,108,117,101, 95,
+118, 97,114,115, 40,102, 97, 99,116, 44, 32,102, 97, 99,103, 44, 32,102, 97, 99,109, 44, 32,102,108,105,112, 41, 59, 10, 10, 9,
+105,110, 99,111,108, 32, 61, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 32, 43, 32,102, 97, 99,116, 42, 97, 98,115, 40,116,
+101,120, 99,111,108, 32, 45, 32,111,117,116, 99,111,108, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,
+108,117,101, 95,100, 97,114,107, 40,102,108,111, 97,116, 32,111,117,116, 99,111,108, 44, 32,102,108,111, 97,116, 32,116,101,120,
+ 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,102,108,111,
+ 97,116, 32,102,108,105,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111,
+ 97,116, 32,102, 97, 99,109, 59, 10, 9,109,116,101,120, 95,118, 97,108,117,101, 95,118, 97,114,115, 40,102, 97, 99,116, 44, 32,
+102, 97, 99,103, 44, 32,102, 97, 99,109, 44, 32,102,108,105,112, 41, 59, 10, 10, 9,102,108,111, 97,116, 32, 99,111,108, 32, 61,
+ 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 59, 10, 9,105,102, 40, 99,111,108, 32, 60, 32,111,117,116, 99,111,108, 41, 32,
+105,110, 99,111,108, 32, 61, 32, 99,111,108, 59, 32,101,108,115,101, 32,105,110, 99,111,108, 32, 61, 32,111,117,116, 99,111,108,
+ 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,108,117,101, 95,108,105,103,104,116, 40,102,108,111, 97,116,
+ 32,111,117,116, 99,111,108, 44, 32,102,108,111, 97,116, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,
+116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,102,108,111, 97,116, 32,102,108,105,112, 44, 32,111,117,116, 32,102,
+108,111, 97,116, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 9,109,116,101,120,
+ 95,118, 97,108,117,101, 95,118, 97,114,115, 40,102, 97, 99,116, 44, 32,102, 97, 99,103, 44, 32,102, 97, 99,109, 44, 32,102,108,
+105,112, 41, 59, 10, 10, 9,102,108,111, 97,116, 32, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 59, 10,
+ 9,105,102, 40, 99,111,108, 32, 62, 32,111,117,116, 99,111,108, 41, 32,105,110, 99,111,108, 32, 61, 32, 99,111,108, 59, 32,101,
+108,115,101, 32,105,110, 99,111,108, 32, 61, 32,111,117,116, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120,
+ 95,118, 97,108,117,101, 95, 99,108, 97,109,112, 95,112,111,115,105,116,105,118,101, 40,102,108,111, 97,116, 32,102, 97, 99, 44,
+ 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,102, 97, 99, 41, 10,123, 10, 9,111,117,116,102, 97, 99, 32, 61, 32,109,
+ 97,120, 40,102, 97, 99, 44, 32, 48, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,108,117,101,
+ 95, 99,108, 97,109,112, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,102,
+ 97, 99, 41, 10,123, 10, 9,111,117,116,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32,
+ 49, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,104, 97,114, 95,100,105,118,105,100,101, 40,102,108,
+111, 97,116, 32,104, 97,114, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,104, 97,114, 41, 10,123, 10, 9,111,117,
+116,104, 97,114, 32, 61, 32,104, 97,114, 47, 49, 50, 56, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,104,
+ 97,114, 95,109,117,108,116,105,112,108,121, 95, 99,108, 97,109,112, 40,102,108,111, 97,116, 32,104, 97,114, 44, 32,111,117,116,
+ 32,102,108,111, 97,116, 32,111,117,116,104, 97,114, 41, 10,123, 10, 9,104, 97,114, 32, 42, 61, 32, 49, 50, 56, 46, 48, 59, 10,
+ 10, 9,105,102, 40,104, 97,114, 32, 60, 32, 49, 46, 48, 41, 32,111,117,116,104, 97,114, 32, 61, 32, 49, 46, 48, 59, 10, 9,101,
+108,115,101, 32,105,102, 40,104, 97,114, 32, 62, 32, 53, 49, 49, 46, 48, 41, 32,111,117,116,104, 97,114, 32, 61, 32, 53, 49, 49,
+ 46, 48, 59, 10, 9,101,108,115,101, 32,111,117,116,104, 97,114, 32, 61, 32,104, 97,114, 59, 10,125, 10, 10,118,111,105,100, 32,
+109,116,101,120, 95, 97,108,112,104, 97, 95,102,114,111,109, 95, 99,111,108, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,111,117,
+116, 32,102,108,111, 97,116, 32, 97,108,112,104, 97, 41, 10,123, 10, 9, 97,108,112,104, 97, 32, 61, 32, 99,111,108, 46, 97, 59,
+ 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95, 97,108,112,104, 97, 95,116,111, 95, 99,111,108, 40,118,101, 99, 52, 32,
+ 99,111,108, 44, 32,102,108,111, 97,116, 32, 97,108,112,104, 97, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,
+108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32,118,101, 99, 52, 40, 99,111,108, 46,114,103, 98, 44, 32, 97,108,112,
+104, 97, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98,116,111,105,110,116, 40,118,101, 99, 52, 32,
+114,103, 98, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110,116,101,110,115,105,116,121, 41, 10,123, 10, 9,105,110,116,
+101,110,115,105,116,121, 32, 61, 32,100,111,116, 40,118,101, 99, 51, 40, 48, 46, 51, 53, 44, 32, 48, 46, 52, 53, 44, 32, 48, 46,
+ 50, 41, 44, 32,114,103, 98, 46,114,103, 98, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,108,117,101,
+ 95,105,110,118,101,114,116, 40,102,108,111, 97,116, 32,105,110,118, 97,108,117,101, 44, 32,111,117,116, 32,102,108,111, 97,116,
+ 32,111,117,116,118, 97,108,117,101, 41, 10,123, 10, 9,111,117,116,118, 97,108,117,101, 32, 61, 32, 49, 46, 48, 32, 45, 32,105,
+110,118, 97,108,117,101, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,105,110,118,101,114,116, 40,
+118,101, 99, 52, 32,105,110,114,103, 98, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116,114,103, 98, 41, 10,123, 10, 9,
+111,117,116,114,103, 98, 32, 61, 32,118,101, 99, 52, 40,118,101, 99, 51, 40, 49, 46, 48, 41, 32, 45, 32,105,110,114,103, 98, 46,
+114,103, 98, 44, 32,105,110,114,103, 98, 46, 97, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,108,117,
+101, 95,115,116,101,110, 99,105,108, 40,102,108,111, 97,116, 32,115,116,101,110, 99,105,108, 44, 32,102,108,111, 97,116, 32,105,
+110,116,101,110,115,105,116,121, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,115,116,101,110, 99,105,108, 44, 32,
+111,117,116, 32,102,108,111, 97,116, 32,111,117,116,105,110,116,101,110,115,105,116,121, 41, 10,123, 10, 9,102,108,111, 97,116,
+ 32,102, 97, 99,116, 32, 61, 32,105,110,116,101,110,115,105,116,121, 59, 10, 9,111,117,116,105,110,116,101,110,115,105,116,121,
+ 32, 61, 32,105,110,116,101,110,115,105,116,121, 42,115,116,101,110, 99,105,108, 59, 10, 9,111,117,116,115,116,101,110, 99,105,
+108, 32, 61, 32,115,116,101,110, 99,105,108, 42,102, 97, 99,116, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,
+103, 98, 95,115,116,101,110, 99,105,108, 40,102,108,111, 97,116, 32,115,116,101,110, 99,105,108, 44, 32,118,101, 99, 52, 32,114,
+103, 98, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,115,116,101,110, 99,105,108, 44, 32,111,117,116, 32,118,101,
+ 99, 52, 32,111,117,116,114,103, 98, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,116, 32, 61, 32,114,103, 98, 46, 97,
+ 59, 10, 9,111,117,116,114,103, 98, 32, 61, 32,118,101, 99, 52, 40,114,103, 98, 46,114,103, 98, 44, 32,114,103, 98, 46, 97, 42,
+115,116,101,110, 99,105,108, 41, 59, 10, 9,111,117,116,115,116,101,110, 99,105,108, 32, 61, 32,115,116,101,110, 99,105,108, 42,
+102, 97, 99,116, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,109, 97,112,112,105,110,103, 95,111,102,115, 40,118,
+101, 99, 51, 32,116,101,120, 99,111, 44, 32,118,101, 99, 51, 32,111,102,115, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,
+116,116,101,120, 99,111, 41, 10,123, 10, 9,111,117,116,116,101,120, 99,111, 32, 61, 32,116,101,120, 99,111, 32, 43, 32,111,102,
+115, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,109, 97,112,112,105,110,103, 95,115,105,122,101, 40,118,101, 99,
+ 51, 32,116,101,120, 99,111, 44, 32,118,101, 99, 51, 32,115,105,122,101, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,
+116,101,120, 99,111, 41, 10,123, 10, 9,111,117,116,116,101,120, 99,111, 32, 61, 32,115,105,122,101, 42,116,101,120, 99,111, 59,
+ 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95, 50,100, 95,109, 97,112,112,105,110,103, 40,118,101, 99, 51, 32,118,101,
+ 99, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32,
+118,101, 99, 51, 40,118,101, 99, 46,120,121, 42, 48, 46, 53, 32, 43, 32,118,101, 99, 50, 40, 48, 46, 53, 44, 32, 48, 46, 53, 41,
+ 44, 32,118,101, 99, 46,122, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,105,109, 97,103,101, 40,118,101, 99,
+ 51, 32,118,101, 99, 44, 32,115, 97,109,112,108,101,114, 50, 68, 32,105,109, 97, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,
+118, 97,108,117,101, 44, 32,111,117,116, 32,118,101, 99, 52, 32, 99,111,108,111,114, 44, 32,111,117,116, 32,118,101, 99, 51, 32,
+110,111,114,109, 97,108, 41, 10,123, 10, 9, 99,111,108,111,114, 32, 61, 32,116,101,120,116,117,114,101, 50, 68, 40,105,109, 97,
+ 44, 32,118,101, 99, 46,120,121, 41, 59, 10, 9,118, 97,108,117,101, 32, 61, 32, 49, 46, 48, 59, 10, 9, 10, 9,110,111,114,109,
+ 97,108, 32, 61, 32, 50, 46, 48, 42, 40,118,101, 99, 51, 40, 99,111,108,111,114, 46,114, 44, 32, 45, 99,111,108,111,114, 46,103,
+ 44, 32, 99,111,108,111,114, 46, 98, 41, 32, 45, 32,118,101, 99, 51, 40, 48, 46, 53, 44, 32, 45, 48, 46, 53, 44, 32, 48, 46, 53,
+ 41, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,110,101,103, 97,116,101, 95,116,101,120,110,111,114,109, 97,
+108, 40,118,101, 99, 51, 32,110,111,114,109, 97,108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,110,111,114,109, 97,
+108, 41, 10,123, 10, 9,111,117,116,110,111,114,109, 97,108, 32, 61, 32,118,101, 99, 51, 40, 45,110,111,114,109, 97,108, 46,120,
+ 44, 32, 45,110,111,114,109, 97,108, 46,121, 44, 32,110,111,114,109, 97,108, 46,122, 41, 59, 10,125, 10, 10,118,111,105,100, 32,
+109,116,101,120, 95,110,115,112, 97, 99,101, 95,116, 97,110,103,101,110,116, 40,118,101, 99, 51, 32,116, 97,110,103,101,110,116,
+ 44, 32,118,101, 99, 51, 32,110,111,114,109, 97,108, 44, 32,118,101, 99, 51, 32,116,101,120,110,111,114,109, 97,108, 44, 32,111,
+117,116, 32,118,101, 99, 51, 32,111,117,116,110,111,114,109, 97,108, 41, 10,123, 10, 9,116, 97,110,103,101,110,116, 32, 61, 32,
+110,111,114,109, 97,108,105,122,101, 40,116, 97,110,103,101,110,116, 41, 59, 10, 9,118,101, 99, 51, 32, 66, 32, 61, 32, 99,114,
+111,115,115, 40,110,111,114,109, 97,108, 44, 32,116, 97,110,103,101,110,116, 41, 59, 10, 10, 9,111,117,116,110,111,114,109, 97,
+108, 32, 61, 32,116,101,120,110,111,114,109, 97,108, 46,120, 42,116, 97,110,103,101,110,116, 32, 43, 32,116,101,120,110,111,114,
+109, 97,108, 46,121, 42, 66, 32, 43, 32,116,101,120,110,111,114,109, 97,108, 46,122, 42,110,111,114,109, 97,108, 59, 10, 9,111,
+117,116,110,111,114,109, 97,108, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,111,117,116,110,111,114,109, 97,108, 41, 59,
+ 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95, 98,108,101,110,100, 95,110,111,114,109, 97,108, 40,102,108,111, 97,116,
+ 32,110,111,114,102, 97, 99, 44, 32,118,101, 99, 51, 32,110,111,114,109, 97,108, 44, 32,118,101, 99, 51, 32,110,101,119,110,111,
+114,109, 97,108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,110,111,114,109, 97,108, 41, 10,123, 10, 9,111,117,116,
+110,111,114,109, 97,108, 32, 61, 32, 40, 49, 46, 48, 32, 45, 32,110,111,114,102, 97, 99, 41, 42,110,111,114,109, 97,108, 32, 43,
+ 32,110,111,114,102, 97, 99, 42,110,101,119,110,111,114,109, 97,108, 59, 10, 9,111,117,116,110,111,114,109, 97,108, 32, 61, 32,
+110,111,114,109, 97,108,105,122,101, 40,111,117,116,110,111,114,109, 97,108, 41, 59, 10,125, 10, 10, 47, 42, 42, 42, 42, 42, 42,
+ 42, 32, 77, 65, 84, 69, 82, 73, 65, 76, 32, 42, 42, 42, 42, 42, 42, 42, 42, 42, 47, 10, 10,118,111,105,100, 32,108, 97,109,112,
+ 95,118,105,115,105, 98,105,108,105,116,121, 95,115,117,110, 95,104,101,109,105, 40,118,101, 99, 51, 32,108, 97,109,112,118,101,
+ 99, 44, 32,111,117,116, 32,118,101, 99, 51, 32,108,118, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,100,105,115,116, 44, 32,
+111,117,116, 32,102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 41, 10,123, 10, 9,108,118, 32, 61, 32,108, 97,109,112,118,
+101, 99, 59, 10, 9,100,105,115,116, 32, 61, 32, 49, 46, 48, 59, 10, 9,118,105,115,105,102, 97, 99, 32, 61, 32, 49, 46, 48, 59,
+ 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,118,105,115,105, 98,105,108,105,116,121, 95,111,116,104,101,114, 40,118,
+101, 99, 51, 32, 99,111, 44, 32,118,101, 99, 51, 32,108, 97,109,112, 99,111, 44, 32,111,117,116, 32,118,101, 99, 51, 32,108,118,
+ 44, 32,111,117,116, 32,102,108,111, 97,116, 32,100,105,115,116, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,118,105,115,105,
+102, 97, 99, 41, 10,123, 10, 9,108,118, 32, 61, 32, 99,111, 32, 45, 32,108, 97,109,112, 99,111, 59, 10, 9,100,105,115,116, 32,
+ 61, 32,108,101,110,103,116,104, 40,108,118, 41, 59, 10, 9,108,118, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,108,118,
+ 41, 59, 10, 9,118,105,115,105,102, 97, 99, 32, 61, 32, 49, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,
+102, 97,108,108,111,102,102, 95,105,110,118,108,105,110,101, 97,114, 40,102,108,111, 97,116, 32,108, 97,109,112,100,105,115,116,
+ 44, 32,102,108,111, 97,116, 32,100,105,115,116, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 41,
+ 10,123, 10, 9,118,105,115,105,102, 97, 99, 32, 61, 32,108, 97,109,112,100,105,115,116, 47, 40,108, 97,109,112,100,105,115,116,
+ 32, 43, 32,100,105,115,116, 41, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,102, 97,108,108,111,102,102, 95,105,
+110,118,115,113,117, 97,114,101, 40,102,108,111, 97,116, 32,108, 97,109,112,100,105,115,116, 44, 32,102,108,111, 97,116, 32,100,
+105,115,116, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 41, 10,123, 10, 9,118,105,115,105,102,
+ 97, 99, 32, 61, 32,108, 97,109,112,100,105,115,116, 47, 40,108, 97,109,112,100,105,115,116, 32, 43, 32,100,105,115,116, 42,100,
+105,115,116, 41, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,102, 97,108,108,111,102,102, 95,115,108,105,100,101,
+114,115, 40,102,108,111, 97,116, 32,108, 97,109,112,100,105,115,116, 44, 32,102,108,111, 97,116, 32,108,100, 49, 44, 32,102,108,
+111, 97,116, 32,108,100, 50, 44, 32,102,108,111, 97,116, 32,100,105,115,116, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,118,
+105,115,105,102, 97, 99, 41, 10,123, 10, 9,102,108,111, 97,116, 32,108, 97,109,112,100,105,115,116,107,119, 32, 61, 32,108, 97,
+109,112,100,105,115,116, 42,108, 97,109,112,100,105,115,116, 59, 10, 10, 9,118,105,115,105,102, 97, 99, 32, 61, 32,108, 97,109,
+112,100,105,115,116, 47, 40,108, 97,109,112,100,105,115,116, 32, 43, 32,108,100, 49, 42,100,105,115,116, 41, 59, 10, 9,118,105,
+115,105,102, 97, 99, 32, 42, 61, 32,108, 97,109,112,100,105,115,116,107,119, 47, 40,108, 97,109,112,100,105,115,116,107,119, 32,
+ 43, 32,108,100, 50, 42,100,105,115,116, 42,100,105,115,116, 41, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,102,
+ 97,108,108,111,102,102, 95, 99,117,114,118,101, 40,102,108,111, 97,116, 32,108, 97,109,112,100,105,115,116, 44, 32,115, 97,109,
+112,108,101,114, 49, 68, 32, 99,117,114,118,101,109, 97,112, 44, 32,102,108,111, 97,116, 32,100,105,115,116, 44, 32,111,117,116,
+ 32,102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 41, 10,123, 10, 9,118,105,115,105,102, 97, 99, 32, 61, 32,116,101,120,
+116,117,114,101, 49, 68, 40, 99,117,114,118,101,109, 97,112, 44, 32,100,105,115,116, 47,108, 97,109,112,100,105,115,116, 41, 46,
+120, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,118,105,115,105, 98,105,108,105,116,121, 95,115,112,104,101,114,
+101, 40,102,108,111, 97,116, 32,108, 97,109,112,100,105,115,116, 44, 32,102,108,111, 97,116, 32,100,105,115,116, 44, 32,102,108,
+111, 97,116, 32,118,105,115,105,102, 97, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118,105,115,105,102, 97,
+ 99, 41, 10,123, 10, 9,102,108,111, 97,116, 32,116, 61, 32,108, 97,109,112,100,105,115,116, 32, 45, 32,100,105,115,116, 59, 10,
+ 10, 9,111,117,116,118,105,115,105,102, 97, 99, 61, 32,118,105,115,105,102, 97, 99, 42,109, 97,120, 40,116, 44, 32, 48, 46, 48,
+ 41, 47,108, 97,109,112,100,105,115,116, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,118,105,115,105, 98,105,108,
+105,116,121, 95,115,112,111,116, 95,115,113,117, 97,114,101, 40,118,101, 99, 51, 32,108, 97,109,112,118,101, 99, 44, 32,109, 97,
+116, 52, 32,108, 97,109,112,105,109, 97,116, 44, 32,118,101, 99, 51, 32,108,118, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,
+105,110,112,114, 41, 10,123, 10, 9,105,102, 40,100,111,116, 40,108,118, 44, 32,108, 97,109,112,118,101, 99, 41, 32, 62, 32, 48,
+ 46, 48, 41, 32,123, 10, 9, 9,118,101, 99, 51, 32,108,118,114,111,116, 32, 61, 32, 40,108, 97,109,112,105,109, 97,116, 42,118,
+101, 99, 52, 40,108,118, 44, 32, 48, 46, 48, 41, 41, 46,120,121,122, 59, 10, 9, 9,102,108,111, 97,116, 32,120, 32, 61, 32,109,
+ 97,120, 40, 97, 98,115, 40,108,118,114,111,116, 46,120, 47,108,118,114,111,116, 46,122, 41, 44, 32, 97, 98,115, 40,108,118,114,
+111,116, 46,121, 47,108,118,114,111,116, 46,122, 41, 41, 59, 10, 10, 9, 9,105,110,112,114, 32, 61, 32, 49, 46, 48, 47,115,113,
+114,116, 40, 49, 46, 48, 32, 43, 32,120, 42,120, 41, 59, 10, 9,125, 10, 9,101,108,115,101, 10, 9, 9,105,110,112,114, 32, 61,
+ 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,118,105,115,105, 98,105,108,105,116,121, 95,115,112,
+111,116, 95, 99,105,114, 99,108,101, 40,118,101, 99, 51, 32,108, 97,109,112,118,101, 99, 44, 32,118,101, 99, 51, 32,108,118, 44,
+ 32,111,117,116, 32,102,108,111, 97,116, 32,105,110,112,114, 41, 10,123, 10, 9,105,110,112,114, 32, 61, 32,100,111,116, 40,108,
+118, 44, 32,108, 97,109,112,118,101, 99, 41, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,118,105,115,105, 98,105,
+108,105,116,121, 95,115,112,111,116, 40,102,108,111, 97,116, 32,115,112,111,116,115,105, 44, 32,102,108,111, 97,116, 32,115,112,
+111,116, 98,108, 44, 32,102,108,111, 97,116, 32,105,110,112,114, 44, 32,102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 44,
+ 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118,105,115,105,102, 97, 99, 41, 10,123, 10, 9,102,108,111, 97,116, 32,
+116, 32, 61, 32,115,112,111,116,115,105, 59, 10, 10, 9,105,102, 40,105,110,112,114, 32, 60, 61, 32,116, 41, 32,123, 10, 9, 9,
+111,117,116,118,105,115,105,102, 97, 99, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, 10, 9, 9,116,
+ 32, 61, 32,105,110,112,114, 32, 45, 32,116, 59, 10, 10, 9, 9, 47, 42, 32,115,111,102,116, 32, 97,114,101, 97, 32, 42, 47, 10,
+ 9, 9,105,102, 40,115,112,111,116, 98,108, 32, 33, 61, 32, 48, 46, 48, 41, 10, 9, 9, 9,105,110,112,114, 32, 42, 61, 32,115,
+109,111,111,116,104,115,116,101,112, 40, 48, 46, 48, 44, 32, 49, 46, 48, 44, 32,116, 47,115,112,111,116, 98,108, 41, 59, 10, 10,
+ 9, 9,111,117,116,118,105,115,105,102, 97, 99, 32, 61, 32,118,105,115,105,102, 97, 99, 42,105,110,112,114, 59, 10, 9,125, 10,
+125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,118,105,115,105, 98,105,108,105,116,121, 95, 99,108, 97,109,112, 40,102,108,
+111, 97,116, 32,118,105,115,105,102, 97, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118,105,115,105,102, 97,
+ 99, 41, 10,123, 10, 9,111,117,116,118,105,115,105,102, 97, 99, 32, 61, 32, 40,118,105,115,105,102, 97, 99, 32, 60, 32, 48, 46,
+ 48, 48, 49, 41, 63, 32, 48, 46, 48, 58, 32,118,105,115,105,102, 97, 99, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,
+101, 95,118,105,101,119, 40,118,101, 99, 51, 32, 99,111, 44, 32,111,117,116, 32,118,101, 99, 51, 32,118,105,101,119, 41, 10,123,
+ 10, 9, 47, 42, 32,104, 97,110,100,108,101, 32,112,101,114,115,112,101, 99,116,105,118,101, 47,111,114,116,104,111,103,114, 97,
+112,104,105, 99, 32, 42, 47, 10, 9,118,105,101,119, 32, 61, 32, 40,103,108, 95, 80,114,111,106,101, 99,116,105,111,110, 77, 97,
+116,114,105,120, 91, 51, 93, 91, 51, 93, 32, 61, 61, 32, 48, 46, 48, 41, 63, 32,110,111,114,109, 97,108,105,122,101, 40, 99,111,
+ 41, 58, 32,118,101, 99, 51, 40, 48, 46, 48, 44, 32, 48, 46, 48, 44, 32, 45, 49, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100,
+ 32,115,104, 97,100,101, 95,116, 97,110,103,101,110,116, 95,118, 40,118,101, 99, 51, 32,108,118, 44, 32,118,101, 99, 51, 32,116,
+ 97,110,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,118,110, 41, 10,123, 10, 9,118,101, 99, 51, 32, 99, 32, 61, 32, 99,114,
+111,115,115, 40,108,118, 44, 32,116, 97,110,103, 41, 59, 10, 9,118,101, 99, 51, 32,118,110,111,114, 32, 61, 32, 99,114,111,115,
+115, 40, 99, 44, 32,116, 97,110,103, 41, 59, 10, 10, 9,118,110, 32, 61, 32, 45,110,111,114,109, 97,108,105,122,101, 40,118,110,
+111,114, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,105,110,112, 40,118,101, 99, 51, 32,118,110, 44, 32,
+118,101, 99, 51, 32,108,118, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110,112, 41, 10,123, 10, 9,105,110,112, 32, 61,
+ 32,100,111,116, 40,118,110, 44, 32,108,118, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,105,115, 95,110,
+111, 95,100,105,102,102,117,115,101, 40,111,117,116, 32,102,108,111, 97,116, 32,105,115, 41, 10,123, 10, 9,105,115, 32, 61, 32,
+ 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,105,115, 95,104,101,109,105, 40,102,108,111, 97,116,
+ 32,105,110,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,115, 41, 10,123, 10, 9,105,115, 32, 61, 32, 48, 46, 53, 42,
+105,110,112, 32, 43, 32, 48, 46, 53, 59, 10,125, 10, 10,102,108,111, 97,116, 32, 97,114,101, 97, 95,108, 97,109,112, 95,101,110,
+101,114,103,121, 40,109, 97,116, 52, 32, 97,114,101, 97, 44, 32,118,101, 99, 51, 32, 99,111, 44, 32,118,101, 99, 51, 32,118,110,
+ 41, 10,123, 10, 9,118,101, 99, 51, 32,118,101, 99, 91, 52, 93, 44, 32, 99, 91, 52, 93, 59, 10, 9,102,108,111, 97,116, 32,114,
+ 97,100, 91, 52, 93, 44, 32,102, 97, 99, 59, 10, 9, 10, 9,118,101, 99, 91, 48, 93, 32, 61, 32,110,111,114,109, 97,108,105,122,
+101, 40, 99,111, 32, 45, 32, 97,114,101, 97, 91, 48, 93, 46,120,121,122, 41, 59, 10, 9,118,101, 99, 91, 49, 93, 32, 61, 32,110,
+111,114,109, 97,108,105,122,101, 40, 99,111, 32, 45, 32, 97,114,101, 97, 91, 49, 93, 46,120,121,122, 41, 59, 10, 9,118,101, 99,
+ 91, 50, 93, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40, 99,111, 32, 45, 32, 97,114,101, 97, 91, 50, 93, 46,120,121,122,
+ 41, 59, 10, 9,118,101, 99, 91, 51, 93, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40, 99,111, 32, 45, 32, 97,114,101, 97,
+ 91, 51, 93, 46,120,121,122, 41, 59, 10, 10, 9, 99, 91, 48, 93, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40, 99,114,111,
+115,115, 40,118,101, 99, 91, 48, 93, 44, 32,118,101, 99, 91, 49, 93, 41, 41, 59, 10, 9, 99, 91, 49, 93, 32, 61, 32,110,111,114,
+109, 97,108,105,122,101, 40, 99,114,111,115,115, 40,118,101, 99, 91, 49, 93, 44, 32,118,101, 99, 91, 50, 93, 41, 41, 59, 10, 9,
+ 99, 91, 50, 93, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40, 99,114,111,115,115, 40,118,101, 99, 91, 50, 93, 44, 32,118,
+101, 99, 91, 51, 93, 41, 41, 59, 10, 9, 99, 91, 51, 93, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40, 99,114,111,115,115,
+ 40,118,101, 99, 91, 51, 93, 44, 32,118,101, 99, 91, 48, 93, 41, 41, 59, 10, 10, 9,114, 97,100, 91, 48, 93, 32, 61, 32, 97, 99,
+111,115, 40,100,111,116, 40,118,101, 99, 91, 48, 93, 44, 32,118,101, 99, 91, 49, 93, 41, 41, 59, 10, 9,114, 97,100, 91, 49, 93,
+ 32, 61, 32, 97, 99,111,115, 40,100,111,116, 40,118,101, 99, 91, 49, 93, 44, 32,118,101, 99, 91, 50, 93, 41, 41, 59, 10, 9,114,
+ 97,100, 91, 50, 93, 32, 61, 32, 97, 99,111,115, 40,100,111,116, 40,118,101, 99, 91, 50, 93, 44, 32,118,101, 99, 91, 51, 93, 41,
+ 41, 59, 10, 9,114, 97,100, 91, 51, 93, 32, 61, 32, 97, 99,111,115, 40,100,111,116, 40,118,101, 99, 91, 51, 93, 44, 32,118,101,
+ 99, 91, 48, 93, 41, 41, 59, 10, 10, 9,102, 97, 99, 61, 32, 32,114, 97,100, 91, 48, 93, 42,100,111,116, 40,118,110, 44, 32, 99,
+ 91, 48, 93, 41, 59, 10, 9,102, 97, 99, 43, 61, 32,114, 97,100, 91, 49, 93, 42,100,111,116, 40,118,110, 44, 32, 99, 91, 49, 93,
+ 41, 59, 10, 9,102, 97, 99, 43, 61, 32,114, 97,100, 91, 50, 93, 42,100,111,116, 40,118,110, 44, 32, 99, 91, 50, 93, 41, 59, 10,
+ 9,102, 97, 99, 43, 61, 32,114, 97,100, 91, 51, 93, 42,100,111,116, 40,118,110, 44, 32, 99, 91, 51, 93, 41, 59, 10, 10, 9,114,
+101,116,117,114,110, 32,109, 97,120, 40,102, 97, 99, 44, 32, 48, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,
+100,101, 95,105,110,112, 95, 97,114,101, 97, 40,118,101, 99, 51, 32,112,111,115,105,116,105,111,110, 44, 32,118,101, 99, 51, 32,
+108, 97,109,112, 99,111, 44, 32,118,101, 99, 51, 32,108, 97,109,112,118,101, 99, 44, 32,118,101, 99, 51, 32,118,110, 44, 32,109,
+ 97,116, 52, 32, 97,114,101, 97, 44, 32,102,108,111, 97,116, 32, 97,114,101, 97,115,105,122,101, 44, 32,102,108,111, 97,116, 32,
+107, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110,112, 41, 10,123, 10, 9,118,101, 99, 51, 32, 99,111, 32, 61, 32,112,
+111,115,105,116,105,111,110, 59, 10, 9,118,101, 99, 51, 32,118,101, 99, 32, 61, 32, 99,111, 32, 45, 32,108, 97,109,112, 99,111,
+ 59, 10, 10, 9,105,102, 40,100,111,116, 40,118,101, 99, 44, 32,108, 97,109,112,118,101, 99, 41, 32, 60, 32, 48, 46, 48, 41, 32,
+123, 10, 9, 9,105,110,112, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, 10, 9, 9,102,108,111, 97,
+116, 32,105,110,116,101,110,115, 32, 61, 32, 97,114,101, 97, 95,108, 97,109,112, 95,101,110,101,114,103,121, 40, 97,114,101, 97,
+ 44, 32, 99,111, 44, 32,118,110, 41, 59, 10, 10, 9, 9,105,110,112, 32, 61, 32,112,111,119, 40,105,110,116,101,110,115, 42, 97,
+114,101, 97,115,105,122,101, 44, 32,107, 41, 59, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,100,105,
+102,102,117,115,101, 95,111,114,101,110, 95,110, 97,121,101,114, 40,102,108,111, 97,116, 32,110,108, 44, 32,118,101, 99, 51, 32,
+110, 44, 32,118,101, 99, 51, 32,108, 44, 32,118,101, 99, 51, 32,118, 44, 32,102,108,111, 97,116, 32,114,111,117,103,104, 44, 32,
+111,117,116, 32,102,108,111, 97,116, 32,105,115, 41, 10,123, 10, 9,118,101, 99, 51, 32,104, 32, 61, 32,110,111,114,109, 97,108,
+105,122,101, 40,118, 32, 43, 32,108, 41, 59, 10, 9,102,108,111, 97,116, 32,110,104, 32, 61, 32,109, 97,120, 40,100,111,116, 40,
+110, 44, 32,104, 41, 44, 32, 48, 46, 48, 41, 59, 10, 9,102,108,111, 97,116, 32,110,118, 32, 61, 32,109, 97,120, 40,100,111,116,
+ 40,110, 44, 32,118, 41, 44, 32, 48, 46, 48, 41, 59, 10, 9,102,108,111, 97,116, 32,114,101, 97,108,110,108, 32, 61, 32,100,111,
+116, 40,110, 44, 32,108, 41, 59, 10, 10, 9,105,102, 40,114,101, 97,108,110,108, 32, 60, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,
+105,115, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,105,102, 40,110,108, 32, 60, 32, 48, 46, 48, 41, 32,
+123, 10, 9, 9,105,115, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, 10, 9, 9,102,108,111, 97,116,
+ 32,118,104, 32, 61, 32,109, 97,120, 40,100,111,116, 40,118, 44, 32,104, 41, 44, 32, 48, 46, 48, 41, 59, 10, 9, 9,102,108,111,
+ 97,116, 32, 76,105,116, 95, 65, 32, 61, 32, 97, 99,111,115, 40,114,101, 97,108,110,108, 41, 59, 10, 9, 9,102,108,111, 97,116,
+ 32, 86,105,101,119, 95, 65, 32, 61, 32, 97, 99,111,115, 40,110,118, 41, 59, 10, 10, 9, 9,118,101, 99, 51, 32, 76,105,116, 95,
+ 66, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,108, 32, 45, 32,114,101, 97,108,110,108, 42,110, 41, 59, 10, 9, 9,118,
+101, 99, 51, 32, 86,105,101,119, 95, 66, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,118, 32, 45, 32,110,118, 42,110, 41,
+ 59, 10, 10, 9, 9,102,108,111, 97,116, 32,116, 32, 61, 32,109, 97,120, 40,100,111,116, 40, 76,105,116, 95, 66, 44, 32, 86,105,
+101,119, 95, 66, 41, 44, 32, 48, 46, 48, 41, 59, 10, 10, 9, 9,102,108,111, 97,116, 32, 97, 44, 32, 98, 59, 10, 10, 9, 9,105,
+102, 40, 76,105,116, 95, 65, 32, 62, 32, 86,105,101,119, 95, 65, 41, 32,123, 10, 9, 9, 9, 97, 32, 61, 32, 76,105,116, 95, 65,
+ 59, 10, 9, 9, 9, 98, 32, 61, 32, 86,105,101,119, 95, 65, 59, 10, 9, 9,125, 10, 9, 9,101,108,115,101, 32,123, 10, 9, 9,
+ 9, 97, 32, 61, 32, 86,105,101,119, 95, 65, 59, 10, 9, 9, 9, 98, 32, 61, 32, 76,105,116, 95, 65, 59, 10, 9, 9,125, 10, 10,
+ 9, 9,102,108,111, 97,116, 32, 65, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40, 48, 46, 53, 42, 40, 40,114,111,117,103,104, 42,114,
+111,117,103,104, 41, 47, 40, 40,114,111,117,103,104, 42,114,111,117,103,104, 41, 32, 43, 32, 48, 46, 51, 51, 41, 41, 41, 59, 10,
+ 9, 9,102,108,111, 97,116, 32, 66, 32, 61, 32, 48, 46, 52, 53, 42, 40, 40,114,111,117,103,104, 42,114,111,117,103,104, 41, 47,
+ 40, 40,114,111,117,103,104, 42,114,111,117,103,104, 41, 32, 43, 32, 48, 46, 48, 57, 41, 41, 59, 10, 10, 9, 9, 98, 32, 42, 61,
+ 32, 48, 46, 57, 53, 59, 10, 9, 9,105,115, 32, 61, 32,110,108, 42, 40, 65, 32, 43, 32, 40, 66, 32, 42, 32,116, 32, 42, 32,115,
+105,110, 40, 97, 41, 32, 42, 32,116, 97,110, 40, 98, 41, 41, 41, 59, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,
+100,101, 95,100,105,102,102,117,115,101, 95,116,111,111,110, 40,118,101, 99, 51, 32,110, 44, 32,118,101, 99, 51, 32,108, 44, 32,
+118,101, 99, 51, 32,118, 44, 32,102,108,111, 97,116, 32,115,105,122,101, 44, 32,102,108,111, 97,116, 32,116,115,109,111,111,116,
+104, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,115, 41, 10,123, 10, 9,102,108,111, 97,116, 32,114,115,108,116, 32, 61,
+ 32,100,111,116, 40,110, 44, 32,108, 41, 59, 10, 9,102,108,111, 97,116, 32, 97,110,103, 32, 61, 32, 97, 99,111,115, 40,114,115,
+108,116, 41, 59, 10, 10, 9,105,102, 40, 97,110,103, 32, 60, 32,115,105,122,101, 41, 32,105,115, 32, 61, 32, 49, 46, 48, 59, 10,
+ 9,101,108,115,101, 32,105,102, 40, 97,110,103, 32, 62, 32, 40,115,105,122,101, 32, 43, 32,116,115,109,111,111,116,104, 41, 32,
+124,124, 32,116,115,109,111,111,116,104, 32, 61, 61, 32, 48, 46, 48, 41, 32,105,115, 32, 61, 32, 48, 46, 48, 59, 10, 9,101,108,
+115,101, 32,105,115, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40, 40, 97,110,103, 32, 45, 32,115,105,122,101, 41, 47,116,115,109,111,
+111,116,104, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,100,105,102,102,117,115,101, 95,109,105,110,110,
+ 97,101,114,116, 40,102,108,111, 97,116, 32,110,108, 44, 32,118,101, 99, 51, 32,110, 44, 32,118,101, 99, 51, 32,118, 44, 32,102,
+108,111, 97,116, 32,100, 97,114,107,110,101,115,115, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,115, 41, 10,123, 10, 9,
+105,102, 40,110,108, 32, 60, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,105,115, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,
+101,108,115,101, 32,123, 10, 9, 9,102,108,111, 97,116, 32,110,118, 32, 61, 32,109, 97,120, 40,100,111,116, 40,110, 44, 32,118,
+ 41, 44, 32, 48, 46, 48, 41, 59, 10, 10, 9, 9,105,102, 40,100, 97,114,107,110,101,115,115, 32, 60, 61, 32, 49, 46, 48, 41, 10,
+ 9, 9, 9,105,115, 32, 61, 32,110,108, 42,112,111,119, 40,109, 97,120, 40,110,118, 42,110,108, 44, 32, 48, 46, 49, 41, 44, 32,
+100, 97,114,107,110,101,115,115, 32, 45, 32, 49, 46, 48, 41, 59, 10, 9, 9,101,108,115,101, 10, 9, 9, 9,105,115, 32, 61, 32,
+110,108, 42,112,111,119, 40, 49, 46, 48, 48, 48, 49, 32, 45, 32,110,118, 44, 32,100, 97,114,107,110,101,115,115, 32, 45, 32, 49,
+ 46, 48, 41, 59, 10, 9,125, 10,125, 10, 10,102,108,111, 97,116, 32,102,114,101,115,110,101,108, 95,102, 97, 99, 40,118,101, 99,
+ 51, 32,118,105,101,119, 44, 32,118,101, 99, 51, 32,118,110, 44, 32,102,108,111, 97,116, 32,103,114, 97,100, 44, 32,102,108,111,
+ 97,116, 32,102, 97, 99, 41, 10,123, 10, 9,102,108,111, 97,116, 32,116, 49, 44, 32,116, 50, 59, 10, 9,102,108,111, 97,116, 32,
+102,102, 97, 99, 59, 10, 10, 9,105,102, 40,102, 97, 99, 61, 61, 48, 46, 48, 41, 32,123, 10, 9, 9,102,102, 97, 99, 32, 61, 32,
+ 49, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, 10, 9, 9,116, 49, 61, 32,100,111,116, 40,118,105,101,119, 44, 32,
+118,110, 41, 59, 10, 9, 9,105,102, 40,116, 49, 62, 48, 46, 48, 41, 32, 32,116, 50, 61, 32, 49, 46, 48, 43,116, 49, 59, 10, 9,
+ 9,101,108,115,101, 32,116, 50, 61, 32, 49, 46, 48, 45,116, 49, 59, 10, 10, 9, 9,116, 50, 61, 32,103,114, 97,100, 32, 43, 32,
+ 40, 49, 46, 48, 45,103,114, 97,100, 41, 42,112,111,119, 40,116, 50, 44, 32,102, 97, 99, 41, 59, 10, 10, 9, 9,105,102, 40,116,
+ 50, 60, 48, 46, 48, 41, 32,102,102, 97, 99, 32, 61, 32, 48, 46, 48, 59, 10, 9, 9,101,108,115,101, 32,105,102, 40,116, 50, 62,
+ 49, 46, 48, 41, 32,102,102, 97, 99, 32, 61, 32, 49, 46, 48, 59, 10, 9, 9,101,108,115,101, 32,102,102, 97, 99, 32, 61, 32,116,
+ 50, 59, 10, 9,125, 10, 10, 9,114,101,116,117,114,110, 32,102,102, 97, 99, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,
+100,101, 95,100,105,102,102,117,115,101, 95,102,114,101,115,110,101,108, 40,118,101, 99, 51, 32,118,110, 44, 32,118,101, 99, 51,
+ 32,108,118, 44, 32,118,101, 99, 51, 32,118,105,101,119, 44, 32,102,108,111, 97,116, 32,102, 97, 99, 95,105, 44, 32,102,108,111,
+ 97,116, 32,102, 97, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,115, 41, 10,123, 10, 9,105,115, 32, 61, 32,102,114,
+101,115,110,101,108, 95,102, 97, 99, 40,108,118, 44, 32,118,110, 44, 32,102, 97, 99, 95,105, 44, 32,102, 97, 99, 41, 59, 10,125,
+ 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95, 99,117, 98,105, 99, 40,102,108,111, 97,116, 32,105,115, 44, 32,111,117,116,
+ 32,102,108,111, 97,116, 32,111,117,116,105,115, 41, 10,123, 10, 9,105,102, 40,105,115, 62, 48, 46, 48, 32, 38, 38, 32,105,115,
+ 60, 49, 46, 48, 41, 10, 9, 9,111,117,116,105,115, 61, 32,115,109,111,111,116,104,115,116,101,112, 40, 48, 46, 48, 44, 32, 49,
+ 46, 48, 44, 32,105,115, 41, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116,105,115, 61, 32,105,115, 59, 10,125, 10, 10,118,
+111,105,100, 32,115,104, 97,100,101, 95,118,105,115,105,102, 97, 99, 40,102,108,111, 97,116, 32,105, 44, 32,102,108,111, 97,116,
+ 32,118,105,115,105,102, 97, 99, 44, 32,102,108,111, 97,116, 32,114,101,102,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,
+111,117,116,105, 41, 10,123, 10, 9, 47, 42,105,102, 40,105, 32, 62, 32, 48, 46, 48, 41, 42, 47, 10, 9, 9,111,117,116,105, 32,
+ 61, 32,109, 97,120, 40,105, 42,118,105,115,105,102, 97, 99, 42,114,101,102,108, 44, 32, 48, 46, 48, 41, 59, 10, 9, 47, 42,101,
+108,115,101, 10, 9, 9,111,117,116,105, 32, 61, 32,105, 59, 42, 47, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,
+116, 97,110,103,101,110,116, 95,118, 95,115,112,101, 99, 40,118,101, 99, 51, 32,116, 97,110,103, 44, 32,111,117,116, 32,118,101,
+ 99, 51, 32,118,110, 41, 10,123, 10, 9,118,110, 32, 61, 32,116, 97,110,103, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,
+100,101, 95, 97,100,100, 95,116,111, 95,100,105,102,102,117,115,101, 40,102,108,111, 97,116, 32,105, 44, 32,118,101, 99, 51, 32,
+108, 97,109,112, 99,111,108, 44, 32,118,101, 99, 51, 32, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116, 99,
+111,108, 41, 10,123, 10, 9,105,102, 40,105, 32, 62, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116, 99,111,108, 32, 61, 32,105, 42,
+108, 97,109,112, 99,111,108, 42, 99,111,108, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116, 99,111,108, 32, 61, 32,118,101,
+ 99, 51, 40, 48, 46, 48, 44, 32, 48, 46, 48, 44, 32, 48, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101,
+ 95,104,101,109,105, 95,115,112,101, 99, 40,118,101, 99, 51, 32,118,110, 44, 32,118,101, 99, 51, 32,108,118, 44, 32,118,101, 99,
+ 51, 32,118,105,101,119, 44, 32,102,108,111, 97,116, 32,115,112,101, 99, 44, 32,102,108,111, 97,116, 32,104, 97,114,100, 44, 32,
+102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,116, 41, 10,123, 10, 9,108,
+118, 32, 43, 61, 32,118,105,101,119, 59, 10, 9,108,118, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,108,118, 41, 59, 10,
+ 10, 9,116, 32, 61, 32,100,111,116, 40,118,110, 44, 32,108,118, 41, 59, 10, 9,116, 32, 61, 32, 48, 46, 53, 42,116, 32, 43, 32,
+ 48, 46, 53, 59, 10, 10, 9,116, 32, 61, 32,118,105,115,105,102, 97, 99, 42,115,112,101, 99, 42,112,111,119, 40,116, 44, 32,104,
+ 97,114,100, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,112,104,111,110,103, 95,115,112,101, 99, 40,118,
+101, 99, 51, 32,110, 44, 32,118,101, 99, 51, 32,108, 44, 32,118,101, 99, 51, 32,118, 44, 32,102,108,111, 97,116, 32,104, 97,114,
+100, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,115,112,101, 99,102, 97, 99, 41, 10,123, 10, 9,118,101, 99, 51, 32,104, 32,
+ 61, 32,110,111,114,109, 97,108,105,122,101, 40,108, 32, 43, 32,118, 41, 59, 10, 9,102,108,111, 97,116, 32,114,115,108,116, 32,
+ 61, 32,109, 97,120, 40,100,111,116, 40,104, 44, 32,110, 41, 44, 32, 48, 46, 48, 41, 59, 10, 10, 9,115,112,101, 99,102, 97, 99,
+ 32, 61, 32,112,111,119, 40,114,115,108,116, 44, 32,104, 97,114,100, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,
+101, 95, 99,111,111,107,116,111,114,114, 95,115,112,101, 99, 40,118,101, 99, 51, 32,110, 44, 32,118,101, 99, 51, 32,108, 44, 32,
+118,101, 99, 51, 32,118, 44, 32,102,108,111, 97,116, 32,104, 97,114,100, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,115,112,
+101, 99,102, 97, 99, 41, 10,123, 10, 9,118,101, 99, 51, 32,104, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,118, 32, 43,
+ 32,108, 41, 59, 10, 9,102,108,111, 97,116, 32,110,104, 32, 61, 32,100,111,116, 40,110, 44, 32,104, 41, 59, 10, 10, 9,105,102,
+ 40,110,104, 32, 60, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,115,112,101, 99,102, 97, 99, 32, 61, 32, 48, 46, 48, 59, 10, 9,125,
+ 10, 9,101,108,115,101, 32,123, 10, 9, 9,102,108,111, 97,116, 32,110,118, 32, 61, 32,109, 97,120, 40,100,111,116, 40,110, 44,
+ 32,118, 41, 44, 32, 48, 46, 48, 41, 59, 10, 9, 9,102,108,111, 97,116, 32,105, 32, 61, 32,112,111,119, 40,110,104, 44, 32,104,
+ 97,114,100, 41, 59, 10, 10, 9, 9,105, 32, 61, 32,105, 47, 40, 48, 46, 49, 43,110,118, 41, 59, 10, 9, 9,115,112,101, 99,102,
+ 97, 99, 32, 61, 32,105, 59, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95, 98,108,105,110,110, 95,115,
+112,101, 99, 40,118,101, 99, 51, 32,110, 44, 32,118,101, 99, 51, 32,108, 44, 32,118,101, 99, 51, 32,118, 44, 32,102,108,111, 97,
+116, 32,114,101,102,114, 97, 99, 44, 32,102,108,111, 97,116, 32,115,112,101, 99, 95,112,111,119,101,114, 44, 32,111,117,116, 32,
+102,108,111, 97,116, 32,115,112,101, 99,102, 97, 99, 41, 10,123, 10, 9,105,102, 40,114,101,102,114, 97, 99, 32, 60, 32, 49, 46,
+ 48, 41, 32,123, 10, 9, 9,115,112,101, 99,102, 97, 99, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,105,
+102, 40,115,112,101, 99, 95,112,111,119,101,114, 32, 61, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,115,112,101, 99,102, 97, 99,
+ 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, 10, 9, 9,105,102, 40,115,112,101, 99, 95,112,111,119,
+101,114, 60, 49, 48, 48, 46, 48, 41, 10, 9, 9, 9,115,112,101, 99, 95,112,111,119,101,114, 61, 32,115,113,114,116, 40, 49, 46,
+ 48, 47,115,112,101, 99, 95,112,111,119,101,114, 41, 59, 10, 9, 9,101,108,115,101, 10, 9, 9, 9,115,112,101, 99, 95,112,111,
+119,101,114, 61, 32, 49, 48, 46, 48, 47,115,112,101, 99, 95,112,111,119,101,114, 59, 10, 10, 9, 9,118,101, 99, 51, 32,104, 32,
+ 61, 32,110,111,114,109, 97,108,105,122,101, 40,118, 32, 43, 32,108, 41, 59, 10, 9, 9,102,108,111, 97,116, 32,110,104, 32, 61,
+ 32,100,111,116, 40,110, 44, 32,104, 41, 59, 10, 9, 9,105,102, 40,110,104, 32, 60, 32, 48, 46, 48, 41, 32,123, 10, 9, 9, 9,
+115,112,101, 99,102, 97, 99, 32, 61, 32, 48, 46, 48, 59, 10, 9, 9,125, 10, 9, 9,101,108,115,101, 32,123, 10, 9, 9, 9,102,
+108,111, 97,116, 32,110,118, 32, 61, 32,109, 97,120, 40,100,111,116, 40,110, 44, 32,118, 41, 44, 32, 48, 46, 48, 49, 41, 59, 10,
+ 9, 9, 9,102,108,111, 97,116, 32,110,108, 32, 61, 32,100,111,116, 40,110, 44, 32,108, 41, 59, 10, 9, 9, 9,105,102, 40,110,
+108, 32, 60, 61, 32, 48, 46, 48, 49, 41, 32,123, 10, 9, 9, 9, 9,115,112,101, 99,102, 97, 99, 32, 61, 32, 48, 46, 48, 59, 10,
+ 9, 9, 9,125, 10, 9, 9, 9,101,108,115,101, 32,123, 10, 9, 9, 9, 9,102,108,111, 97,116, 32,118,104, 32, 61, 32,109, 97,
+120, 40,100,111,116, 40,118, 44, 32,104, 41, 44, 32, 48, 46, 48, 49, 41, 59, 10, 10, 9, 9, 9, 9,102,108,111, 97,116, 32, 97,
+ 32, 61, 32, 49, 46, 48, 59, 10, 9, 9, 9, 9,102,108,111, 97,116, 32, 98, 32, 61, 32, 40, 50, 46, 48, 42,110,104, 42,110,118,
+ 41, 47,118,104, 59, 10, 9, 9, 9, 9,102,108,111, 97,116, 32, 99, 32, 61, 32, 40, 50, 46, 48, 42,110,104, 42,110,108, 41, 47,
+118,104, 59, 10, 10, 9, 9, 9, 9,102,108,111, 97,116, 32,103, 32, 61, 32, 48, 46, 48, 59, 10, 10, 9, 9, 9, 9,105,102, 40,
+ 97, 32, 60, 32, 98, 32, 38, 38, 32, 97, 32, 60, 32, 99, 41, 32,103, 32, 61, 32, 97, 59, 10, 9, 9, 9, 9,101,108,115,101, 32,
+105,102, 40, 98, 32, 60, 32, 97, 32, 38, 38, 32, 98, 32, 60, 32, 99, 41, 32,103, 32, 61, 32, 98, 59, 10, 9, 9, 9, 9,101,108,
+115,101, 32,105,102, 40, 99, 32, 60, 32, 97, 32, 38, 38, 32, 99, 32, 60, 32, 98, 41, 32,103, 32, 61, 32, 99, 59, 10, 10, 9, 9,
+ 9, 9,102,108,111, 97,116, 32,112, 32, 61, 32,115,113,114,116, 40, 40, 40,114,101,102,114, 97, 99, 32, 42, 32,114,101,102,114,
+ 97, 99, 41, 43, 40,118,104, 42,118,104, 41, 45, 49, 46, 48, 41, 41, 59, 10, 9, 9, 9, 9,102,108,111, 97,116, 32,102, 32, 61,
+ 32, 40, 40, 40,112, 45,118,104, 41, 42, 40,112, 45,118,104, 41, 41, 47, 40, 40,112, 43,118,104, 41, 42, 40,112, 43,118,104, 41,
+ 41, 41, 42, 40, 49, 46, 48, 43, 40, 40, 40, 40,118,104, 42, 40,112, 43,118,104, 41, 41, 45, 49, 46, 48, 41, 42, 40, 40,118,104,
+ 42, 40,112, 43,118,104, 41, 41, 45, 49, 46, 48, 41, 41, 47, 40, 40, 40,118,104, 42, 40,112, 45,118,104, 41, 41, 43, 49, 46, 48,
+ 41, 42, 40, 40,118,104, 42, 40,112, 45,118,104, 41, 41, 43, 49, 46, 48, 41, 41, 41, 41, 59, 10, 9, 9, 9, 9,102,108,111, 97,
+116, 32, 97,110,103, 32, 61, 32, 97, 99,111,115, 40,110,104, 41, 59, 10, 10, 9, 9, 9, 9,115,112,101, 99,102, 97, 99, 32, 61,
+ 32,109, 97,120, 40,102, 42,103, 42,101,120,112, 95, 98,108,101,110,100,101,114, 40, 40, 45, 40, 97,110,103, 42, 97,110,103, 41,
+ 47, 40, 50, 46, 48, 42,115,112,101, 99, 95,112,111,119,101,114, 42,115,112,101, 99, 95,112,111,119,101,114, 41, 41, 41, 44, 32,
+ 48, 46, 48, 41, 59, 10, 9, 9, 9,125, 10, 9, 9,125, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,
+119, 97,114,100,105,115,111, 95,115,112,101, 99, 40,118,101, 99, 51, 32,110, 44, 32,118,101, 99, 51, 32,108, 44, 32,118,101, 99,
+ 51, 32,118, 44, 32,102,108,111, 97,116, 32,114,109,115, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,115,112,101, 99,102, 97,
+ 99, 41, 10,123, 10, 9,118,101, 99, 51, 32,104, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,108, 32, 43, 32,118, 41, 59,
+ 10, 9,102,108,111, 97,116, 32,110,104, 32, 61, 32,109, 97,120, 40,100,111,116, 40,110, 44, 32,104, 41, 44, 32, 48, 46, 48, 48,
+ 49, 41, 59, 10, 9,102,108,111, 97,116, 32,110,118, 32, 61, 32,109, 97,120, 40,100,111,116, 40,110, 44, 32,118, 41, 44, 32, 48,
+ 46, 48, 48, 49, 41, 59, 10, 9,102,108,111, 97,116, 32,110,108, 32, 61, 32,109, 97,120, 40,100,111,116, 40,110, 44, 32,108, 41,
+ 44, 32, 48, 46, 48, 48, 49, 41, 59, 10, 9,102,108,111, 97,116, 32, 97,110,103,108,101, 32, 61, 32,116, 97,110, 40, 97, 99,111,
+115, 40,110,104, 41, 41, 59, 10, 9,102,108,111, 97,116, 32, 97,108,112,104, 97, 32, 61, 32,109, 97,120, 40,114,109,115, 44, 32,
+ 48, 46, 48, 48, 49, 41, 59, 10, 10, 9,115,112,101, 99,102, 97, 99, 61, 32,110,108, 32, 42, 32, 40, 49, 46, 48, 47, 40, 52, 46,
+ 48, 42, 77, 95, 80, 73, 42, 97,108,112,104, 97, 42, 97,108,112,104, 97, 41, 41, 42, 40,101,120,112, 95, 98,108,101,110,100,101,
+114, 40, 45, 40, 97,110,103,108,101, 42, 97,110,103,108,101, 41, 47, 40, 97,108,112,104, 97, 42, 97,108,112,104, 97, 41, 41, 47,
+ 40,115,113,114,116, 40,110,118, 42,110,108, 41, 41, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,116,111,
+111,110, 95,115,112,101, 99, 40,118,101, 99, 51, 32,110, 44, 32,118,101, 99, 51, 32,108, 44, 32,118,101, 99, 51, 32,118, 44, 32,
+102,108,111, 97,116, 32,115,105,122,101, 44, 32,102,108,111, 97,116, 32,116,115,109,111,111,116,104, 44, 32,111,117,116, 32,102,
+108,111, 97,116, 32,115,112,101, 99,102, 97, 99, 41, 10,123, 10, 9,118,101, 99, 51, 32,104, 32, 61, 32,110,111,114,109, 97,108,
+105,122,101, 40,108, 32, 43, 32,118, 41, 59, 10, 9,102,108,111, 97,116, 32,114,115,108,116, 32, 61, 32,100,111,116, 40,104, 44,
+ 32,110, 41, 59, 10, 9,102,108,111, 97,116, 32, 97,110,103, 32, 61, 32, 97, 99,111,115, 40,114,115,108,116, 41, 59, 10, 10, 9,
+105,102, 40, 97,110,103, 32, 60, 32,115,105,122,101, 41, 32,114,115,108,116, 32, 61, 32, 49, 46, 48, 59, 10, 9,101,108,115,101,
+ 32,105,102, 40, 97,110,103, 32, 62, 61, 32, 40,115,105,122,101, 32, 43, 32,116,115,109,111,111,116,104, 41, 32,124,124, 32,116,
+115,109,111,111,116,104, 32, 61, 61, 32, 48, 46, 48, 41, 32,114,115,108,116, 32, 61, 32, 48, 46, 48, 59, 10, 9,101,108,115,101,
+ 32,114,115,108,116, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40, 40, 97,110,103, 32, 45, 32,115,105,122,101, 41, 47,116,115,109,111,
+111,116,104, 41, 59, 10, 10, 9,115,112,101, 99,102, 97, 99, 32, 61, 32,114,115,108,116, 59, 10,125, 10, 10,118,111,105,100, 32,
+115,104, 97,100,101, 95,115,112,101, 99, 95, 97,114,101, 97, 95,105,110,112, 40,102,108,111, 97,116, 32,115,112,101, 99,102, 97,
+ 99, 44, 32,102,108,111, 97,116, 32,105,110,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,115,112,101, 99,102,
+ 97, 99, 41, 10,123, 10, 9,111,117,116,115,112,101, 99,102, 97, 99, 32, 61, 32,115,112,101, 99,102, 97, 99, 42,105,110,112, 59,
+ 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,115,112,101, 99, 95,116, 40,102,108,111, 97,116, 32,115,104, 97,100,
+102, 97, 99, 44, 32,102,108,111, 97,116, 32,115,112,101, 99, 44, 32,102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 44, 32,
+102,108,111, 97,116, 32,115,112,101, 99,102, 97, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,116, 41, 10,123, 10, 9,116,
+ 32, 61, 32,115,104, 97,100,102, 97, 99, 42,115,112,101, 99, 42,118,105,115,105,102, 97, 99, 42,115,112,101, 99,102, 97, 99, 59,
+ 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95, 97,100,100, 95,115,112,101, 99, 40,102,108,111, 97,116, 32,116, 44,
+ 32,118,101, 99, 51, 32,108, 97,109,112, 99,111,108, 44, 32,118,101, 99, 51, 32,115,112,101, 99, 99,111,108, 44, 32,111,117,116,
+ 32,118,101, 99, 51, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32,116, 42,108, 97,109,112,
+ 99,111,108, 42,115,112,101, 99, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95, 97,100,100, 40,118,
+101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,
+116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 49, 32, 43, 32, 99,111,108, 50, 59, 10,125,
+ 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,109, 97,100,100, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,118,101, 99, 52,
+ 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,
+108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 32, 43, 32, 99,111,108, 49, 42, 99,111,108, 50, 59, 10,
+125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,109, 97,100,100,102, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,102,108,
+111, 97,116, 32,102, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,
+108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 32, 43, 32,102, 42, 99,111,108, 49, 59, 10,125, 10, 10,
+118,111,105,100, 32,115,104, 97,100,101, 95,109,117,108, 40,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,
+111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32,
+ 61, 32, 99,111,108, 49, 42, 99,111,108, 50, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,109,117,108, 95,118,
+ 97,108,117,101, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 44, 32,111,117,116, 32,118,101,
+ 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 42,102, 97, 99, 59, 10,
+125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,111, 98, 99,111,108,111,114, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,
+118,101, 99, 52, 32,111, 98, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,
+111,117,116, 99,111,108, 32, 61, 32,118,101, 99, 52, 40, 99,111,108, 46,114,103, 98, 42,111, 98, 99,111,108, 46,114,103, 98, 44,
+ 32, 99,111,108, 46, 97, 41, 59, 10,125, 10, 10,118,111,105,100, 32,114, 97,109,112, 95,114,103, 98,116,111, 98,119, 40,118,101,
+ 99, 51, 32, 99,111,108,111,114, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,
+117,116,118, 97,108, 32, 61, 32, 99,111,108,111,114, 46,114, 42, 48, 46, 51, 32, 43, 32, 99,111,108,111,114, 46,103, 42, 48, 46,
+ 53, 56, 32, 43, 32, 99,111,108,111,114, 46, 98, 42, 48, 46, 49, 50, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101,
+ 95,111,110,108,121, 95,115,104, 97,100,111,119, 40,102,108,111, 97,116, 32,105, 44, 32,102,108,111, 97,116, 32,115,104, 97,100,
+102, 97, 99, 44, 32,102,108,111, 97,116, 32,101,110,101,114,103,121, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,
+115,104, 97,100,102, 97, 99, 41, 10,123, 10, 9,111,117,116,115,104, 97,100,102, 97, 99, 32, 61, 32,105, 42,101,110,101,114,103,
+121, 42, 40, 49, 46, 48, 32, 45, 32,115,104, 97,100,102, 97, 99, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101,
+ 95,111,110,108,121, 95,115,104, 97,100,111,119, 95,100,105,102,102,117,115,101, 40,102,108,111, 97,116, 32,115,104, 97,100,102,
+ 97, 99, 44, 32,118,101, 99, 51, 32,114,103, 98, 44, 32,118,101, 99, 52, 32,100,105,102,102, 44, 32,111,117,116, 32,118,101, 99,
+ 52, 32,111,117,116,100,105,102,102, 41, 10,123, 10, 9,111,117,116,100,105,102,102, 32, 61, 32,100,105,102,102, 32, 45, 32,118,
+101, 99, 52, 40,114,103, 98, 42,115,104, 97,100,102, 97, 99, 44, 32, 48, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,
+104, 97,100,101, 95,111,110,108,121, 95,115,104, 97,100,111,119, 95,115,112,101, 99,117,108, 97,114, 40,102,108,111, 97,116, 32,
+115,104, 97,100,102, 97, 99, 44, 32,118,101, 99, 51, 32,115,112,101, 99,114,103, 98, 44, 32,118,101, 99, 52, 32,115,112,101, 99,
+ 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116,115,112,101, 99, 41, 10,123, 10, 9,111,117,116,115,112,101, 99, 32, 61,
+ 32,115,112,101, 99, 32, 45, 32,118,101, 99, 52, 40,115,112,101, 99,114,103, 98, 42,115,104, 97,100,102, 97, 99, 44, 32, 48, 46,
+ 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,115,116, 95,115,104, 97,100,111,119, 98,117,102, 40,118,101, 99, 51, 32,
+114, 99,111, 44, 32,115, 97,109,112,108,101,114, 50, 68, 83,104, 97,100,111,119, 32,115,104, 97,100,111,119,109, 97,112, 44, 32,
+109, 97,116, 52, 32,115,104, 97,100,111,119,112,101,114,115,109, 97,116, 44, 32,102,108,111, 97,116, 32,115,104, 97,100,111,119,
+ 98,105, 97,115, 44, 32,102,108,111, 97,116, 32,105,110,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,114,101,115,117,108,
+116, 41, 10,123, 10, 9,105,102, 40,105,110,112, 32, 60, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,114,101,115,117,108,116, 32,
+ 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, 10, 9, 9,118,101, 99, 52, 32, 99,111, 32, 61, 32,115,104,
+ 97,100,111,119,112,101,114,115,109, 97,116, 42,118,101, 99, 52, 40,114, 99,111, 44, 32, 49, 46, 48, 41, 59, 10, 10, 9, 9, 47,
+ 47,102,108,111, 97,116, 32, 98,105, 97,115, 32, 61, 32, 40, 49, 46, 53, 32, 45, 32,105,110,112, 42,105,110,112, 41, 42,115,104,
+ 97,100,111,119, 98,105, 97,115, 59, 10, 9, 9, 99,111, 46,122, 32, 45, 61, 32,115,104, 97,100,111,119, 98,105, 97,115, 42, 99,
+111, 46,119, 59, 10, 10, 9, 9,114,101,115,117,108,116, 32, 61, 32,115,104, 97,100,111,119, 50, 68, 80,114,111,106, 40,115,104,
+ 97,100,111,119,109, 97,112, 44, 32, 99,111, 41, 46,120, 59, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101,
+ 95,101,120,112,111,115,117,114,101, 95, 99,111,114,114,101, 99,116, 40,118,101, 99, 51, 32, 99,111,108, 44, 32,102,108,111, 97,
+116, 32,108,105,110,102, 97, 99, 44, 32,102,108,111, 97,116, 32,108,111,103,102, 97, 99, 44, 32,111,117,116, 32,118,101, 99, 51,
+ 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32,108,105,110,102, 97, 99, 42, 40, 49, 46, 48,
+ 32, 45, 32,101,120,112, 40, 99,111,108, 42,108,111,103,102, 97, 99, 41, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,
+100,101, 95,109,105,115,116, 95,102, 97, 99,116,111,114, 40,118,101, 99, 51, 32, 99,111, 44, 32,102,108,111, 97,116, 32,109,105,
+115,116,115,116, 97, 44, 32,102,108,111, 97,116, 32,109,105,115,116,100,105,115,116, 44, 32,102,108,111, 97,116, 32,109,105,115,
+116,116,121,112,101, 44, 32,102,108,111, 97,116, 32,109,105,115,105, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,
+102, 97, 99, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99, 44, 32,122, 99,111,114, 59, 10, 10, 9,122, 99,111,114, 32,
+ 61, 32, 40,103,108, 95, 80,114,111,106,101, 99,116,105,111,110, 77, 97,116,114,105,120, 91, 51, 93, 91, 51, 93, 32, 61, 61, 32,
+ 48, 46, 48, 41, 63, 32,108,101,110,103,116,104, 40, 99,111, 41, 58, 32, 45, 99,111, 91, 50, 93, 59, 10, 9, 10, 9,102, 97, 99,
+ 32, 61, 32, 99,108, 97,109,112, 40, 40,122, 99,111,114, 45,109,105,115,116,115,116, 97, 41, 47,109,105,115,116,100,105,115,116,
+ 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,105,102, 40,109,105,115,116,116,121,112,101, 32, 61, 61, 32, 48, 46, 48,
+ 41, 32,102, 97, 99, 32, 42, 61, 32,102, 97, 99, 59, 10, 9,101,108,115,101, 32,105,102, 40,109,105,115,116,116,121,112,101, 32,
+ 61, 61, 32, 49, 46, 48, 41, 59, 10, 9,101,108,115,101, 32,102, 97, 99, 32, 61, 32,115,113,114,116, 40,102, 97, 99, 41, 59, 10,
+ 10, 9,111,117,116,102, 97, 99, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40, 49, 46, 48, 45,102, 97, 99, 41, 42, 40, 49, 46, 48, 45,
+109,105,115,105, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,119,111,114,108,100, 95,109,105,120, 40,118,
+101, 99, 51, 32,104,111,114, 44, 32,118,101, 99, 52, 32, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,
+111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40, 99,111,108, 46, 97, 44, 32,
+ 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 32, 61, 32,118,101, 99, 52, 40,109,105,120, 40,104,111,
+114, 44, 32, 99,111,108, 46,114,103, 98, 44, 32,102, 97, 99, 41, 44, 32, 99,111,108, 46, 97, 41, 59, 10,125, 10, 10,118,111,105,
+100, 32,115,104, 97,100,101, 95, 97,108,112,104, 97, 95,111,112, 97,113,117,101, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,111,
+117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32,118,101, 99, 52,
+ 40, 99,111,108, 46,114,103, 98, 44, 32, 49, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95, 97,108,
+112,104, 97, 95,111, 98, 99,111,108,111,114, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,118,101, 99, 52, 32,111, 98, 99,111,108,
+ 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32,118,
+101, 99, 52, 40, 99,111,108, 46,114,103, 98, 44, 32, 99,111,108, 46, 97, 42,111, 98, 99,111,108, 46, 97, 41, 59, 10,125, 10, 10,
+ 0};
+
diff --git a/source/blender/gpu/intern/gpu_shader_vertex.glsl b/source/blender/gpu/intern/gpu_shader_vertex.glsl
new file mode 100644
index 00000000000..ba9ef7dead6
--- /dev/null
+++ b/source/blender/gpu/intern/gpu_shader_vertex.glsl
@@ -0,0 +1,12 @@
+
+varying vec3 varposition;
+varying vec3 varnormal;
+
+void main()
+{
+ vec4 co = gl_ModelViewMatrix * gl_Vertex;
+
+ varposition = co.xyz;
+ varnormal = gl_NormalMatrix * gl_Normal;
+ gl_Position = gl_ProjectionMatrix * co;
+
diff --git a/source/blender/gpu/intern/gpu_shader_vertex.glsl.c b/source/blender/gpu/intern/gpu_shader_vertex.glsl.c
new file mode 100644
index 00000000000..edf93d838d5
--- /dev/null
+++ b/source/blender/gpu/intern/gpu_shader_vertex.glsl.c
@@ -0,0 +1,13 @@
+/* DataToC output of file <gpu_shader_vertex_glsl> */
+
+int datatoc_gpu_shader_vertex_glsl_size= 217;
+char datatoc_gpu_shader_vertex_glsl[]= {
+ 10,118, 97,114,121,105,110,103, 32,118,101, 99, 51, 32,118, 97,114,112,111,115,105,116,105,111,110,
+ 59, 10,118, 97,114,121,105,110,103, 32,118,101, 99, 51, 32,118, 97,114,110,111,114,109, 97,108, 59, 10, 10,118,111,105,100, 32,
+109, 97,105,110, 40, 41, 10,123, 10, 9,118,101, 99, 52, 32, 99,111, 32, 61, 32,103,108, 95, 77,111,100,101,108, 86,105,101,119,
+ 77, 97,116,114,105,120, 32, 42, 32,103,108, 95, 86,101,114,116,101,120, 59, 10, 10, 9,118, 97,114,112,111,115,105,116,105,111,
+110, 32, 61, 32, 99,111, 46,120,121,122, 59, 10, 9,118, 97,114,110,111,114,109, 97,108, 32, 61, 32,103,108, 95, 78,111,114,109,
+ 97,108, 77, 97,116,114,105,120, 32, 42, 32,103,108, 95, 78,111,114,109, 97,108, 59, 10, 9,103,108, 95, 80,111,115,105,116,105,
+111,110, 32, 61, 32,103,108, 95, 80,114,111,106,101, 99,116,105,111,110, 77, 97,116,114,105,120, 32, 42, 32, 99,111, 59, 10, 10,
+ 0};
+
diff --git a/source/blender/imbuf/CMakeLists.txt b/source/blender/imbuf/CMakeLists.txt
index 0aac462573a..2d41a6d73e6 100644
--- a/source/blender/imbuf/CMakeLists.txt
+++ b/source/blender/imbuf/CMakeLists.txt
@@ -54,5 +54,9 @@ IF(WITH_FFMPEG)
ADD_DEFINITIONS(-DWITH_FFMPEG)
ENDIF(WITH_FFMPEG)
+if(WITH_DDS)
+ ADD_DEFINITIONS(-DWITH_DDS)
+ENDIF(WITH_DDS)
+
BLENDERLIB(bf_imbuf "${SRC}" "${INC}")
#env.BlenderLib ( libname = 'bf_imbuf', sources = sources, includes = Split(incs), defines = defs, libtype=['core','player'], priority = [80, 40] )
diff --git a/source/blender/imbuf/IMB_imbuf.h b/source/blender/imbuf/IMB_imbuf.h
index 338f96cb4f4..d4d8030bf10 100644
--- a/source/blender/imbuf/IMB_imbuf.h
+++ b/source/blender/imbuf/IMB_imbuf.h
@@ -318,7 +318,7 @@ void IMB_antialias(struct ImBuf * ibuf);
*/
void IMB_filter(struct ImBuf *ibuf);
void IMB_filterN(struct ImBuf *out, struct ImBuf *in);
-void IMB_filter_extend(struct ImBuf *ibuf);
+void IMB_filter_extend(struct ImBuf *ibuf, char *mask);
void IMB_makemipmap(struct ImBuf *ibuf, int use_filter);
/**
diff --git a/source/blender/imbuf/IMB_imbuf_types.h b/source/blender/imbuf/IMB_imbuf_types.h
index ce210e7834d..73ef83393b0 100644
--- a/source/blender/imbuf/IMB_imbuf_types.h
+++ b/source/blender/imbuf/IMB_imbuf_types.h
@@ -92,7 +92,7 @@ typedef struct ImBuf {
int userflags; /**< Used to set imbuf to Dirty and other stuff */
int *zbuf; /**< z buffer data, original zbuffer */
float *zbuf_float; /**< z buffer data, camera coordinates */
- void *userdata;
+ void *userdata; /**< temporary storage, only used by baking at the moment */
unsigned char *encodedbuffer; /**< Compressed image only used with png currently */
unsigned int encodedsize; /**< Size of data written to encodedbuffer */
unsigned int encodedbuffersize; /**< Size of encodedbuffer */
@@ -149,6 +149,7 @@ typedef enum {
#define IB_zbuffloat (1 << 16)
#define IB_multilayer (1 << 17)
#define IB_imginfo (1 << 18)
+#define IB_animdeinterlace (1 << 19)
/*
* The bit flag is stored in the ImBuf.ftype variable.
@@ -167,6 +168,7 @@ typedef enum {
#define RADHDR (1 << 24)
#define TIF (1 << 23)
+#define TIF_16BIT (1 << 8 )
#define OPENEXR (1 << 22)
#define OPENEXR_HALF (1 << 8 )
diff --git a/source/blender/imbuf/SConscript b/source/blender/imbuf/SConscript
index 9d8bcf56ec7..cb4759ed240 100644
--- a/source/blender/imbuf/SConscript
+++ b/source/blender/imbuf/SConscript
@@ -4,7 +4,7 @@ Import ('env')
sources = env.Glob('intern/*.c')
incs = '. ../makesdna #/intern/guardedalloc #/intern/memutil ../blenlib'
-incs += ' ../avi ../quicktime ../blenkernel'
+incs += ' ../avi ../blenkernel'
incs += ' ' + env['BF_JPEG_INC']
incs += ' ' + env['BF_PNG_INC']
@@ -17,18 +17,26 @@ if env['WITH_BF_VERSE']:
defs.append('WITH_VERSE')
incs += ' ' + env['BF_VERSE_INCLUDE']
-if env['WITH_BF_OPENEXR'] == 1:
- defs.append('WITH_OPENEXR')
+if env['WITH_BF_OPENEXR']:
+ defs.append('WITH_OPENEXR')
-if env['WITH_BF_DDS'] == 1:
- defs.append('WITH_DDS')
+if env['WITH_BF_DDS']:
+ defs.append('WITH_DDS')
-if env['WITH_BF_FFMPEG'] == 1:
- defs.append('WITH_FFMPEG')
- incs += ' ' + env['BF_FFMPEG_INC']
+if env['WITH_BF_FFMPEG']:
+ defs.append('WITH_FFMPEG')
+ incs += ' ' + env['BF_FFMPEG_INC']
-if env['WITH_BF_QUICKTIME']==1:
- incs += ' ' + env['BF_QUICKTIME_INC']
+if env['WITH_BF_OPENJPEG']:
+ defs.append('WITH_OPENJPEG')
+ incs += ' ' + env['BF_OPENJPEG_INC']
+
+if env['WITH_BF_REDCODE']:
+ defs.append('WITH_REDCODE')
+ incs += ' ' + env['BF_REDCODE_INC']
+
+if env['WITH_BF_QUICKTIME']:
+ incs += ' ../quicktime ' + env['BF_QUICKTIME_INC']
defs.append('WITH_QUICKTIME')
env.BlenderLib ( libname = 'bf_imbuf', sources = sources, includes = Split(incs), defines = defs, libtype=['core','player'], priority = [95, 35] )
diff --git a/source/blender/imbuf/intern/IMB_anim.h b/source/blender/imbuf/intern/IMB_anim.h
index 2c7f8bddbe6..745248d3218 100644
--- a/source/blender/imbuf/intern/IMB_anim.h
+++ b/source/blender/imbuf/intern/IMB_anim.h
@@ -81,6 +81,14 @@
#include <ffmpeg/swscale.h>
#endif
+#ifdef WITH_REDCODE
+#ifdef _WIN32 /* on windows we use the one in extern instead */
+#include "libredcode/format.h"
+#else
+#include "libredcode/format.h"
+#endif
+#endif
+
#include "IMB_imbuf_types.h"
#include "IMB_imbuf.h"
@@ -96,7 +104,7 @@
#define SWAP_S(x) (((x << 8) & 0xff00) | ((x >> 8) & 0xff))
/* more endianness... should move to a separate file... */
-#if defined(__sgi) || defined (__sparc) || (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
+#if defined(__sgi) || defined (__sparc) || (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__hppa__) || defined (__BIG_ENDIAN__)
#define GET_ID GET_BIG_LONG
#define LITTLE_LONG SWAP_LONG
#else
@@ -116,6 +124,7 @@
#define ANIM_AVI (1 << 6)
#define ANIM_QTIME (1 << 7)
#define ANIM_FFMPEG (1 << 8)
+#define ANIM_REDCODE (1 << 9)
#define ANIM5_MMAP 0
#define ANIM5_MALLOC 1
@@ -178,12 +187,16 @@ struct anim {
AVFormatContext *pFormatCtx;
AVCodecContext *pCodecCtx;
AVCodec *pCodec;
- AVFrame *pFrameRGB;
AVFrame *pFrame;
+ AVFrame *pFrameRGB;
+ AVFrame *pFrameDeinterlaced;
struct SwsContext *img_convert_ctx;
int videoStream;
#endif
+#ifdef WITH_REDCODE
+ struct redcode_handle * redcodeCtx;
+#endif
};
#endif
diff --git a/source/blender/imbuf/intern/allocimbuf.c b/source/blender/imbuf/intern/allocimbuf.c
index be462d67238..ad7b1dce2e0 100644
--- a/source/blender/imbuf/intern/allocimbuf.c
+++ b/source/blender/imbuf/intern/allocimbuf.c
@@ -277,6 +277,7 @@ short imb_addrectfloatImBuf(struct ImBuf * ibuf)
size = ibuf->x * ibuf->y;
size = size * 4 * sizeof(float);
+ ibuf->channels= 4;
if ( (ibuf->rect_float = MEM_mapallocN(size, "imb_addrectfloatImBuf")) ){
ibuf->mall |= IB_rectfloat;
@@ -442,7 +443,7 @@ struct ImBuf *IMB_dupImBuf(struct ImBuf *ibuf1)
memcpy(ibuf2->rect, ibuf1->rect, x * y * sizeof(int));
if (flags & IB_rectfloat)
- memcpy(ibuf2->rect_float, ibuf1->rect_float, 4 * x * y * sizeof(float));
+ memcpy(ibuf2->rect_float, ibuf1->rect_float, ibuf1->channels * x * y * sizeof(float));
if (flags & IB_planes)
memcpy(*(ibuf2->planes),*(ibuf1->planes),ibuf1->depth * ibuf1->skipx * y * sizeof(int));
@@ -474,6 +475,7 @@ struct ImBuf *IMB_dupImBuf(struct ImBuf *ibuf1)
// set malloc flag
tbuf.mall = ibuf2->mall;
tbuf.c_handle = 0;
+ tbuf.refcounter = 0;
// for now don't duplicate image info
tbuf.img_info = 0;
diff --git a/source/blender/imbuf/intern/amiga.c b/source/blender/imbuf/intern/amiga.c
index fa13b55874a..534e4945aa3 100644
--- a/source/blender/imbuf/intern/amiga.c
+++ b/source/blender/imbuf/intern/amiga.c
@@ -29,8 +29,12 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#ifdef WIN32
+#ifdef _WIN32
#include <io.h>
+#define open _open
+#define read _read
+#define close _close
+#define write _write
#endif
#include "imbuf.h"
#include "imbuf_patch.h"
@@ -52,7 +56,7 @@
#define SWAP_S(x) (((x << 8) & 0xff00) | ((x >> 8) & 0xff))
/* more endianness... should move to a separate file... */
-#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
+#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__hppa__) || defined (__BIG_ENDIAN__)
#define GET_ID GET_BIG_LONG
#define LITTLE_LONG SWAP_LONG
#else
diff --git a/source/blender/imbuf/intern/anim.c b/source/blender/imbuf/intern/anim.c
index ef3dd79db73..80bf401bec0 100644
--- a/source/blender/imbuf/intern/anim.c
+++ b/source/blender/imbuf/intern/anim.c
@@ -96,6 +96,16 @@
#endif
+#ifdef WITH_REDCODE
+#ifdef _WIN32 /* on windows we use the ones in extern instead */
+#include "libredcode/format.h"
+#include "libredcode/codec.h"
+#else
+#include "libredcode/format.h"
+#include "libredcode/codec.h"
+#endif
+#endif
+
/****/
#ifdef __sgi
@@ -307,6 +317,9 @@ void IMB_free_anim_ibuf(struct anim * anim) {
#ifdef WITH_FFMPEG
static void free_anim_ffmpeg(struct anim * anim);
#endif
+#ifdef WITH_REDCODE
+static void free_anim_redcode(struct anim * anim);
+#endif
void IMB_free_anim(struct anim * anim) {
if (anim == NULL) {
@@ -325,6 +338,9 @@ void IMB_free_anim(struct anim * anim) {
#ifdef WITH_FFMPEG
free_anim_ffmpeg(anim);
#endif
+#ifdef WITH_REDCODE
+ free_anim_redcode(anim);
+#endif
free(anim);
}
@@ -589,19 +605,31 @@ static int startffmpeg(struct anim * anim) {
anim->videoStream = videoStream;
anim->pFrame = avcodec_alloc_frame();
+ anim->pFrameDeinterlaced = avcodec_alloc_frame();
anim->pFrameRGB = avcodec_alloc_frame();
- if (avpicture_get_size(PIX_FMT_RGBA32, anim->x, anim->y)
+ if (avpicture_get_size(PIX_FMT_BGR32, anim->x, anim->y)
!= anim->x * anim->y * 4) {
fprintf (stderr,
"ffmpeg has changed alloc scheme ... ARGHHH!\n");
avcodec_close(anim->pCodecCtx);
av_close_input_file(anim->pFormatCtx);
av_free(anim->pFrameRGB);
+ av_free(anim->pFrameDeinterlaced);
av_free(anim->pFrame);
+ anim->pCodecCtx = NULL;
return -1;
}
+ if (anim->ib_flags & IB_animdeinterlace) {
+ avpicture_fill((AVPicture*) anim->pFrameDeinterlaced,
+ MEM_callocN(avpicture_get_size(
+ anim->pCodecCtx->pix_fmt,
+ anim->x, anim->y),
+ "ffmpeg deinterlace"),
+ anim->pCodecCtx->pix_fmt, anim->x, anim->y);
+ }
+
if (pCodecCtx->has_b_frames) {
anim->preseek = 25; /* FIXME: detect gopsize ... */
} else {
@@ -614,10 +642,22 @@ static int startffmpeg(struct anim * anim) {
anim->pCodecCtx->pix_fmt,
anim->pCodecCtx->width,
anim->pCodecCtx->height,
- PIX_FMT_RGBA,
+ PIX_FMT_BGR32,
SWS_FAST_BILINEAR | SWS_PRINT_INFO,
NULL, NULL, NULL);
-
+
+ if (!anim->img_convert_ctx) {
+ fprintf (stderr,
+ "Can't transform color space??? Bailing out...\n");
+ avcodec_close(anim->pCodecCtx);
+ av_close_input_file(anim->pFormatCtx);
+ av_free(anim->pFrameRGB);
+ av_free(anim->pFrameDeinterlaced);
+ av_free(anim->pFrame);
+ anim->pCodecCtx = NULL;
+ return -1;
+ }
+
return (0);
}
@@ -627,14 +667,15 @@ static ImBuf * ffmpeg_fetchibuf(struct anim * anim, int position) {
AVPacket packet;
int64_t pts_to_search = 0;
int pos_found = 1;
+ int filter_y = 0;
if (anim == 0) return (0);
ibuf = IMB_allocImBuf(anim->x, anim->y, 24, IB_rect, 0);
- avpicture_fill((AVPicture *)anim->pFrameRGB,
+ avpicture_fill((AVPicture*) anim->pFrameRGB,
(unsigned char*) ibuf->rect,
- PIX_FMT_RGBA32, anim->x, anim->y);
+ PIX_FMT_BGR32, anim->x, anim->y);
if (position != anim->curposition + 1) {
if (position > anim->curposition + 1
@@ -711,35 +752,135 @@ static ImBuf * ffmpeg_fetchibuf(struct anim * anim, int position) {
}
if(frameFinished && pos_found == 1) {
- int * dstStride = anim->pFrameRGB->linesize;
- uint8_t** dst = anim->pFrameRGB->data;
- int dstStride2[4]= { -dstStride[0], 0, 0, 0 };
- uint8_t* dst2[4]= {
- dst[0] + (anim->y - 1)*dstStride[0],
- 0, 0, 0 };
- int i;
-
- sws_scale(anim->img_convert_ctx,
- anim->pFrame->data,
- anim->pFrame->linesize,
- 0,
- anim->pCodecCtx->height,
- dst2,
- dstStride2);
-
- /* workaround: sws_scale sets alpha = 0... */
- for (i = 0; i < ibuf->x * ibuf->y; i++) {
- ibuf->rect[i] |= 0xff000000;
+ AVFrame * input = anim->pFrame;
+
+ /* This means the data wasnt read properly,
+ this check stops crashing */
+ if (input->data[0]==0 && input->data[1]==0
+ && input->data[2]==0 && input->data[3]==0){
+ av_free_packet(&packet);
+ break;
}
- av_free_packet(&packet);
- break;
+ if (anim->ib_flags & IB_animdeinterlace) {
+ if (avpicture_deinterlace(
+ (AVPicture*)
+ anim->pFrameDeinterlaced,
+ (const AVPicture*)
+ anim->pFrame,
+ anim->pCodecCtx->pix_fmt,
+ anim->pCodecCtx->width,
+ anim->pCodecCtx->height)
+ < 0) {
+ filter_y = 1;
+ } else {
+ input = anim->pFrameDeinterlaced;
+ }
+ }
+
+ if (G.order == B_ENDIAN) {
+ int * dstStride
+ = anim->pFrameRGB->linesize;
+ uint8_t** dst = anim->pFrameRGB->data;
+ int dstStride2[4]
+ = { dstStride[0], 0, 0, 0 };
+ uint8_t* dst2[4]= {
+ dst[0], 0, 0, 0 };
+ int x,y,h,w;
+ unsigned char* bottom;
+ unsigned char* top;
+
+ sws_scale(anim->img_convert_ctx,
+ input->data,
+ input->linesize,
+ 0,
+ anim->pCodecCtx->height,
+ dst2,
+ dstStride2);
+
+ /* workaround: sws_scale
+ sets alpha = 0 and compensate
+ for altivec-bugs and flipy... */
+
+ bottom = (unsigned char*) ibuf->rect;
+ top = bottom
+ + ibuf->x * (ibuf->y-1) * 4;
+
+ h = (ibuf->y + 1) / 2;
+ w = ibuf->x;
+
+ for (y = 0; y < h; y++) {
+ unsigned char tmp[4];
+ unsigned long * tmp_l =
+ (unsigned long*) tmp;
+ tmp[3] = 0xff;
+
+ for (x = 0; x < w; x++) {
+ tmp[0] = bottom[3];
+ tmp[1] = bottom[2];
+ tmp[2] = bottom[1];
+
+ bottom[0] = top[3];
+ bottom[1] = top[2];
+ bottom[2] = top[1];
+ bottom[3] = 0xff;
+
+ *(unsigned long*) top
+ = *tmp_l;
+
+ bottom +=4;
+ top += 4;
+ }
+ top -= 8 * w;
+ }
+
+ av_free_packet(&packet);
+ break;
+ } else {
+ int * dstStride
+ = anim->pFrameRGB->linesize;
+ uint8_t** dst = anim->pFrameRGB->data;
+ int dstStride2[4]
+ = { -dstStride[0], 0, 0, 0 };
+ uint8_t* dst2[4]= {
+ dst[0]
+ + (anim->y - 1)*dstStride[0],
+ 0, 0, 0 };
+ int i;
+ unsigned char* r;
+
+
+ sws_scale(anim->img_convert_ctx,
+ input->data,
+ input->linesize,
+ 0,
+ anim->pCodecCtx->height,
+ dst2,
+ dstStride2);
+
+ /* workaround: sws_scale
+ sets alpha = 0... */
+
+ r = (unsigned char*) ibuf->rect;
+
+ for (i = 0; i < ibuf->x * ibuf->y;i++){
+ r[3] = 0xff;
+ r+=4;
+ }
+
+ av_free_packet(&packet);
+ break;
+ }
}
}
av_free_packet(&packet);
}
+ if (filter_y && ibuf) {
+ IMB_filtery(ibuf);
+ }
+
return(ibuf);
}
@@ -751,6 +892,11 @@ static void free_anim_ffmpeg(struct anim * anim) {
av_close_input_file(anim->pFormatCtx);
av_free(anim->pFrameRGB);
av_free(anim->pFrame);
+
+ if (anim->ib_flags & IB_animdeinterlace) {
+ MEM_freeN(anim->pFrameDeinterlaced->data[0]);
+ }
+ av_free(anim->pFrameDeinterlaced);
sws_freeContext(anim->img_convert_ctx);
}
anim->duration = 0;
@@ -758,6 +904,58 @@ static void free_anim_ffmpeg(struct anim * anim) {
#endif
+#ifdef WITH_REDCODE
+
+static int startredcode(struct anim * anim) {
+ anim->redcodeCtx = redcode_open(anim->name);
+ if (!anim->redcodeCtx) {
+ return -1;
+ }
+ anim->duration = redcode_get_length(anim->redcodeCtx);
+
+ return 0;
+}
+
+static ImBuf * redcode_fetchibuf(struct anim * anim, int position) {
+ struct ImBuf * ibuf;
+ struct redcode_frame * frame;
+ struct redcode_frame_raw * raw_frame;
+
+ if (!anim->redcodeCtx) {
+ return NULL;
+ }
+
+ frame = redcode_read_video_frame(anim->redcodeCtx, position);
+
+ if (!frame) {
+ return NULL;
+ }
+
+ raw_frame = redcode_decode_video_raw(frame, 1);
+
+ redcode_free_frame(frame);
+
+ if (!raw_frame) {
+ return NULL;
+ }
+
+ ibuf = IMB_allocImBuf(raw_frame->width * 2,
+ raw_frame->height * 2, 32, IB_rectfloat, 0);
+
+ redcode_decode_video_float(raw_frame, ibuf->rect_float, 1);
+
+ return ibuf;
+}
+
+static void free_anim_redcode(struct anim * anim) {
+ if (anim->redcodeCtx) {
+ redcode_close(anim->redcodeCtx);
+ anim->redcodeCtx = 0;
+ }
+ anim->duration = 0;
+}
+
+#endif
/* probeer volgende plaatje te lezen */
/* Geen plaatje, probeer dan volgende animatie te openen */
@@ -777,6 +975,10 @@ static struct ImBuf * anim_getnew(struct anim * anim) {
#ifdef WITH_FFMPEG
free_anim_ffmpeg(anim);
#endif
+#ifdef WITH_REDCODE
+ free_anim_redcode(anim);
+#endif
+
if (anim->curtype != 0) return (0);
anim->curtype = imb_get_anim_type(anim->name);
@@ -816,8 +1018,13 @@ static struct ImBuf * anim_getnew(struct anim * anim) {
ibuf = IMB_allocImBuf (anim->x, anim->y, 24, 0, 0);
break;
#endif
+#ifdef WITH_REDCODE
+ case ANIM_REDCODE:
+ if (startredcode(anim)) return (0);
+ ibuf = IMB_allocImBuf (8, 8, 32, 0, 0);
+ break;
+#endif
}
-
return(ibuf);
}
@@ -839,6 +1046,7 @@ struct ImBuf * IMB_anim_absolute(struct anim * anim, int position) {
char head[256], tail[256];
unsigned short digits;
int pic;
+ int filter_y = (anim->ib_flags & IB_animdeinterlace);
if (anim == NULL) return(0);
@@ -896,12 +1104,20 @@ struct ImBuf * IMB_anim_absolute(struct anim * anim, int position) {
case ANIM_FFMPEG:
ibuf = ffmpeg_fetchibuf(anim, position);
if (ibuf) anim->curposition = position;
+ filter_y = 0; /* done internally */
+ break;
+#endif
+#ifdef WITH_REDCODE
+ case ANIM_REDCODE:
+ ibuf = redcode_fetchibuf(anim, position);
+ if (ibuf) anim->curposition = position;
break;
#endif
}
if (ibuf) {
if (anim->ib_flags & IB_ttob) IMB_flipy(ibuf);
+ if (filter_y) IMB_filtery(ibuf);
sprintf(ibuf->name, "%s.%04d", anim->name, anim->curposition + 1);
}
diff --git a/source/blender/imbuf/intern/bmp.c b/source/blender/imbuf/intern/bmp.c
index 2aa276a5f53..141b8a985cf 100644
--- a/source/blender/imbuf/intern/bmp.c
+++ b/source/blender/imbuf/intern/bmp.c
@@ -164,9 +164,9 @@ struct ImBuf *imb_bmp_decode(unsigned char *mem, int size, int flags)
}
} else if (depth == 32) {
for (i = x * y; i > 0; i--) {
- rect[0] = bmp[0];
+ rect[0] = bmp[2];
rect[1] = bmp[1];
- rect[2] = bmp[2];
+ rect[2] = bmp[0];
rect[3] = bmp[3];
rect += 4; bmp += 4;
}
diff --git a/source/blender/imbuf/intern/cineon/SConscript b/source/blender/imbuf/intern/cineon/SConscript
index 9d3bbcbc058..f887516443c 100644
--- a/source/blender/imbuf/intern/cineon/SConscript
+++ b/source/blender/imbuf/intern/cineon/SConscript
@@ -4,13 +4,13 @@ Import ('env')
source_files = env.Glob('*.c')
incs = ['.',
- '../../../blenkernel',
- '../../',
- '..',
- '../../../blenlib',
- 'intern/include',
- '#/intern/guardedalloc',
- '../../../makesdna']
+ '../../../blenkernel',
+ '../../',
+ '..',
+ '../../../blenlib',
+ 'intern/include',
+ '#/intern/guardedalloc',
+ '../../../makesdna']
defs = []
diff --git a/source/blender/imbuf/intern/cineon/cineon_dpx.c b/source/blender/imbuf/intern/cineon/cineon_dpx.c
index 691b81745e0..514d6b5522b 100644
--- a/source/blender/imbuf/intern/cineon/cineon_dpx.c
+++ b/source/blender/imbuf/intern/cineon/cineon_dpx.c
@@ -42,14 +42,29 @@
#include "MEM_guardedalloc.h"
+/* ugly bad level, should be fixed */
+#include "DNA_scene_types.h"
+#include "BKE_global.h"
+
+static void cineon_conversion_parameters(LogImageByteConversionParameters *params)
+{
+ params->blackPoint = G.scene?G.scene->r.cineonblack:95;
+ params->whitePoint = G.scene?G.scene->r.cineonwhite:685;
+ params->gamma = G.scene?G.scene->r.cineongamma:1.7f;
+ params->doLogarithm = G.scene?G.scene->r.subimtype & R_CINEON_LOG:0;
+}
+
static struct ImBuf *imb_load_dpx_cineon(unsigned char *mem, int use_cineon, int size, int flags)
{
+ LogImageByteConversionParameters conversion;
ImBuf *ibuf;
LogImageFile *image;
int x, y;
unsigned short *row, *upix;
int width, height, depth;
float *frow;
+
+ cineon_conversion_parameters(&conversion);
image = logImageOpenFromMem(mem, size, use_cineon);
@@ -70,6 +85,8 @@ static struct ImBuf *imb_load_dpx_cineon(unsigned char *mem, int use_cineon, int
return NULL;
}
+ logImageSetByteConversion(image, &conversion);
+
ibuf = IMB_allocImBuf(width, height, 32, IB_rectfloat | flags, 0);
row = MEM_mallocN(sizeof(unsigned short)*width*depth, "row in cineon_dpx.c");
@@ -107,10 +124,9 @@ static int imb_save_dpx_cineon(ImBuf *buf, char *filename, int use_cineon, int f
int i, j;
int index;
float *fline;
-
- conversion.blackPoint = 95;
- conversion.whitePoint = 685;
- conversion.gamma = 1;
+
+ cineon_conversion_parameters(&conversion);
+
/*
* Get the drawable for the current image...
*/
@@ -119,7 +135,13 @@ static int imb_save_dpx_cineon(ImBuf *buf, char *filename, int use_cineon, int f
height = buf->y;
depth = 3;
- if (!buf->rect_float) return 0;
+
+ if (!buf->rect_float) {
+ IMB_float_from_rect(buf);
+ if (!buf->rect_float) { /* in the unlikely event that converting to a float buffer fails */
+ return 0;
+ }
+ }
logImageSetVerbose(0);
logImage = logImageCreate(filename, use_cineon, width, height, depth);
diff --git a/source/blender/imbuf/intern/cineon/cineonlib.c b/source/blender/imbuf/intern/cineon/cineonlib.c
index 20f4e0d4de4..75516bbf3ae 100644
--- a/source/blender/imbuf/intern/cineon/cineonlib.c
+++ b/source/blender/imbuf/intern/cineon/cineonlib.c
@@ -67,12 +67,12 @@ fillCineonFileInfo(CineonFile* cineon, CineonFileInformation* fileInfo, const ch
static void
dumpCineonFileInfo(CineonFileInformation* fileInfo) {
d_printf("\n--File Information--\n");
- d_printf("Magic: %8.8lX\n", (unsigned long)ntohl(fileInfo->magic_num));
- d_printf("Image Offset %ld\n", (long)ntohl(fileInfo->image_offset));
- d_printf("Generic Header size %ld\n", (long)ntohl(fileInfo->gen_hdr_size));
- d_printf("Industry Header size %ld\n", (long)ntohl(fileInfo->ind_hdr_size));
- d_printf("User Data size %ld\n", (long)ntohl(fileInfo->user_data_size));
- d_printf("File size %ld\n", (long)ntohl(fileInfo->file_size));
+ d_printf("Magic: %8.8lX\n", (uintptr_t)ntohl(fileInfo->magic_num));
+ d_printf("Image Offset %ld\n", (intptr_t)ntohl(fileInfo->image_offset));
+ d_printf("Generic Header size %ld\n", (intptr_t)ntohl(fileInfo->gen_hdr_size));
+ d_printf("Industry Header size %ld\n", (intptr_t)ntohl(fileInfo->ind_hdr_size));
+ d_printf("User Data size %ld\n", (intptr_t)ntohl(fileInfo->user_data_size));
+ d_printf("File size %ld\n", (intptr_t)ntohl(fileInfo->file_size));
d_printf("Version \"%s\"\n", fileInfo->vers);
d_printf("File name \"%s\"\n", fileInfo->file_name);
d_printf("Creation date \"%s\"\n", fileInfo->create_date);
@@ -112,11 +112,11 @@ dumpCineonChannelInfo(CineonChannelInformation* chan) {
default: d_printf(" (unknown)\n"); break;
}
d_printf(" Bits per pixel %d\n", chan->bits_per_pixel);
- d_printf(" Pixels per line %ld\n", (long)ntohl(chan->pixels_per_line));
- d_printf(" Lines per image %ld\n", (long)ntohl(chan->lines_per_image));
- d_printf(" Ref low data %ld\n", (long)ntohl(chan->ref_low_data));
+ d_printf(" Pixels per line %ld\n", (intptr_t)ntohl(chan->pixels_per_line));
+ d_printf(" Lines per image %ld\n", (intptr_t)ntohl(chan->lines_per_image));
+ d_printf(" Ref low data %ld\n", (intptr_t)ntohl(chan->ref_low_data));
d_printf(" Ref low quantity %f\n", ntohf(chan->ref_low_quantity));
- d_printf(" Ref high data %ld\n", (long)ntohl(chan->ref_high_data));
+ d_printf(" Ref high data %ld\n", (intptr_t)ntohl(chan->ref_high_data));
d_printf(" Ref high quantity %f\n", ntohf(chan->ref_high_quantity));
}
@@ -231,8 +231,8 @@ dumpCineonFormatInfo(CineonFormatInformation* formatInfo) {
} else {
d_printf(" positive\n");
}
- d_printf("End of line padding %ld\n", (long)ntohl(formatInfo->line_padding));
- d_printf("End of channel padding %ld\n", (long)ntohl(formatInfo->channel_padding));
+ d_printf("End of line padding %ld\n", (intptr_t)ntohl(formatInfo->line_padding));
+ d_printf("End of channel padding %ld\n", (intptr_t)ntohl(formatInfo->channel_padding));
}
static void
@@ -256,8 +256,8 @@ fillCineonOriginationInfo(CineonFile* cineon,
static void
dumpCineonOriginationInfo(CineonOriginationInformation* originInfo) {
d_printf("\n--Origination Information--\n");
- d_printf("X offset %ld\n", (long)ntohl(originInfo->x_offset));
- d_printf("Y offset %ld\n", (long)ntohl(originInfo->y_offset));
+ d_printf("X offset %ld\n", (intptr_t)ntohl(originInfo->x_offset));
+ d_printf("Y offset %ld\n", (intptr_t)ntohl(originInfo->y_offset));
d_printf("File name \"%s\"\n", originInfo->file_name);
d_printf("Creation date \"%s\"\n", originInfo->create_date);
d_printf("Creation time \"%s\"\n", originInfo->create_time);
@@ -350,8 +350,10 @@ cineonGetRowBytes(CineonFile* cineon, unsigned short* row, int y) {
/* extract required pixels */
for (pixelIndex = 0; pixelIndex < numPixels; ++pixelIndex) {
- /* row[pixelIndex] = cineon->lut10[cineon->pixelBuffer[pixelIndex]]; */
- row[pixelIndex] = cineon->pixelBuffer[pixelIndex] << 6;
+ if(cineon->params.doLogarithm)
+ row[pixelIndex] = cineon->lut10_16[cineon->pixelBuffer[pixelIndex]];
+ else
+ row[pixelIndex] = cineon->pixelBuffer[pixelIndex] << 6;
}
return 0;
@@ -367,8 +369,10 @@ cineonSetRowBytes(CineonFile* cineon, const unsigned short* row, int y) {
/* put new pixels into pixelBuffer */
for (pixelIndex = 0; pixelIndex < numPixels; ++pixelIndex) {
- /* cineon->pixelBuffer[pixelIndex] = cineon->lut8[row[pixelIndex]]; */
- cineon->pixelBuffer[pixelIndex] = row[pixelIndex] >> 6;
+ if(cineon->params.doLogarithm)
+ cineon->pixelBuffer[pixelIndex] = cineon->lut16_16[row[pixelIndex]];
+ else
+ cineon->pixelBuffer[pixelIndex] = row[pixelIndex] >> 6;
}
/* pack into longwords */
@@ -525,7 +529,7 @@ cineonOpen(const char* filename) {
/* let's assume cineon files are always network order */
if (header.fileInfo.magic_num != ntohl(CINEON_FILE_MAGIC)) {
if (verbose) d_printf("Bad magic number %8.8lX in \"%s\".\n",
- (unsigned long)ntohl(header.fileInfo.magic_num), filename);
+ (uintptr_t)ntohl(header.fileInfo.magic_num), filename);
cineonClose(cineon);
return 0;
}
@@ -613,7 +617,7 @@ cineonOpenFromMem(unsigned char *mem, unsigned int size) {
cineon->file = 0;
cineon->reading = 1;
- verbose = 1;
+ verbose = 0;
if (size < sizeof(CineonGenericHeader)) {
if (verbose) d_printf("Not enough data for header!\n");
cineonClose(cineon);
@@ -624,7 +628,7 @@ cineonOpenFromMem(unsigned char *mem, unsigned int size) {
/* let's assume cineon files are always network order */
if (header.fileInfo.magic_num != ntohl(CINEON_FILE_MAGIC)) {
- if (verbose) d_printf("Bad magic number %8.8lX in\n", (unsigned long)ntohl(header.fileInfo.magic_num));
+ if (verbose) d_printf("Bad magic number %8.8lX in\n", (uintptr_t)ntohl(header.fileInfo.magic_num));
cineonClose(cineon);
return 0;
diff --git a/source/blender/imbuf/intern/cineon/dpxlib.c b/source/blender/imbuf/intern/cineon/dpxlib.c
index b769d1e6132..8a9adc73cdc 100644
--- a/source/blender/imbuf/intern/cineon/dpxlib.c
+++ b/source/blender/imbuf/intern/cineon/dpxlib.c
@@ -58,15 +58,15 @@ fillDpxChannelInfo(DpxFile* dpx, DpxChannelInformation* chan, int des) {
static void
dumpDpxChannelInfo(DpxChannelInformation* chan) {
- d_printf(" Signage %ld", (long)ntohl(chan->signage));
- d_printf(" Ref low data %ld\n", (long)ntohl(chan->ref_low_data));
+ d_printf(" Signage %ld", (intptr_t)ntohl(chan->signage));
+ d_printf(" Ref low data %ld\n", (intptr_t)ntohl(chan->ref_low_data));
d_printf(" Ref low quantity %f\n", ntohf(chan->ref_low_quantity));
- d_printf(" Ref high data %ld\n", (long)ntohl(chan->ref_high_data));
+ d_printf(" Ref high data %ld\n", (intptr_t)ntohl(chan->ref_high_data));
d_printf(" Ref high quantity %f\n", ntohf(chan->ref_high_quantity));
d_printf(" Designator1: %d,", chan->designator1);
d_printf(" Bits per pixel %d\n", chan->bits_per_pixel);
d_printf(" Packing: %d,", ntohs(chan->packing));
- d_printf(" Data Offset: %ld,", (long)ntohl(chan->data_offset));
+ d_printf(" Data Offset: %ld,", (intptr_t)ntohl(chan->data_offset));
}
static void
@@ -110,19 +110,19 @@ static void
dumpDpxFileInfo(DpxFileInformation* fileInfo) {
d_printf("\n--File Information--\n");
d_printf("Magic: %8.8lX\n", (unsigned long)ntohl(fileInfo->magic_num));
- d_printf("Image Offset %ld\n", (long)ntohl(fileInfo->offset));
+ d_printf("Image Offset %ld\n", (intptr_t)ntohl(fileInfo->offset));
d_printf("Version \"%s\"\n", fileInfo->vers);
- d_printf("File size %ld\n", (long)ntohl(fileInfo->file_size));
- d_printf("Ditto key %ld\n", (long)ntohl(fileInfo->ditto_key));
- d_printf("Generic Header size %ld\n", (long)ntohl(fileInfo->gen_hdr_size));
- d_printf("Industry Header size %ld\n", (long)ntohl(fileInfo->ind_hdr_size));
- d_printf("User Data size %ld\n", (long)ntohl(fileInfo->user_data_size));
+ d_printf("File size %ld\n", (intptr_t)ntohl(fileInfo->file_size));
+ d_printf("Ditto key %ld\n", (intptr_t)ntohl(fileInfo->ditto_key));
+ d_printf("Generic Header size %ld\n", (intptr_t)ntohl(fileInfo->gen_hdr_size));
+ d_printf("Industry Header size %ld\n", (intptr_t)ntohl(fileInfo->ind_hdr_size));
+ d_printf("User Data size %ld\n", (intptr_t)ntohl(fileInfo->user_data_size));
d_printf("File name \"%s\"\n", fileInfo->file_name);
d_printf("Creation date \"%s\"\n", fileInfo->create_date);
d_printf("Creator \"%s\"\n", fileInfo->creator);
d_printf("Project \"%s\"\n", fileInfo->project);
d_printf("Copyright \"%s\"\n", fileInfo->copyright);
- d_printf("Key %ld\n", (long)ntohl(fileInfo->key));
+ d_printf("Key %ld\n", (intptr_t)ntohl(fileInfo->key));
}
static void
@@ -150,8 +150,8 @@ dumpDpxImageInfo(DpxImageInformation* imageInfo) {
d_printf("Image orientation %d,", ntohs(imageInfo->orientation));
n = ntohs(imageInfo->channels_per_image);
d_printf("Channels %d\n", n);
- d_printf("Pixels per line %ld\n", (long)ntohl(imageInfo->pixels_per_line));
- d_printf("Lines per image %ld\n", (long)ntohl(imageInfo->lines_per_image));
+ d_printf("Pixels per line %ld\n", (intptr_t)ntohl(imageInfo->pixels_per_line));
+ d_printf("Lines per image %ld\n", (intptr_t)ntohl(imageInfo->lines_per_image));
for (i = 0; i < n; ++i) {
d_printf(" --Channel %d--\n", i);
dumpDpxChannelInfo(&imageInfo->channel[i]);
@@ -166,12 +166,12 @@ fillDpxOriginationInfo(
static void
dumpDpxOriginationInfo(DpxOriginationInformation* originInfo) {
d_printf("\n--Origination Information--\n");
- d_printf("X offset %ld\n", (long)ntohl(originInfo->x_offset));
- d_printf("Y offset %ld\n", (long)ntohl(originInfo->y_offset));
+ d_printf("X offset %ld\n", (intptr_t)ntohl(originInfo->x_offset));
+ d_printf("Y offset %ld\n", (intptr_t)ntohl(originInfo->y_offset));
d_printf("X centre %f\n", ntohf(originInfo->x_centre));
d_printf("Y centre %f\n", ntohf(originInfo->y_centre));
- d_printf("Original X %ld\n", (long)ntohl(originInfo->x_original_size));
- d_printf("Original Y %ld\n", (long)ntohl(originInfo->y_original_size));
+ d_printf("Original X %ld\n", (intptr_t)ntohl(originInfo->x_original_size));
+ d_printf("Original Y %ld\n", (intptr_t)ntohl(originInfo->y_original_size));
d_printf("File name \"%s\"\n", originInfo->file_name);
d_printf("Creation time \"%s\"\n", originInfo->creation_time);
d_printf("Input device \"%s\"\n", originInfo->input_device);
@@ -275,8 +275,10 @@ dpxGetRowBytes(DpxFile* dpx, unsigned short* row, int y) {
/* extract required pixels */
for (pixelIndex = 0; pixelIndex < numPixels; ++pixelIndex) {
- /* row[pixelIndex] = dpx->lut10[dpx->pixelBuffer[pixelIndex]]; */
- row[pixelIndex] = dpx->pixelBuffer[pixelIndex] << 6;
+ if(dpx->params.doLogarithm)
+ row[pixelIndex] = dpx->lut10_16[dpx->pixelBuffer[pixelIndex]];
+ else
+ row[pixelIndex] = dpx->pixelBuffer[pixelIndex] << 6;
}
/* save remaining pixels */
@@ -316,8 +318,10 @@ dpxSetRowBytes(DpxFile* dpx, const unsigned short* row, int y) {
/* put new pixels into pixelBuffer */
for (pixelIndex = 0; pixelIndex < numPixels; ++pixelIndex) {
- /* dpx->pixelBuffer[dpx->pixelBufferUsed + pixelIndex] = dpx->lut8[row[pixelIndex]]; */
- dpx->pixelBuffer[dpx->pixelBufferUsed + pixelIndex] = row[pixelIndex] >> 6;
+ if(dpx->params.doLogarithm)
+ dpx->pixelBuffer[dpx->pixelBufferUsed + pixelIndex] = dpx->lut16_16[row[pixelIndex]];
+ else
+ dpx->pixelBuffer[dpx->pixelBufferUsed + pixelIndex] = row[pixelIndex] >> 6;
}
dpx->pixelBufferUsed += numPixels;
@@ -413,7 +417,7 @@ intern_dpxOpen(int mode, const char* bytestuff, int bufsize) {
/* let's assume dpx files are always network order */
if (header.fileInfo.magic_num != ntohl(DPX_FILE_MAGIC)) {
if (verbose) d_printf("Bad magic number %8.8lX in \"%s\".\n",
- (unsigned long)ntohl(header.fileInfo.magic_num), filename);
+ (uintptr_t)ntohl(header.fileInfo.magic_num), filename);
dpxClose(dpx);
return 0;
}
@@ -437,10 +441,15 @@ intern_dpxOpen(int mode, const char* bytestuff, int bufsize) {
default: break;
}
}
- dpx->bitsPerPixel = 10;
- /* dpx->bitsPerPixel = header.imageInfo.channel[0].bits_per_pixel; */
- dpx->imageOffset = ntohl(header.fileInfo.offset);
+ /* dpx->bitsPerPixel = 10; */
+ dpx->bitsPerPixel = header.imageInfo.channel[0].bits_per_pixel;
+ if (dpx->bitsPerPixel != 10) {
+ if (verbose) d_printf("Don't support depth: %d\n", dpx->bitsPerPixel);
+ dpxClose(dpx);
+ return 0;
+ }
+ dpx->imageOffset = ntohl(header.fileInfo.offset);
dpx->lineBufferLength = pixelsToLongs(dpx->width * dpx->depth);
dpx->lineBuffer = malloc(dpx->lineBufferLength * 4);
if (dpx->lineBuffer == 0) {
@@ -467,6 +476,26 @@ intern_dpxOpen(int mode, const char* bytestuff, int bufsize) {
dpx->fileYPos = 0;
logImageGetByteConversionDefaults(&dpx->params);
+ /* The SMPTE define this code:
+ * 2 - Linear
+ * 3 - Logarithmic
+ *
+ * Note that transfer_characteristics is U8, don't need
+ * check the byte order.
+ */
+ switch (header.imageInfo.channel[0].transfer_characteristics) {
+ case 2:
+ dpx->params.doLogarithm= 0;
+ break;
+ case 3:
+ dpx->params.doLogarithm= 1;
+ break;
+ default:
+ if (verbose) d_printf("Un-supported Transfer Characteristics: %d\n", header.imageInfo.channel[0].transfer_characteristics);
+ dpxClose(dpx);
+ return 0;
+ break;
+ }
setupLut(dpx);
dpx->getRow = &dpxGetRowBytes;
@@ -559,6 +588,18 @@ dpxCreate(const char* filename, int width, int height, int depth) {
++shortFilename;
}
initDpxMainHeader(dpx, &header, shortFilename);
+ logImageGetByteConversionDefaults(&dpx->params);
+ /* Need set the file type before write the header!
+ * 2 - Linear
+ * 3 - Logarithmic
+ *
+ * Note that transfer characteristics is U8, don't need
+ * check the byte order.
+ */
+ if (dpx->params.doLogarithm == 0)
+ header.imageInfo.channel[0].transfer_characteristics= 2;
+ else
+ header.imageInfo.channel[0].transfer_characteristics= 3;
if (fwrite(&header, sizeof(header), 1, dpx->file) == 0) {
if (verbose) d_printf("Couldn't write image header\n");
@@ -566,8 +607,6 @@ dpxCreate(const char* filename, int width, int height, int depth) {
return 0;
}
dpx->fileYPos = 0;
-
- logImageGetByteConversionDefaults(&dpx->params);
setupLut(dpx);
dpx->getRow = 0;
diff --git a/source/blender/imbuf/intern/cineon/logImageCore.c b/source/blender/imbuf/intern/cineon/logImageCore.c
index e88e9241443..6032f342ed8 100644
--- a/source/blender/imbuf/intern/cineon/logImageCore.c
+++ b/source/blender/imbuf/intern/cineon/logImageCore.c
@@ -93,6 +93,35 @@ setupLut(LogImageFile *logImage) {
}
}
+/* set up the 10 bit to 16 bit and 16 bit to 10 bit tables */
+void
+setupLut16(LogImageFile *logImage) {
+
+ int i;
+ double f_black;
+ double scale;
+
+ f_black = convertTo(logImage->params.blackPoint, logImage->params.whitePoint, logImage->params.gamma);
+ scale = 65535.0 / (1.0 - f_black);
+
+ for (i = 0; i <= logImage->params.blackPoint; ++i) {
+ logImage->lut10_16[i] = 0;
+ }
+ for (; i < logImage->params.whitePoint; ++i) {
+ double f_i;
+ f_i = convertTo(i, logImage->params.whitePoint, logImage->params.gamma);
+ logImage->lut10_16[i] = (int)rint(scale * (f_i - f_black));
+ }
+ for (; i < 1024; ++i) {
+ logImage->lut10_16[i] = 65535;
+ }
+
+ for (i = 0; i < 65536; ++i) {
+ double f_i = f_black + (i / 65535.0) * (1.0 - f_black);
+ logImage->lut16_16[i] = convertFrom(f_i, logImage->params.whitePoint, logImage->params.gamma);
+ }
+}
+
/* how many longwords to hold this many pixels? */
int
pixelsToLongs(int numPixels) {
diff --git a/source/blender/imbuf/intern/cineon/logImageCore.h b/source/blender/imbuf/intern/cineon/logImageCore.h
index 1af18d5e3b8..2646e8b3c12 100644
--- a/source/blender/imbuf/intern/cineon/logImageCore.h
+++ b/source/blender/imbuf/intern/cineon/logImageCore.h
@@ -34,7 +34,9 @@
extern "C" {
#endif
-
+#include "BLO_sys_types.h" // for intptr_t support
+#undef ntohl
+#undef htonl
typedef int (GetRowFn)(LogImageFile* logImage, unsigned short* row, int lineNum);
typedef int (SetRowFn)(LogImageFile* logImage, const unsigned short* row, int lineNum);
typedef void (CloseFn)(LogImageFile* logImage);
@@ -71,17 +73,21 @@ struct _Log_Image_File_t_
unsigned char lut10[1024];
unsigned short lut8[256];
+ unsigned short lut10_16[1024];
+ unsigned short lut16_16[65536];
+
/* pixel access functions */
GetRowFn* getRow;
SetRowFn* setRow;
CloseFn* close;
unsigned char *membuffer;
- unsigned long membuffersize;
+ uintptr_t membuffersize;
unsigned char *memcursor;
};
void setupLut(LogImageFile*);
+void setupLut16(LogImageFile*);
int pixelsToLongs(int numPixels);
diff --git a/source/blender/imbuf/intern/cineon/logImageLib.c b/source/blender/imbuf/intern/cineon/logImageLib.c
index ff209d5ebd0..2fc52959ff6 100644
--- a/source/blender/imbuf/intern/cineon/logImageLib.c
+++ b/source/blender/imbuf/intern/cineon/logImageLib.c
@@ -89,6 +89,7 @@ logImageGetByteConversionDefaults(LogImageByteConversionParameters* params) {
params->gamma = DEFAULT_GAMMA;
params->blackPoint = DEFAULT_BLACK_POINT;
params->whitePoint = DEFAULT_WHITE_POINT;
+ params->doLogarithm = 0;
return 0;
}
@@ -97,6 +98,7 @@ logImageGetByteConversion(const LogImageFile* logImage, LogImageByteConversionPa
params->gamma = logImage->params.gamma;
params->blackPoint = logImage->params.blackPoint;
params->whitePoint = logImage->params.whitePoint;
+ params->doLogarithm = 0;
return 0;
}
@@ -110,7 +112,8 @@ logImageSetByteConversion(LogImageFile* logImage, const LogImageByteConversionPa
logImage->params.gamma = params->gamma;
logImage->params.blackPoint = params->blackPoint;
logImage->params.whitePoint = params->whitePoint;
- setupLut(logImage);
+ logImage->params.doLogarithm = params->doLogarithm;
+ setupLut16(logImage);
return 0;
}
return 1;
diff --git a/source/blender/imbuf/intern/cineon/logImageLib.h b/source/blender/imbuf/intern/cineon/logImageLib.h
index ea45c675fe2..617da1d0d92 100644
--- a/source/blender/imbuf/intern/cineon/logImageLib.h
+++ b/source/blender/imbuf/intern/cineon/logImageLib.h
@@ -47,6 +47,7 @@ typedef struct {
float gamma;
int blackPoint;
int whitePoint;
+ int doLogarithm;
} LogImageByteConversionParameters;
/* int functions return 0 for OK */
diff --git a/source/blender/imbuf/intern/cineon/logmemfile.c b/source/blender/imbuf/intern/cineon/logmemfile.c
index 20359335933..160e8453713 100644
--- a/source/blender/imbuf/intern/cineon/logmemfile.c
+++ b/source/blender/imbuf/intern/cineon/logmemfile.c
@@ -24,10 +24,10 @@
#include "logImageCore.h"
-int logimage_fseek(void* logfile, long offsett, int origin)
+int logimage_fseek(void* logfile, intptr_t offsett, int origin)
{
struct _Log_Image_File_t_ *file = (struct _Log_Image_File_t_*) logfile;
- long offset = offsett;
+ intptr_t offset = offsett;
if (file->file) fseek(file->file, offset, origin);
else { /*we're seeking in memory*/
@@ -38,7 +38,7 @@ int logimage_fseek(void* logfile, long offsett, int origin)
if (offset > file->membuffersize) return 1;
file->memcursor = (file->membuffer + file->membuffersize) - offset;
} else if (origin==SEEK_CUR) {
- unsigned long pos = (unsigned long)file->membuffer - (unsigned long)file->memcursor;
+ uintptr_t pos = (uintptr_t)file->membuffer - (uintptr_t)file->memcursor;
if (pos + offset > file->membuffersize) return 1;
if (pos < 0) return 1;
file->memcursor += offset;
diff --git a/source/blender/imbuf/intern/cineon/logmemfile.h b/source/blender/imbuf/intern/cineon/logmemfile.h
index 6e82cf2b145..39e2f36dad9 100644
--- a/source/blender/imbuf/intern/cineon/logmemfile.h
+++ b/source/blender/imbuf/intern/cineon/logmemfile.h
@@ -22,7 +22,7 @@
#ifndef _LOGMEMFILE_H
#define _LOGMEMFILE_H
-int logimage_fseek(void* logfile, long offsett, int origin);
+int logimage_fseek(void* logfile, intptr_t offsett, int origin);
int logimage_fwrite(void *buffer, unsigned int size, unsigned int count, void *logfile);
int logimage_fread(void *buffer, unsigned int size, unsigned int count, void *logfile);
diff --git a/source/blender/imbuf/intern/dds/BlockDXT.cpp b/source/blender/imbuf/intern/dds/BlockDXT.cpp
index 44435317f69..2a8a2c470c4 100644
--- a/source/blender/imbuf/intern/dds/BlockDXT.cpp
+++ b/source/blender/imbuf/intern/dds/BlockDXT.cpp
@@ -61,7 +61,7 @@
BlockDXT1
----------------------------------------------------------------------------*/
-unsigned int BlockDXT1::evaluatePalette(Color32 color_array[4]) const
+uint BlockDXT1::evaluatePalette(Color32 color_array[4]) const
{
// Does bit expansion before interpolation.
color_array[0].b = (col0.b << 3) | (col0.b >> 2);
@@ -176,9 +176,9 @@ void BlockDXT1::decodeBlock(ColorBlock * block) const
evaluatePalette(color_array);
// Write color block.
- for( unsigned int j = 0; j < 4; j++ ) {
- for( unsigned int i = 0; i < 4; i++ ) {
- unsigned int idx = (row[j] >> (2 * i)) & 3;
+ for( uint j = 0; j < 4; j++ ) {
+ for( uint i = 0; i < 4; i++ ) {
+ uint idx = (row[j] >> (2 * i)) & 3;
block->color(i, j) = color_array[idx];
}
}
@@ -187,7 +187,7 @@ void BlockDXT1::decodeBlock(ColorBlock * block) const
void BlockDXT1::setIndices(int * idx)
{
indices = 0;
- for(unsigned int i = 0; i < 16; i++) {
+ for(uint i = 0; i < 16; i++) {
indices |= (idx[i] & 3) << (2 * i);
}
}
@@ -196,16 +196,14 @@ void BlockDXT1::setIndices(int * idx)
/// Flip DXT1 block vertically.
inline void BlockDXT1::flip4()
{
- unsigned char tmp;
- swap(row[0], row[3], tmp);
- swap(row[1], row[2], tmp);
+ swap(row[0], row[3]);
+ swap(row[1], row[2]);
}
/// Flip half DXT1 block vertically.
inline void BlockDXT1::flip2()
{
- unsigned char tmp;
- swap(row[0], row[1], tmp);
+ swap(row[0], row[1]);
}
@@ -245,16 +243,14 @@ void AlphaBlockDXT3::decodeBlock(ColorBlock * block) const
/// Flip DXT3 alpha block vertically.
void AlphaBlockDXT3::flip4()
{
- unsigned short tmp;
- swap(row[0], row[3], tmp);
- swap(row[1], row[2], tmp);
+ swap(row[0], row[3]);
+ swap(row[1], row[2]);
}
/// Flip half DXT3 alpha block vertically.
void AlphaBlockDXT3::flip2()
{
- unsigned short tmp;
- swap(row[0], row[1], tmp);
+ swap(row[0], row[1]);
}
/// Flip DXT3 block vertically.
@@ -276,9 +272,9 @@ void BlockDXT3::flip2()
BlockDXT5
----------------------------------------------------------------------------*/
-void AlphaBlockDXT5::evaluatePalette(unsigned char alpha[8]) const
+void AlphaBlockDXT5::evaluatePalette(uint8 alpha[8]) const
{
- if (alpha0 > alpha1) {
+ if (alpha0() > alpha1()) {
evaluatePalette8(alpha);
}
else {
@@ -286,100 +282,100 @@ void AlphaBlockDXT5::evaluatePalette(unsigned char alpha[8]) const
}
}
-void AlphaBlockDXT5::evaluatePalette8(unsigned char alpha[8]) const
+void AlphaBlockDXT5::evaluatePalette8(uint8 alpha[8]) const
{
// 8-alpha block: derive the other six alphas.
// Bit code 000 = alpha0, 001 = alpha1, others are interpolated.
- alpha[0] = alpha0;
- alpha[1] = alpha1;
- alpha[2] = (6 * alpha0 + 1 * alpha1) / 7; // bit code 010
- alpha[3] = (5 * alpha0 + 2 * alpha1) / 7; // bit code 011
- alpha[4] = (4 * alpha0 + 3 * alpha1) / 7; // bit code 100
- alpha[5] = (3 * alpha0 + 4 * alpha1) / 7; // bit code 101
- alpha[6] = (2 * alpha0 + 5 * alpha1) / 7; // bit code 110
- alpha[7] = (1 * alpha0 + 6 * alpha1) / 7; // bit code 111
+ alpha[0] = alpha0();
+ alpha[1] = alpha1();
+ alpha[2] = (6 * alpha[0] + 1 * alpha[1]) / 7; // bit code 010
+ alpha[3] = (5 * alpha[0] + 2 * alpha[1]) / 7; // bit code 011
+ alpha[4] = (4 * alpha[0] + 3 * alpha[1]) / 7; // bit code 100
+ alpha[5] = (3 * alpha[0] + 4 * alpha[1]) / 7; // bit code 101
+ alpha[6] = (2 * alpha[0] + 5 * alpha[1]) / 7; // bit code 110
+ alpha[7] = (1 * alpha[0] + 6 * alpha[1]) / 7; // bit code 111
}
-void AlphaBlockDXT5::evaluatePalette6(unsigned char alpha[8]) const
+void AlphaBlockDXT5::evaluatePalette6(uint8 alpha[8]) const
{
// 6-alpha block.
// Bit code 000 = alpha0, 001 = alpha1, others are interpolated.
- alpha[0] = alpha0;
- alpha[1] = alpha1;
- alpha[2] = (4 * alpha0 + 1 * alpha1) / 5; // Bit code 010
- alpha[3] = (3 * alpha0 + 2 * alpha1) / 5; // Bit code 011
- alpha[4] = (2 * alpha0 + 3 * alpha1) / 5; // Bit code 100
- alpha[5] = (1 * alpha0 + 4 * alpha1) / 5; // Bit code 101
+ alpha[0] = alpha0();
+ alpha[1] = alpha1();
+ alpha[2] = (4 * alpha[0] + 1 * alpha[1]) / 5; // Bit code 010
+ alpha[3] = (3 * alpha[0] + 2 * alpha[1]) / 5; // Bit code 011
+ alpha[4] = (2 * alpha[0] + 3 * alpha[1]) / 5; // Bit code 100
+ alpha[5] = (1 * alpha[0] + 4 * alpha[1]) / 5; // Bit code 101
alpha[6] = 0x00; // Bit code 110
alpha[7] = 0xFF; // Bit code 111
}
-void AlphaBlockDXT5::indices(unsigned char index_array[16]) const
+void AlphaBlockDXT5::indices(uint8 index_array[16]) const
{
- index_array[0x0] = bits0;
- index_array[0x1] = bits1;
- index_array[0x2] = bits2;
- index_array[0x3] = bits3;
- index_array[0x4] = bits4;
- index_array[0x5] = bits5;
- index_array[0x6] = bits6;
- index_array[0x7] = bits7;
- index_array[0x8] = bits8;
- index_array[0x9] = bits9;
- index_array[0xA] = bitsA;
- index_array[0xB] = bitsB;
- index_array[0xC] = bitsC;
- index_array[0xD] = bitsD;
- index_array[0xE] = bitsE;
- index_array[0xF] = bitsF;
+ index_array[0x0] = bits0();
+ index_array[0x1] = bits1();
+ index_array[0x2] = bits2();
+ index_array[0x3] = bits3();
+ index_array[0x4] = bits4();
+ index_array[0x5] = bits5();
+ index_array[0x6] = bits6();
+ index_array[0x7] = bits7();
+ index_array[0x8] = bits8();
+ index_array[0x9] = bits9();
+ index_array[0xA] = bitsA();
+ index_array[0xB] = bitsB();
+ index_array[0xC] = bitsC();
+ index_array[0xD] = bitsD();
+ index_array[0xE] = bitsE();
+ index_array[0xF] = bitsF();
}
-unsigned int AlphaBlockDXT5::index(unsigned int index) const
+uint AlphaBlockDXT5::index(uint index) const
{
int offset = (3 * index + 16);
- return (this->u >> offset) & 0x7;
+ return uint((this->u >> offset) & 0x7);
}
-void AlphaBlockDXT5::setIndex(unsigned int index, unsigned int value)
+void AlphaBlockDXT5::setIndex(uint index, uint value)
{
int offset = (3 * index + 16);
- unsigned long long mask = ((unsigned long long)(0x7)) << offset;
- this->u = (this->u & ~mask) | (((unsigned long long)(value)) << offset);
+ uint64 mask = uint64(0x7) << offset;
+ this->u = (this->u & ~mask) | (uint64(value) << offset);
}
void AlphaBlockDXT5::decodeBlock(ColorBlock * block) const
{
- unsigned char alpha_array[8];
+ uint8 alpha_array[8];
evaluatePalette(alpha_array);
- unsigned char index_array[16];
+ uint8 index_array[16];
indices(index_array);
- for(unsigned int i = 0; i < 16; i++) {
+ for(uint i = 0; i < 16; i++) {
block->color(i).a = alpha_array[index_array[i]];
}
}
void AlphaBlockDXT5::flip4()
{
- unsigned long long * b = (unsigned long long *)this;
+ uint64 * b = (uint64 *)this;
// @@ The masks might have to be byte swapped.
- unsigned long long tmp = (*b & (unsigned long long)(0x000000000000FFFFLL));
- tmp |= (*b & (unsigned long long)(0x000000000FFF0000LL)) << 36;
- tmp |= (*b & (unsigned long long)(0x000000FFF0000000LL)) << 12;
- tmp |= (*b & (unsigned long long)(0x000FFF0000000000LL)) >> 12;
- tmp |= (*b & (unsigned long long)(0xFFF0000000000000LL)) >> 36;
+ uint64 tmp = (*b & (uint64)(0x000000000000FFFFLL));
+ tmp |= (*b & (uint64)(0x000000000FFF0000LL)) << 36;
+ tmp |= (*b & (uint64)(0x000000FFF0000000LL)) << 12;
+ tmp |= (*b & (uint64)(0x000FFF0000000000LL)) >> 12;
+ tmp |= (*b & (uint64)(0xFFF0000000000000LL)) >> 36;
*b = tmp;
}
void AlphaBlockDXT5::flip2()
{
- unsigned int * b = (unsigned int *)this;
+ uint * b = (uint *)this;
// @@ The masks might have to be byte swapped.
- unsigned int tmp = (*b & 0xFF000000);
+ uint tmp = (*b & 0xFF000000);
tmp |= (*b & 0x00000FFF) << 12;
tmp |= (*b & 0x00FFF000) >> 12;
@@ -393,6 +389,7 @@ void BlockDXT5::decodeBlock(ColorBlock * block) const
// Decode alpha.
alpha.decodeBlock(block);
+
}
/// Flip DXT5 block vertically.
@@ -413,13 +410,13 @@ void BlockDXT5::flip2()
/// Decode ATI1 block.
void BlockATI1::decodeBlock(ColorBlock * block) const
{
- unsigned char alpha_array[8];
+ uint8 alpha_array[8];
alpha.evaluatePalette(alpha_array);
- unsigned char index_array[16];
+ uint8 index_array[16];
alpha.indices(index_array);
- for(unsigned int i = 0; i < 16; i++) {
+ for(uint i = 0; i < 16; i++) {
Color32 & c = block->color(i);
c.b = c.g = c.r = alpha_array[index_array[i]];
c.a = 255;
@@ -442,13 +439,13 @@ void BlockATI1::flip2()
/// Decode ATI2 block.
void BlockATI2::decodeBlock(ColorBlock * block) const
{
- unsigned char alpha_array[8];
- unsigned char index_array[16];
+ uint8 alpha_array[8];
+ uint8 index_array[16];
x.evaluatePalette(alpha_array);
x.indices(index_array);
- for(unsigned int i = 0; i < 16; i++) {
+ for(uint i = 0; i < 16; i++) {
Color32 & c = block->color(i);
c.r = alpha_array[index_array[i]];
}
@@ -456,7 +453,7 @@ void BlockATI2::decodeBlock(ColorBlock * block) const
y.evaluatePalette(alpha_array);
y.indices(index_array);
- for(unsigned int i = 0; i < 16; i++) {
+ for(uint i = 0; i < 16; i++) {
Color32 & c = block->color(i);
c.g = alpha_array[index_array[i]];
c.b = 0;
@@ -478,6 +475,68 @@ void BlockATI2::flip2()
y.flip2();
}
+
+void BlockCTX1::evaluatePalette(Color32 color_array[4]) const
+{
+ // Does bit expansion before interpolation.
+ color_array[0].b = 0x00;
+ color_array[0].g = col0[1];
+ color_array[0].r = col0[0];
+ color_array[0].a = 0xFF;
+
+ color_array[1].r = 0x00;
+ color_array[1].g = col0[1];
+ color_array[1].b = col1[0];
+ color_array[1].a = 0xFF;
+
+ color_array[2].r = 0x00;
+ color_array[2].g = (2 * color_array[0].g + color_array[1].g) / 3;
+ color_array[2].b = (2 * color_array[0].b + color_array[1].b) / 3;
+ color_array[2].a = 0xFF;
+
+ color_array[3].r = 0x00;
+ color_array[3].g = (2 * color_array[1].g + color_array[0].g) / 3;
+ color_array[3].b = (2 * color_array[1].b + color_array[0].b) / 3;
+ color_array[3].a = 0xFF;
+}
+
+void BlockCTX1::decodeBlock(ColorBlock * block) const
+{
+ // Decode color block.
+ Color32 color_array[4];
+ evaluatePalette(color_array);
+
+ // Write color block.
+ for( uint j = 0; j < 4; j++ ) {
+ for( uint i = 0; i < 4; i++ ) {
+ uint idx = (row[j] >> (2 * i)) & 3;
+ block->color(i, j) = color_array[idx];
+ }
+ }
+}
+
+void BlockCTX1::setIndices(int * idx)
+{
+ indices = 0;
+ for(uint i = 0; i < 16; i++) {
+ indices |= (idx[i] & 3) << (2 * i);
+ }
+}
+
+
+/// Flip CTX1 block vertically.
+inline void BlockCTX1::flip4()
+{
+ swap(row[0], row[3]);
+ swap(row[1], row[2]);
+}
+
+/// Flip half CTX1 block vertically.
+inline void BlockCTX1::flip2()
+{
+ swap(row[0], row[1]);
+}
+
void mem_read(Stream & mem, BlockDXT1 & block)
{
mem_read(mem, block.col0.u);
@@ -518,3 +577,12 @@ void mem_read(Stream & mem, BlockATI2 & block)
mem_read(mem, block.y);
}
+void mem_read(Stream & mem, BlockCTX1 & block)
+{
+ mem_read(mem, block.col0[0]);
+ mem_read(mem, block.col0[1]);
+ mem_read(mem, block.col1[0]);
+ mem_read(mem, block.col1[1]);
+ mem_read(mem, block.indices);
+}
+
diff --git a/source/blender/imbuf/intern/dds/BlockDXT.h b/source/blender/imbuf/intern/dds/BlockDXT.h
index 8381c4705ae..3f9a81e40c8 100644
--- a/source/blender/imbuf/intern/dds/BlockDXT.h
+++ b/source/blender/imbuf/intern/dds/BlockDXT.h
@@ -55,6 +55,7 @@
#ifndef _DDS_BLOCKDXT_H
#define _DDS_BLOCKDXT_H
+#include <Common.h>
#include <Color.h>
#include <ColorBlock.h>
#include <Stream.h>
@@ -65,14 +66,14 @@ struct BlockDXT1
Color16 col0;
Color16 col1;
union {
- unsigned char row[4];
- unsigned int indices;
+ uint8 row[4];
+ uint indices;
};
bool isFourColorMode() const;
- unsigned int evaluatePalette(Color32 color_array[4]) const;
- unsigned int evaluatePaletteFast(Color32 color_array[4]) const;
+ uint evaluatePalette(Color32 color_array[4]) const;
+ uint evaluatePaletteFast(Color32 color_array[4]) const;
void evaluatePalette3(Color32 color_array[4]) const;
void evaluatePalette4(Color32 color_array[4]) const;
@@ -87,7 +88,7 @@ struct BlockDXT1
/// Return true if the block uses four color mode, false otherwise.
inline bool BlockDXT1::isFourColorMode() const
{
- return col0.u >= col1.u; // @@ > or >= ?
+ return col0.u > col1.u;
}
@@ -96,24 +97,24 @@ struct AlphaBlockDXT3
{
union {
struct {
- unsigned int alpha0 : 4;
- unsigned int alpha1 : 4;
- unsigned int alpha2 : 4;
- unsigned int alpha3 : 4;
- unsigned int alpha4 : 4;
- unsigned int alpha5 : 4;
- unsigned int alpha6 : 4;
- unsigned int alpha7 : 4;
- unsigned int alpha8 : 4;
- unsigned int alpha9 : 4;
- unsigned int alphaA : 4;
- unsigned int alphaB : 4;
- unsigned int alphaC : 4;
- unsigned int alphaD : 4;
- unsigned int alphaE : 4;
- unsigned int alphaF : 4;
+ uint alpha0 : 4;
+ uint alpha1 : 4;
+ uint alpha2 : 4;
+ uint alpha3 : 4;
+ uint alpha4 : 4;
+ uint alpha5 : 4;
+ uint alpha6 : 4;
+ uint alpha7 : 4;
+ uint alpha8 : 4;
+ uint alpha9 : 4;
+ uint alphaA : 4;
+ uint alphaB : 4;
+ uint alphaC : 4;
+ uint alphaD : 4;
+ uint alphaE : 4;
+ uint alphaF : 4;
};
- unsigned short row[4];
+ uint16 row[4];
};
void decodeBlock(ColorBlock * block) const;
@@ -139,37 +140,59 @@ struct BlockDXT3
/// DXT5 alpha block.
struct AlphaBlockDXT5
{
+ // uint64 unions do not compile on all platforms
+ /*
union {
struct {
- unsigned int alpha0 : 8; // 8
- unsigned int alpha1 : 8; // 16
- unsigned int bits0 : 3; // 3 - 19
- unsigned int bits1 : 3; // 6 - 22
- unsigned int bits2 : 3; // 9 - 25
- unsigned int bits3 : 3; // 12 - 28
- unsigned int bits4 : 3; // 15 - 31
- unsigned int bits5 : 3; // 18 - 34
- unsigned int bits6 : 3; // 21 - 37
- unsigned int bits7 : 3; // 24 - 40
- unsigned int bits8 : 3; // 27 - 43
- unsigned int bits9 : 3; // 30 - 46
- unsigned int bitsA : 3; // 33 - 49
- unsigned int bitsB : 3; // 36 - 52
- unsigned int bitsC : 3; // 39 - 55
- unsigned int bitsD : 3; // 42 - 58
- unsigned int bitsE : 3; // 45 - 61
- unsigned int bitsF : 3; // 48 - 64
+ uint64 alpha0 : 8; // 8
+ uint64 alpha1 : 8; // 16
+ uint64 bits0 : 3; // 3 - 19
+ uint64 bits1 : 3; // 6 - 22
+ uint64 bits2 : 3; // 9 - 25
+ uint64 bits3 : 3; // 12 - 28
+ uint64 bits4 : 3; // 15 - 31
+ uint64 bits5 : 3; // 18 - 34
+ uint64 bits6 : 3; // 21 - 37
+ uint64 bits7 : 3; // 24 - 40
+ uint64 bits8 : 3; // 27 - 43
+ uint64 bits9 : 3; // 30 - 46
+ uint64 bitsA : 3; // 33 - 49
+ uint64 bitsB : 3; // 36 - 52
+ uint64 bitsC : 3; // 39 - 55
+ uint64 bitsD : 3; // 42 - 58
+ uint64 bitsE : 3; // 45 - 61
+ uint64 bitsF : 3; // 48 - 64
};
- unsigned long long u;
+ uint64 u;
};
+ */
+ uint64 u;
+ uint8 alpha0() const { return u & 0xffLL; };
+ uint8 alpha1() const { return (u >> 8) & 0xffLL; };
+ uint8 bits0() const { return (u >> 16) & 0x7LL; };
+ uint8 bits1() const { return (u >> 19) & 0x7LL; };
+ uint8 bits2() const { return (u >> 22) & 0x7LL; };
+ uint8 bits3() const { return (u >> 25) & 0x7LL; };
+ uint8 bits4() const { return (u >> 28) & 0x7LL; };
+ uint8 bits5() const { return (u >> 31) & 0x7LL; };
+ uint8 bits6() const { return (u >> 34) & 0x7LL; };
+ uint8 bits7() const { return (u >> 37) & 0x7LL; };
+ uint8 bits8() const { return (u >> 40) & 0x7LL; };
+ uint8 bits9() const { return (u >> 43) & 0x7LL; };
+ uint8 bitsA() const { return (u >> 46) & 0x7LL; };
+ uint8 bitsB() const { return (u >> 49) & 0x7LL; };
+ uint8 bitsC() const { return (u >> 52) & 0x7LL; };
+ uint8 bitsD() const { return (u >> 55) & 0x7LL; };
+ uint8 bitsE() const { return (u >> 58) & 0x7LL; };
+ uint8 bitsF() const { return (u >> 61) & 0x7LL; };
- void evaluatePalette(unsigned char alpha[8]) const;
- void evaluatePalette8(unsigned char alpha[8]) const;
- void evaluatePalette6(unsigned char alpha[8]) const;
- void indices(unsigned char index_array[16]) const;
+ void evaluatePalette(uint8 alpha[8]) const;
+ void evaluatePalette8(uint8 alpha[8]) const;
+ void evaluatePalette6(uint8 alpha[8]) const;
+ void indices(uint8 index_array[16]) const;
- unsigned int index(unsigned int index) const;
- void setIndex(unsigned int index, unsigned int value);
+ uint index(uint index) const;
+ void setIndex(uint index, uint value);
void decodeBlock(ColorBlock * block) const;
@@ -213,6 +236,25 @@ struct BlockATI2
void flip2();
};
+/// CTX1 block.
+struct BlockCTX1
+{
+ uint8 col0[2];
+ uint8 col1[2];
+ union {
+ uint8 row[4];
+ uint indices;
+ };
+
+ void evaluatePalette(Color32 color_array[4]) const;
+ void setIndices(int * idx);
+
+ void decodeBlock(ColorBlock * block) const;
+
+ void flip4();
+ void flip2();
+};
+
void mem_read(Stream & mem, BlockDXT1 & block);
void mem_read(Stream & mem, AlphaBlockDXT3 & block);
void mem_read(Stream & mem, BlockDXT3 & block);
@@ -220,5 +262,6 @@ void mem_read(Stream & mem, AlphaBlockDXT5 & block);
void mem_read(Stream & mem, BlockDXT5 & block);
void mem_read(Stream & mem, BlockATI1 & block);
void mem_read(Stream & mem, BlockATI2 & block);
+void mem_read(Stream & mem, BlockCTX1 & block);
#endif // _DDS_BLOCKDXT_H
diff --git a/source/blender/imbuf/intern/dds/CMakeLists.txt b/source/blender/imbuf/intern/dds/CMakeLists.txt
new file mode 100644
index 00000000000..842f53bd88b
--- /dev/null
+++ b/source/blender/imbuf/intern/dds/CMakeLists.txt
@@ -0,0 +1,45 @@
+# $Id: CMakeLists.txt 14444 2008-04-16 22:40:48Z hos $
+# ***** BEGIN GPL LICENSE BLOCK *****
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software Foundation,
+# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+# The Original Code is Copyright (C) 2006, Blender Foundation
+# All rights reserved.
+#
+# The Original Code is: all of this file.
+#
+# Contributor(s):
+#
+# ***** END GPL LICENSE BLOCK *****
+
+FILE (GLOB SRC *.cpp)
+
+SET(INC
+ .
+ ../../../blenkernel
+ ../../../makesdna
+ ../../
+ ..
+ ../../../blenlib
+ intern/include
+ ../../../../../intern/guardedalloc
+)
+
+if(WITH_DDS)
+ ADD_DEFINITIONS(-DWITH_DDS)
+ENDIF(WITH_DDS)
+
+BLENDERLIB(bf_dds "${SRC}" "${INC}")
+#env.BlenderLib ('bf_dds', source_files, incs, defs, libtype=['core','player'], priority = [90, 200])
diff --git a/source/blender/imbuf/intern/dds/ColorBlock.cpp b/source/blender/imbuf/intern/dds/ColorBlock.cpp
index 2511f6b8b30..043fba9d675 100644
--- a/source/blender/imbuf/intern/dds/ColorBlock.cpp
+++ b/source/blender/imbuf/intern/dds/ColorBlock.cpp
@@ -36,13 +36,13 @@
#include <Common.h>
// Get approximate luminance.
- inline static unsigned int colorLuminance(Color32 c)
+ inline static uint colorLuminance(Color32 c)
{
return c.r + c.g + c.b;
}
// Get the euclidean distance between the given colors.
- inline static unsigned int colorDistance(Color32 c0, Color32 c1)
+ inline static uint colorDistance(Color32 c0, Color32 c1)
{
return (c0.r - c1.r) * (c0.r - c1.r) + (c0.g - c1.g) * (c0.g - c1.g) + (c0.b - c1.b) * (c0.b - c1.b);
}
@@ -53,25 +53,33 @@ ColorBlock::ColorBlock()
{
}
+/// Init the color block from an array of colors.
+ColorBlock::ColorBlock(const uint * linearImage)
+{
+ for(uint i = 0; i < 16; i++) {
+ color(i) = Color32(linearImage[i]);
+ }
+}
+
/// Init the color block with the contents of the given block.
ColorBlock::ColorBlock(const ColorBlock & block)
{
- for(unsigned int i = 0; i < 16; i++) {
+ for(uint i = 0; i < 16; i++) {
color(i) = block.color(i);
}
}
/// Initialize this color block.
-ColorBlock::ColorBlock(const Image * img, unsigned int x, unsigned int y)
+ColorBlock::ColorBlock(const Image * img, uint x, uint y)
{
init(img, x, y);
}
-void ColorBlock::init(const Image * img, unsigned int x, unsigned int y)
+void ColorBlock::init(const Image * img, uint x, uint y)
{
- const unsigned int bw = min(img->width() - x, 4U);
- const unsigned int bh = min(img->height() - y, 4U);
+ const uint bw = min(img->width() - x, 4U);
+ const uint bh = min(img->height() - y, 4U);
static int remainder[] = {
0, 0, 0, 0,
@@ -83,10 +91,10 @@ void ColorBlock::init(const Image * img, unsigned int x, unsigned int y)
// Blocks that are smaller than 4x4 are handled by repeating the pixels.
// @@ Thats only correct when block size is 1, 2 or 4, but not with 3. :(
- for(unsigned int i = 0; i < 4; i++) {
+ for(uint i = 0; i < 4; i++) {
//const int by = i % bh;
const int by = remainder[(bh - 1) * 4 + i];
- for(unsigned int e = 0; e < 4; e++) {
+ for(uint e = 0; e < 4; e++) {
//const int bx = e % bw;
const int bx = remainder[(bw - 1) * 4 + e];
color(e, i) = img->pixel(x + bx, y + by);
@@ -100,7 +108,7 @@ void ColorBlock::swizzleDXT5n()
for(int i = 0; i < 16; i++)
{
Color32 c = m_color[i];
- m_color[i] = Color32(0, c.g, 0, c.r);
+ m_color[i] = Color32(0xFF, c.g, 0, c.r);
}
}
@@ -108,7 +116,7 @@ void ColorBlock::splatX()
{
for(int i = 0; i < 16; i++)
{
- unsigned char x = m_color[i].r;
+ uint8 x = m_color[i].r;
m_color[i] = Color32(x, x, x, x);
}
}
@@ -117,16 +125,56 @@ void ColorBlock::splatY()
{
for(int i = 0; i < 16; i++)
{
- unsigned char y = m_color[i].g;
+ uint8 y = m_color[i].g;
m_color[i] = Color32(y, y, y, y);
}
}
+/// Returns true if the block has a single color.
+bool ColorBlock::isSingleColor() const
+{
+ Color32 mask(0xFF, 0xFF, 0xFF, 0x00);
+ uint u = m_color[0].u & mask.u;
+
+ for(int i = 1; i < 16; i++)
+ {
+ if (u != (m_color[i].u & mask.u))
+ {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+/// Returns true if the block has a single color, ignoring transparent pixels.
+bool ColorBlock::isSingleColorNoAlpha() const
+{
+ Color32 c;
+ int i;
+ for(i = 0; i < 16; i++)
+ {
+ if (m_color[i].a != 0) c = m_color[i];
+ }
+
+ Color32 mask(0xFF, 0xFF, 0xFF, 0x00);
+ uint u = c.u & mask.u;
+
+ for(; i < 16; i++)
+ {
+ if (u != (m_color[i].u & mask.u))
+ {
+ return false;
+ }
+ }
+
+ return true;
+}
/// Count number of unique colors in this color block.
-unsigned int ColorBlock::countUniqueColors() const
+uint ColorBlock::countUniqueColors() const
{
- unsigned int count = 0;
+ uint count = 0;
// @@ This does not have to be o(n^2)
for(int i = 0; i < 16; i++)
@@ -149,17 +197,27 @@ unsigned int ColorBlock::countUniqueColors() const
/// Get average color of the block.
Color32 ColorBlock::averageColor() const
{
- unsigned int r, g, b, a;
+ uint r, g, b, a;
r = g = b = a = 0;
- for(unsigned int i = 0; i < 16; i++) {
+ for(uint i = 0; i < 16; i++) {
r += m_color[i].r;
g += m_color[i].g;
b += m_color[i].b;
a += m_color[i].a;
}
- return Color32((unsigned char)(r / 16), (unsigned char)(g / 16), (unsigned char)(b / 16), (unsigned char)(a / 16));
+ return Color32(uint8(r / 16), uint8(g / 16), uint8(b / 16), uint8(a / 16));
+}
+
+/// Return true if the block is not fully opaque.
+bool ColorBlock::hasAlpha() const
+{
+ for (uint i = 0; i < 16; i++)
+ {
+ if (m_color[i].a != 255) return true;
+ }
+ return false;
}
@@ -167,11 +225,11 @@ Color32 ColorBlock::averageColor() const
void ColorBlock::diameterRange(Color32 * start, Color32 * end) const
{
Color32 c0, c1;
- unsigned int best_dist = 0;
+ uint best_dist = 0;
for(int i = 0; i < 16; i++) {
for (int j = i+1; j < 16; j++) {
- unsigned int dist = colorDistance(m_color[i], m_color[j]);
+ uint dist = colorDistance(m_color[i], m_color[j]);
if( dist > best_dist ) {
best_dist = dist;
c0 = m_color[i];
@@ -188,13 +246,13 @@ void ColorBlock::diameterRange(Color32 * start, Color32 * end) const
void ColorBlock::luminanceRange(Color32 * start, Color32 * end) const
{
Color32 minColor, maxColor;
- unsigned int minLuminance, maxLuminance;
+ uint minLuminance, maxLuminance;
maxLuminance = minLuminance = colorLuminance(m_color[0]);
- for(unsigned int i = 1; i < 16; i++)
+ for(uint i = 1; i < 16; i++)
{
- unsigned int luminance = colorLuminance(m_color[i]);
+ uint luminance = colorLuminance(m_color[i]);
if (luminance > maxLuminance) {
maxLuminance = luminance;
@@ -216,7 +274,7 @@ void ColorBlock::boundsRange(Color32 * start, Color32 * end) const
Color32 minColor(255, 255, 255);
Color32 maxColor(0, 0, 0);
- for(unsigned int i = 0; i < 16; i++)
+ for(uint i = 0; i < 16; i++)
{
if (m_color[i].r < minColor.r) { minColor.r = m_color[i].r; }
if (m_color[i].g < minColor.g) { minColor.g = m_color[i].g; }
@@ -250,7 +308,7 @@ void ColorBlock::boundsRangeAlpha(Color32 * start, Color32 * end) const
Color32 minColor(255, 255, 255, 255);
Color32 maxColor(0, 0, 0, 0);
- for(unsigned int i = 0; i < 16; i++)
+ for(uint i = 0; i < 16; i++)
{
if (m_color[i].r < minColor.r) { minColor.r = m_color[i].r; }
if (m_color[i].g < minColor.g) { minColor.g = m_color[i].g; }
@@ -287,11 +345,11 @@ void ColorBlock::boundsRangeAlpha(Color32 * start, Color32 * end) const
void ColorBlock::sortColorsByAbsoluteValue()
{
// Dummy selection sort.
- for( unsigned int a = 0; a < 16; a++ ) {
- unsigned int max = a;
+ for( uint a = 0; a < 16; a++ ) {
+ uint max = a;
Color16 cmax(m_color[a]);
- for( unsigned int b = a+1; b < 16; b++ ) {
+ for( uint b = a+1; b < 16; b++ ) {
Color16 cb(m_color[b]);
if( cb.u > cmax.u ) {
@@ -299,9 +357,6 @@ void ColorBlock::sortColorsByAbsoluteValue()
cmax = cb;
}
}
- Color32 tmp;
- swap( m_color[a], m_color[max], tmp );
+ swap( m_color[a], m_color[max] );
}
}
-
-
diff --git a/source/blender/imbuf/intern/dds/ColorBlock.h b/source/blender/imbuf/intern/dds/ColorBlock.h
index 0d195f73811..537c17346a1 100644
--- a/source/blender/imbuf/intern/dds/ColorBlock.h
+++ b/source/blender/imbuf/intern/dds/ColorBlock.h
@@ -41,23 +41,26 @@
struct ColorBlock
{
ColorBlock();
+ ColorBlock(const uint * linearImage);
ColorBlock(const ColorBlock & block);
- ColorBlock(const Image * img, unsigned int x, unsigned int y);
+ ColorBlock(const Image * img, uint x, uint y);
- void init(const Image * img, unsigned int x, unsigned int y);
+ void init(const Image * img, uint x, uint y);
void swizzleDXT5n();
void splatX();
void splatY();
- unsigned int countUniqueColors() const;
+ bool isSingleColor() const;
+ bool isSingleColorNoAlpha() const;
+ uint countUniqueColors() const;
Color32 averageColor() const;
+ bool hasAlpha() const;
void diameterRange(Color32 * start, Color32 * end) const;
void luminanceRange(Color32 * start, Color32 * end) const;
void boundsRange(Color32 * start, Color32 * end) const;
void boundsRangeAlpha(Color32 * start, Color32 * end) const;
- void bestFitRange(Color32 * start, Color32 * end) const;
void sortColorsByAbsoluteValue();
@@ -66,11 +69,11 @@ struct ColorBlock
// Accessors
const Color32 * colors() const;
- Color32 color(unsigned int i) const;
- Color32 & color(unsigned int i);
+ Color32 color(uint i) const;
+ Color32 & color(uint i);
- Color32 color(unsigned int x, unsigned int y) const;
- Color32 & color(unsigned int x, unsigned int y);
+ Color32 color(uint x, uint y) const;
+ Color32 & color(uint x, uint y);
private:
@@ -86,25 +89,25 @@ inline const Color32 * ColorBlock::colors() const
}
/// Get block color.
-inline Color32 ColorBlock::color(unsigned int i) const
+inline Color32 ColorBlock::color(uint i) const
{
return m_color[i];
}
/// Get block color.
-inline Color32 & ColorBlock::color(unsigned int i)
+inline Color32 & ColorBlock::color(uint i)
{
return m_color[i];
}
/// Get block color.
-inline Color32 ColorBlock::color(unsigned int x, unsigned int y) const
+inline Color32 ColorBlock::color(uint x, uint y) const
{
return m_color[y * 4 + x];
}
/// Get block color.
-inline Color32 & ColorBlock::color(unsigned int x, unsigned int y)
+inline Color32 & ColorBlock::color(uint x, uint y)
{
return m_color[y * 4 + x];
}
diff --git a/source/blender/imbuf/intern/dds/Common.h b/source/blender/imbuf/intern/dds/Common.h
index e504e7b1241..6f09346f770 100644
--- a/source/blender/imbuf/intern/dds/Common.h
+++ b/source/blender/imbuf/intern/dds/Common.h
@@ -34,8 +34,20 @@
#ifndef clamp
#define clamp(x,a,b) min(max((x), (a)), (b))
#endif
-#ifndef swap
-#define swap(a,b,tmp) tmp=a; a=b; b=tmp;
-#endif
+
+template<typename T>
+inline void
+swap(T & a, T & b)
+{
+ T tmp = a;
+ a = b;
+ b = tmp;
+}
+
+typedef unsigned char uint8;
+typedef unsigned short uint16;
+typedef unsigned int uint;
+typedef unsigned int uint32;
+typedef unsigned long long uint64;
#endif
diff --git a/source/blender/imbuf/intern/dds/DirectDrawSurface.cpp b/source/blender/imbuf/intern/dds/DirectDrawSurface.cpp
index f8eb7afa66b..0981ae88db6 100644
--- a/source/blender/imbuf/intern/dds/DirectDrawSurface.cpp
+++ b/source/blender/imbuf/intern/dds/DirectDrawSurface.cpp
@@ -52,103 +52,374 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
-#include <Common.h>
#include <DirectDrawSurface.h>
#include <BlockDXT.h>
+#include <PixelFormat.h>
#include <stdio.h> // printf
#include <math.h> // sqrt
+#include <sys/types.h>
/*** declarations ***/
#if !defined(MAKEFOURCC)
# define MAKEFOURCC(ch0, ch1, ch2, ch3) \
- ((unsigned int)((unsigned char)(ch0)) | \
- ((unsigned int)((unsigned char)(ch1)) << 8) | \
- ((unsigned int)((unsigned char)(ch2)) << 16) | \
- ((unsigned int)((unsigned char)(ch3)) << 24 ))
+ ((uint)((unsigned char)(ch0)) | \
+ ((uint)((unsigned char)(ch1)) << 8) | \
+ ((uint)((unsigned char)(ch2)) << 16) | \
+ ((uint)((unsigned char)(ch3)) << 24 ))
#endif
-static const unsigned int FOURCC_DDS = MAKEFOURCC('D', 'D', 'S', ' ');
-static const unsigned int FOURCC_DXT1 = MAKEFOURCC('D', 'X', 'T', '1');
-static const unsigned int FOURCC_DXT2 = MAKEFOURCC('D', 'X', 'T', '2');
-static const unsigned int FOURCC_DXT3 = MAKEFOURCC('D', 'X', 'T', '3');
-static const unsigned int FOURCC_DXT4 = MAKEFOURCC('D', 'X', 'T', '4');
-static const unsigned int FOURCC_DXT5 = MAKEFOURCC('D', 'X', 'T', '5');
-static const unsigned int FOURCC_RXGB = MAKEFOURCC('R', 'X', 'G', 'B');
-static const unsigned int FOURCC_ATI1 = MAKEFOURCC('A', 'T', 'I', '1');
-static const unsigned int FOURCC_ATI2 = MAKEFOURCC('A', 'T', 'I', '2');
-
-// RGB formats.
-static const unsigned int D3DFMT_R8G8B8 = 20;
-static const unsigned int D3DFMT_A8R8G8B8 = 21;
-static const unsigned int D3DFMT_X8R8G8B8 = 22;
-static const unsigned int D3DFMT_R5G6B5 = 23;
-static const unsigned int D3DFMT_X1R5G5B5 = 24;
-static const unsigned int D3DFMT_A1R5G5B5 = 25;
-static const unsigned int D3DFMT_A4R4G4B4 = 26;
-static const unsigned int D3DFMT_R3G3B2 = 27;
-static const unsigned int D3DFMT_A8 = 28;
-static const unsigned int D3DFMT_A8R3G3B2 = 29;
-static const unsigned int D3DFMT_X4R4G4B4 = 30;
-static const unsigned int D3DFMT_A2B10G10R10 = 31;
-static const unsigned int D3DFMT_A8B8G8R8 = 32;
-static const unsigned int D3DFMT_X8B8G8R8 = 33;
-static const unsigned int D3DFMT_G16R16 = 34;
-static const unsigned int D3DFMT_A2R10G10B10 = 35;
-static const unsigned int D3DFMT_A16B16G16R16 = 36;
+static const uint FOURCC_DDS = MAKEFOURCC('D', 'D', 'S', ' ');
+static const uint FOURCC_DXT1 = MAKEFOURCC('D', 'X', 'T', '1');
+static const uint FOURCC_DXT2 = MAKEFOURCC('D', 'X', 'T', '2');
+static const uint FOURCC_DXT3 = MAKEFOURCC('D', 'X', 'T', '3');
+static const uint FOURCC_DXT4 = MAKEFOURCC('D', 'X', 'T', '4');
+static const uint FOURCC_DXT5 = MAKEFOURCC('D', 'X', 'T', '5');
+static const uint FOURCC_RXGB = MAKEFOURCC('R', 'X', 'G', 'B');
+static const uint FOURCC_ATI1 = MAKEFOURCC('A', 'T', 'I', '1');
+static const uint FOURCC_ATI2 = MAKEFOURCC('A', 'T', 'I', '2');
+
+static const uint FOURCC_A2XY = MAKEFOURCC('A', '2', 'X', 'Y');
+
+static const uint FOURCC_DX10 = MAKEFOURCC('D', 'X', '1', '0');
+
+// 32 bit RGB formats.
+static const uint D3DFMT_R8G8B8 = 20;
+static const uint D3DFMT_A8R8G8B8 = 21;
+static const uint D3DFMT_X8R8G8B8 = 22;
+static const uint D3DFMT_R5G6B5 = 23;
+static const uint D3DFMT_X1R5G5B5 = 24;
+static const uint D3DFMT_A1R5G5B5 = 25;
+static const uint D3DFMT_A4R4G4B4 = 26;
+static const uint D3DFMT_R3G3B2 = 27;
+static const uint D3DFMT_A8 = 28;
+static const uint D3DFMT_A8R3G3B2 = 29;
+static const uint D3DFMT_X4R4G4B4 = 30;
+static const uint D3DFMT_A2B10G10R10 = 31;
+static const uint D3DFMT_A8B8G8R8 = 32;
+static const uint D3DFMT_X8B8G8R8 = 33;
+static const uint D3DFMT_G16R16 = 34;
+static const uint D3DFMT_A2R10G10B10 = 35;
+
+static const uint D3DFMT_A16B16G16R16 = 36;
// Palette formats.
-static const unsigned int D3DFMT_A8P8 = 40;
-static const unsigned int D3DFMT_P8 = 41;
+static const uint D3DFMT_A8P8 = 40;
+static const uint D3DFMT_P8 = 41;
// Luminance formats.
-static const unsigned int D3DFMT_L8 = 50;
-static const unsigned int D3DFMT_A8L8 = 51;
-static const unsigned int D3DFMT_A4L4 = 52;
+static const uint D3DFMT_L8 = 50;
+static const uint D3DFMT_A8L8 = 51;
+static const uint D3DFMT_A4L4 = 52;
+static const uint D3DFMT_L16 = 81;
// Floating point formats
-static const unsigned int D3DFMT_R16F = 111;
-static const unsigned int D3DFMT_G16R16F = 112;
-static const unsigned int D3DFMT_A16B16G16R16F = 113;
-static const unsigned int D3DFMT_R32F = 114;
-static const unsigned int D3DFMT_G32R32F = 115;
-static const unsigned int D3DFMT_A32B32G32R32F = 116;
-
-static const unsigned int DDSD_CAPS = 0x00000001U;
-static const unsigned int DDSD_PIXELFORMAT = 0x00001000U;
-static const unsigned int DDSD_WIDTH = 0x00000004U;
-static const unsigned int DDSD_HEIGHT = 0x00000002U;
-static const unsigned int DDSD_PITCH = 0x00000008U;
-static const unsigned int DDSD_MIPMAPCOUNT = 0x00020000U;
-static const unsigned int DDSD_LINEARSIZE = 0x00080000U;
-static const unsigned int DDSD_DEPTH = 0x00800000U;
-
-static const unsigned int DDSCAPS_COMPLEX = 0x00000008U;
-static const unsigned int DDSCAPS_TEXTURE = 0x00001000U;
-static const unsigned int DDSCAPS_MIPMAP = 0x00400000U;
-static const unsigned int DDSCAPS2_VOLUME = 0x00200000U;
-static const unsigned int DDSCAPS2_CUBEMAP = 0x00000200U;
-
-static const unsigned int DDSCAPS2_CUBEMAP_POSITIVEX = 0x00000400U;
-static const unsigned int DDSCAPS2_CUBEMAP_NEGATIVEX = 0x00000800U;
-static const unsigned int DDSCAPS2_CUBEMAP_POSITIVEY = 0x00001000U;
-static const unsigned int DDSCAPS2_CUBEMAP_NEGATIVEY = 0x00002000U;
-static const unsigned int DDSCAPS2_CUBEMAP_POSITIVEZ = 0x00004000U;
-static const unsigned int DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x00008000U;
-static const unsigned int DDSCAPS2_CUBEMAP_ALL_FACES = 0x0000FC00U;
-
-static const unsigned int DDPF_ALPHAPIXELS = 0x00000001U;
-static const unsigned int DDPF_ALPHA = 0x00000002U;
-static const unsigned int DDPF_FOURCC = 0x00000004U;
-static const unsigned int DDPF_RGB = 0x00000040U;
-static const unsigned int DDPF_PALETTEINDEXED1 = 0x00000800U;
-static const unsigned int DDPF_PALETTEINDEXED2 = 0x00001000U;
-static const unsigned int DDPF_PALETTEINDEXED4 = 0x00000008U;
-static const unsigned int DDPF_PALETTEINDEXED8 = 0x00000020U;
-static const unsigned int DDPF_LUMINANCE = 0x00020000U;
-static const unsigned int DDPF_ALPHAPREMULT = 0x00008000U;
-static const unsigned int DDPF_NORMAL = 0x80000000U; // @@ Custom nv flag.
+static const uint D3DFMT_R16F = 111;
+static const uint D3DFMT_G16R16F = 112;
+static const uint D3DFMT_A16B16G16R16F = 113;
+static const uint D3DFMT_R32F = 114;
+static const uint D3DFMT_G32R32F = 115;
+static const uint D3DFMT_A32B32G32R32F = 116;
+
+static const uint DDSD_CAPS = 0x00000001U;
+static const uint DDSD_PIXELFORMAT = 0x00001000U;
+static const uint DDSD_WIDTH = 0x00000004U;
+static const uint DDSD_HEIGHT = 0x00000002U;
+static const uint DDSD_PITCH = 0x00000008U;
+static const uint DDSD_MIPMAPCOUNT = 0x00020000U;
+static const uint DDSD_LINEARSIZE = 0x00080000U;
+static const uint DDSD_DEPTH = 0x00800000U;
+
+static const uint DDSCAPS_COMPLEX = 0x00000008U;
+static const uint DDSCAPS_TEXTURE = 0x00001000U;
+static const uint DDSCAPS_MIPMAP = 0x00400000U;
+static const uint DDSCAPS2_VOLUME = 0x00200000U;
+static const uint DDSCAPS2_CUBEMAP = 0x00000200U;
+
+static const uint DDSCAPS2_CUBEMAP_POSITIVEX = 0x00000400U;
+static const uint DDSCAPS2_CUBEMAP_NEGATIVEX = 0x00000800U;
+static const uint DDSCAPS2_CUBEMAP_POSITIVEY = 0x00001000U;
+static const uint DDSCAPS2_CUBEMAP_NEGATIVEY = 0x00002000U;
+static const uint DDSCAPS2_CUBEMAP_POSITIVEZ = 0x00004000U;
+static const uint DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x00008000U;
+static const uint DDSCAPS2_CUBEMAP_ALL_FACES = 0x0000FC00U;
+
+static const uint DDPF_ALPHAPIXELS = 0x00000001U;
+static const uint DDPF_ALPHA = 0x00000002U;
+static const uint DDPF_FOURCC = 0x00000004U;
+static const uint DDPF_RGB = 0x00000040U;
+static const uint DDPF_PALETTEINDEXED1 = 0x00000800U;
+static const uint DDPF_PALETTEINDEXED2 = 0x00001000U;
+static const uint DDPF_PALETTEINDEXED4 = 0x00000008U;
+static const uint DDPF_PALETTEINDEXED8 = 0x00000020U;
+static const uint DDPF_LUMINANCE = 0x00020000U;
+static const uint DDPF_ALPHAPREMULT = 0x00008000U;
+static const uint DDPF_NORMAL = 0x80000000U; // @@ Custom nv flag.
+
+ // DX10 formats.
+ enum DXGI_FORMAT
+ {
+ DXGI_FORMAT_UNKNOWN = 0,
+
+ DXGI_FORMAT_R32G32B32A32_TYPELESS = 1,
+ DXGI_FORMAT_R32G32B32A32_FLOAT = 2,
+ DXGI_FORMAT_R32G32B32A32_UINT = 3,
+ DXGI_FORMAT_R32G32B32A32_SINT = 4,
+
+ DXGI_FORMAT_R32G32B32_TYPELESS = 5,
+ DXGI_FORMAT_R32G32B32_FLOAT = 6,
+ DXGI_FORMAT_R32G32B32_UINT = 7,
+ DXGI_FORMAT_R32G32B32_SINT = 8,
+
+ DXGI_FORMAT_R16G16B16A16_TYPELESS = 9,
+ DXGI_FORMAT_R16G16B16A16_FLOAT = 10,
+ DXGI_FORMAT_R16G16B16A16_UNORM = 11,
+ DXGI_FORMAT_R16G16B16A16_UINT = 12,
+ DXGI_FORMAT_R16G16B16A16_SNORM = 13,
+ DXGI_FORMAT_R16G16B16A16_SINT = 14,
+
+ DXGI_FORMAT_R32G32_TYPELESS = 15,
+ DXGI_FORMAT_R32G32_FLOAT = 16,
+ DXGI_FORMAT_R32G32_UINT = 17,
+ DXGI_FORMAT_R32G32_SINT = 18,
+
+ DXGI_FORMAT_R32G8X24_TYPELESS = 19,
+ DXGI_FORMAT_D32_FLOAT_S8X24_UINT = 20,
+ DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS = 21,
+ DXGI_FORMAT_X32_TYPELESS_G8X24_UINT = 22,
+
+ DXGI_FORMAT_R10G10B10A2_TYPELESS = 23,
+ DXGI_FORMAT_R10G10B10A2_UNORM = 24,
+ DXGI_FORMAT_R10G10B10A2_UINT = 25,
+
+ DXGI_FORMAT_R11G11B10_FLOAT = 26,
+
+ DXGI_FORMAT_R8G8B8A8_TYPELESS = 27,
+ DXGI_FORMAT_R8G8B8A8_UNORM = 28,
+ DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 29,
+ DXGI_FORMAT_R8G8B8A8_UINT = 30,
+ DXGI_FORMAT_R8G8B8A8_SNORM = 31,
+ DXGI_FORMAT_R8G8B8A8_SINT = 32,
+
+ DXGI_FORMAT_R16G16_TYPELESS = 33,
+ DXGI_FORMAT_R16G16_FLOAT = 34,
+ DXGI_FORMAT_R16G16_UNORM = 35,
+ DXGI_FORMAT_R16G16_UINT = 36,
+ DXGI_FORMAT_R16G16_SNORM = 37,
+ DXGI_FORMAT_R16G16_SINT = 38,
+
+ DXGI_FORMAT_R32_TYPELESS = 39,
+ DXGI_FORMAT_D32_FLOAT = 40,
+ DXGI_FORMAT_R32_FLOAT = 41,
+ DXGI_FORMAT_R32_UINT = 42,
+ DXGI_FORMAT_R32_SINT = 43,
+
+ DXGI_FORMAT_R24G8_TYPELESS = 44,
+ DXGI_FORMAT_D24_UNORM_S8_UINT = 45,
+ DXGI_FORMAT_R24_UNORM_X8_TYPELESS = 46,
+ DXGI_FORMAT_X24_TYPELESS_G8_UINT = 47,
+
+ DXGI_FORMAT_R8G8_TYPELESS = 48,
+ DXGI_FORMAT_R8G8_UNORM = 49,
+ DXGI_FORMAT_R8G8_UINT = 50,
+ DXGI_FORMAT_R8G8_SNORM = 51,
+ DXGI_FORMAT_R8G8_SINT = 52,
+
+ DXGI_FORMAT_R16_TYPELESS = 53,
+ DXGI_FORMAT_R16_FLOAT = 54,
+ DXGI_FORMAT_D16_UNORM = 55,
+ DXGI_FORMAT_R16_UNORM = 56,
+ DXGI_FORMAT_R16_UINT = 57,
+ DXGI_FORMAT_R16_SNORM = 58,
+ DXGI_FORMAT_R16_SINT = 59,
+
+ DXGI_FORMAT_R8_TYPELESS = 60,
+ DXGI_FORMAT_R8_UNORM = 61,
+ DXGI_FORMAT_R8_UINT = 62,
+ DXGI_FORMAT_R8_SNORM = 63,
+ DXGI_FORMAT_R8_SINT = 64,
+ DXGI_FORMAT_A8_UNORM = 65,
+
+ DXGI_FORMAT_R1_UNORM = 66,
+
+ DXGI_FORMAT_R9G9B9E5_SHAREDEXP = 67,
+
+ DXGI_FORMAT_R8G8_B8G8_UNORM = 68,
+ DXGI_FORMAT_G8R8_G8B8_UNORM = 69,
+
+ DXGI_FORMAT_BC1_TYPELESS = 70,
+ DXGI_FORMAT_BC1_UNORM = 71,
+ DXGI_FORMAT_BC1_UNORM_SRGB = 72,
+
+ DXGI_FORMAT_BC2_TYPELESS = 73,
+ DXGI_FORMAT_BC2_UNORM = 74,
+ DXGI_FORMAT_BC2_UNORM_SRGB = 75,
+
+ DXGI_FORMAT_BC3_TYPELESS = 76,
+ DXGI_FORMAT_BC3_UNORM = 77,
+ DXGI_FORMAT_BC3_UNORM_SRGB = 78,
+
+ DXGI_FORMAT_BC4_TYPELESS = 79,
+ DXGI_FORMAT_BC4_UNORM = 80,
+ DXGI_FORMAT_BC4_SNORM = 81,
+
+ DXGI_FORMAT_BC5_TYPELESS = 82,
+ DXGI_FORMAT_BC5_UNORM = 83,
+ DXGI_FORMAT_BC5_SNORM = 84,
+
+ DXGI_FORMAT_B5G6R5_UNORM = 85,
+ DXGI_FORMAT_B5G5R5A1_UNORM = 86,
+ DXGI_FORMAT_B8G8R8A8_UNORM = 87,
+ DXGI_FORMAT_B8G8R8X8_UNORM = 88,
+ };
+
+ enum D3D10_RESOURCE_DIMENSION
+ {
+ D3D10_RESOURCE_DIMENSION_UNKNOWN = 0,
+ D3D10_RESOURCE_DIMENSION_BUFFER = 1,
+ D3D10_RESOURCE_DIMENSION_TEXTURE1D = 2,
+ D3D10_RESOURCE_DIMENSION_TEXTURE2D = 3,
+ D3D10_RESOURCE_DIMENSION_TEXTURE3D = 4,
+ };
+
+
+ const char * getDxgiFormatString(DXGI_FORMAT dxgiFormat)
+ {
+#define CASE(format) case DXGI_FORMAT_##format: return #format
+ switch(dxgiFormat)
+ {
+ CASE(UNKNOWN);
+
+ CASE(R32G32B32A32_TYPELESS);
+ CASE(R32G32B32A32_FLOAT);
+ CASE(R32G32B32A32_UINT);
+ CASE(R32G32B32A32_SINT);
+
+ CASE(R32G32B32_TYPELESS);
+ CASE(R32G32B32_FLOAT);
+ CASE(R32G32B32_UINT);
+ CASE(R32G32B32_SINT);
+
+ CASE(R16G16B16A16_TYPELESS);
+ CASE(R16G16B16A16_FLOAT);
+ CASE(R16G16B16A16_UNORM);
+ CASE(R16G16B16A16_UINT);
+ CASE(R16G16B16A16_SNORM);
+ CASE(R16G16B16A16_SINT);
+
+ CASE(R32G32_TYPELESS);
+ CASE(R32G32_FLOAT);
+ CASE(R32G32_UINT);
+ CASE(R32G32_SINT);
+
+ CASE(R32G8X24_TYPELESS);
+ CASE(D32_FLOAT_S8X24_UINT);
+ CASE(R32_FLOAT_X8X24_TYPELESS);
+ CASE(X32_TYPELESS_G8X24_UINT);
+
+ CASE(R10G10B10A2_TYPELESS);
+ CASE(R10G10B10A2_UNORM);
+ CASE(R10G10B10A2_UINT);
+
+ CASE(R11G11B10_FLOAT);
+
+ CASE(R8G8B8A8_TYPELESS);
+ CASE(R8G8B8A8_UNORM);
+ CASE(R8G8B8A8_UNORM_SRGB);
+ CASE(R8G8B8A8_UINT);
+ CASE(R8G8B8A8_SNORM);
+ CASE(R8G8B8A8_SINT);
+
+ CASE(R16G16_TYPELESS);
+ CASE(R16G16_FLOAT);
+ CASE(R16G16_UNORM);
+ CASE(R16G16_UINT);
+ CASE(R16G16_SNORM);
+ CASE(R16G16_SINT);
+
+ CASE(R32_TYPELESS);
+ CASE(D32_FLOAT);
+ CASE(R32_FLOAT);
+ CASE(R32_UINT);
+ CASE(R32_SINT);
+
+ CASE(R24G8_TYPELESS);
+ CASE(D24_UNORM_S8_UINT);
+ CASE(R24_UNORM_X8_TYPELESS);
+ CASE(X24_TYPELESS_G8_UINT);
+
+ CASE(R8G8_TYPELESS);
+ CASE(R8G8_UNORM);
+ CASE(R8G8_UINT);
+ CASE(R8G8_SNORM);
+ CASE(R8G8_SINT);
+
+ CASE(R16_TYPELESS);
+ CASE(R16_FLOAT);
+ CASE(D16_UNORM);
+ CASE(R16_UNORM);
+ CASE(R16_UINT);
+ CASE(R16_SNORM);
+ CASE(R16_SINT);
+
+ CASE(R8_TYPELESS);
+ CASE(R8_UNORM);
+ CASE(R8_UINT);
+ CASE(R8_SNORM);
+ CASE(R8_SINT);
+ CASE(A8_UNORM);
+
+ CASE(R1_UNORM);
+
+ CASE(R9G9B9E5_SHAREDEXP);
+
+ CASE(R8G8_B8G8_UNORM);
+ CASE(G8R8_G8B8_UNORM);
+
+ CASE(BC1_TYPELESS);
+ CASE(BC1_UNORM);
+ CASE(BC1_UNORM_SRGB);
+
+ CASE(BC2_TYPELESS);
+ CASE(BC2_UNORM);
+ CASE(BC2_UNORM_SRGB);
+
+ CASE(BC3_TYPELESS);
+ CASE(BC3_UNORM);
+ CASE(BC3_UNORM_SRGB);
+
+ CASE(BC4_TYPELESS);
+ CASE(BC4_UNORM);
+ CASE(BC4_SNORM);
+
+ CASE(BC5_TYPELESS);
+ CASE(BC5_UNORM);
+ CASE(BC5_SNORM);
+
+ CASE(B5G6R5_UNORM);
+ CASE(B5G5R5A1_UNORM);
+ CASE(B8G8R8A8_UNORM);
+ CASE(B8G8R8X8_UNORM);
+
+ default:
+ return "UNKNOWN";
+ }
+#undef CASE
+ }
+
+ const char * getD3d10ResourceDimensionString(D3D10_RESOURCE_DIMENSION resourceDimension)
+ {
+ switch(resourceDimension)
+ {
+ default:
+ case D3D10_RESOURCE_DIMENSION_UNKNOWN: return "UNKNOWN";
+ case D3D10_RESOURCE_DIMENSION_BUFFER: return "BUFFER";
+ case D3D10_RESOURCE_DIMENSION_TEXTURE1D: return "TEXTURE1D";
+ case D3D10_RESOURCE_DIMENSION_TEXTURE2D: return "TEXTURE2D";
+ case D3D10_RESOURCE_DIMENSION_TEXTURE3D: return "TEXTURE3D";
+ }
+ }
/*** implementation ***/
@@ -172,6 +443,15 @@ void mem_read(Stream & mem, DDSCaps & caps)
mem_read(mem, caps.caps4);
}
+void mem_read(Stream & mem, DDSHeader10 & header)
+{
+ mem_read(mem, header.dxgiFormat);
+ mem_read(mem, header.resourceDimension);
+ mem_read(mem, header.miscFlag);
+ mem_read(mem, header.arraySize);
+ mem_read(mem, header.reserved);
+}
+
void mem_read(Stream & mem, DDSHeader & header)
{
mem_read(mem, header.fourcc);
@@ -182,12 +462,19 @@ void mem_read(Stream & mem, DDSHeader & header)
mem_read(mem, header.pitch);
mem_read(mem, header.depth);
mem_read(mem, header.mipmapcount);
- for (unsigned int i = 0; i < 11; i++) mem_read(mem, header.reserved[i]);
+ for (uint i = 0; i < 11; i++) mem_read(mem, header.reserved[i]);
mem_read(mem, header.pf);
mem_read(mem, header.caps);
mem_read(mem, header.notused);
+
+ if (header.hasDX10Header())
+ {
+ mem_read(mem, header.header10);
+ }
}
+
+
DDSHeader::DDSHeader()
{
this->fourcc = FOURCC_DDS;
@@ -198,11 +485,11 @@ DDSHeader::DDSHeader()
this->pitch = 0;
this->depth = 0;
this->mipmapcount = 0;
- for (unsigned int i = 0; i < 11; i++) this->reserved[i] = 0;
+ for (uint i = 0; i < 11; i++) this->reserved[i] = 0;
// Store version information on the reserved header attributes.
this->reserved[9] = MAKEFOURCC('N', 'V', 'T', 'T');
- this->reserved[10] = (0 << 16) | (9 << 8) | (3); // major.minor.revision
+ this->reserved[10] = (0 << 16) | (9 << 8) | (5); // major.minor.revision
this->pf.size = 32;
this->pf.flags = 0;
@@ -217,29 +504,35 @@ DDSHeader::DDSHeader()
this->caps.caps3 = 0;
this->caps.caps4 = 0;
this->notused = 0;
+
+ this->header10.dxgiFormat = DXGI_FORMAT_UNKNOWN;
+ this->header10.resourceDimension = D3D10_RESOURCE_DIMENSION_UNKNOWN;
+ this->header10.miscFlag = 0;
+ this->header10.arraySize = 0;
+ this->header10.reserved = 0;
}
-void DDSHeader::setWidth(unsigned int w)
+void DDSHeader::setWidth(uint w)
{
this->flags |= DDSD_WIDTH;
this->width = w;
}
-void DDSHeader::setHeight(unsigned int h)
+void DDSHeader::setHeight(uint h)
{
this->flags |= DDSD_HEIGHT;
this->height = h;
}
-void DDSHeader::setDepth(unsigned int d)
+void DDSHeader::setDepth(uint d)
{
this->flags |= DDSD_DEPTH;
this->height = d;
}
-void DDSHeader::setMipmapCount(unsigned int count)
+void DDSHeader::setMipmapCount(uint count)
{
- if (count == 0)
+ if (count == 0 || count == 1)
{
this->flags &= ~DDSD_MIPMAPCOUNT;
this->mipmapcount = 0;
@@ -262,47 +555,61 @@ void DDSHeader::setMipmapCount(unsigned int count)
void DDSHeader::setTexture2D()
{
- // nothing to do here.
+ this->header10.resourceDimension = D3D10_RESOURCE_DIMENSION_TEXTURE2D;
}
void DDSHeader::setTexture3D()
{
this->caps.caps2 = DDSCAPS2_VOLUME;
+
+ this->header10.resourceDimension = D3D10_RESOURCE_DIMENSION_TEXTURE3D;
}
void DDSHeader::setTextureCube()
{
this->caps.caps1 |= DDSCAPS_COMPLEX;
this->caps.caps2 = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_ALL_FACES;
+
+ this->header10.resourceDimension = D3D10_RESOURCE_DIMENSION_TEXTURE2D;
+ this->header10.arraySize = 6;
}
-void DDSHeader::setLinearSize(unsigned int size)
+void DDSHeader::setLinearSize(uint size)
{
this->flags &= ~DDSD_PITCH;
this->flags |= DDSD_LINEARSIZE;
this->pitch = size;
}
-void DDSHeader::setPitch(unsigned int pitch)
+void DDSHeader::setPitch(uint pitch)
{
this->flags &= ~DDSD_LINEARSIZE;
this->flags |= DDSD_PITCH;
this->pitch = pitch;
}
-void DDSHeader::setFourCC(unsigned char c0, unsigned char c1, unsigned char c2, unsigned char c3)
+void DDSHeader::setFourCC(uint8 c0, uint8 c1, uint8 c2, uint8 c3)
{
// set fourcc pixel format.
this->pf.flags = DDPF_FOURCC;
this->pf.fourcc = MAKEFOURCC(c0, c1, c2, c3);
- this->pf.bitcount = 0;
+
+ if (this->pf.fourcc == FOURCC_ATI2)
+ {
+ this->pf.bitcount = FOURCC_A2XY;
+ }
+ else
+ {
+ this->pf.bitcount = 0;
+ }
+
this->pf.rmask = 0;
this->pf.gmask = 0;
this->pf.bmask = 0;
this->pf.amask = 0;
}
-void DDSHeader::setPixelFormat(unsigned int bitcount, unsigned int rmask, unsigned int gmask, unsigned int bmask, unsigned int amask)
+void DDSHeader::setPixelFormat(uint bitcount, uint rmask, uint gmask, uint bmask, uint amask)
{
// Make sure the masks are correct.
if ((rmask & gmask) || \
@@ -324,15 +631,25 @@ void DDSHeader::setPixelFormat(unsigned int bitcount, unsigned int rmask, unsign
if (bitcount == 0)
{
// Compute bit count from the masks.
- unsigned int total = rmask | gmask | bmask | amask;
+ uint total = rmask | gmask | bmask | amask;
while(total != 0) {
bitcount++;
total >>= 1;
}
- // @@ Align to 8?
}
- this->pf.fourcc = 0;
+ if (!(bitcount > 0 && bitcount <= 32)) {
+ printf("DDS: bad bit count, pixel format not set\n");
+ return;
+ }
+
+ // Align to 8.
+ if (bitcount <= 8) bitcount = 8;
+ else if (bitcount <= 16) bitcount = 16;
+ else if (bitcount <= 24) bitcount = 24;
+ else bitcount = 32;
+
+ this->pf.fourcc = 0; //findD3D9Format(bitcount, rmask, gmask, bmask, amask);
this->pf.bitcount = bitcount;
this->pf.rmask = rmask;
this->pf.gmask = gmask;
@@ -340,48 +657,33 @@ void DDSHeader::setPixelFormat(unsigned int bitcount, unsigned int rmask, unsign
this->pf.amask = amask;
}
+void DDSHeader::setDX10Format(uint format)
+{
+ //this->pf.flags = 0;
+ this->pf.fourcc = FOURCC_DX10;
+ this->header10.dxgiFormat = format;
+}
+
void DDSHeader::setNormalFlag(bool b)
{
if (b) this->pf.flags |= DDPF_NORMAL;
else this->pf.flags &= ~DDPF_NORMAL;
}
-/*
-void DDSHeader::swapBytes()
+bool DDSHeader::hasDX10Header() const
{
- this->fourcc = POSH_LittleU32(this->fourcc);
- this->size = POSH_LittleU32(this->size);
- this->flags = POSH_LittleU32(this->flags);
- this->height = POSH_LittleU32(this->height);
- this->width = POSH_LittleU32(this->width);
- this->pitch = POSH_LittleU32(this->pitch);
- this->depth = POSH_LittleU32(this->depth);
- this->mipmapcount = POSH_LittleU32(this->mipmapcount);
-
- for(int i = 0; i < 11; i++) {
- this->reserved[i] = POSH_LittleU32(this->reserved[i]);
- }
-
- this->pf.size = POSH_LittleU32(this->pf.size);
- this->pf.flags = POSH_LittleU32(this->pf.flags);
- this->pf.fourcc = POSH_LittleU32(this->pf.fourcc);
- this->pf.bitcount = POSH_LittleU32(this->pf.bitcount);
- this->pf.rmask = POSH_LittleU32(this->pf.rmask);
- this->pf.gmask = POSH_LittleU32(this->pf.gmask);
- this->pf.bmask = POSH_LittleU32(this->pf.bmask);
- this->pf.amask = POSH_LittleU32(this->pf.amask);
- this->caps.caps1 = POSH_LittleU32(this->caps.caps1);
- this->caps.caps2 = POSH_LittleU32(this->caps.caps2);
- this->caps.caps3 = POSH_LittleU32(this->caps.caps3);
- this->caps.caps4 = POSH_LittleU32(this->caps.caps4);
- this->notused = POSH_LittleU32(this->notused);
+ return this->pf.fourcc == FOURCC_DX10; // @@ This is according to AMD
+ //return this->pf.flags == 0; // @@ This is according to MS
}
-*/
-
-DirectDrawSurface::DirectDrawSurface(unsigned char *mem, unsigned int size) : stream(mem, size), header()
+DirectDrawSurface::DirectDrawSurface(unsigned char *mem, uint size) : stream(mem, size), header()
{
mem_read(stream, header);
+
+ // some ATI2 compressed normal maps do not have their
+ // normal flag set, so force it here (the original nvtt don't do
+ // this, but the decompressor has a -forcenormal flag)
+ if (header.pf.fourcc == FOURCC_ATI2) header.setNormalFlag(true);
}
DirectDrawSurface::~DirectDrawSurface()
@@ -395,7 +697,7 @@ bool DirectDrawSurface::isValid() const
return false;
}
- const unsigned int required = (DDSD_WIDTH|DDSD_HEIGHT|DDSD_CAPS|DDSD_PIXELFORMAT);
+ const uint required = (DDSD_WIDTH|DDSD_HEIGHT/*|DDSD_CAPS|DDSD_PIXELFORMAT*/);
if( (header.flags & required) != required ) {
return false;
}
@@ -416,78 +718,72 @@ bool DirectDrawSurface::isValid() const
bool DirectDrawSurface::isSupported() const
{
- if (header.pf.flags & DDPF_FOURCC)
+ if (header.hasDX10Header())
{
- if (header.pf.fourcc != FOURCC_DXT1 &&
- header.pf.fourcc != FOURCC_DXT2 &&
- header.pf.fourcc != FOURCC_DXT3 &&
- header.pf.fourcc != FOURCC_DXT4 &&
- header.pf.fourcc != FOURCC_DXT5 &&
- header.pf.fourcc != FOURCC_RXGB &&
- header.pf.fourcc != FOURCC_ATI1 &&
- header.pf.fourcc != FOURCC_ATI2)
- {
- // Unknown fourcc code.
- return false;
- }
}
- else if (header.pf.flags & DDPF_RGB)
+ else
{
- if (header.pf.bitcount == 24)
+ if (header.pf.flags & DDPF_FOURCC)
{
- return true;
+ if (header.pf.fourcc != FOURCC_DXT1 &&
+ header.pf.fourcc != FOURCC_DXT2 &&
+ header.pf.fourcc != FOURCC_DXT3 &&
+ header.pf.fourcc != FOURCC_DXT4 &&
+ header.pf.fourcc != FOURCC_DXT5 &&
+ header.pf.fourcc != FOURCC_RXGB &&
+ header.pf.fourcc != FOURCC_ATI1 &&
+ header.pf.fourcc != FOURCC_ATI2)
+ {
+ // Unknown fourcc code.
+ return false;
+ }
}
- else if (header.pf.bitcount == 32)
+ else if (header.pf.flags & DDPF_RGB)
{
- return true;
+ // All RGB formats are supported now.
}
else
{
- // Unsupported pixel format.
return false;
}
- }
- else
- {
- return false;
- }
-
- if (isTextureCube() && (header.caps.caps2 & DDSCAPS2_CUBEMAP_ALL_FACES) != DDSCAPS2_CUBEMAP_ALL_FACES)
- {
- // Cubemaps must contain all faces.
- return false;
- }
+
+ if (isTextureCube() && (header.caps.caps2 & DDSCAPS2_CUBEMAP_ALL_FACES) != DDSCAPS2_CUBEMAP_ALL_FACES)
+ {
+ // Cubemaps must contain all faces.
+ return false;
+ }
- if (isTexture3D())
- {
- // @@ 3D textures not supported yet.
- return false;
+ if (isTexture3D())
+ {
+ // @@ 3D textures not supported yet.
+ return false;
+ }
}
return true;
}
-unsigned int DirectDrawSurface::mipmapCount() const
+uint DirectDrawSurface::mipmapCount() const
{
if (header.flags & DDSD_MIPMAPCOUNT) return header.mipmapcount;
- else return 0;
+ else return 1;
}
-unsigned int DirectDrawSurface::width() const
+uint DirectDrawSurface::width() const
{
if (header.flags & DDSD_WIDTH) return header.width;
else return 1;
}
-unsigned int DirectDrawSurface::height() const
+uint DirectDrawSurface::height() const
{
if (header.flags & DDSD_HEIGHT) return header.height;
else return 1;
}
-unsigned int DirectDrawSurface::depth() const
+uint DirectDrawSurface::depth() const
{
if (header.flags & DDSD_DEPTH) return header.depth;
else return 1;
@@ -509,14 +805,37 @@ bool DirectDrawSurface::hasAlpha() const
}
}
+bool DirectDrawSurface::isTexture1D() const
+{
+ if (header.hasDX10Header())
+ {
+ return header.header10.resourceDimension == D3D10_RESOURCE_DIMENSION_TEXTURE1D;
+ }
+ return false;
+}
+
bool DirectDrawSurface::isTexture2D() const
{
- return !isTexture3D() && !isTextureCube();
+ if (header.hasDX10Header())
+ {
+ return header.header10.resourceDimension == D3D10_RESOURCE_DIMENSION_TEXTURE2D;
+ }
+ else
+ {
+ return !isTexture3D() && !isTextureCube();
+ }
}
bool DirectDrawSurface::isTexture3D() const
{
+ if (header.hasDX10Header())
+ {
+ return header.header10.resourceDimension == D3D10_RESOURCE_DIMENSION_TEXTURE3D;
+ }
+ else
+ {
return (header.caps.caps2 & DDSCAPS2_VOLUME) != 0;
+ }
}
bool DirectDrawSurface::isTextureCube() const
@@ -524,18 +843,23 @@ bool DirectDrawSurface::isTextureCube() const
return (header.caps.caps2 & DDSCAPS2_CUBEMAP) != 0;
}
-void DirectDrawSurface::mipmap(Image * img, unsigned int face, unsigned int mipmap)
+void DirectDrawSurface::setNormalFlag(bool b)
+{
+ header.setNormalFlag(b);
+}
+
+void DirectDrawSurface::mipmap(Image * img, uint face, uint mipmap)
{
stream.seek(offset(face, mipmap));
- unsigned int w = width();
- unsigned int h = height();
+ uint w = width();
+ uint h = height();
// Compute width and height.
- for (unsigned int m = 0; m < mipmap; m++)
+ for (uint m = 0; m < mipmap; m++)
{
- w = max(w/2, 1U);
- h = max(h/2, 1U);
+ w = max(1U, w / 2);
+ h = max(1U, h / 2);
}
img->allocate(w, h);
@@ -550,94 +874,57 @@ void DirectDrawSurface::mipmap(Image * img, unsigned int face, unsigned int mipm
}
}
-/* helper function for readLinearImage */
-void maskShiftAndSize(unsigned int mask, unsigned int * shift, unsigned int * size)
-{
- if (!mask)
- {
- *shift = 0;
- *size = 0;
- return;
- }
-
- *shift = 0;
- while((mask & 1) == 0) {
- ++(*shift);
- mask >>= 1;
- }
-
- *size = 0;
- while((mask & 1) == 1) {
- ++(*size);
- mask >>= 1;
- }
-}
-
-/* helper function for readLinearImage */
-unsigned int convert(unsigned int c, unsigned int inbits, unsigned int outbits)
-{
- if (inbits == 0) {
- return 0;
- }
- else if (inbits == outbits)
- {
- return c;
- }
- else if (inbits > outbits)
- {
- // truncate
- return c >> (inbits - outbits);
- }
- else
- {
- // bitexpand
- return (c << (outbits - inbits)) | convert(c, inbits, outbits - inbits);
- }
-}
-
void DirectDrawSurface::readLinearImage(Image * img)
{
- const unsigned int w = img->width();
- const unsigned int h = img->height();
-
- unsigned int rshift, rsize;
- maskShiftAndSize(header.pf.rmask, &rshift, &rsize);
- unsigned int gshift, gsize;
- maskShiftAndSize(header.pf.gmask, &gshift, &gsize);
+ const uint w = img->width();
+ const uint h = img->height();
+
+ uint rshift, rsize;
+ PixelFormat::maskShiftAndSize(header.pf.rmask, &rshift, &rsize);
- unsigned int bshift, bsize;
- maskShiftAndSize(header.pf.bmask, &bshift, &bsize);
+ uint gshift, gsize;
+ PixelFormat::maskShiftAndSize(header.pf.gmask, &gshift, &gsize);
- unsigned int ashift, asize;
- maskShiftAndSize(header.pf.amask, &ashift, &asize);
+ uint bshift, bsize;
+ PixelFormat::maskShiftAndSize(header.pf.bmask, &bshift, &bsize);
+
+ uint ashift, asize;
+ PixelFormat::maskShiftAndSize(header.pf.amask, &ashift, &asize);
+
+ uint byteCount = (header.pf.bitcount + 7) / 8;
- unsigned int byteCount = (header.pf.bitcount + 7) / 8;
if (byteCount > 4)
{
/* just in case... we could have segfaults later on if byteCount > 4 */
- printf("DDS: bitcount too large (file corrupt?)");
+ printf("DDS: bitcount too large");
return;
}
- if (header.pf.amask != 0)
+ // set image format: RGB or ARGB
+ // alpha channel exists if and only if the alpha mask is non-zero
+ if (header.pf.amask == 0)
+ {
+ img->setFormat(Image::Format_RGB);
+ }
+ else
{
img->setFormat(Image::Format_ARGB);
}
// Read linear RGB images.
- for (unsigned int y = 0; y < h; y++)
+ for (uint y = 0; y < h; y++)
{
- for (unsigned int x = 0; x < w; x++)
+ for (uint x = 0; x < w; x++)
{
- unsigned int c = 0;
+ uint c = 0;
mem_read(stream, (unsigned char *)(&c), byteCount);
Color32 pixel(0, 0, 0, 0xFF);
- pixel.r = convert(c >> rshift, rsize, 8);
- pixel.g = convert(c >> gshift, gsize, 8);
- pixel.b = convert(c >> bshift, bsize, 8);
- pixel.a = convert(c >> ashift, asize, 8);
+ pixel.r = PixelFormat::convert(c >> rshift, rsize, 8);
+ pixel.g = PixelFormat::convert(c >> gshift, gsize, 8);
+ pixel.b = PixelFormat::convert(c >> bshift, bsize, 8);
+ pixel.a = PixelFormat::convert(c >> ashift, asize, 8);
img->pixel(x, y) = pixel;
}
@@ -646,15 +933,29 @@ void DirectDrawSurface::readLinearImage(Image * img)
void DirectDrawSurface::readBlockImage(Image * img)
{
- const unsigned int w = img->width();
- const unsigned int h = img->height();
+
+ // set image format: RGB or ARGB
+ if (header.pf.fourcc == FOURCC_RXGB ||
+ header.pf.fourcc == FOURCC_ATI1 ||
+ header.pf.fourcc == FOURCC_ATI2 ||
+ header.pf.flags & DDPF_NORMAL)
+ {
+ img->setFormat(Image::Format_RGB);
+ }
+ else
+ {
+ img->setFormat(Image::Format_ARGB);
+ }
+
+ const uint w = img->width();
+ const uint h = img->height();
- const unsigned int bw = (w + 3) / 4;
- const unsigned int bh = (h + 3) / 4;
+ const uint bw = (w + 3) / 4;
+ const uint bh = (h + 3) / 4;
- for (unsigned int by = 0; by < bh; by++)
+ for (uint by = 0; by < bh; by++)
{
- for (unsigned int bx = 0; bx < bw; bx++)
+ for (uint bx = 0; bx < bw; bx++)
{
ColorBlock block;
@@ -662,9 +963,9 @@ void DirectDrawSurface::readBlockImage(Image * img)
readBlock(&block);
// Write color block.
- for (unsigned int y = 0; y < min(4U, h-4*by); y++)
+ for (uint y = 0; y < min(4U, h-4*by); y++)
{
- for (unsigned int x = 0; x < min(4U, w-4*bx); x++)
+ for (uint x = 0; x < min(4U, w-4*bx); x++)
{
img->pixel(4*bx+x, 4*by+y) = block.color(x, y);
}
@@ -673,12 +974,13 @@ void DirectDrawSurface::readBlockImage(Image * img)
}
}
-static Color32 buildNormal(unsigned char x, unsigned char y)
+static Color32 buildNormal(uint8 x, uint8 y)
{
- float nx = 2 * (x / 255) - 1;
- float ny = 2 * (x / 255) - 1;
- float nz = sqrt(1 - nx*nx - ny*ny);
- unsigned char z = clamp(int(255 * (nz + 1) / 2), 0, 255);
+ float nx = 2 * (x / 255.0f) - 1;
+ float ny = 2 * (y / 255.0f) - 1;
+ float nz = 0.0f;
+ if (1 - nx*nx - ny*ny > 0) nz = sqrt(1 - nx*nx - ny*ny);
+ uint8 z = clamp(int(255.0f * (nz + 1) / 2.0f), 0, 255);
return Color32(x, y, z);
}
@@ -713,7 +1015,7 @@ void DirectDrawSurface::readBlock(ColorBlock * rgba)
for (int i = 0; i < 16; i++)
{
Color32 & c = rgba->color(i);
- unsigned int tmp = c.r;
+ uint tmp = c.r;
c.r = c.a;
c.a = tmp;
}
@@ -748,14 +1050,14 @@ void DirectDrawSurface::readBlock(ColorBlock * rgba)
for (int i = 0; i < 16; i++)
{
Color32 & c = rgba->color(i);
- c = buildNormal(c.g, c.a);
+ c = buildNormal(c.a, c.g);
}
}
}
}
-unsigned int DirectDrawSurface::blockSize() const
+uint DirectDrawSurface::blockSize() const
{
switch(header.pf.fourcc)
{
@@ -775,13 +1077,13 @@ unsigned int DirectDrawSurface::blockSize() const
return 0;
}
-unsigned int DirectDrawSurface::mipmapSize(unsigned int mipmap) const
+uint DirectDrawSurface::mipmapSize(uint mipmap) const
{
- unsigned int w = width();
- unsigned int h = height();
- unsigned int d = depth();
+ uint w = width();
+ uint h = height();
+ uint d = depth();
- for (unsigned int m = 0; m < mipmap; m++)
+ for (uint m = 0; m < mipmap; m++)
{
w = max(1U, w / 2);
h = max(1U, h / 2);
@@ -798,10 +1100,10 @@ unsigned int DirectDrawSurface::mipmapSize(unsigned int mipmap) const
else if (header.pf.flags & DDPF_RGB)
{
// Align pixels to bytes.
- unsigned int byteCount = (header.pf.bitcount + 7) / 8;
+ uint byteCount = (header.pf.bitcount + 7) / 8;
// Align pitch to 4 bytes.
- unsigned int pitch = 4 * ((w * byteCount + 3) / 4);
+ uint pitch = 4 * ((w * byteCount + 3) / 4);
return pitch * h * d;
}
@@ -811,12 +1113,12 @@ unsigned int DirectDrawSurface::mipmapSize(unsigned int mipmap) const
};
}
-unsigned int DirectDrawSurface::faceSize() const
+uint DirectDrawSurface::faceSize() const
{
- const unsigned int count = mipmapCount();
- unsigned int size = 0;
+ const uint count = mipmapCount();
+ uint size = 0;
- for (unsigned int m = 0; m < count; m++)
+ for (uint m = 0; m < count; m++)
{
size += mipmapSize(m);
}
@@ -824,16 +1126,21 @@ unsigned int DirectDrawSurface::faceSize() const
return size;
}
-unsigned int DirectDrawSurface::offset(const unsigned int face, const unsigned int mipmap)
+uint DirectDrawSurface::offset(const uint face, const uint mipmap)
{
- unsigned int size = sizeof(DDSHeader);
+ uint size = 128; //sizeof(DDSHeader);
+ if (header.hasDX10Header())
+ {
+ size += 20; // sizeof(DDSHeader10);
+ }
+
if (face != 0)
{
size += face * faceSize();
}
- for (unsigned int m = 0; m < mipmap; m++)
+ for (uint m = 0; m < mipmap; m++)
{
size += mipmapSize(m);
}
@@ -876,8 +1183,23 @@ void DirectDrawSurface::printInfo() const
if (header.pf.flags & DDPF_ALPHAPREMULT) printf("\t\tDDPF_ALPHAPREMULT\n");
if (header.pf.flags & DDPF_NORMAL) printf("\t\tDDPF_NORMAL\n");
- printf("\tFourCC: '%c%c%c%c'\n", ((header.pf.fourcc >> 0) & 0xFF), ((header.pf.fourcc >> 8) & 0xFF), ((header.pf.fourcc >> 16) & 0xFF), ((header.pf.fourcc >> 24) & 0xFF));
- printf("\tBit count: %d\n", header.pf.bitcount);
+ printf("\tFourCC: '%c%c%c%c'\n",
+ ((header.pf.fourcc >> 0) & 0xFF),
+ ((header.pf.fourcc >> 8) & 0xFF),
+ ((header.pf.fourcc >> 16) & 0xFF),
+ ((header.pf.fourcc >> 24) & 0xFF));
+ if ((header.pf.fourcc & DDPF_FOURCC) && (header.pf.bitcount != 0))
+ {
+ printf("\tSwizzle: '%c%c%c%c'\n",
+ (header.pf.bitcount >> 0) & 0xFF,
+ (header.pf.bitcount >> 8) & 0xFF,
+ (header.pf.bitcount >> 16) & 0xFF,
+ (header.pf.bitcount >> 24) & 0xFF);
+ }
+ else
+ {
+ printf("\tBit count: %d\n", header.pf.bitcount);
+ }
printf("\tRed mask: 0x%.8X\n", header.pf.rmask);
printf("\tGreen mask: 0x%.8X\n", header.pf.gmask);
printf("\tBlue mask: 0x%.8X\n", header.pf.bmask);
@@ -908,6 +1230,15 @@ void DirectDrawSurface::printInfo() const
printf("\tCaps 3: 0x%.8X\n", header.caps.caps3);
printf("\tCaps 4: 0x%.8X\n", header.caps.caps4);
+ if (header.hasDX10Header())
+ {
+ printf("DX10 Header:\n");
+ printf("\tDXGI Format: %u (%s)\n", header.header10.dxgiFormat, getDxgiFormatString((DXGI_FORMAT)header.header10.dxgiFormat));
+ printf("\tResource dimension: %u (%s)\n", header.header10.resourceDimension, getD3d10ResourceDimensionString((D3D10_RESOURCE_DIMENSION)header.header10.resourceDimension));
+ printf("\tMisc flag: %u\n", header.header10.miscFlag);
+ printf("\tArray size: %u\n", header.header10.arraySize);
+ }
+
if (header.reserved[9] == MAKEFOURCC('N', 'V', 'T', 'T'))
{
int major = (header.reserved[10] >> 16) & 0xFF;
diff --git a/source/blender/imbuf/intern/dds/DirectDrawSurface.h b/source/blender/imbuf/intern/dds/DirectDrawSurface.h
index 76272717332..28fcc95fe83 100644
--- a/source/blender/imbuf/intern/dds/DirectDrawSurface.h
+++ b/source/blender/imbuf/intern/dds/DirectDrawSurface.h
@@ -55,92 +55,114 @@
#ifndef _DDS_DIRECTDRAWSURFACE_H
#define _DDS_DIRECTDRAWSURFACE_H
+#include <Common.h>
#include <Stream.h>
#include <ColorBlock.h>
#include <Image.h>
-struct DDSPixelFormat {
- unsigned int size;
- unsigned int flags;
- unsigned int fourcc;
- unsigned int bitcount;
- unsigned int rmask;
- unsigned int gmask;
- unsigned int bmask;
- unsigned int amask;
+struct DDSPixelFormat
+{
+ uint size;
+ uint flags;
+ uint fourcc;
+ uint bitcount;
+ uint rmask;
+ uint gmask;
+ uint bmask;
+ uint amask;
+};
+
+struct DDSCaps
+{
+ uint caps1;
+ uint caps2;
+ uint caps3;
+ uint caps4;
};
-struct DDSCaps {
- unsigned int caps1;
- unsigned int caps2;
- unsigned int caps3;
- unsigned int caps4;
+/// DDS file header for DX10.
+struct DDSHeader10
+{
+ uint dxgiFormat;
+ uint resourceDimension;
+ uint miscFlag;
+ uint arraySize;
+ uint reserved;
};
/// DDS file header.
-struct DDSHeader {
- unsigned int fourcc;
- unsigned int size;
- unsigned int flags;
- unsigned int height;
- unsigned int width;
- unsigned int pitch;
- unsigned int depth;
- unsigned int mipmapcount;
- unsigned int reserved[11];
+struct DDSHeader
+{
+ uint fourcc;
+ uint size;
+ uint flags;
+ uint height;
+ uint width;
+ uint pitch;
+ uint depth;
+ uint mipmapcount;
+ uint reserved[11];
DDSPixelFormat pf;
DDSCaps caps;
- unsigned int notused;
-
+ uint notused;
+ DDSHeader10 header10;
+
+
// Helper methods.
DDSHeader();
- void setWidth(unsigned int w);
- void setHeight(unsigned int h);
- void setDepth(unsigned int d);
- void setMipmapCount(unsigned int count);
+ void setWidth(uint w);
+ void setHeight(uint h);
+ void setDepth(uint d);
+ void setMipmapCount(uint count);
void setTexture2D();
void setTexture3D();
void setTextureCube();
- void setLinearSize(unsigned int size);
- void setPitch(unsigned int pitch);
- void setFourCC(unsigned char c0, unsigned char c1, unsigned char c2, unsigned char c3);
- void setPixelFormat(unsigned int bitcount, unsigned int rmask, unsigned int gmask, unsigned int bmask, unsigned int amask);
+ void setLinearSize(uint size);
+ void setPitch(uint pitch);
+ void setFourCC(uint8 c0, uint8 c1, uint8 c2, uint8 c3);
+ void setPixelFormat(uint bitcount, uint rmask, uint gmask, uint bmask, uint amask);
+ void setDX10Format(uint format);
void setNormalFlag(bool b);
- /* void swapBytes(); */
+ bool hasDX10Header() const;
};
/// DirectDraw Surface. (DDS)
class DirectDrawSurface
{
public:
- DirectDrawSurface(unsigned char *mem, unsigned int size);
+ DirectDrawSurface(unsigned char *mem, uint size);
~DirectDrawSurface();
bool isValid() const;
bool isSupported() const;
- unsigned int mipmapCount() const;
- unsigned int width() const;
- unsigned int height() const;
- unsigned int depth() const;
+ uint mipmapCount() const;
+ uint width() const;
+ uint height() const;
+ uint depth() const;
+ bool isTexture1D() const;
bool isTexture2D() const;
bool isTexture3D() const;
bool isTextureCube() const;
- bool hasAlpha() const; /* false for DXT1, true for all others */
+
+ void setNormalFlag(bool b);
+
+ bool hasAlpha() const; /* false for DXT1, true for all other DXTs */
- void mipmap(Image * img, unsigned int f, unsigned int m);
+ void mipmap(Image * img, uint f, uint m);
+ // void mipmap(FloatImage * img, uint f, uint m);
void printInfo() const;
private:
- unsigned int blockSize() const;
- unsigned int faceSize() const;
- unsigned int mipmapSize(unsigned int m) const;
+ uint blockSize() const;
+ uint faceSize() const;
+ uint mipmapSize(uint m) const;
- unsigned int offset(unsigned int f, unsigned int m);
+ uint offset(uint f, uint m);
void readLinearImage(Image * img);
void readBlockImage(Image * img);
@@ -155,5 +177,6 @@ private:
void mem_read(Stream & mem, DDSPixelFormat & pf);
void mem_read(Stream & mem, DDSCaps & caps);
void mem_read(Stream & mem, DDSHeader & header);
+void mem_read(Stream & mem, DDSHeader10 & header);
#endif // _DDS_DIRECTDRAWSURFACE_H
diff --git a/source/blender/imbuf/intern/dds/Image.cpp b/source/blender/imbuf/intern/dds/Image.cpp
index 6a751591f3e..8f6ac8658ba 100644
--- a/source/blender/imbuf/intern/dds/Image.cpp
+++ b/source/blender/imbuf/intern/dds/Image.cpp
@@ -45,7 +45,7 @@ Image::~Image()
free();
}
-void Image::allocate(unsigned int w, unsigned int h)
+void Image::allocate(uint w, uint h)
{
free();
m_width = w;
@@ -60,17 +60,17 @@ void Image::free()
}
-unsigned int Image::width() const
+uint Image::width() const
{
return m_width;
}
-unsigned int Image::height() const
+uint Image::height() const
{
return m_height;
}
-const Color32 * Image::scanline(unsigned int h) const
+const Color32 * Image::scanline(uint h) const
{
if (h >= m_height) {
printf("DDS: scanline beyond dimensions of image");
@@ -79,7 +79,7 @@ const Color32 * Image::scanline(unsigned int h) const
return m_data + h * m_width;
}
-Color32 * Image::scanline(unsigned int h)
+Color32 * Image::scanline(uint h)
{
if (h >= m_height) {
printf("DDS: scanline beyond dimensions of image");
@@ -98,7 +98,7 @@ Color32 * Image::pixels()
return m_data;
}
-const Color32 & Image::pixel(unsigned int idx) const
+const Color32 & Image::pixel(uint idx) const
{
if (idx >= m_width * m_height) {
printf("DDS: pixel beyond dimensions of image");
@@ -107,7 +107,7 @@ const Color32 & Image::pixel(unsigned int idx) const
return m_data[idx];
}
-Color32 & Image::pixel(unsigned int idx)
+Color32 & Image::pixel(uint idx)
{
if (idx >= m_width * m_height) {
printf("DDS: pixel beyond dimensions of image");
diff --git a/source/blender/imbuf/intern/dds/Image.h b/source/blender/imbuf/intern/dds/Image.h
index 3a656995857..f2ff9e4fbf3 100644
--- a/source/blender/imbuf/intern/dds/Image.h
+++ b/source/blender/imbuf/intern/dds/Image.h
@@ -34,6 +34,7 @@
#ifndef _DDS_IMAGE_H
#define _DDS_IMAGE_H
+#include <Common.h>
#include <Color.h>
/// 32 bit RGBA image.
@@ -50,28 +51,28 @@ public:
Image();
~Image();
- void allocate(unsigned int w, unsigned int h);
+ void allocate(uint w, uint h);
/*
bool load(const char * name);
- void wrap(void * data, unsigned int w, unsigned int h);
+ void wrap(void * data, uint w, uint h);
void unwrap();
*/
- unsigned int width() const;
- unsigned int height() const;
+ uint width() const;
+ uint height() const;
- const Color32 * scanline(unsigned int h) const;
- Color32 * scanline(unsigned int h);
+ const Color32 * scanline(uint h) const;
+ Color32 * scanline(uint h);
const Color32 * pixels() const;
Color32 * pixels();
- const Color32 & pixel(unsigned int idx) const;
- Color32 & pixel(unsigned int idx);
+ const Color32 & pixel(uint idx) const;
+ Color32 & pixel(uint idx);
- const Color32 & pixel(unsigned int x, unsigned int y) const;
- Color32 & pixel(unsigned int x, unsigned int y);
+ const Color32 & pixel(uint x, uint y) const;
+ Color32 & pixel(uint x, uint y);
Format format() const;
void setFormat(Format f);
@@ -80,19 +81,19 @@ private:
void free();
private:
- unsigned int m_width;
- unsigned int m_height;
+ uint m_width;
+ uint m_height;
Format m_format;
Color32 * m_data;
};
-inline const Color32 & Image::pixel(unsigned int x, unsigned int y) const
+inline const Color32 & Image::pixel(uint x, uint y) const
{
return pixel(y * width() + x);
}
-inline Color32 & Image::pixel(unsigned int x, unsigned int y)
+inline Color32 & Image::pixel(uint x, uint y)
{
return pixel(y * width() + x);
}
diff --git a/source/blender/imbuf/intern/dds/PixelFormat.h b/source/blender/imbuf/intern/dds/PixelFormat.h
new file mode 100644
index 00000000000..2004d689a3e
--- /dev/null
+++ b/source/blender/imbuf/intern/dds/PixelFormat.h
@@ -0,0 +1,107 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * Contributors: Amorilia (amorilia@gamebox.net)
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/*
+ * This file is based on a similar file from the NVIDIA texture tools
+ * (http://nvidia-texture-tools.googlecode.com/)
+ *
+ * Original license from NVIDIA follows.
+ */
+
+// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com>
+//
+// Permission is hereby granted, free of charge, to any person
+// obtaining a copy of this software and associated documentation
+// files (the "Software"), to deal in the Software without
+// restriction, including without limitation the rights to use,
+// copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the
+// Software is furnished to do so, subject to the following
+// conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+// OTHER DEALINGS IN THE SOFTWARE.
+
+#ifndef _DDS_PIXELFORMAT_H
+#define _DDS_PIXELFORMAT_H
+
+#include <Common.h>
+
+ namespace PixelFormat
+ {
+
+ // Convert component @a c having @a inbits to the returned value having @a outbits.
+ inline uint convert(uint c, uint inbits, uint outbits)
+ {
+ if (inbits == 0)
+ {
+ return 0;
+ }
+ else if (inbits >= outbits)
+ {
+ // truncate
+ return c >> (inbits - outbits);
+ }
+ else
+ {
+ // bitexpand
+ return (c << (outbits - inbits)) | convert(c, inbits, outbits - inbits);
+ }
+ }
+
+ // Get pixel component shift and size given its mask.
+ inline void maskShiftAndSize(uint mask, uint * shift, uint * size)
+ {
+ if (!mask)
+ {
+ *shift = 0;
+ *size = 0;
+ return;
+ }
+
+ *shift = 0;
+ while((mask & 1) == 0) {
+ ++(*shift);
+ mask >>= 1;
+ }
+
+ *size = 0;
+ while((mask & 1) == 1) {
+ ++(*size);
+ mask >>= 1;
+ }
+ }
+
+ } // PixelFormat namespace
+
+#endif // _DDS_IMAGE_PIXELFORMAT_H
diff --git a/source/blender/imbuf/intern/dds/dds_api.cpp b/source/blender/imbuf/intern/dds/dds_api.cpp
index b41b940dca7..cf2f6c16d08 100644
--- a/source/blender/imbuf/intern/dds/dds_api.cpp
+++ b/source/blender/imbuf/intern/dds/dds_api.cpp
@@ -94,6 +94,7 @@ struct ImBuf *imb_load_dds(unsigned char *mem, int size, int flags)
}
/* convert DDS into ImBuf */
+ // TODO use the image RGB or RGBA tag to determine the bits per pixel
if (dds.hasAlpha()) bits_per_pixel = 32;
else bits_per_pixel = 24;
ibuf = IMB_allocImBuf(dds.width(), dds.height(), bits_per_pixel, 0, 0);
diff --git a/source/blender/imbuf/intern/divers.c b/source/blender/imbuf/intern/divers.c
index 84588b52573..8043e594454 100644
--- a/source/blender/imbuf/intern/divers.c
+++ b/source/blender/imbuf/intern/divers.c
@@ -38,6 +38,7 @@
#include "IMB_imbuf.h"
#include "IMB_allocimbuf.h"
#include "IMB_divers.h"
+#include "BKE_utildefines.h"
void imb_checkncols(struct ImBuf *ibuf)
{
@@ -171,7 +172,6 @@ void IMB_gamwarp(struct ImBuf *ibuf, double gamma)
}
}
-#define FTOCHAR(val) val<=0.0f?0: (val>=1.0f?255: (char)(255.99f*val))
void IMB_rect_from_float(struct ImBuf *ibuf)
{
diff --git a/source/blender/imbuf/intern/dynlibtiff.c b/source/blender/imbuf/intern/dynlibtiff.c
index d2ca19e8282..b9186e482c5 100644
--- a/source/blender/imbuf/intern/dynlibtiff.c
+++ b/source/blender/imbuf/intern/dynlibtiff.c
@@ -80,13 +80,19 @@ void libtiff_loadlibtiff(void)
/* Try to find libtiff in a couple of standard places */
libtiff = PIL_dynlib_open("libtiff.so");
if (libtiff != NULL) return;
+ libtiff = PIL_dynlib_open("libtiff.so.3");
+ if (libtiff != NULL) return;
libtiff = PIL_dynlib_open("libtiff.dll");
if (libtiff != NULL) return;
libtiff = PIL_dynlib_open("/usr/lib/libtiff.so");
if (libtiff != NULL) return;
- /* OSX has version specific library */
libtiff = PIL_dynlib_open("/usr/lib/libtiff.so.3");
if (libtiff != NULL) return;
+ /* OSX has version specific library */
+#ifdef __x86_64__
+ libtiff = PIL_dynlib_open("/usr/lib64/libtiff.so.3");
+ if (libtiff != NULL) return;
+#endif
libtiff = PIL_dynlib_open("/usr/local/lib/libtiff.so");
if (libtiff != NULL) return;
/* For solaris */
@@ -100,8 +106,11 @@ void *libtiff_findsymbol(char *name)
assert(libtiff != NULL);
symbol = PIL_dynlib_find_symbol(libtiff, name);
if (symbol == NULL) {
- printf("libtiff_findsymbol: error %s\n",
- PIL_dynlib_get_error_as_string(libtiff));
+ char *err = PIL_dynlib_get_error_as_string(libtiff);
+
+ if (err) printf("libtiff_findsymbol: error %s\n",err);
+ else printf("libtiff_findsymbol: error Unknown.\n");
+
libtiff = NULL;
G.have_libtiff = (0);
return NULL;
diff --git a/source/blender/imbuf/intern/filter.c b/source/blender/imbuf/intern/filter.c
index fda79315268..9802405fd8d 100644
--- a/source/blender/imbuf/intern/filter.c
+++ b/source/blender/imbuf/intern/filter.c
@@ -203,29 +203,46 @@ void imb_filterx(struct ImBuf *ibuf)
void IMB_filterN(ImBuf *out, ImBuf *in)
{
register char *row1, *row2, *row3;
- register char *cp;
+ register char *cp, *r11, *r13, *r21, *r23, *r31, *r33;
int rowlen, x, y;
rowlen= in->x;
- for(y=2; y<in->y; y++) {
+ for(y=0; y<in->y; y++) {
/* setup rows */
- row1= (char *)(in->rect + (y-2)*rowlen);
- row2= row1 + 4*rowlen;
- row3= row2 + 4*rowlen;
+ row2= (char*)(in->rect + y*rowlen);
+ row1= (y == 0)? row2: row2 - 4*rowlen;
+ row3= (y == in->y-1)? row2: row2 + 4*rowlen;
- cp= (char *)(out->rect + (y-1)*rowlen);
- cp[0]= row2[0];
- cp[1]= row2[1];
- cp[2]= row2[2];
- cp[3]= row2[3];
- cp+= 4;
+ cp= (char *)(out->rect + y*rowlen);
- for(x=2; x<rowlen; x++) {
- cp[0]= (row1[0] + 2*row1[4] + row1[8] + 2*row2[0] + 4*row2[4] + 2*row2[8] + row3[0] + 2*row3[4] + row3[8])>>4;
- cp[1]= (row1[1] + 2*row1[5] + row1[9] + 2*row2[1] + 4*row2[5] + 2*row2[9] + row3[1] + 2*row3[5] + row3[9])>>4;
- cp[2]= (row1[2] + 2*row1[6] + row1[10] + 2*row2[2] + 4*row2[6] + 2*row2[10] + row3[2] + 2*row3[6] + row3[10])>>4;
- cp[3]= (row1[3] + 2*row1[7] + row1[11] + 2*row2[3] + 4*row2[7] + 2*row2[11] + row3[3] + 2*row3[7] + row3[11])>>4;
+ for(x=0; x<rowlen; x++) {
+ if(x == 0) {
+ r11 = row1;
+ r21 = row1;
+ r31 = row1;
+ }
+ else {
+ r11 = row1-4;
+ r21 = row1-4;
+ r31 = row1-4;
+ }
+
+ if(x == rowlen-1) {
+ r13 = row1;
+ r23 = row1;
+ r33 = row1;
+ }
+ else {
+ r13 = row1+4;
+ r23 = row1+4;
+ r33 = row1+4;
+ }
+
+ cp[0]= (r11[0] + 2*row1[0] + r13[0] + 2*r21[0] + 4*row2[0] + 2*r23[0] + r31[0] + 2*row3[0] + r33[0])>>4;
+ cp[1]= (r11[1] + 2*row1[1] + r13[1] + 2*r21[1] + 4*row2[1] + 2*r23[1] + r31[1] + 2*row3[1] + r33[1])>>4;
+ cp[2]= (r11[2] + 2*row1[2] + r13[2] + 2*r21[2] + 4*row2[2] + 2*r23[2] + r31[2] + 2*row3[2] + r33[2])>>4;
+ cp[3]= (r11[3] + 2*row1[3] + r13[3] + 2*r21[3] + 4*row2[3] + 2*r23[3] + r31[3] + 2*row3[3] + r33[3])>>4;
cp+=4; row1+=4; row2+=4; row3+=4;
}
}
@@ -237,18 +254,72 @@ void IMB_filter(struct ImBuf *ibuf)
imb_filterx(ibuf);
}
-#define EXTEND_PIXEL(a, w) if((a)[3]) {r+= w*(a)[0]; g+= w*(a)[1]; b+= w*(a)[2]; tot+=w;}
+#define EXTEND_PIXEL(color, w) if((color)[3]) {r+= w*(color)[0]; g+= w*(color)[1]; b+= w*(color)[2]; a+= w*(color)[3]; tot+=w;}
-/* if alpha is zero, it checks surrounding pixels and averages color. sets new alphas to 255 */
-void IMB_filter_extend(struct ImBuf *ibuf)
+/* if alpha is zero, it checks surrounding pixels and averages color. sets new alphas to 1.0
+ *
+ * When a mask is given, only effect pixels with a mask value of 1, defined as BAKE_MASK_MARGIN in rendercore.c
+ * */
+void IMB_filter_extend(struct ImBuf *ibuf, char *mask)
{
register char *row1, *row2, *row3;
- register char *cp;
+ register char *cp;
int rowlen, x, y;
rowlen= ibuf->x;
- if(ibuf->rect) {
+
+ if (ibuf->rect_float) {
+ float *temprect;
+ float *row1f, *row2f, *row3f;
+ float *fp;
+ temprect= MEM_dupallocN(ibuf->rect_float);
+
+ for(y=1; y<=ibuf->y; y++) {
+ /* setup rows */
+ row1f= (float *)(temprect + (y-2)*rowlen*4);
+ row2f= row1f + 4*rowlen;
+ row3f= row2f + 4*rowlen;
+ if(y==1)
+ row1f= row2f;
+ else if(y==ibuf->y)
+ row3f= row2f;
+
+ fp= (float *)(ibuf->rect_float + (y-1)*rowlen*4);
+
+ for(x=0; x<rowlen; x++) {
+ if((mask==NULL && fp[3]==0.0f) || (mask && mask[((y-1)*rowlen)+x]==1)) {
+ int tot= 0;
+ float r=0.0f, g=0.0f, b=0.0f, a=0.0f;
+
+ EXTEND_PIXEL(row1f, 1);
+ EXTEND_PIXEL(row2f, 2);
+ EXTEND_PIXEL(row3f, 1);
+ EXTEND_PIXEL(row1f+4, 2);
+ EXTEND_PIXEL(row3f+4, 2);
+ if(x!=rowlen-1) {
+ EXTEND_PIXEL(row1f+8, 1);
+ EXTEND_PIXEL(row2f+8, 2);
+ EXTEND_PIXEL(row3f+8, 1);
+ }
+ if(tot) {
+ fp[0]= r/tot;
+ fp[1]= g/tot;
+ fp[2]= b/tot;
+ fp[3]= a/tot;
+ }
+ }
+ fp+=4;
+
+ if(x!=0) {
+ row1f+=4; row2f+=4; row3f+=4;
+ }
+ }
+ }
+
+ MEM_freeN(temprect);
+ }
+ else if(ibuf->rect) {
int *temprect;
/* make a copy, to prevent flooding */
@@ -267,8 +338,9 @@ void IMB_filter_extend(struct ImBuf *ibuf)
cp= (char *)(ibuf->rect + (y-1)*rowlen);
for(x=0; x<rowlen; x++) {
- if(cp[3]==0) {
- int tot= 0, r=0, g=0, b=0;
+ /*if(cp[3]==0) {*/
+ if((mask==NULL && cp[3]==0) || (mask && mask[((y-1)*rowlen)+x]==1)) {
+ int tot= 0, r=0, g=0, b=0, a=0;
EXTEND_PIXEL(row1, 1);
EXTEND_PIXEL(row2, 2);
@@ -284,10 +356,10 @@ void IMB_filter_extend(struct ImBuf *ibuf)
cp[0]= r/tot;
cp[1]= g/tot;
cp[2]= b/tot;
- cp[3]= 255;
+ cp[3]= a/tot;
}
}
- cp+=4;
+ cp+=4;
if(x!=0) {
row1+=4; row2+=4; row3+=4;
diff --git a/source/blender/imbuf/intern/gen_dynlibtiff.py b/source/blender/imbuf/intern/gen_dynlibtiff.py
index 9cd6b638658..4dba5b13aa0 100755
--- a/source/blender/imbuf/intern/gen_dynlibtiff.py
+++ b/source/blender/imbuf/intern/gen_dynlibtiff.py
@@ -119,13 +119,19 @@ void libtiff_loadlibtiff(void)
/* Try to find libtiff in a couple of standard places */
libtiff = PIL_dynlib_open("libtiff.so");
if (libtiff != NULL) return;
+ libtiff = PIL_dynlib_open("libtiff.so.3");
+ if (libtiff != NULL) return;
libtiff = PIL_dynlib_open("libtiff.dll");
if (libtiff != NULL) return;
libtiff = PIL_dynlib_open("/usr/lib/libtiff.so");
if (libtiff != NULL) return;
- /* OSX has version specific library */
libtiff = PIL_dynlib_open("/usr/lib/libtiff.so.3");
if (libtiff != NULL) return;
+ /* OSX has version specific library */
+#ifdef __x86_64__
+ libtiff = PIL_dynlib_open("/usr/lib64/libtiff.so.3");
+ if (libtiff != NULL) return;
+#endif
libtiff = PIL_dynlib_open("/usr/local/lib/libtiff.so");
if (libtiff != NULL) return;
/* For solaris */
diff --git a/source/blender/imbuf/intern/hamx.c b/source/blender/imbuf/intern/hamx.c
index 8db21fc64f1..2f32d155407 100644
--- a/source/blender/imbuf/intern/hamx.c
+++ b/source/blender/imbuf/intern/hamx.c
@@ -53,7 +53,7 @@
#define SWAP_S(x) (((x << 8) & 0xff00) | ((x >> 8) & 0xff))
/* more endianness... should move to a separate file... */
-#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
+#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__hppa__) || defined (__BIG_ENDIAN__)
#define GET_ID GET_BIG_LONG
#define LITTLE_LONG SWAP_LONG
#else
diff --git a/source/blender/imbuf/intern/imageprocess.c b/source/blender/imbuf/intern/imageprocess.c
index 4890e240c6b..d7f1ab4419d 100644
--- a/source/blender/imbuf/intern/imageprocess.c
+++ b/source/blender/imbuf/intern/imageprocess.c
@@ -48,22 +48,28 @@ I stole it from util.h in the plugins api */
/* Only this one is used liberally here, and in imbuf */
void IMB_convert_rgba_to_abgr(struct ImBuf *ibuf)
{
- int size, do_float=0;
+ int size;
unsigned char rt, *cp = (unsigned char *)ibuf->rect;
float rtf, *cpf = ibuf->rect_float;
-
- if (ibuf->rect_float) do_float = 1;
- size = ibuf->x * ibuf->y;
- while(size-- > 0) {
- rt= cp[0];
- cp[0]= cp[3];
- cp[3]= rt;
- rt= cp[1];
- cp[1]= cp[2];
- cp[2]= rt;
- cp+= 4;
- if (do_float) {
+ if (ibuf->rect) {
+ size = ibuf->x * ibuf->y;
+
+ while(size-- > 0) {
+ rt= cp[0];
+ cp[0]= cp[3];
+ cp[3]= rt;
+ rt= cp[1];
+ cp[1]= cp[2];
+ cp[2]= rt;
+ cp+= 4;
+ }
+ }
+
+ if (ibuf->rect_float) {
+ size = ibuf->x * ibuf->y;
+
+ while(size-- > 0) {
rtf= cpf[0];
cpf[0]= cpf[3];
cpf[3]= rtf;
@@ -87,16 +93,14 @@ void IMB_convert_rgba_to_abgr(struct ImBuf *ibuf)
*/
/* function assumes out to be zero'ed, only does RGBA */
static float P(float k){
- float aux;
- aux=(float)(1.0f/6.0f)*( pow( MAX2(k+2.0f,0) , 3.0f ) - 4.0f * pow( MAX2(k+1.0f,0) , 3.0f ) + 6.0f * pow( MAX2(k,0) , 3.0f ) - 4.0f * pow( MAX2(k-1.0f,0) , 3.0f));
- return aux ;
+ return (float)(1.0f/6.0f)*( pow( MAX2(k+2.0f,0) , 3.0f ) - 4.0f * pow( MAX2(k+1.0f,0) , 3.0f ) + 6.0f * pow( MAX2(k,0) , 3.0f ) - 4.0f * pow( MAX2(k-1.0f,0) , 3.0f));
}
void bicubic_interpolation(ImBuf *in, ImBuf *out, float x, float y, int xout, int yout)
{
int i,j,n,m,x1,y1;
unsigned char *dataI,*outI;
- float a,b, outR,outG,outB,outA,*dataF,*outF;
+ float a,b,w,wx,wy[4], outR,outG,outB,outA,*dataF,*outF;
int do_rect, do_float;
if (in == NULL) return;
@@ -114,24 +118,39 @@ void bicubic_interpolation(ImBuf *in, ImBuf *out, float x, float y, int xout, in
outG= 0.0f;
outB= 0.0f;
outA= 0.0f;
+
+ /* avoid calling multiple times */
+ wy[0] = P(b-(-1));
+ wy[1] = P(b- 0);
+ wy[2] = P(b- 1);
+ wy[3] = P(b- 2);
+
for(n= -1; n<= 2; n++){
- for(m= -1; m<= 2; m++){
- x1= i+n;
- y1= j+m;
- if (x1>0 && x1 < in->x && y1>0 && y1<in->y) {
- if (do_float) {
- dataF= in->rect_float + in->x * y1 * 4 + 4*x1;
- outR+= dataF[0] * P(n-a) * P(b-m);
- outG+= dataF[1] * P(n-a) * P(b-m);
- outB+= dataF[2] * P(n-a) * P(b-m);
- outA+= dataF[3] * P(n-a) * P(b-m);
- }
- if (do_rect) {
- dataI= (unsigned char*)in->rect + in->x * y1 * 4 + 4*x1;
- outR+= dataI[0] * P(n-a) * P(b-m);
- outG+= dataI[1] * P(n-a) * P(b-m);
- outB+= dataI[2] * P(n-a) * P(b-m);
- outA+= dataI[3] * P(n-a) * P(b-m);
+ x1= i+n;
+ if (x1>0 && x1 < in->x) {
+ wx = P(n-a);
+ for(m= -1; m<= 2; m++){
+ y1= j+m;
+ if (y1>0 && y1<in->y) {
+ /* normally we could do this */
+ /* w = P(n-a) * P(b-m); */
+ /* except that would call P() 16 times per pixel therefor pow() 64 times, better precalc these */
+ w = wx * wy[m+1];
+
+ if (do_float) {
+ dataF= in->rect_float + in->x * y1 * 4 + 4*x1;
+ outR+= dataF[0] * w;
+ outG+= dataF[1] * w;
+ outB+= dataF[2] * w;
+ outA+= dataF[3] * w;
+ }
+ if (do_rect) {
+ dataI= (unsigned char*)in->rect + in->x * y1 * 4 + 4*x1;
+ outR+= dataI[0] * w;
+ outG+= dataI[1] * w;
+ outB+= dataI[2] * w;
+ outA+= dataI[3] * w;
+ }
}
}
}
diff --git a/source/blender/imbuf/intern/imbuf.h b/source/blender/imbuf/intern/imbuf.h
index 9bdcd278f66..bd2a0d3082f 100644
--- a/source/blender/imbuf/intern/imbuf.h
+++ b/source/blender/imbuf/intern/imbuf.h
@@ -60,7 +60,7 @@
#define ENDIAN_NOP(x) (x)
-#if defined(__sgi) || defined(__sparc) || defined(__sparc__) || defined (__PPC__) || (defined (__APPLE__) && !defined(__LITTLE_ENDIAN__))
+#if defined(__sgi) || defined(__sparc) || defined(__sparc__) || defined (__PPC__) || defined (__hppa__) || (defined (__APPLE__) && !defined(__LITTLE_ENDIAN__))
#define LITTLE_SHORT SWAP_SHORT
#define LITTLE_LONG SWAP_LONG
#define BIG_SHORT ENDIAN_NOP
diff --git a/source/blender/imbuf/intern/imbuf_patch.h b/source/blender/imbuf/intern/imbuf_patch.h
index 0405ce7bc05..cdd6048f1ad 100644
--- a/source/blender/imbuf/intern/imbuf_patch.h
+++ b/source/blender/imbuf/intern/imbuf_patch.h
@@ -50,7 +50,7 @@ typedef unsigned char uchar;
/* Endianness: flip the byte order. It's strange that this is needed..
* After all, there is an internal endian.{c,h}... */
-#if defined(__sgi) || defined (__sparc) || defined(__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
+#if defined(__sgi) || defined (__sparc) || defined(__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__hppa__) || defined (__BIG_ENDIAN__)
#define MAKE_ID(a,b,c,d) ( (int)(a)<<24 | (int)(b)<<16 | (c)<<8 | (d) )
#else
#define MAKE_ID(a,b,c,d) ( (int)(d)<<24 | (int)(c)<<16 | (b)<<8 | (a) )
diff --git a/source/blender/imbuf/intern/openexr/openexr_api.cpp b/source/blender/imbuf/intern/openexr/openexr_api.cpp
index 3cbada812b9..3e618a483e3 100644
--- a/source/blender/imbuf/intern/openexr/openexr_api.cpp
+++ b/source/blender/imbuf/intern/openexr/openexr_api.cpp
@@ -180,7 +180,7 @@ static void openexr_header_compression(Header *header, int compression)
static short imb_save_openexr_half(struct ImBuf *ibuf, char *name, int flags)
{
-
+ int channels = ibuf->channels;
int width = ibuf->x;
int height = ibuf->y;
int write_zbuf = (flags & IB_zbuffloat) && ibuf->zbuf_float != NULL; // summarize
@@ -194,7 +194,7 @@ static short imb_save_openexr_half(struct ImBuf *ibuf, char *name, int flags)
header.channels().insert ("R", Channel (HALF));
header.channels().insert ("G", Channel (HALF));
header.channels().insert ("B", Channel (HALF));
- if (ibuf->depth==32)
+ if (ibuf->depth==32 && channels >= 4)
header.channels().insert ("A", Channel (HALF));
if (write_zbuf) // z we do as float always
header.channels().insert ("Z", Channel (FLOAT));
@@ -207,29 +207,29 @@ static short imb_save_openexr_half(struct ImBuf *ibuf, char *name, int flags)
RGBAZ *to = pixels;
int xstride= sizeof (RGBAZ);
int ystride= xstride*width;
-
+
/* indicate used buffers */
frameBuffer.insert ("R", Slice (HALF, (char *) &pixels[0].r, xstride, ystride));
frameBuffer.insert ("G", Slice (HALF, (char *) &pixels[0].g, xstride, ystride));
frameBuffer.insert ("B", Slice (HALF, (char *) &pixels[0].b, xstride, ystride));
- if (ibuf->depth==32)
+ if (ibuf->depth==32 && channels >= 4)
frameBuffer.insert ("A", Slice (HALF, (char *) &pixels[0].a, xstride, ystride));
if (write_zbuf)
- frameBuffer.insert ("Z", Slice (FLOAT, (char *) ibuf->zbuf_float + 4*(height-1)*width,
+ frameBuffer.insert ("Z", Slice (FLOAT, (char *)(ibuf->zbuf_float + (height-1)*width),
sizeof(float), sizeof(float) * -width));
if(ibuf->rect_float) {
float *from;
for (int i = ibuf->y-1; i >= 0; i--)
{
- from= ibuf->rect_float + 4*i*width;
+ from= ibuf->rect_float + channels*i*width;
for (int j = ibuf->x; j > 0; j--)
{
to->r = from[0];
- to->g = from[1];
- to->b = from[2];
- to->a = from[3];
+ to->g = (channels >= 2)? from[1]: from[0];
+ to->b = (channels >= 3)? from[2]: from[0];
+ to->a = (channels >= 4)? from[3]: from[0];
to++; from += 4;
}
}
@@ -239,14 +239,14 @@ static short imb_save_openexr_half(struct ImBuf *ibuf, char *name, int flags)
for (int i = ibuf->y-1; i >= 0; i--)
{
- from= (unsigned char *)(ibuf->rect + i*width);
+ from= (unsigned char *)ibuf->rect + channels*i*width;
for (int j = ibuf->x; j > 0; j--)
{
to->r = (float)(from[0])/255.0;
- to->g = (float)(from[1])/255.0;
- to->b = (float)(from[2])/255.0;
- to->a = (float)(from[3])/255.0;
+ to->g = (float)((channels >= 2)? from[1]: from[0])/255.0;
+ to->b = (float)((channels >= 3)? from[2]: from[0])/255.0;
+ to->a = (float)((channels >= 4)? from[3]: from[0])/255.0;
to++; from += 4;
}
}
@@ -272,7 +272,7 @@ static short imb_save_openexr_half(struct ImBuf *ibuf, char *name, int flags)
static short imb_save_openexr_float(struct ImBuf *ibuf, char *name, int flags)
{
-
+ int channels = ibuf->channels;
int width = ibuf->x;
int height = ibuf->y;
int write_zbuf = (flags & IB_zbuffloat) && ibuf->zbuf_float != NULL; // summarize
@@ -286,24 +286,29 @@ static short imb_save_openexr_float(struct ImBuf *ibuf, char *name, int flags)
header.channels().insert ("R", Channel (FLOAT));
header.channels().insert ("G", Channel (FLOAT));
header.channels().insert ("B", Channel (FLOAT));
- if (ibuf->depth==32)
+ if (ibuf->depth==32 && channels >= 4)
header.channels().insert ("A", Channel (FLOAT));
if (write_zbuf)
header.channels().insert ("Z", Channel (FLOAT));
FrameBuffer frameBuffer;
OutputFile *file = new OutputFile(name, header);
- float *first= ibuf->rect_float + 4*(height-1)*width;
- int xstride = sizeof(float) * 4;
+ int xstride = sizeof(float) * channels;
int ystride = - xstride*width;
-
- frameBuffer.insert ("R", Slice (FLOAT, (char *) first, xstride, ystride));
- frameBuffer.insert ("G", Slice (FLOAT, (char *) (first+1), xstride, ystride));
- frameBuffer.insert ("B", Slice (FLOAT, (char *) (first+2), xstride, ystride));
- if (ibuf->depth==32)
- frameBuffer.insert ("A", Slice (FLOAT, (char *) (first+3), xstride, ystride));
+ float *rect[4] = {NULL, NULL, NULL, NULL};
+
+ rect[0]= ibuf->rect_float + channels*(height-1)*width;
+ rect[1]= (channels >= 2)? rect[0]+1: rect[0];
+ rect[2]= (channels >= 3)? rect[0]+2: rect[0];
+ rect[3]= (channels >= 4)? rect[0]+3: rect[0];
+
+ frameBuffer.insert ("R", Slice (FLOAT, (char *)rect[0], xstride, ystride));
+ frameBuffer.insert ("G", Slice (FLOAT, (char *)rect[1], xstride, ystride));
+ frameBuffer.insert ("B", Slice (FLOAT, (char *)rect[2], xstride, ystride));
+ if (ibuf->depth==32 && channels >= 4)
+ frameBuffer.insert ("A", Slice (FLOAT, (char *)rect[3], xstride, ystride));
if (write_zbuf)
- frameBuffer.insert ("Z", Slice (FLOAT, (char *) ibuf->zbuf_float + 4*(height-1)*width,
+ frameBuffer.insert ("Z", Slice (FLOAT, (char *) (ibuf->zbuf_float + (height-1)*width),
sizeof(float), sizeof(float) * -width));
file->setFrameBuffer (frameBuffer);
file->writePixels (height);
@@ -362,6 +367,7 @@ typedef struct ExrHandle {
OutputFile *ofile;
int tilex, tiley;
int width, height;
+ int mipmap;
ListBase channels; /* flattened out, ExrChannel */
ListBase layers; /* hierarchical, pointing in end to ExrChannel */
@@ -445,12 +451,12 @@ void IMB_exr_begin_write(void *handle, char *filename, int width, int height, in
openexr_header_compression(&header, compress);
/* header.lineOrder() = DECREASING_Y; this crashes in windows for file read! */
- header.insert ("BlenderMultiChannel", StringAttribute ("Blender V2.43"));
+ header.insert ("BlenderMultiChannel", StringAttribute ("Blender V2.43 and newer"));
data->ofile = new OutputFile(filename, header);
}
-void IMB_exrtile_begin_write(void *handle, char *filename, int width, int height, int tilex, int tiley)
+void IMB_exrtile_begin_write(void *handle, char *filename, int mipmap, int width, int height, int tilex, int tiley)
{
ExrHandle *data= (ExrHandle *)handle;
Header header (width, height);
@@ -460,11 +466,12 @@ void IMB_exrtile_begin_write(void *handle, char *filename, int width, int height
data->tiley= tiley;
data->width= width;
data->height= height;
+ data->mipmap= mipmap;
for(echan= (ExrChannel *)data->channels.first; echan; echan= echan->next)
header.channels().insert (echan->name, Channel (FLOAT));
- header.setTileDescription (TileDescription (tilex, tiley, ONE_LEVEL));
+ header.setTileDescription (TileDescription (tilex, tiley, (mipmap)? MIPMAP_LEVELS: ONE_LEVEL));
header.lineOrder() = RANDOM_Y;
header.compression() = RLE_COMPRESSION;
@@ -478,7 +485,7 @@ int IMB_exr_begin_read(void *handle, char *filename, int *width, int *height)
{
ExrHandle *data= (ExrHandle *)handle;
- if(BLI_exists(filename)) {
+ if(BLI_exists(filename) && BLI_filepathsize(filename)>32) { /* 32 is arbitrary, but zero length files crashes exr */
data->ifile = new InputFile(filename);
if(data->ifile) {
Box2i dw = data->ifile->header().dataWindow();
@@ -533,7 +540,7 @@ void IMB_exrtile_clear_channels(void *handle)
BLI_freelistN(&data->channels);
}
-void IMB_exrtile_write_channels(void *handle, int partx, int party)
+void IMB_exrtile_write_channels(void *handle, int partx, int party, int level)
{
ExrHandle *data= (ExrHandle *)handle;
FrameBuffer frameBuffer;
@@ -547,9 +554,14 @@ void IMB_exrtile_write_channels(void *handle, int partx, int party)
}
data->tofile->setFrameBuffer (frameBuffer);
- // printf("write tile %d %d\n", partx/data->tilex, party/data->tiley);
- data->tofile->writeTile (partx/data->tilex, party/data->tiley);
-
+
+ try {
+ // printf("write tile %d %d\n", partx/data->tilex, party/data->tiley);
+ data->tofile->writeTile (partx/data->tilex, party/data->tiley, level);
+ }
+ catch (const std::exception &exc) {
+ std::cerr << "OpenEXR-writeTile: ERROR: " << exc.what() << std::endl;
+ }
}
void IMB_exr_write_channels(void *handle)
@@ -615,7 +627,6 @@ void IMB_exr_multilayer_convert(void *handle, void *base,
void IMB_exr_close(void *handle)
{
ExrHandle *data= (ExrHandle *)handle;
- ExrChannel *echan;
ExrLayer *lay;
ExrPass *pass;
@@ -778,28 +789,28 @@ static ExrHandle *imb_exr_begin_read_mem(InputFile *file, int width, int height)
/* we can have RGB(A), XYZ(W), UVA */
if(pass->totchan==3 || pass->totchan==4) {
if(pass->chan[0]->chan_id=='B' || pass->chan[1]->chan_id=='B' || pass->chan[2]->chan_id=='B') {
- lookup['R']= 0;
- lookup['G']= 1;
- lookup['B']= 2;
- lookup['A']= 3;
+ lookup[(unsigned int)'R']= 0;
+ lookup[(unsigned int)'G']= 1;
+ lookup[(unsigned int)'B']= 2;
+ lookup[(unsigned int)'A']= 3;
}
else if(pass->chan[0]->chan_id=='Y' || pass->chan[1]->chan_id=='Y' || pass->chan[2]->chan_id=='Y') {
- lookup['X']= 0;
- lookup['Y']= 1;
- lookup['Z']= 2;
- lookup['W']= 3;
+ lookup[(unsigned int)'X']= 0;
+ lookup[(unsigned int)'Y']= 1;
+ lookup[(unsigned int)'Z']= 2;
+ lookup[(unsigned int)'W']= 3;
}
else {
- lookup['U']= 0;
- lookup['V']= 1;
- lookup['A']= 2;
+ lookup[(unsigned int)'U']= 0;
+ lookup[(unsigned int)'V']= 1;
+ lookup[(unsigned int)'A']= 2;
}
for(a=0; a<pass->totchan; a++) {
echan= pass->chan[a];
- echan->rect= pass->rect + lookup[echan->chan_id];
+ echan->rect= pass->rect + lookup[(unsigned int)echan->chan_id];
echan->xstride= pass->totchan;
echan->ystride= width*pass->totchan;
- pass->chan_id[ lookup[echan->chan_id] ]= echan->chan_id;
+ pass->chan_id[ (unsigned int)lookup[(unsigned int)echan->chan_id] ]= echan->chan_id;
}
}
else { /* unknown */
@@ -831,6 +842,7 @@ typedef struct RGBA
} RGBA;
+/* debug only */
static void exr_print_filecontents(InputFile *file)
{
const ChannelList &channels = file->header().channels();
@@ -842,13 +854,33 @@ static void exr_print_filecontents(InputFile *file)
}
}
-static int exr_has_zbuffer(InputFile *file)
+/* for non-multilayer, map R G B A channel names to something that's in this file */
+static const char *exr_rgba_channelname(InputFile *file, const char *chan)
{
const ChannelList &channels = file->header().channels();
for (ChannelList::ConstIterator i = channels.begin(); i != channels.end(); ++i)
{
const Channel &channel = i.channel();
+ const char *str= i.name();
+ int len= strlen(str);
+ if(len) {
+ if(BLI_strcasecmp(chan, str+len-1)==0) {
+ return str;
+ }
+ }
+ }
+ return chan;
+}
+
+
+
+static int exr_has_zbuffer(InputFile *file)
+{
+ const ChannelList &channels = file->header().channels();
+
+ for (ChannelList::ConstIterator i = channels.begin(); i != channels.end(); ++i)
+ {
if(strcmp("Z", i.name())==0)
return 1;
}
@@ -884,7 +916,8 @@ struct ImBuf *imb_load_openexr(unsigned char *mem, int size, int flags)
//printf("OpenEXR-load: image data window %d %d %d %d\n",
// dw.min.x, dw.min.y, dw.max.x, dw.max.y);
- // exr_print_filecontents(file);
+ if(0) // debug
+ exr_print_filecontents(file);
is_multi= exr_is_renderresult(file);
@@ -923,11 +956,15 @@ struct ImBuf *imb_load_openexr(unsigned char *mem, int size, int flags)
/* but, since we read y-flipped (negative y stride) we move to last scanline */
first+= 4*(height-1)*width;
- frameBuffer.insert ("R", Slice (FLOAT, (char *) first, xstride, ystride));
- frameBuffer.insert ("G", Slice (FLOAT, (char *) (first+1), xstride, ystride));
- frameBuffer.insert ("B", Slice (FLOAT, (char *) (first+2), xstride, ystride));
- /* 1.0 is fill value */
- frameBuffer.insert ("A", Slice (FLOAT, (char *) (first+3), xstride, ystride, 1, 1, 1.0f));
+ frameBuffer.insert ( exr_rgba_channelname(file, "R"),
+ Slice (FLOAT, (char *) first, xstride, ystride));
+ frameBuffer.insert ( exr_rgba_channelname(file, "G"),
+ Slice (FLOAT, (char *) (first+1), xstride, ystride));
+ frameBuffer.insert ( exr_rgba_channelname(file, "B"),
+ Slice (FLOAT, (char *) (first+2), xstride, ystride));
+
+ frameBuffer.insert ( exr_rgba_channelname(file, "A"),
+ Slice (FLOAT, (char *) (first+3), xstride, ystride, 1, 1, 1.0f)); /* 1.0 is fill value */
if(exr_has_zbuffer(file))
{
diff --git a/source/blender/imbuf/intern/openexr/openexr_multi.h b/source/blender/imbuf/intern/openexr/openexr_multi.h
index ca4f7405f44..be4d1314a80 100644
--- a/source/blender/imbuf/intern/openexr/openexr_multi.h
+++ b/source/blender/imbuf/intern/openexr/openexr_multi.h
@@ -46,13 +46,13 @@ void IMB_exr_add_channel (void *handle, const char *layname, const char *passn
int IMB_exr_begin_read (void *handle, char *filename, int *width, int *height);
void IMB_exr_begin_write (void *handle, char *filename, int width, int height, int compress);
-void IMB_exrtile_begin_write (void *handle, char *filename, int width, int height, int tilex, int tiley);
+void IMB_exrtile_begin_write (void *handle, char *filename, int mipmap, int width, int height, int tilex, int tiley);
void IMB_exr_set_channel (void *handle, char *layname, char *passname, int xstride, int ystride, float *rect);
void IMB_exr_read_channels (void *handle);
void IMB_exr_write_channels (void *handle);
-void IMB_exrtile_write_channels (void *handle, int partx, int party);
+void IMB_exrtile_write_channels (void *handle, int partx, int party, int level);
void IMB_exrtile_clear_channels (void *handle);
void IMB_exr_multilayer_convert (void *handle, void *base,
@@ -71,13 +71,13 @@ void IMB_exr_add_channel (void *handle, const char *layname, const char *chann
int IMB_exr_begin_read (void *handle, char *filename, int *width, int *height) {return 0;}
void IMB_exr_begin_write (void *handle, char *filename, int width, int height, int compress) {}
-void IMB_exrtile_begin_write (void *handle, char *filename, int width, int height, int tilex, int tiley) {}
+void IMB_exrtile_begin_write (void *handle, char *filename, int mipmap, int width, int height, int tilex, int tiley) {}
void IMB_exr_set_channel (void *handle, char *layname, char *channame, int xstride, int ystride, float *rect) {}
void IMB_exr_read_channels (void *handle) {}
void IMB_exr_write_channels (void *handle) {}
-void IMB_exrtile_write_channels (void *handle, int partx, int party) {}
+void IMB_exrtile_write_channels (void *handle, int partx, int party, int level) {}
void IMB_exrtile_clear_channels (void *handle) {}
void IMB_exr_multilayer_convert (void *handle, void *base,
diff --git a/source/blender/imbuf/intern/radiance_hdr.c b/source/blender/imbuf/intern/radiance_hdr.c
index 3cb9ca79ffc..b4e384ada72 100644
--- a/source/blender/imbuf/intern/radiance_hdr.c
+++ b/source/blender/imbuf/intern/radiance_hdr.c
@@ -61,6 +61,7 @@
#define BLU 2
#define EXP 3
#define COLXS 128
+#define STR_MAX 540
typedef unsigned char RGBE[4];
typedef float fCOLOR[3];
/* copy source -> dest */
@@ -192,7 +193,8 @@ struct ImBuf *imb_loadhdr(unsigned char *mem, int size, int flags)
}
}
if (found) {
- sscanf((char*)&mem[x+1], "%s %d %s %d", (char*)&oriY, &height, (char*)&oriX, &width);
+ if (sscanf((char *)&mem[x+1], "%79s %d %79s %d", (char*)&oriY, &height,
+ (char*)&oriX, &width) != 4) return NULL;
/* find end of this line, data right behind it */
ptr = (unsigned char *)strchr((char*)&mem[x+1], '\n');
@@ -249,7 +251,7 @@ struct ImBuf *imb_loadhdr(unsigned char *mem, int size, int flags)
}
/* ImBuf write */
-static int fwritecolrs(FILE* file, int width, unsigned char* ibufscan, float* fpscan)
+static int fwritecolrs(FILE* file, int width, int channels, unsigned char* ibufscan, float* fpscan)
{
int x, i, j, beg, c2, cnt=0;
fCOLOR fcol;
@@ -264,16 +266,16 @@ static int fwritecolrs(FILE* file, int width, unsigned char* ibufscan, float* fp
for (i=0;i<width;i++) {
if (fpscan) {
fcol[RED] = fpscan[j];
- fcol[GRN] = fpscan[j+1];
- fcol[BLU] = fpscan[j+2];
+ fcol[GRN] = (channels >= 2)? fpscan[j+1]: fpscan[j];
+ fcol[BLU] = (channels >= 3)? fpscan[j+2]: fpscan[j];
} else {
fcol[RED] = (float)ibufscan[j] / 255.f;
- fcol[GRN] = (float)ibufscan[j+1] / 255.f;
- fcol[BLU] = (float)ibufscan[j+2] /255.f;
+ fcol[GRN] = (float)((channels >= 2)? ibufscan[j+1]: ibufscan[j]) / 255.f;
+ fcol[BLU] = (float)((channels >= 3)? ibufscan[j+2]: ibufscan[j]) / 255.f;
}
FLOAT2RGBE(fcol, rgbe);
copy_rgbe(rgbe, rgbe_scan[i]);
- j+=4;
+ j+=channels;
}
if ((width < MINELEN) | (width > MAXELEN)) { /* OOBs, write out flat */
@@ -346,18 +348,18 @@ short imb_savehdr(struct ImBuf *ibuf, char *name, int flags)
writeHeader(file, width, height);
if(ibuf->rect)
- cp= (unsigned char *)(ibuf->rect + (height-1)*width);
+ cp= (unsigned char *)ibuf->rect + ibuf->channels*(height-1)*width;
if(ibuf->rect_float)
- fp= ibuf->rect_float + 4*(height-1)*width;
+ fp= ibuf->rect_float + ibuf->channels*(height-1)*width;
for (y=height-1;y>=0;y--) {
- if (fwritecolrs(file, width, cp, fp) < 0) {
+ if (fwritecolrs(file, width, ibuf->channels, cp, fp) < 0) {
fclose(file);
printf("HDR write error\n");
return 0;
}
- if(cp) cp-= 4*width;
- if(fp) fp-= 4*width;
+ if(cp) cp-= ibuf->channels*width;
+ if(fp) fp-= ibuf->channels*width;
}
fclose(file);
diff --git a/source/blender/imbuf/intern/readimage.c b/source/blender/imbuf/intern/readimage.c
index b9c04e621ed..05e7921665b 100644
--- a/source/blender/imbuf/intern/readimage.c
+++ b/source/blender/imbuf/intern/readimage.c
@@ -29,8 +29,14 @@
* $Id$
*/
-#ifdef WIN32
+#ifdef _WIN32
#include <io.h>
+#include <stddef.h>
+#include <sys/types.h>
+#include "mmap_win.h"
+#define open _open
+#define read _read
+#define close _close
#endif
#include "BLI_blenlib.h"
@@ -73,7 +79,7 @@
#define SWAP_S(x) (((x << 8) & 0xff00) | ((x >> 8) & 0xff))
/* more endianness... should move to a separate file... */
-#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
+#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined(__hppa__) || defined (__BIG_ENDIAN__)
#define GET_ID GET_BIG_LONG
#define LITTLE_LONG SWAP_LONG
#else
@@ -229,7 +235,7 @@ struct ImBuf *IMB_loadifffile(int file, int flags) {
size = BLI_filesize(file);
-#if defined(AMIGA) || defined(__BeOS) || defined(WIN32)
+#if defined(AMIGA) || defined(__BeOS)
mem= (int *)malloc(size);
if (mem==0) {
printf("Out of mem\n");
diff --git a/source/blender/imbuf/intern/rectop.c b/source/blender/imbuf/intern/rectop.c
index 8b3902f77bf..56714c3b481 100644
--- a/source/blender/imbuf/intern/rectop.c
+++ b/source/blender/imbuf/intern/rectop.c
@@ -37,6 +37,7 @@
#include "IMB_imbuf.h"
#include "IMB_allocimbuf.h"
+#include "BKE_utildefines.h"
/* blend modes */
@@ -514,15 +515,13 @@ void IMB_rectfill(struct ImBuf *drect, float col[4])
}
}
-/* maybe we should use BKE_utildefines.h */
-#define FTOCHAR(val) (val<=0.0f ? 0: (val>=1.0f ? 255: (char)(255.99f*val)))
-#define CLAMP(a, b, c) if((a)<(b)) (a)=(b); else if((a)>(c)) (a)=(c)
-#define SWAP(type, a, b) { type sw_ap; sw_ap=(a); (a)=(b); (b)=sw_ap; }
void buf_rectfill_area(unsigned char *rect, float *rectf, int width, int height, float *col, int x1, int y1, int x2, int y2)
{
int i, j;
- float a, ai;
+ float a; /* alpha */
+ float ai; /* alpha inverted */
+ float aich; /* alpha, inverted, ai/255.0 - Convert char to float at the same time */
if ((!rect && !rectf) || (!col) || col[3]==0.0)
return;
@@ -538,7 +537,7 @@ void buf_rectfill_area(unsigned char *rect, float *rectf, int width, int height,
a = col[3];
ai = 1-a;
-
+ aich = ai/255.0f;
if (rect) {
unsigned char *pixel;
@@ -563,9 +562,9 @@ void buf_rectfill_area(unsigned char *rect, float *rectf, int width, int height,
pixel[1] = chg;
pixel[2] = chb;
} else {
- pixel[0] = (char)(fr + ((float)pixel[0]*ai));
- pixel[1] = (char)(fg + ((float)pixel[1]*ai));
- pixel[2] = (char)(fb + ((float)pixel[2]*ai));
+ pixel[0] = (char)((fr + ((float)pixel[0]*aich))*255.0f);
+ pixel[1] = (char)((fg + ((float)pixel[1]*aich))*255.0f);
+ pixel[2] = (char)((fb + ((float)pixel[2]*aich))*255.0f);
}
}
}
diff --git a/source/blender/imbuf/intern/rotate.c b/source/blender/imbuf/intern/rotate.c
index ca7ea01eaa6..c04987b3e71 100644
--- a/source/blender/imbuf/intern/rotate.c
+++ b/source/blender/imbuf/intern/rotate.c
@@ -40,48 +40,55 @@
void IMB_flipy(struct ImBuf * ibuf)
{
- short x, y;
- unsigned int *top, *bottom, do_float=0, *line;
- float *topf=NULL, *bottomf=NULL, *linef=NULL;
+ int x, y;
if (ibuf == NULL) return;
- if (ibuf->rect == NULL) return;
-
- if (ibuf->rect_float) do_float =1;
- x = ibuf->x;
- y = ibuf->y;
+ if (ibuf->rect) {
+ unsigned int *top, *bottom, *line;
+
+ x = ibuf->x;
+ y = ibuf->y;
- top = ibuf->rect;
- bottom = top + ((y-1) * x);
- line= MEM_mallocN(x*sizeof(int), "linebuf");
+ top = ibuf->rect;
+ bottom = top + ((y-1) * x);
+ line= MEM_mallocN(x*sizeof(int), "linebuf");
- if (do_float) {
+ y >>= 1;
+
+ for(;y>0;y--) {
+ memcpy(line, top, x*sizeof(int));
+ memcpy(top, bottom, x*sizeof(int));
+ memcpy(bottom, line, x*sizeof(int));
+ bottom -= x;
+ top+= x;
+ }
+
+ MEM_freeN(line);
+ }
+
+ if (ibuf->rect_float) {
+ float *topf=NULL, *bottomf=NULL, *linef=NULL;
+
+ x = ibuf->x;
+ y = ibuf->y;
+
topf= ibuf->rect_float;
bottomf = topf + 4*((y-1) * x);
linef= MEM_mallocN(4*x*sizeof(float), "linebuff");
- }
- y >>= 1;
-
- for(;y>0;y--) {
-
- memcpy(line, top, x*sizeof(int));
- memcpy(top, bottom, x*sizeof(int));
- memcpy(bottom, line, x*sizeof(int));
- bottom -= x;
- top+= x;
-
- if(do_float) {
+
+ y >>= 1;
+
+ for(;y>0;y--) {
memcpy(linef, topf, 4*x*sizeof(float));
memcpy(topf, bottomf, 4*x*sizeof(float));
memcpy(bottomf, linef, 4*x*sizeof(float));
bottomf -= 4*x;
topf+= 4*x;
}
+
+ MEM_freeN(linef);
}
-
- MEM_freeN(line);
- if(linef) MEM_freeN(linef);
}
void IMB_flipx(struct ImBuf * ibuf)
diff --git a/source/blender/imbuf/intern/scaling.c b/source/blender/imbuf/intern/scaling.c
index c46a4bf1e93..8257eb4643e 100644
--- a/source/blender/imbuf/intern/scaling.c
+++ b/source/blender/imbuf/intern/scaling.c
@@ -39,6 +39,8 @@
#include "IMB_allocimbuf.h"
#include "IMB_filter.h"
+#include "BLO_sys_types.h" // for intptr_t support
+
/************************************************************************/
/* SCALING */
/************************************************************************/
@@ -480,6 +482,468 @@ struct ImBuf *IMB_halflace(struct ImBuf *ibuf1)
return (ibuf2);
}
+/* q_scale_linear_interpolation helper functions */
+
+static void enlarge_picture_byte(
+ unsigned char* src, unsigned char* dst, int src_width,
+ int src_height, int dst_width, int dst_height)
+{
+ double ratiox = (double) (dst_width - 1.0)
+ / (double) (src_width - 1.001);
+ double ratioy = (double) (dst_height - 1.0)
+ / (double) (src_height - 1.001);
+ uintptr_t x_src, dx_src, x_dst;
+ uintptr_t y_src, dy_src, y_dst;
+
+ dx_src = 65536.0 / ratiox;
+ dy_src = 65536.0 / ratioy;
+
+ y_src = 0;
+ for (y_dst = 0; y_dst < dst_height; y_dst++) {
+ unsigned char* line1 = src + (y_src >> 16) * 4 * src_width;
+ unsigned char* line2 = line1 + 4 * src_width;
+ uintptr_t weight1y = 65536 - (y_src & 0xffff);
+ uintptr_t weight2y = 65536 - weight1y;
+
+ if ((y_src >> 16) == src_height - 1) {
+ line2 = line1;
+ }
+
+ x_src = 0;
+ for (x_dst = 0; x_dst < dst_width; x_dst++) {
+ uintptr_t weight1x = 65536 - (x_src & 0xffff);
+ uintptr_t weight2x = 65536 - weight1x;
+
+ unsigned long x = (x_src >> 16) * 4;
+
+ *dst++ = ((((line1[x] * weight1y) >> 16)
+ * weight1x) >> 16)
+ + ((((line2[x] * weight2y) >> 16)
+ * weight1x) >> 16)
+ + ((((line1[4 + x] * weight1y) >> 16)
+ * weight2x) >> 16)
+ + ((((line2[4 + x] * weight2y) >> 16)
+ * weight2x) >> 16);
+
+ *dst++ = ((((line1[x + 1] * weight1y) >> 16)
+ * weight1x) >> 16)
+ + ((((line2[x + 1] * weight2y) >> 16)
+ * weight1x) >> 16)
+ + ((((line1[4 + x + 1] * weight1y) >> 16)
+ * weight2x) >> 16)
+ + ((((line2[4 + x + 1] * weight2y) >> 16)
+ * weight2x) >> 16);
+
+ *dst++ = ((((line1[x + 2] * weight1y) >> 16)
+ * weight1x) >> 16)
+ + ((((line2[x + 2] * weight2y) >> 16)
+ * weight1x) >> 16)
+ + ((((line1[4 + x + 2] * weight1y) >> 16)
+ * weight2x) >> 16)
+ + ((((line2[4 + x + 2] * weight2y) >> 16)
+ * weight2x) >> 16);
+
+ *dst++ = ((((line1[x + 3] * weight1y) >> 16)
+ * weight1x) >> 16)
+ + ((((line2[x + 3] * weight2y) >> 16)
+ * weight1x) >> 16)
+ + ((((line1[4 + x + 3] * weight1y) >> 16)
+ * weight2x) >> 16)
+ + ((((line2[4 + x + 3] * weight2y) >> 16)
+ * weight2x) >> 16);
+
+ x_src += dx_src;
+ }
+ y_src += dy_src;
+ }
+}
+
+struct scale_outpix_byte {
+ uintptr_t r;
+ uintptr_t g;
+ uintptr_t b;
+ uintptr_t a;
+
+ uintptr_t weight;
+};
+
+static void shrink_picture_byte(
+ unsigned char* src, unsigned char* dst, int src_width,
+ int src_height, int dst_width, int dst_height)
+{
+ double ratiox = (double) (dst_width) / (double) (src_width);
+ double ratioy = (double) (dst_height) / (double) (src_height);
+ uintptr_t x_src, dx_dst, x_dst;
+ uintptr_t y_src, dy_dst, y_dst;
+ intptr_t y_counter;
+ unsigned char * dst_begin = dst;
+
+ struct scale_outpix_byte * dst_line1 = NULL;
+ struct scale_outpix_byte * dst_line2 = NULL;
+
+ dst_line1 = (struct scale_outpix_byte*) MEM_callocN(
+ (dst_width + 1) * sizeof(struct scale_outpix_byte),
+ "shrink_picture_byte 1");
+ dst_line2 = (struct scale_outpix_byte*) MEM_callocN(
+ (dst_width + 1) * sizeof(struct scale_outpix_byte),
+ "shrink_picture_byte 2");
+
+ dx_dst = 65536.0 * ratiox;
+ dy_dst = 65536.0 * ratioy;
+
+ y_dst = 0;
+ y_counter = 65536;
+ for (y_src = 0; y_src < src_height; y_src++) {
+ unsigned char* line = src + y_src * 4 * src_width;
+ uintptr_t weight1y = 65536 - (y_dst & 0xffff);
+ uintptr_t weight2y = 65536 - weight1y;
+ x_dst = 0;
+ for (x_src = 0; x_src < src_width; x_src++) {
+ uintptr_t weight1x = 65536 - (x_dst & 0xffff);
+ uintptr_t weight2x = 65536 - weight1x;
+
+ uintptr_t x = x_dst >> 16;
+
+ uintptr_t w;
+
+ w = (weight1y * weight1x) >> 16;
+
+ dst_line1[x].r += (line[0] * w) >> 16;
+ dst_line1[x].g += (line[1] * w) >> 16;
+ dst_line1[x].b += (line[2] * w) >> 16;
+ dst_line1[x].a += (line[3] * w) >> 16;
+ dst_line1[x].weight += w;
+
+ w = (weight2y * weight1x) >> 16;
+
+ dst_line2[x].r += (line[0] * w) >> 16;
+ dst_line2[x].g += (line[1] * w) >> 16;
+ dst_line2[x].b += (line[2] * w) >> 16;
+ dst_line2[x].a += (line[3] * w) >> 16;
+ dst_line2[x].weight += w;
+
+ w = (weight1y * weight2x) >> 16;
+
+ dst_line1[x+1].r += (line[0] * w) >> 16;
+ dst_line1[x+1].g += (line[1] * w) >> 16;
+ dst_line1[x+1].b += (line[2] * w) >> 16;
+ dst_line1[x+1].a += (line[3] * w) >> 16;
+ dst_line1[x+1].weight += w;
+
+ w = (weight2y * weight2x) >> 16;
+
+ dst_line2[x+1].r += (line[0] * w) >> 16;
+ dst_line2[x+1].g += (line[1] * w) >> 16;
+ dst_line2[x+1].b += (line[2] * w) >> 16;
+ dst_line2[x+1].a += (line[3] * w) >> 16;
+ dst_line2[x+1].weight += w;
+
+ x_dst += dx_dst;
+ line += 4;
+ }
+
+ y_dst += dy_dst;
+ y_counter -= dy_dst;
+ if (y_counter < 0) {
+ uintptr_t x;
+ struct scale_outpix_byte * temp;
+
+ y_counter += 65536;
+
+ for (x=0; x < dst_width; x++) {
+ uintptr_t f = 0x80000000UL
+ / dst_line1[x].weight;
+ *dst++ = (dst_line1[x].r * f) >> 15;
+ *dst++ = (dst_line1[x].g * f) >> 15;
+ *dst++ = (dst_line1[x].b * f) >> 15;
+ *dst++ = (dst_line1[x].a * f) >> 15;
+ }
+ memset(dst_line1, 0, dst_width *
+ sizeof(struct scale_outpix_byte));
+ temp = dst_line1;
+ dst_line1 = dst_line2;
+ dst_line2 = temp;
+ }
+ }
+ if (dst - dst_begin < dst_width * dst_height * 4) {
+ uintptr_t x;
+ for (x = 0; x < dst_width; x++) {
+ uintptr_t f = 0x80000000UL / dst_line1[x].weight;
+ *dst++ = (dst_line1[x].r * f) >> 15;
+ *dst++ = (dst_line1[x].g * f) >> 15;
+ *dst++ = (dst_line1[x].b * f) >> 15;
+ *dst++ = (dst_line1[x].a * f) >> 15;
+ }
+ }
+ MEM_freeN(dst_line1);
+ MEM_freeN(dst_line2);
+}
+
+
+static void q_scale_byte(unsigned char* in, unsigned char* out, int in_width,
+ int in_height, int dst_width, int dst_height)
+{
+ if (dst_width > in_width && dst_height > in_height) {
+ enlarge_picture_byte(in, out, in_width, in_height,
+ dst_width, dst_height);
+ } else if (dst_width < in_width && dst_height < in_height) {
+ shrink_picture_byte(in, out, in_width, in_height,
+ dst_width, dst_height);
+ }
+}
+
+static void enlarge_picture_float(
+ float* src, float* dst, int src_width,
+ int src_height, int dst_width, int dst_height)
+{
+ double ratiox = (double) (dst_width - 1.0)
+ / (double) (src_width - 1.001);
+ double ratioy = (double) (dst_height - 1.0)
+ / (double) (src_height - 1.001);
+ uintptr_t x_dst;
+ uintptr_t y_dst;
+ double x_src, dx_src;
+ double y_src, dy_src;
+
+ dx_src = 1.0 / ratiox;
+ dy_src = 1.0 / ratioy;
+
+ y_src = 0;
+ for (y_dst = 0; y_dst < dst_height; y_dst++) {
+ float* line1 = src + ((int) y_src) * 4 * src_width;
+ float* line2 = line1 + 4 * src_width;
+ float weight1y = 1.0 - (y_src - (int) y_src);
+ float weight2y = 1.0 - weight1y;
+
+ if ((int) y_src == src_height - 1) {
+ line2 = line1;
+ }
+
+ x_src = 0;
+ for (x_dst = 0; x_dst < dst_width; x_dst++) {
+ float weight1x = 1.0 - (x_src - (int) x_src);
+ float weight2x = 1.0 - weight1x;
+
+ float w11 = weight1y * weight1x;
+ float w21 = weight2y * weight1x;
+ float w12 = weight1y * weight2x;
+ float w22 = weight2y * weight2x;
+
+ uintptr_t x = ((int) x_src) * 4;
+
+ *dst++ = line1[x] * w11
+ + line2[x] * w21
+ + line1[4 + x] * w12
+ + line2[4 + x] * w22;
+
+ *dst++ = line1[x + 1] * w11
+ + line2[x + 1] * w21
+ + line1[4 + x + 1] * w12
+ + line2[4 + x + 1] * w22;
+
+ *dst++ = line1[x + 2] * w11
+ + line2[x + 2] * w21
+ + line1[4 + x + 2] * w12
+ + line2[4 + x + 2] * w22;
+
+ *dst++ = line1[x + 3] * w11
+ + line2[x + 3] * w21
+ + line1[4 + x + 3] * w12
+ + line2[4 + x + 3] * w22;
+
+ x_src += dx_src;
+ }
+ y_src += dy_src;
+ }
+}
+
+struct scale_outpix_float {
+ float r;
+ float g;
+ float b;
+ float a;
+
+ float weight;
+};
+
+static void shrink_picture_float(
+ float* src, float* dst, int src_width,
+ int src_height, int dst_width, int dst_height)
+{
+ double ratiox = (double) (dst_width) / (double) (src_width);
+ double ratioy = (double) (dst_height) / (double) (src_height);
+ uintptr_t x_src;
+ uintptr_t y_src;
+ float dx_dst, x_dst;
+ float dy_dst, y_dst;
+ float y_counter;
+ float * dst_begin = dst;
+
+ struct scale_outpix_float * dst_line1;
+ struct scale_outpix_float * dst_line2;
+
+ dst_line1 = (struct scale_outpix_float*) MEM_callocN(
+ (dst_width + 1) * sizeof(struct scale_outpix_float),
+ "shrink_picture_float 1");
+ dst_line2 = (struct scale_outpix_float*) MEM_callocN(
+ (dst_width + 1) * sizeof(struct scale_outpix_float),
+ "shrink_picture_float 2");
+
+ dx_dst = ratiox;
+ dy_dst = ratioy;
+
+ y_dst = 0;
+ y_counter = 1.0;
+ for (y_src = 0; y_src < src_height; y_src++) {
+ float* line = src + y_src * 4 * src_width;
+ uintptr_t weight1y = 1.0 - (y_dst - (int) y_dst);
+ uintptr_t weight2y = 1.0 - weight1y;
+ x_dst = 0;
+ for (x_src = 0; x_src < src_width; x_src++) {
+ uintptr_t weight1x = 1.0 - (x_dst - (int) x_dst);
+ uintptr_t weight2x = 1.0 - weight1x;
+
+ uintptr_t x = (int) x_dst;
+
+ float w;
+
+ w = weight1y * weight1x;
+
+ dst_line1[x].r += line[0] * w;
+ dst_line1[x].g += line[1] * w;
+ dst_line1[x].b += line[2] * w;
+ dst_line1[x].a += line[3] * w;
+ dst_line1[x].weight += w;
+
+ w = weight2y * weight1x;
+
+ dst_line2[x].r += line[0] * w;
+ dst_line2[x].g += line[1] * w;
+ dst_line2[x].b += line[2] * w;
+ dst_line2[x].a += line[3] * w;
+ dst_line2[x].weight += w;
+
+ w = weight1y * weight2x;
+
+ dst_line1[x+1].r += line[0] * w;
+ dst_line1[x+1].g += line[1] * w;
+ dst_line1[x+1].b += line[2] * w;
+ dst_line1[x+1].a += line[3] * w;
+ dst_line1[x+1].weight += w;
+
+ w = weight2y * weight2x;
+
+ dst_line2[x+1].r += line[0] * w;
+ dst_line2[x+1].g += line[1] * w;
+ dst_line2[x+1].b += line[2] * w;
+ dst_line2[x+1].a += line[3] * w;
+ dst_line2[x+1].weight += w;
+
+ x_dst += dx_dst;
+ line += 4;
+ }
+
+ y_dst += dy_dst;
+ y_counter -= dy_dst;
+ if (y_counter < 0) {
+ uintptr_t x;
+ struct scale_outpix_float * temp;
+
+ y_counter += 1.0;
+
+ for (x=0; x < dst_width; x++) {
+ float f = 1.0 / dst_line1[x].weight;
+ *dst++ = dst_line1[x].r * f;
+ *dst++ = dst_line1[x].g * f;
+ *dst++ = dst_line1[x].b * f;
+ *dst++ = dst_line1[x].a * f;
+ }
+ memset(dst_line1, 0, dst_width *
+ sizeof(struct scale_outpix_float));
+ temp = dst_line1;
+ dst_line1 = dst_line2;
+ dst_line2 = temp;
+ }
+ }
+ if (dst - dst_begin < dst_width * dst_height * 4) {
+ uintptr_t x;
+ for (x = 0; x < dst_width; x++) {
+ float f = 1.0 / dst_line1[x].weight;
+ *dst++ = dst_line1[x].r * f;
+ *dst++ = dst_line1[x].g * f;
+ *dst++ = dst_line1[x].b * f;
+ *dst++ = dst_line1[x].a * f;
+ }
+ }
+ MEM_freeN(dst_line1);
+ MEM_freeN(dst_line2);
+}
+
+
+static void q_scale_float(float* in, float* out, int in_width,
+ int in_height, int dst_width, int dst_height)
+{
+ if (dst_width > in_width && dst_height > in_height) {
+ enlarge_picture_float(in, out, in_width, in_height,
+ dst_width, dst_height);
+ } else if (dst_width < in_width && dst_height < in_height) {
+ shrink_picture_float(in, out, in_width, in_height,
+ dst_width, dst_height);
+ }
+}
+
+/* q_scale_linear_interpolation (derived from ppmqscale, http://libdv.sf.net)
+
+ q stands for quick _and_ quality :)
+
+ only handles common cases when we either
+
+ scale both, x and y or
+ shrink both, x and y
+
+ but that is pretty fast:
+ * does only blit once instead of two passes like the old code
+ (fewer cache misses)
+ * uses fixed point integer arithmetic for byte buffers
+ * doesn't branch in tight loops
+
+ Should be comparable in speed to the ImBuf ..._fast functions at least
+ for byte-buffers.
+
+*/
+static int q_scale_linear_interpolation(
+ struct ImBuf *ibuf, int newx, int newy)
+{
+ if ((newx >= ibuf->x && newy <= ibuf->y) ||
+ (newx <= ibuf->x && newy >= ibuf->y)) {
+ return FALSE;
+ }
+
+ if (ibuf->rect) {
+ unsigned char * newrect =
+ MEM_mallocN(newx * newy * sizeof(int), "q_scale rect");
+ q_scale_byte((unsigned char *)ibuf->rect, newrect, ibuf->x, ibuf->y,
+ newx, newy);
+
+ imb_freerectImBuf(ibuf);
+ ibuf->mall |= IB_rect;
+ ibuf->rect = (unsigned int *) newrect;
+ }
+ if (ibuf->rect_float) {
+ float * newrect =
+ MEM_mallocN(newx * newy * 4 *sizeof(float),
+ "q_scale rectfloat");
+ q_scale_float(ibuf->rect_float, newrect, ibuf->x, ibuf->y,
+ newx, newy);
+ imb_freerectfloatImBuf(ibuf);
+ ibuf->mall |= IB_rectfloat;
+ ibuf->rect_float = newrect;
+ }
+ ibuf->x = newx;
+ ibuf->y = newy;
+
+ return TRUE;
+}
static struct ImBuf *scaledownx(struct ImBuf *ibuf, int newx)
{
@@ -1110,11 +1574,18 @@ struct ImBuf *IMB_scaleImBuf(struct ImBuf * ibuf, short newx, short newy)
{
if (ibuf==NULL) return (0);
if (ibuf->rect==NULL && ibuf->rect_float==NULL) return (ibuf);
+
+ if (newx == ibuf->x && newy == ibuf->y) { return ibuf; }
- // scaleup / scaledown functions below change ibuf->x and ibuf->y
- // so we first scale the Z-buffer (if any)
+ /* scaleup / scaledown functions below change ibuf->x and ibuf->y
+ so we first scale the Z-buffer (if any) */
scalefast_Z_ImBuf(ibuf, newx, newy);
+ /* try to scale common cases in a fast way */
+ if (q_scale_linear_interpolation(ibuf, newx, newy)) {
+ return ibuf;
+ }
+
if (newx < ibuf->x) if (newx) scaledownx(ibuf,newx);
if (newy < ibuf->y) if (newy) scaledowny(ibuf,newy);
if (newx > ibuf->x) if (newx) scaleupx(ibuf,newx);
diff --git a/source/blender/imbuf/intern/thumbs.c b/source/blender/imbuf/intern/thumbs.c
index 9097fb84dcd..14d6cb2d54b 100644
--- a/source/blender/imbuf/intern/thumbs.c
+++ b/source/blender/imbuf/intern/thumbs.c
@@ -78,18 +78,17 @@ static int get_thumb_dir( char* dir , ThumbSize size)
#endif
switch(size) {
case THB_NORMAL:
- strcat(dir, "/.thumbnails/normal");
+ strcat(dir, "/.thumbnails/normal/");
break;
case THB_LARGE:
- strcat(dir, "/.thumbnails/large");
+ strcat(dir, "/.thumbnails/large/");
break;
case THB_FAIL:
- strcat(dir, "/.thumbnails/fail/blender");
+ strcat(dir, "/.thumbnails/fail/blender/");
break;
default:
return 0; /* unknown size */
}
- BLI_cleanup_dir(G.sce, dir);
return 1;
}
diff --git a/source/blender/imbuf/intern/tiff.c b/source/blender/imbuf/intern/tiff.c
index 34d486fff11..194082d3e19 100644
--- a/source/blender/imbuf/intern/tiff.c
+++ b/source/blender/imbuf/intern/tiff.c
@@ -309,7 +309,7 @@ struct ImBuf *imb_loadtiff(unsigned char *mem, int size, int flags)
struct ImBuf *ibuf = NULL;
struct ImbTIFFMemFile memFile;
uint32 width, height;
- int bytesperpixel;
+ int bytesperpixel, bitspersample;
int success;
unsigned int pixel_i, byte_i;
uint32 *raster = NULL;
@@ -321,7 +321,7 @@ struct ImBuf *imb_loadtiff(unsigned char *mem, int size, int flags)
memFile.size = size;
/* check whether or not we have a TIFF file */
- if (size < IMB_TIFF_NCB) {
+ if (size < IMB_TIFF_NCB) {
fprintf(stderr, "imb_loadtiff: size < IMB_TIFF_NCB\n");
return NULL;
}
@@ -343,6 +343,7 @@ struct ImBuf *imb_loadtiff(unsigned char *mem, int size, int flags)
bytesperpixel = 4; /* 1 byte per channel, 4 channels */
libtiff_TIFFGetField(image, TIFFTAG_IMAGEWIDTH, &width);
libtiff_TIFFGetField(image, TIFFTAG_IMAGELENGTH, &height);
+ libtiff_TIFFGetField(image, TIFFTAG_BITSPERSAMPLE, &bitspersample);
ibuf = IMB_allocImBuf(width, height, 8*bytesperpixel, 0, 0);
if (ibuf) {
ibuf->ftype = TIF;
@@ -415,8 +416,6 @@ struct ImBuf *imb_loadtiff(unsigned char *mem, int size, int flags)
return (ibuf);
}
-
-
/**
* Saves a TIFF file.
*
@@ -432,14 +431,19 @@ struct ImBuf *imb_loadtiff(unsigned char *mem, int size, int flags)
*
* @return: 1 if the function is successful, 0 on failure.
*/
+
+#define FTOUSHORT(val) ((val >= 1.0f-0.5f/65535)? 65535: (val <= 0.0f)? 0: (unsigned short)(val*65535.0f + 0.5f))
+
short imb_savetiff(struct ImBuf *ibuf, char *name, int flags)
{
TIFF *image = NULL;
- uint16 samplesperpixel;
+ uint16 samplesperpixel, bitspersample;
size_t npixels;
unsigned char *pixels = NULL;
unsigned char *from = NULL, *to = NULL;
- int x, y, from_i, to_i;
+ unsigned short *pixels16 = NULL, *to16 = NULL;
+ float *fromf = NULL;
+ int x, y, from_i, to_i, i;
int extraSampleTypes[1] = { EXTRASAMPLE_ASSOCALPHA };
/* check for a valid number of bytes per pixel. Like the PNG writer,
@@ -453,6 +457,11 @@ short imb_savetiff(struct ImBuf *ibuf, char *name, int flags)
return (0);
}
+ if((ibuf->ftype & TIF_16BIT) && ibuf->rect_float)
+ bitspersample = 16;
+ else
+ bitspersample = 8;
+
/* open TIFF file for writing */
if (flags & IB_mem) {
/* bork at the creation of a TIFF in memory */
@@ -472,67 +481,67 @@ short imb_savetiff(struct ImBuf *ibuf, char *name, int flags)
/* allocate array for pixel data */
npixels = ibuf->x * ibuf->y;
- pixels = (unsigned char*)libtiff__TIFFmalloc(npixels *
- samplesperpixel * sizeof(unsigned char));
- if (pixels == NULL) {
+ if(bitspersample == 16)
+ pixels16 = (unsigned short*)libtiff__TIFFmalloc(npixels *
+ samplesperpixel * sizeof(unsigned short));
+ else
+ pixels = (unsigned char*)libtiff__TIFFmalloc(npixels *
+ samplesperpixel * sizeof(unsigned char));
+
+ if (pixels == NULL && pixels16 == NULL) {
fprintf(stderr,
"imb_savetiff: could not allocate pixels array.\n");
libtiff_TIFFClose(image);
return (0);
}
- /* copy pixel data. While copying, we flip the image
- * vertically. */
- from = (unsigned char*)ibuf->rect;
- to = pixels;
+ /* setup pointers */
+ if(bitspersample == 16) {
+ fromf = ibuf->rect_float;
+ to16 = pixels16;
+ }
+ else {
+ from = (unsigned char*)ibuf->rect;
+ to = pixels;
+ }
+
+ /* setup samples per pixel */
+ libtiff_TIFFSetField(image, TIFFTAG_BITSPERSAMPLE, bitspersample);
libtiff_TIFFSetField(image, TIFFTAG_SAMPLESPERPIXEL, samplesperpixel);
- switch (samplesperpixel) {
- case 4: /* RGBA images, 8 bits per channel */
- libtiff_TIFFSetField(image, TIFFTAG_EXTRASAMPLES, 1,
- extraSampleTypes);
- libtiff_TIFFSetField(image, TIFFTAG_BITSPERSAMPLE, 8);
- libtiff_TIFFSetField(image, TIFFTAG_PHOTOMETRIC,
- PHOTOMETRIC_RGB);
- for (x = 0; x < ibuf->x; x++) {
- for (y = 0; y < ibuf->y; y++) {
- from_i = 4*(y*ibuf->x+x);
- to_i = 4*((ibuf->y-y-1)*ibuf->x+x);
-
- to[to_i++] = from[from_i++];
- to[to_i++] = from[from_i++];
- to[to_i++] = from[from_i++];
- to[to_i] = from[from_i];
- }
- }
- break;
- case 3: /* RGB images, 8 bits per channel */
- libtiff_TIFFSetField(image, TIFFTAG_BITSPERSAMPLE, 8);
- libtiff_TIFFSetField(image, TIFFTAG_PHOTOMETRIC,
- PHOTOMETRIC_RGB);
- for (x = 0; x < ibuf->x; x++) {
- for (y = 0; y < ibuf->y; y++) {
- from_i = 4*(y*ibuf->x+x);
- to_i = 3*((ibuf->y-y-1)*ibuf->x+x);
-
- to[to_i++] = from[from_i++];
- to[to_i++] = from[from_i++];
- to[to_i] = from[from_i];
- }
- }
- break;
- case 1: /* greyscale images, 1 channel with 8 bits */
- libtiff_TIFFSetField(image, TIFFTAG_BITSPERSAMPLE, 8);
- libtiff_TIFFSetField(image, TIFFTAG_PHOTOMETRIC,
- PHOTOMETRIC_MINISBLACK);
- for (x = 0; x < ibuf->x; x++) {
- for (y = 0; y < ibuf->y; y++) {
- from_i = 4*(y*ibuf->x+x);
- to_i = 1*((ibuf->y-y-1)*ibuf->x+x);
+ if(samplesperpixel == 4) {
+ /* RGBA images */
+ libtiff_TIFFSetField(image, TIFFTAG_EXTRASAMPLES, 1,
+ extraSampleTypes);
+ libtiff_TIFFSetField(image, TIFFTAG_PHOTOMETRIC,
+ PHOTOMETRIC_RGB);
+ }
+ else if(samplesperpixel == 3) {
+ /* RGB images */
+ libtiff_TIFFSetField(image, TIFFTAG_PHOTOMETRIC,
+ PHOTOMETRIC_RGB);
+ }
+ else if(samplesperpixel == 1) {
+ /* greyscale images, 1 channel */
+ libtiff_TIFFSetField(image, TIFFTAG_PHOTOMETRIC,
+ PHOTOMETRIC_MINISBLACK);
+ }
+
+ /* copy pixel data. While copying, we flip the image vertically. */
+ for (x = 0; x < ibuf->x; x++) {
+ for (y = 0; y < ibuf->y; y++) {
+ from_i = 4*(y*ibuf->x+x);
+ to_i = samplesperpixel*((ibuf->y-y-1)*ibuf->x+x);
+
+ if(pixels16) {
+ for (i = 0; i < samplesperpixel; i++, to_i++, from_i++)
+ to16[to_i] = FTOUSHORT(fromf[from_i]);
+ }
+ else {
+ for (i = 0; i < samplesperpixel; i++, to_i++, from_i++)
to[to_i] = from[from_i];
- }
}
- break;
+ }
}
/* write the actual TIFF file */
@@ -545,18 +554,21 @@ short imb_savetiff(struct ImBuf *ibuf, char *name, int flags)
libtiff_TIFFSetField(image, TIFFTAG_XRESOLUTION, 150.0);
libtiff_TIFFSetField(image, TIFFTAG_YRESOLUTION, 150.0);
libtiff_TIFFSetField(image, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH);
- if (libtiff_TIFFWriteEncodedStrip(image, 0, pixels,
- ibuf->x*ibuf->y*samplesperpixel) == -1) {
+ if (libtiff_TIFFWriteEncodedStrip(image, 0,
+ (bitspersample == 16)? (unsigned char*)pixels16: pixels,
+ ibuf->x*ibuf->y*samplesperpixel*bitspersample/8) == -1) {
fprintf(stderr,
"imb_savetiff: Could not write encoded TIFF.\n");
libtiff_TIFFClose(image);
- libtiff__TIFFfree(pixels);
+ if(pixels) libtiff__TIFFfree(pixels);
+ if(pixels16) libtiff__TIFFfree(pixels16);
return (1);
}
/* close the TIFF file */
libtiff_TIFFClose(image);
- libtiff__TIFFfree(pixels);
+ if(pixels) libtiff__TIFFfree(pixels);
+ if(pixels16) libtiff__TIFFfree(pixels16);
return (1);
}
diff --git a/source/blender/imbuf/intern/util.c b/source/blender/imbuf/intern/util.c
index 4620797518a..c86f9b017bf 100644
--- a/source/blender/imbuf/intern/util.c
+++ b/source/blender/imbuf/intern/util.c
@@ -29,6 +29,13 @@
* $Id$
*/
+#ifdef _WIN32
+#include <io.h>
+#define open _open
+#define read _read
+#define close _close
+#endif
+
#include "BLI_blenlib.h"
#include "DNA_userdef_types.h"
@@ -64,6 +71,8 @@
#ifdef WITH_FFMPEG
#include <ffmpeg/avcodec.h>
#include <ffmpeg/avformat.h>
+//#include <ffmpeg/avdevice.h>
+#include <ffmpeg/log.h>
#if LIBAVFORMAT_VERSION_INT < (49 << 16)
#define FFMPEG_OLD_FRAME_RATE 1
@@ -229,12 +238,32 @@ static int isqtime (char *name) {
#endif
#ifdef WITH_FFMPEG
+
+void silence_log_ffmpeg(int quiet)
+{
+ if (quiet)
+ {
+ av_log_set_level(AV_LOG_QUIET);
+ }
+ else
+ {
+ av_log_set_level(AV_LOG_INFO);
+ }
+}
+
+extern void do_init_ffmpeg();
void do_init_ffmpeg()
{
static int ffmpeg_init = 0;
if (!ffmpeg_init) {
ffmpeg_init = 1;
av_register_all();
+ //avdevice_register_all();
+
+ if ((G.f & G_DEBUG) == 0)
+ {
+ silence_log_ffmpeg(1);
+ }
}
}
@@ -253,7 +282,8 @@ static AVCodecContext* get_codec_from_stream(AVStream* stream)
static int isffmpeg (char *filename) {
AVFormatContext *pFormatCtx;
- int i, videoStream;
+ unsigned int i;
+ int videoStream;
AVCodec *pCodec;
AVCodecContext *pCodecCtx;
@@ -286,8 +316,9 @@ static int isffmpeg (char *filename) {
/* Find the first video stream */
videoStream=-1;
for(i=0; i<pFormatCtx->nb_streams; i++)
- if(get_codec_from_stream(pFormatCtx->streams[i])
- ->codec_type==CODEC_TYPE_VIDEO)
+ if(pFormatCtx->streams[i] &&
+ get_codec_from_stream(pFormatCtx->streams[i]) &&
+ (get_codec_from_stream(pFormatCtx->streams[i])->codec_type==CODEC_TYPE_VIDEO))
{
videoStream=i;
break;
@@ -303,13 +334,11 @@ static int isffmpeg (char *filename) {
/* Find the decoder for the video stream */
pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
if(pCodec==NULL) {
- avcodec_close(pCodecCtx);
av_close_input_file(pFormatCtx);
return 0;
}
if(avcodec_open(pCodecCtx, pCodec)<0) {
- avcodec_close(pCodecCtx);
av_close_input_file(pFormatCtx);
return 0;
}
@@ -321,6 +350,19 @@ static int isffmpeg (char *filename) {
}
#endif
+#ifdef WITH_REDCODE
+static int isredcode(char * filename)
+{
+ struct redcode_handle * h = redcode_open(filename);
+ if (!h) {
+ return 0;
+ }
+ redcode_close(h);
+ return 1;
+}
+
+#endif
+
int imb_get_anim_type(char * name) {
int type;
struct stat st;
@@ -355,6 +397,9 @@ int imb_get_anim_type(char * name) {
if (isffmpeg(name)) return (ANIM_FFMPEG);
# endif
#endif
+#ifdef WITH_REDCODE
+ if (isredcode(name)) return (ANIM_REDCODE);
+#endif
type = IMB_ispic(name);
if (type == ANIM) return (ANIM_ANIM5);
if (type) return(ANIM_SEQUENCE);
@@ -369,6 +414,7 @@ int IMB_isanim(char *filename) {
if( BLI_testextensie(filename, ".avi")
|| BLI_testextensie(filename, ".flc")
|| BLI_testextensie(filename, ".dv")
+ || BLI_testextensie(filename, ".r3d")
|| BLI_testextensie(filename, ".mov")
|| BLI_testextensie(filename, ".movie")
|| BLI_testextensie(filename, ".mv")) {
@@ -379,6 +425,7 @@ int IMB_isanim(char *filename) {
} else { // no quicktime
if( BLI_testextensie(filename, ".avi")
|| BLI_testextensie(filename, ".dv")
+ || BLI_testextensie(filename, ".r3d")
|| BLI_testextensie(filename, ".mv")) {
type = imb_get_anim_type(filename);
}
diff --git a/source/blender/makesdna/DNA_ID.h b/source/blender/makesdna/DNA_ID.h
index 8db04b37581..ccf9becbce5 100644
--- a/source/blender/makesdna/DNA_ID.h
+++ b/source/blender/makesdna/DNA_ID.h
@@ -46,7 +46,7 @@ struct ID;
typedef struct IDPropertyData {
void *pointer;
ListBase group;
- int val, pad;
+ int val, val2; /*note, we actually fit a double into these two ints*/
} IDPropertyData;
typedef struct IDProperty {
@@ -77,6 +77,7 @@ typedef struct IDProperty {
/* the ID link property type hasn't been implemented yet, this will require
some cleanup of blenkernel, most likely.*/
#define IDP_ID 7
+#define IDP_DOUBLE 8
/* add any future new id property types here.*/
@@ -139,7 +140,7 @@ typedef struct PreviewImage {
*
**/
-#if defined(__sgi) || defined(__sparc) || defined(__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
+#if defined(__sgi) || defined(__sparc) || defined(__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__hppa__) || defined (__BIG_ENDIAN__)
/* big endian */
#define MAKE_ID2(c, d) ( (c)<<8 | (d) )
#define MOST_SIG_BYTE 0
diff --git a/source/blender/makesdna/DNA_action_types.h b/source/blender/makesdna/DNA_action_types.h
index db6a2bda53c..4a10ecf2368 100644
--- a/source/blender/makesdna/DNA_action_types.h
+++ b/source/blender/makesdna/DNA_action_types.h
@@ -32,11 +32,15 @@
#include "DNA_listBase.h"
#include "DNA_ID.h"
+#include "DNA_gpencil_types.h"
#include "DNA_view2d_types.h"
+#include "DNA_userdef_types.h"
struct SpaceLink;
struct Object;
+/* -------------- Poses ----------------- */
+
/* PoseChannel stores the results of Actions (ipos) and transform information
with respect to the restposition of Armature bones */
typedef struct bPoseChannel {
@@ -49,7 +53,7 @@ typedef struct bPoseChannel {
short ikflag; /* settings for IK bones */
short selectflag; /* copy of bone flag, so you can work with library armatures */
short protectflag; /* protect channels from being transformed */
- short customCol; /* index of custom color set to use (0=default - used for all old files) */
+ short agrp_index; /* index of action-group this bone belongs to (0 = default/no group) */
int pathlen; /* for drawing paths, the amount of frames */
int pathsf; /* for drawing paths, the start frame number */
@@ -90,17 +94,59 @@ typedef struct bPoseChannel {
*/
typedef struct bPose {
ListBase chanbase; /* list of pose channels */
+
short flag, proxy_layer; /* proxy layer: copy from armature, gets synced */
+
float ctime; /* local action time of this pose */
float stride_offset[3]; /* applied to object */
float cyclic_offset[3]; /* result of match and cycles, applied in where_is_pose() */
+
+
+ ListBase agroups; /* list of bActionGroups */
+
+ int active_group; /* index of active group (starts from 1) */
+ int pad;
} bPose;
+
+/* ------------- Action ---------------- */
+
+/* Action-Channel Group. These are stored as a list per-Action, and are only used to
+ * group that Action's Action-Channels when displayed in the Action Editor.
+ *
+ * Even though all Action-Channels live in a big list per Action, each group they are in also
+ * holds references to the achans within that list which belong to it. Care must be taken to
+ * ensure that action-groups never end up being the sole 'owner' of a channel.
+ *
+ *
+ * This is also exploited for bone-groups. Bone-Groups are stored per bPose, and are used
+ * primarily to colour bones in the 3d-view. There are other benefits too, but those are mostly related
+ * to Action-Groups.
+ */
+typedef struct bActionGroup {
+ struct bActionGroup *next, *prev;
+
+ ListBase channels; /* Note: this must not be touched by standard listbase functions */
+
+ int flag; /* settings for this action-group */
+ int customCol; /* index of custom color set to use when used for bones (0=default - used for all old files, -1=custom set) */
+ char name[32]; /* name of the group */
+
+ ThemeWireColor cs; /* color set to use when customCol == -1 */
+} bActionGroup;
+
/* Action Channels belong to Actions. They are linked with an IPO block, and can also own
* Constraint Channels in certain situations.
+ *
+ * Action-Channels can only belong to one group at a time, but they still live the Action's
+ * list of achans (to preserve backwards compatability, and also minimise the code
+ * that would need to be recoded). Grouped achans are stored at the start of the list, according
+ * to the position of the group in the list, and their position within the group.
*/
typedef struct bActionChannel {
struct bActionChannel *next, *prev;
+ bActionGroup *grp; /* Action Group this Action Channel belongs to */
+
struct Ipo *ipo; /* IPO block this action channel references */
ListBase constraintChannels; /* Constraint Channels (when Action Channel represents an Object or Bone) */
@@ -114,9 +160,18 @@ typedef struct bActionChannel {
*/
typedef struct bAction {
ID id;
+
ListBase chanbase; /* Action Channels in this Action */
+ ListBase groups; /* Action Groups in the Action */
+ ListBase markers; /* TimeMarkers local to this Action for labelling 'poses' */
+
+ int active_marker; /* Index of active-marker (first marker = 1) */
+ int pad;
} bAction;
+
+/* ------------- Action Editor --------------------- */
+
/* Action Editor Space. This is defined here instead of in DNA_space_types.h */
typedef struct SpaceAction {
struct SpaceLink *next, *prev;
@@ -129,12 +184,17 @@ typedef struct SpaceAction {
View2D v2d;
bAction *action; /* the currently active action */
- short flag, autosnap; /* flag: bitmapped settings; autosnap: automatic keyframe snapping mode */
- short pin, actnr, lock; /* pin: keep showing current action; actnr: used for finding chosen action from menu; lock: lock time to other windows */
+
+ char mode, autosnap; /* mode: editing context; autosnap: automatic keyframe snapping mode */
+ short flag, actnr; /* flag: bitmapped settings; */
+ short pin, lock; /* pin: keep showing current action; actnr: used for finding chosen action from menu; lock: lock time to other windows */
short actwidth; /* width of the left-hand side name panel (in pixels?) */
float timeslide; /* for Time-Slide transform mode drawing - current frame? */
} SpaceAction;
+
+/* -------------- Action Flags -------------- */
+
/* Action Channel flags */
typedef enum ACHAN_FLAG {
ACHAN_SELECTED = (1<<0),
@@ -147,18 +207,52 @@ typedef enum ACHAN_FLAG {
ACHAN_MOVED = (1<<31),
} ACHAN_FLAG;
+
+/* Action Group flags */
+typedef enum AGRP_FLAG {
+ AGRP_SELECTED = (1<<0),
+ AGRP_ACTIVE = (1<<1),
+ AGRP_PROTECTED = (1<<2),
+ AGRP_EXPANDED = (1<<3),
+
+ AGRP_TEMP = (1<<30),
+ AGRP_MOVED = (1<<31)
+} AGRP_FLAG;
+
+/* ------------ Action Editor Flags -------------- */
+
/* SpaceAction flag */
typedef enum SACTION_FLAG {
- /* during transform */
+ /* during transform (only set for TimeSlide) */
SACTION_MOVING = (1<<0),
/* show sliders (if relevant) */
SACTION_SLIDERS = (1<<1),
/* draw time in seconds instead of time in frames */
SACTION_DRAWTIME = (1<<2),
/* don't filter action channels according to visibility */
- SACTION_NOHIDE = (1<<3)
+ SACTION_NOHIDE = (1<<3),
+ /* don't kill overlapping keyframes after transform */
+ SACTION_NOTRANSKEYCULL = (1<<4),
+ /* don't include keyframes that are out of view */
+ SACTION_HORIZOPTIMISEON = (1<<5),
+ /* hack for moving pose-markers (temp flag) */
+ SACTION_POSEMARKERS_MOVE = (1<<6),
+ /* don't draw action channels using group colours (where applicable) */
+ SACTION_NODRAWGCOLORS = (1<<7)
} SACTION_FLAG;
+/* SpaceAction Mode Settings */
+typedef enum SACTCONT_MODES {
+ /* action (default) */
+ SACTCONT_ACTION = 0,
+ /* editing of shapekey's IPO block */
+ SACTCONT_SHAPEKEY,
+ /* editing of gpencil data */
+ SACTCONT_GPENCIL,
+ /* dopesheet (unimplemented... future idea?) */
+ SACTCONT_DOPESHEET
+} SACTCONTEXT_MODES;
+
/* SpaceAction AutoSnap Settings (also used by SpaceNLA) */
typedef enum SACTSNAP_MODES {
/* no auto-snap */
@@ -170,6 +264,9 @@ typedef enum SACTSNAP_MODES {
/* snap to nearest marker */
SACTSNAP_MARKER,
} SACTSNAP_MODES;
+
+
+/* --------- Pose Flags --------------- */
/* Pose->flag */
typedef enum POSE_FLAG {
@@ -178,7 +275,11 @@ typedef enum POSE_FLAG {
/* prevents any channel from getting overridden by anim from IPO */
POSE_LOCKED = (1<<1),
/* clears the POSE_LOCKED flag for the next time the pose is evaluated */
- POSE_DO_UNLOCK = (1<<2)
+ POSE_DO_UNLOCK = (1<<2),
+ /* pose has constraints which depend on time (used when depsgraph updates for a new frame) */
+ POSE_CONSTRAINTS_TIMEDEPEND = (1<<3),
+ /* recalculate bone paths */
+ POSE_RECALCPATHS = (1<<4),
} POSE_FLAG;
/* PoseChannel (transform) flags */
diff --git a/source/blender/makesdna/DNA_actuator_types.h b/source/blender/makesdna/DNA_actuator_types.h
index 53f167a99dc..43dada97d0e 100644
--- a/source/blender/makesdna/DNA_actuator_types.h
+++ b/source/blender/makesdna/DNA_actuator_types.h
@@ -35,6 +35,7 @@ struct Object;
struct Mesh;
struct Scene;
struct Group;
+struct Text;
/* ****************** ACTUATORS ********************* */
@@ -49,8 +50,10 @@ typedef struct bActionActuator {
short type, flag; /* Playback type */
int sta, end; /* Start & End frames */
char name[32]; /* For property-driven playback */
- int blendin; /* Number of frames of blending */
- short priority; /* Execution priority */
+ char frameProp[32]; /* Set this property to the actions current frame */
+ short blendin; /* Number of frames of blending */
+ short priority; /* Execution priority */
+ short end_reset; /* Ending the actuator (negative pulse) wont reset the the action to its starting frame */
short strideaxis; /* Displacement axis */
float stridelength; /* Displacement incurred by cycle */
} bActionActuator;
@@ -78,8 +81,10 @@ typedef struct bEditObjectActuator {
struct Mesh *me;
char name[32];
float linVelocity[3]; /* initial lin. velocity on creation */
- short localflag; /* flag for the lin. vel: apply locally */
- short pad;
+ float angVelocity[3]; /* initial ang. velocity on creation */
+ float pad;
+ short localflag; /* flag for the lin & ang. vel: apply locally */
+ short dyn_operation;
} bEditObjectActuator;
typedef struct bSceneActuator {
@@ -96,7 +101,8 @@ typedef struct bPropertyActuator {
} bPropertyActuator;
typedef struct bObjectActuator {
- int flag, type;
+ short flag, type, otype;
+ short damping;
float forceloc[3], forcerot[3];
float loc[3], rot[3];
float dloc[3], drot[3];
@@ -107,6 +113,7 @@ typedef struct bIpoActuator {
short flag, type;
int sta, end;
char name[32];
+ char frameProp[32]; /* Set this property to the actions current frame */
short pad1, cur, butsta, butend;
@@ -121,10 +128,13 @@ typedef struct bCameraActuator {
} bCameraActuator ;
typedef struct bConstraintActuator {
+ short type, mode;
short flag, damp;
- float slow;
+ short time, rotdamp;
+ int pad;
float minloc[3], maxloc[3];
float minrot[3], maxrot[3];
+ char matprop[32];
} bConstraintActuator;
typedef struct bGroupActuator {
@@ -184,10 +194,35 @@ typedef struct bGameActuator {
} bGameActuator;
typedef struct bVisibilityActuator {
- /** bit 0: Is this object visible? */
+ /** bit 0: Is this object visible?
+ ** bit 1: Apply recursively */
int flag;
} bVisibilityActuator;
+typedef struct bTwoDFilterActuator{
+ char pad[4];
+ /* Tells what type of 2D Filter */
+ short type;
+ /* (flag == 0) means 2D filter is activate and
+ (flag != 0) means 2D filter is inactive */
+ short flag;
+ int int_arg;
+ /* a float argument */
+ float float_arg;
+ struct Text *text;
+}bTwoDFilterActuator;
+
+typedef struct bParentActuator {
+ char pad[4];
+ int type;
+ struct Object *ob;
+} bParentActuator;
+
+typedef struct bStateActuator {
+ int type; /* 0=Set, 1=Add, 2=Rem, 3=Chg */
+ unsigned int mask; /* the bits to change */
+} bStateActuator;
+
typedef struct bActuator {
struct bActuator *next, *prev, *mynew;
short type;
@@ -220,19 +255,19 @@ typedef struct FreeCamera {
/* objectactuator->flag */
#define ACT_FORCE_LOCAL 1
#define ACT_TORQUE_LOCAL 2
+#define ACT_SERVO_LIMIT_X 2
#define ACT_DLOC_LOCAL 4
+#define ACT_SERVO_LIMIT_Y 4
#define ACT_DROT_LOCAL 8
+#define ACT_SERVO_LIMIT_Z 8
#define ACT_LIN_VEL_LOCAL 16
#define ACT_ANG_VEL_LOCAL 32
//#define ACT_ADD_LIN_VEL_LOCAL 64
#define ACT_ADD_LIN_VEL 64
-#define ACT_OBJECT_FORCE 0
-#define ACT_OBJECT_TORQUE 1
-#define ACT_OBJECT_DLOC 2
-#define ACT_OBJECT_DROT 3
-#define ACT_OBJECT_LINV 4
-#define ACT_OBJECT_ANGV 5
+/* objectactuator->type */
+#define ACT_OBJECT_NORMAL 0
+#define ACT_OBJECT_SERVO 1
/* actuator->type */
#define ACT_OBJECT 0
@@ -256,11 +291,18 @@ typedef struct FreeCamera {
#define ACT_CD 16
#define ACT_GAME 17
#define ACT_VISIBILITY 18
+#define ACT_2DFILTER 19
+#define ACT_PARENT 20
+#define ACT_SHAPEACTION 21
+#define ACT_STATE 22
/* actuator flag */
#define ACT_SHOW 1
#define ACT_DEL 2
#define ACT_NEW 4
+#define ACT_LINKED 8
+#define ACT_VISIBLE 16
+#define ACT_PIN 32
/* link codes */
#define LINK_SENSOR 0
@@ -301,8 +343,9 @@ typedef struct FreeCamera {
/* ipoactuator->flag */
#define ACT_IPOFORCE (1 << 0)
#define ACT_IPOEND (1 << 1)
-#define ACT_IPOFORCE_LOCAL (1 << 2)
-#define ACT_IPOCHILD (1 << 4)
+#define ACT_IPOLOCAL (1 << 2)
+#define ACT_IPOCHILD (1 << 4)
+#define ACT_IPOADD (1 << 5)
/* ipoactuator->flag for k2k */
#define ACT_K2K_PREV 1
@@ -322,14 +365,38 @@ typedef struct FreeCamera {
#define ACT_CONST_ROTX 8
#define ACT_CONST_ROTY 16
#define ACT_CONST_ROTZ 32
+#define ACT_CONST_NORMAL 64
+#define ACT_CONST_MATERIAL 128
+#define ACT_CONST_PERMANENT 256
+#define ACT_CONST_DISTANCE 512
+#define ACT_CONST_LOCAL 1024
+#define ACT_CONST_DOROTFH 2048
+
+/* constraint mode */
+#define ACT_CONST_DIRPX 1
+#define ACT_CONST_DIRPY 2
+#define ACT_CONST_DIRPZ 4
+#define ACT_CONST_DIRNX 8
+#define ACT_CONST_DIRNY 16
+#define ACT_CONST_DIRNZ 32
+
+/* constraint type */
+#define ACT_CONST_TYPE_LOC 0
+#define ACT_CONST_TYPE_DIST 1
+#define ACT_CONST_TYPE_ORI 2
+#define ACT_CONST_TYPE_FH 3
/* editObjectActuator->type */
#define ACT_EDOB_ADD_OBJECT 0
#define ACT_EDOB_END_OBJECT 1
-#define ACT_EDOB_REPLACE_MESH 2
+#define ACT_EDOB_REPLACE_MESH 2
#define ACT_EDOB_TRACK_TO 3
-#define ACT_EDOB_MAKE_CHILD 4
-#define ACT_EDOB_END_CHILD 5
+#define ACT_EDOB_DYNAMICS 4
+
+/* editObjectActuator->localflag */
+#define ACT_EDOB_LOCAL_LINV 2
+#define ACT_EDOB_LOCAL_ANGV 4
+
/* editObjectActuator->flag */
#define ACT_TRACK_3D 1
@@ -383,10 +450,35 @@ typedef struct FreeCamera {
#define ACT_GAME_START 1
#define ACT_GAME_RESTART 2
#define ACT_GAME_QUIT 3
+#define ACT_GAME_SAVECFG 4
+#define ACT_GAME_LOADCFG 5
/* visibilityact->flag */
/* Set means the object will become invisible */
#define ACT_VISIBILITY_INVISIBLE (1 << 0)
-
+#define ACT_VISIBILITY_RECURSIVE (1 << 1)
+
+/* twodfilter->type */
+#define ACT_2DFILTER_ENABLED -2
+#define ACT_2DFILTER_DISABLED -1
+#define ACT_2DFILTER_NOFILTER 0
+#define ACT_2DFILTER_MOTIONBLUR 1
+#define ACT_2DFILTER_BLUR 2
+#define ACT_2DFILTER_SHARPEN 3
+#define ACT_2DFILTER_DILATION 4
+#define ACT_2DFILTER_EROSION 5
+#define ACT_2DFILTER_LAPLACIAN 6
+#define ACT_2DFILTER_SOBEL 7
+#define ACT_2DFILTER_PREWITT 8
+#define ACT_2DFILTER_GRAYSCALE 9
+#define ACT_2DFILTER_SEPIA 10
+#define ACT_2DFILTER_INVERT 11
+#define ACT_2DFILTER_CUSTOMFILTER 12
+#define ACT_2DFILTER_NUMBER_OF_FILTERS 13
+
+/* parentactuator->type */
+#define ACT_PARENT_SET 0
+#define ACT_PARENT_REMOVE 1
#endif
+
diff --git a/source/blender/makesdna/DNA_armature_types.h b/source/blender/makesdna/DNA_armature_types.h
index 21f88c71a6e..93cb9f59860 100644
--- a/source/blender/makesdna/DNA_armature_types.h
+++ b/source/blender/makesdna/DNA_armature_types.h
@@ -97,7 +97,7 @@ typedef enum eArmature_Flag {
ARM_MIRROR_EDIT = (1<<8),
ARM_AUTO_IK = (1<<9),
ARM_NO_CUSTOM = (1<<10), /* made option negative, for backwards compat */
- ARM_COL_CUSTOM = (1<<11), /* draw custom colours - not yet used... */
+ ARM_COL_CUSTOM = (1<<11), /* draw custom colours */
ARM_GHOST_ONLYSEL = (1<<12) /* when ghosting, only show selected bones (this should belong to ghostflag instead) */
} eArmature_Flag;
@@ -140,7 +140,7 @@ typedef enum eBone_Flag {
BONE_ROOTSEL = (1<<1),
BONE_TIPSEL = (1<<2),
BONE_TRANSFORM = (1<<3), /* Used instead of BONE_SELECTED during transform */
- BONE_CONNECTED = (1<<4),
+ BONE_CONNECTED = (1<<4), /* when bone has a parent, connect head of bone to parent's tail*/
/* 32 used to be quatrot, was always set in files, do not reuse unless you clear it always */
BONE_HIDDEN_P = (1<<6), /* hidden Bones when drawing PoseChannels */
BONE_DONE = (1<<7), /* For detecting cyclic dependancies */
@@ -148,11 +148,15 @@ typedef enum eBone_Flag {
BONE_HINGE = (1<<9), /* No parent rotation or scale */
BONE_HIDDEN_A = (1<<10), /* hidden Bones when drawing Armature Editmode */
BONE_MULT_VG_ENV = (1<<11), /* multiplies vgroup with envelope */
- BONE_NO_DEFORM = (1<<12),
+ BONE_NO_DEFORM = (1<<12), /* bone doesn't deform geometry */
BONE_UNKEYED = (1<<13), /* set to prevent destruction of its unkeyframed pose (after transform) */
BONE_HINGE_CHILD_TRANSFORM = (1<<14), /* set to prevent hinge child bones from influencing the transform center */
BONE_NO_SCALE = (1<<15), /* No parent scale */
- BONE_HIDDEN_PG = (1<<16) /* hidden bone when drawing PoseChannels (for ghost drawing) */
+ BONE_HIDDEN_PG = (1<<16), /* hidden bone when drawing PoseChannels (for ghost drawing) */
+ BONE_DRAWWIRE = (1<<17), /* bone should be drawn as OB_WIRE, regardless of draw-types of view+armature */
+ BONE_NO_CYCLICOFFSET = (1<<18), /* when no parent, bone will not get cyclic offset */
+ BONE_EDITMODE_LOCKED = (1<<19), /* bone transforms are locked in EditMode */
+ BONE_TRANSFORM_CHILD = (1<<20), /* Indicates that a parent is also being transformed */
} eBone_Flag;
#endif
diff --git a/source/blender/makesdna/DNA_brush_types.h b/source/blender/makesdna/DNA_brush_types.h
index 1c272105067..c7196763358 100644
--- a/source/blender/makesdna/DNA_brush_types.h
+++ b/source/blender/makesdna/DNA_brush_types.h
@@ -33,7 +33,7 @@
#include "DNA_ID.h"
#ifndef MAX_MTEX
-#define MAX_MTEX 10
+#define MAX_MTEX 18
#endif
struct MTex;
@@ -58,7 +58,7 @@ typedef struct Brush {
float alpha; /* opacity */
short texact, pad;
- struct MTex *mtex[10];
+ struct MTex *mtex[18]; /* MAX_MTEX */
struct BrushClone clone;
} Brush;
diff --git a/source/blender/makesdna/DNA_cloth_types.h b/source/blender/makesdna/DNA_cloth_types.h
new file mode 100644
index 00000000000..c99dc44cd5e
--- /dev/null
+++ b/source/blender/makesdna/DNA_cloth_types.h
@@ -0,0 +1,95 @@
+/**
+* $Id: DNA_cloth_types.h,v 1.1 2007/08/01 02:28:34 daniel Exp $
+*
+* ***** BEGIN GPL LICENSE BLOCK *****
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 2
+* of the License, or (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software Foundation,
+* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*
+* The Original Code is Copyright (C) 2006 by NaN Holding BV.
+* All rights reserved.
+*
+* The Original Code is: all of this file.
+*
+* Contributor(s): Daniel (Genscher)
+*
+* ***** END GPL LICENSE BLOCK *****
+*/
+#ifndef DNA_CLOTH_TYPES_H
+#define DNA_CLOTH_TYPES_H
+
+/**
+* This struct contains all the global data required to run a simulation.
+* At the time of this writing, this structure contains data appropriate
+* to run a simulation as described in Deformation Constraints in a
+* Mass-Spring Model to Describe Rigid Cloth Behavior by Xavier Provot.
+*
+* I've tried to keep similar, if not exact names for the variables as
+* are presented in the paper. Where I've changed the concept slightly,
+* as in stepsPerFrame comapred to the time step in the paper, I've used
+* variables with different names to minimize confusion.
+**/
+
+typedef struct ClothSimSettings
+{
+ struct LinkNode *cache; /* UNUSED atm */
+ float mingoal; /* see SB */
+ float Cdis; /* Mechanical damping of springs. */
+ float Cvi; /* Viscous/fluid damping. */
+ float gravity [3]; /* Gravity/external force vector. */
+ float dt; /* This is the duration of our time step, computed. */
+ float mass; /* The mass of the entire cloth. */
+ float structural; /* Structural spring stiffness. */
+ float shear; /* Shear spring stiffness. */
+ float bending; /* Flexion spring stiffness. */
+ float max_bend; /* max bending scaling value, min is "bending" */
+ float max_struct; /* max structural scaling value, min is "structural" */
+ float max_shear; /* max shear scaling value, UNUSED */
+ float avg_spring_len; /* used for normalized springs */
+ float timescale; /* parameter how fast cloth runs */
+ float maxgoal; /* see SB */
+ float eff_force_scale;/* Scaling of effector forces (see softbody_calc_forces).*/
+ float eff_wind_scale; /* Scaling of effector wind (see softbody_calc_forces). */
+ float sim_time_old;
+ float defgoal;
+ float goalspring;
+ float goalfrict;
+ int stepsPerFrame; /* Number of time steps per frame. */
+ int flags; /* flags, see CSIMSETT_FLAGS enum above. */
+ int preroll; /* How many frames of simulation to do before we start. */
+ int maxspringlen; /* in percent!; if tearing enabled, a spring will get cut */
+ short solver_type; /* which solver should be used? txold */
+ short vgroup_bend; /* vertex group for scaling bending stiffness */
+ short vgroup_mass; /* optional vertexgroup name for assigning weight.*/
+ short vgroup_struct; /* vertex group for scaling structural stiffness */
+ short presets; /* used for presets on GUI */
+ short pad;
+ int pad2;
+} ClothSimSettings;
+
+
+typedef struct ClothCollSettings
+{
+ struct LinkNode *collision_list; /* e.g. pointer to temp memory for collisions */
+ float epsilon; /* min distance for collisions. */
+ float self_friction; /* Fiction/damping with self contact. */
+ float friction; /* Friction/damping applied on contact with other object.*/
+ float selfepsilon; /* for selfcollision */
+ int flags; /* collision flags defined in BKE_cloth.h */
+ short self_loop_count; /* How many iterations for the selfcollision loop */
+ short loop_count; /* How many iterations for the collision loop. */
+} ClothCollSettings;
+
+
+#endif
diff --git a/source/blender/makesdna/DNA_color_types.h b/source/blender/makesdna/DNA_color_types.h
index a4224976f5f..3caa74c9a72 100644
--- a/source/blender/makesdna/DNA_color_types.h
+++ b/source/blender/makesdna/DNA_color_types.h
@@ -69,13 +69,16 @@ typedef struct CurveMapping {
CurveMap cm[4]; /* max 4 builtin curves per mapping struct now */
float black[3], white[3]; /* black/white point (black[0] abused for current frame) */
- float bwmul[3], padf; /* black/white point multiply value, for speed */
+ float bwmul[3]; /* black/white point multiply value, for speed */
+
+ float sample[3]; /* sample values, if flag set it draws line and intersection */
} CurveMapping;
/* cumapping->flag */
#define CUMA_DO_CLIP 1
#define CUMA_PREMULLED 2
#define CUMA_DRAW_CFRA 4
+#define CUMA_DRAW_SAMPLE 8
#endif
diff --git a/source/blender/makesdna/DNA_constraint_types.h b/source/blender/makesdna/DNA_constraint_types.h
index 1a82ec07f00..fe19cf60f12 100644
--- a/source/blender/makesdna/DNA_constraint_types.h
+++ b/source/blender/makesdna/DNA_constraint_types.h
@@ -304,6 +304,19 @@ typedef struct bSizeLimitConstraint {
short flag2;
} bSizeLimitConstraint;
+/* Limit Distance Constraint */
+typedef struct bDistLimitConstraint {
+ Object *tar;
+ char subtarget[32];
+
+ float dist; /* distance (radius of clamping sphere) from target */
+ float soft; /* distance from clamping-sphere to start applying 'fade' */
+
+ short flag; /* settings */
+ short mode; /* how to limit in relation to clamping sphere */
+ int pad;
+} bDistLimitConstraint;
+
/* ------------------------------------------ */
/* bConstraint->type
@@ -325,13 +338,14 @@ typedef enum B_CONSTAINT_TYPES {
CONSTRAINT_TYPE_PYTHON, /* Unimplemented no longer :) - Aligorith. Scripts */
CONSTRAINT_TYPE_ACTION,
CONSTRAINT_TYPE_LOCKTRACK, /* New Tracking constraint that locks an axis in place - theeth */
- CONSTRAINT_TYPE_DISTANCELIMIT, /* was never properly coded - removed! */
+ CONSTRAINT_TYPE_DISTLIMIT, /* limit distance */
CONSTRAINT_TYPE_STRETCHTO, /* claiming this to be mine :) is in tuhopuu bjornmose */
CONSTRAINT_TYPE_MINMAX, /* floor constraint */
CONSTRAINT_TYPE_RIGIDBODYJOINT, /* rigidbody constraint */
CONSTRAINT_TYPE_CLAMPTO, /* clampto constraint */
CONSTRAINT_TYPE_TRANSFORM, /* transformation (loc/rot/size -> loc/rot/size) constraint */
+
/* NOTE: everytime a new constraint is added, update this */
NUM_CONSTRAINT_TYPES= CONSTRAINT_TYPE_TRANSFORM
} B_CONSTRAINT_TYPES;
@@ -349,7 +363,9 @@ typedef enum B_CONSTRAINT_FLAG {
/* to indicate that the owner's space should only be changed into ownspace, but not out of it */
CONSTRAINT_SPACEONCE = (1<<6),
/* influence ipo is on constraint itself, not in action channel */
- CONSTRAINT_OWN_IPO = (1<<7)
+ CONSTRAINT_OWN_IPO = (1<<7),
+ /* indicates that constraint was added locally (i.e. didn't come from the proxy-lib) */
+ CONSTRAINT_PROXY_LOCAL = (1<<8)
} B_CONSTRAINT_FLAG;
/* bConstraint->ownspace/tarspace */
@@ -359,11 +375,13 @@ typedef enum B_CONSTRAINT_SPACETYPES {
/* for objects (relative to parent/without parent influence),
* for bones (along normals of bone, without parent/restpositions)
*/
- CONSTRAINT_SPACE_LOCAL,
+ CONSTRAINT_SPACE_LOCAL, /* = 1 */
/* for posechannels - pose space */
- CONSTRAINT_SPACE_POSE,
- /* for posechannels - local with parent */
- CONSTRAINT_SPACE_PARLOCAL,
+ CONSTRAINT_SPACE_POSE, /* = 2 */
+ /* for posechannels - local with parent */
+ CONSTRAINT_SPACE_PARLOCAL, /* = 3 */
+ /* for files from between 2.43-2.46 (should have been parlocal) */
+ CONSTRAINT_SPACE_INVALID, /* = 4. do not exchange for anything! */
} B_CONSTRAINT_SPACETYPES;
/* bConstraintChannel.flag */
@@ -445,7 +463,9 @@ typedef enum B_CONSTRAINTCHANNEL_FLAG {
/* bKinematicConstraint->flag */
#define CONSTRAINT_IK_TIP 1
#define CONSTRAINT_IK_ROT 2
+ /* targetless */
#define CONSTRAINT_IK_AUTO 4
+ /* autoik */
#define CONSTRAINT_IK_TEMP 8
#define CONSTRAINT_IK_STRETCH 16
#define CONSTRAINT_IK_POS 32
@@ -473,6 +493,15 @@ typedef enum B_CONSTRAINTCHANNEL_FLAG {
#define LIMIT_NOPARENT 0x01
/* for all Limit constraints - allow to be used during transform? */
#define LIMIT_TRANSFORM 0x02
+
+/* distance limit constraint */
+ /* bDistLimitConstraint->flag */
+#define LIMITDIST_USESOFT (1<<0)
+
+ /* bDistLimitConstraint->mode */
+#define LIMITDIST_INSIDE 0
+#define LIMITDIST_OUTSIDE 1
+#define LIMITDIST_ONSURFACE 2
/* python constraint -> flag */
#define PYCON_USETARGETS 0x01
@@ -491,6 +520,7 @@ typedef enum B_CONSTRAINTCHANNEL_FLAG {
/* Rigid-Body Constraint */
#define CONSTRAINT_DRAW_PIVOT 0x40
+#define CONSTRAINT_DISABLE_LINKED_COLLISION 0x80
/* important: these defines need to match up with PHY_DynamicTypes headerfile */
#define CONSTRAINT_RB_BALL 1
diff --git a/source/blender/makesdna/DNA_controller_types.h b/source/blender/makesdna/DNA_controller_types.h
index 95c9b0d0cf7..376f95b0145 100644
--- a/source/blender/makesdna/DNA_controller_types.h
+++ b/source/blender/makesdna/DNA_controller_types.h
@@ -57,7 +57,7 @@ typedef struct bController {
struct bSensor **slinks;
short val, valo;
- int pad5;
+ unsigned int state_mask;
} bController;
@@ -66,11 +66,16 @@ typedef struct bController {
#define CONT_LOGIC_OR 1
#define CONT_EXPRESSION 2
#define CONT_PYTHON 3
+#define CONT_LOGIC_NAND 4
+#define CONT_LOGIC_NOR 5
+#define CONT_LOGIC_XOR 6
+#define CONT_LOGIC_XNOR 7
/* controller->flag */
#define CONT_SHOW 1
#define CONT_DEL 2
#define CONT_NEW 4
+#define CONT_MASK 8
#endif
diff --git a/source/blender/makesdna/DNA_curve_types.h b/source/blender/makesdna/DNA_curve_types.h
index a4fb8dc1150..f809cac037d 100644
--- a/source/blender/makesdna/DNA_curve_types.h
+++ b/source/blender/makesdna/DNA_curve_types.h
@@ -68,7 +68,7 @@ typedef struct BevList {
#
#
typedef struct BevPoint {
- float x, y, z, alfa, sina, cosa, mat[3][3];
+ float x, y, z, alfa, radius, sina, cosa, mat[3][3];
short f1, f2;
} BevPoint;
@@ -115,7 +115,7 @@ typedef struct Nurb {
BezTriple *bezt;
short tilt_interp; /* KEY_LINEAR, KEY_CARDINAL, KEY_BSPLINE */
- short pad;
+ short radius_interp;
int charidx;
} Nurb;
@@ -187,37 +187,6 @@ typedef struct Curve {
struct CharInfo curinfo;
} Curve;
-typedef struct IpoDriver {
- struct Object *ob;
- short blocktype, adrcode, type, flag;
- char name[128]; /* bone or constraint(?), or python expression here */
-} IpoDriver;
-
-/* temp? we store more bone names in 1 driver... */
-#define DRIVER_NAME_OFFS 32
-
-typedef struct IpoCurve {
- struct IpoCurve *next, *prev;
-
- struct BPoint *bp; /* are these even used anywhere? */
- struct BezTriple *bezt; /* array of BezTriples (sizeof(BezTriple)*totvert. i.e. keyframes */
-
- rctf maxrct, totrct; /* bounding boxes */
-
- short blocktype, adrcode, vartype; /* blocktype= ipo-blocktype; adrcode= type of ipo-curve; vartype= 'format' of data */
- short totvert; /* total number of BezTriples (i.e. keyframes) on curve */
- short ipo, extrap; /* interpolation and extrapolation modes */
- short flag, rt; /* flag= settings; rt= ??? */
- float ymin, ymax; /* minimum/maximum y-extents for curve */
- unsigned int bitmask; /* ??? */
-
- float slide_min, slide_max; /* minimum/maximum values for sliders (in action editor) */
- float curval; /* value of ipo-curve for current frame */
-
- IpoDriver *driver; /* pointer to ipo-driver for this curve */
-
-} IpoCurve;
-
/* **************** CURVE ********************* */
/* texflag */
@@ -273,15 +242,5 @@ typedef struct IpoCurve {
#define CU_UNDERLINE 4
#define CU_WRAP 8 /* wordwrap occured here */
-/* *************** driver ****************** */
-
-/* driver->type */
-#define IPO_DRIVER_TYPE_NORMAL 0
-#define IPO_DRIVER_TYPE_PYTHON 1
-
-/* driver->flag */
-/* invalid flag: currently only used for buggy pydriver expressions: */
-#define IPO_DRIVER_FLAG_INVALID 1
-
#endif
diff --git a/source/blender/makesdna/DNA_customdata_types.h b/source/blender/makesdna/DNA_customdata_types.h
index 73a39abac55..6c098e220bb 100644
--- a/source/blender/makesdna/DNA_customdata_types.h
+++ b/source/blender/makesdna/DNA_customdata_types.h
@@ -26,6 +26,7 @@
*
* ***** END GPL LICENSE BLOCK *****
*/
+
#ifndef DNA_CUSTOMDATA_TYPES_H
#define DNA_CUSTOMDATA_TYPES_H
@@ -48,6 +49,7 @@ typedef struct CustomData {
CustomDataLayer *layers; /* CustomDataLayers, ordered by type */
int totlayer, maxlayer; /* number of layers, size of layers array */
int totsize, pad; /* in editmode, total size of all data layers */
+ void *pool; /* for Bmesh: Memory pool for allocation of blocks*/
} CustomData;
/* CustomData.type */
@@ -66,7 +68,11 @@ typedef struct CustomData {
#define CD_PROP_STR 12
#define CD_ORIGSPACE 13 /* for modifier stack face location mapping */
#define CD_ORCO 14
-#define CD_NUMTYPES 15
+#define CD_MTEXPOLY 15
+#define CD_MLOOPUV 16
+#define CD_MLOOPCOL 17
+#define CD_TANGENT 18
+#define CD_NUMTYPES 19
/* Bits for CustomDataMask */
#define CD_MASK_MVERT (1 << CD_MVERT)
@@ -84,6 +90,10 @@ typedef struct CustomData {
#define CD_MASK_PROP_STR (1 << CD_PROP_STR)
#define CD_MASK_ORIGSPACE (1 << CD_ORIGSPACE)
#define CD_MASK_ORCO (1 << CD_ORCO)
+#define CD_MASK_MTEXPOLY (1 << CD_MTEXPOLY)
+#define CD_MASK_MLOOPUV (1 << CD_MLOOPUV)
+#define CD_MASK_MLOOPCOL (1 << CD_MLOOPCOL)
+#define CD_MASK_TANGENT (1 << CD_TANGENT)
/* CustomData.flag */
diff --git a/source/blender/makesdna/DNA_gpencil_types.h b/source/blender/makesdna/DNA_gpencil_types.h
new file mode 100644
index 00000000000..70f469b2bb8
--- /dev/null
+++ b/source/blender/makesdna/DNA_gpencil_types.h
@@ -0,0 +1,145 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2008, Blender Foundation.
+ * This is a new part of Blender
+ *
+ * Contributor(s): Joshua Leung
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef DNA_GPENCIL_TYPES_H
+#define DNA_GPENCIL_TYPES_H
+
+#include "DNA_listBase.h"
+#include "DNA_ID.h"
+
+/* Grease-Pencil Annotations - 'Stroke Point'
+ * -> Coordinates may either be 2d or 3d depending on settings at the time
+ * -> Coordinates of point on stroke, in proportions of window size
+ * (i.e. n/1000). This assumes that the bottom-left corner is (0,0)
+ */
+typedef struct bGPDspoint {
+ float x, y, z; /* co-ordinates of point (usually 2d, but can be 3d as well) */
+ float pressure; /* pressure of input device (from 0 to 1) at this point */
+} bGPDspoint;
+
+/* Grease-Pencil Annotations - 'Stroke'
+ * -> A stroke represents a (simplified version) of the curve
+ * drawn by the user in one 'mousedown'->'mouseup' operation
+ */
+typedef struct bGPDstroke {
+ struct bGPDstroke *next, *prev;
+
+ bGPDspoint *points; /* array of data-points for stroke */
+ int totpoints; /* number of data-points in array */
+
+ short thickness; /* thickness of stroke (currently not used) */
+ short flag; /* various settings about this stroke */
+} bGPDstroke;
+
+/* bGPDstroke->flag */
+ /* stroke is in 3d-space */
+#define GP_STROKE_3DSPACE (1<<0)
+ /* stroke is in 2d-space */
+#define GP_STROKE_2DSPACE (1<<1)
+ /* stroke is in 2d-space (but with special 'image' scaling) */
+#define GP_STROKE_2DIMAGE (1<<2)
+ /* only for use with stroke-buffer (while drawing eraser) */
+#define GP_STROKE_ERASER (1<<15)
+
+
+/* Grease-Pencil Annotations - 'Frame'
+ * -> Acts as storage for the 'image' formed by strokes
+ */
+typedef struct bGPDframe {
+ struct bGPDframe *next, *prev;
+
+ ListBase strokes; /* list of the simplified 'strokes' that make up the frame's data */
+
+ int framenum; /* frame number of this frame */
+ int flag; /* temp settings */
+} bGPDframe;
+
+/* bGPDframe->flag */
+ /* frame is being painted on */
+#define GP_FRAME_PAINT (1<<0)
+ /* for editing in Action Editor */
+#define GP_FRAME_SELECT (1<<1)
+
+
+/* Grease-Pencil Annotations - 'Layer' */
+typedef struct bGPDlayer {
+ struct bGPDlayer *next, *prev;
+
+ ListBase frames; /* list of annotations to display for frames (bGPDframe list) */
+ bGPDframe *actframe; /* active frame (should be the frame that is currently being displayed) */
+
+ int flag; /* settings for layer */
+ short thickness; /* current thickness to apply to strokes */
+ short gstep; /* max number of frames between active and ghost to show (0=only those on either side) */
+
+ float color[4]; /* color that should be used to draw all the strokes in this layer */
+
+ char info[128]; /* optional reference info about this layer (i.e. "director's comments, 12/3") */
+} bGPDlayer;
+
+/* bGPDlayer->flag */
+ /* don't display layer */
+#define GP_LAYER_HIDE (1<<0)
+ /* protected from further editing */
+#define GP_LAYER_LOCKED (1<<1)
+ /* layer is 'active' layer being edited */
+#define GP_LAYER_ACTIVE (1<<2)
+ /* draw points of stroke for debugging purposes */
+#define GP_LAYER_DRAWDEBUG (1<<3)
+ /* do onionskinning */
+#define GP_LAYER_ONIONSKIN (1<<4)
+ /* for editing in Action Editor */
+#define GP_LAYER_SELECT (1<<5)
+
+
+/* Grease-Pencil Annotations - 'DataBlock' */
+typedef struct bGPdata {
+ /* saved Grease-Pencil data */
+ ListBase layers; /* bGPDlayers */
+ int flag; /* settings for this datablock */
+
+ /* not-saved stroke buffer data (only used during paint-session)
+ * - buffer must be initialised before use, but freed after
+ * whole paint operation is over
+ */
+ short sbuffer_size; /* number of elements currently in cache */
+ short sbuffer_sflag; /* flags for stroke that cache represents */
+ void *sbuffer; /* stroke buffer (can hold GP_STROKE_BUFFER_MAX) */
+} bGPdata;
+
+/* bGPdata->flag */
+ /* don't allow painting to occur at all */
+#define GP_DATA_LMBPLOCK (1<<0)
+ /* show debugging info in viewport (i.e. status print) */
+#define GP_DATA_DISPINFO (1<<1)
+ /* in Action Editor, show as expanded channel */
+#define GP_DATA_EXPAND (1<<2)
+ /* is the block overriding all clicks? */
+#define GP_DATA_EDITPAINT (1<<3)
+ /* new strokes are added in viewport space */
+#define GP_DATA_VIEWALIGN (1<<4)
+
+#endif /* DNA_GPENCIL_TYPES_H */
diff --git a/source/blender/makesdna/DNA_group_types.h b/source/blender/makesdna/DNA_group_types.h
index 1bb18ca2ca2..0987050261d 100644
--- a/source/blender/makesdna/DNA_group_types.h
+++ b/source/blender/makesdna/DNA_group_types.h
@@ -54,7 +54,7 @@ typedef struct Group {
* the objects that show in the group can change depending
* on the last used scene */
unsigned int layer;
- int pad;
+ float dupli_ofs[3];
} Group;
diff --git a/source/blender/makesdna/DNA_image_types.h b/source/blender/makesdna/DNA_image_types.h
index b1e632661e8..e1d79f0f875 100644
--- a/source/blender/makesdna/DNA_image_types.h
+++ b/source/blender/makesdna/DNA_image_types.h
@@ -37,6 +37,7 @@ struct PackedFile;
struct anim;
struct ImBuf;
struct RenderResult;
+struct GPUTexture;
/* ImageUser is in Texture, in Nodes, Background Image, Image Window, .... */
@@ -55,13 +56,15 @@ typedef struct ImageUser {
/* iuser->flag */
#define IMA_ANIM_ALWAYS 1
#define IMA_ANIM_REFRESHED 2
+/* #define IMA_DO_PREMUL 4 */
typedef struct Image {
ID id;
char name[240]; /* file path */
- ListBase ibufs; /* not written in file */
+ ListBase ibufs; /* not written in file */
+ struct GPUTexture *gputexture; /* not written in file */
/* sources from: */
struct anim *anim;
@@ -101,11 +104,12 @@ typedef struct Image {
/* flag */
#define IMA_FIELDS 1
#define IMA_STD_FIELD 2
+#define IMA_DO_PREMUL 4
#define IMA_REFLECT 16
#define IMA_NOCOLLECT 32
#define IMA_ANTIALI 64
-#define IMA_DO_PREMUL 128
+#define IMA_OLD_PREMUL 128
/* tpageflag */
#define IMA_TILES 1
diff --git a/source/blender/makesdna/DNA_ipo_types.h b/source/blender/makesdna/DNA_ipo_types.h
index 3954a500dc7..432399e3581 100644
--- a/source/blender/makesdna/DNA_ipo_types.h
+++ b/source/blender/makesdna/DNA_ipo_types.h
@@ -24,7 +24,7 @@
*
* The Original Code is: all of this file.
*
- * Contributor(s): none yet.
+ * Contributor(s): Joshua Leung
*
* ***** END GPL LICENSE BLOCK *****
*/
@@ -32,10 +32,54 @@
#define DNA_IPO_TYPES_H
#include "DNA_listBase.h"
+#include "DNA_curve_types.h"
#include "DNA_vec_types.h"
#include "DNA_ID.h"
+/* -------------------------- Type Defines --------------------------- */
+
+/* sometimes used - mainly for GE/Ketsji */
+typedef short IPO_Channel;
+
+
+/* --- IPO Curve Driver --- */
+
+/* IPO Curve Driver */
+typedef struct IpoDriver {
+ struct Object *ob; /* target/driver ob */
+ short blocktype, adrcode; /* sub-channel to use */
+
+ short type, flag; /* driver settings */
+ char name[128]; /* bone, or python expression here */
+} IpoDriver;
+
+/* --- IPO Curve --- */
+
+/* IPO Curve */
+typedef struct IpoCurve {
+ struct IpoCurve *next, *prev;
+
+ struct BPoint *bp; /* array of BPoints (sizeof(BPoint)*totvert) - i.e. baked/imported data */
+ struct BezTriple *bezt; /* array of BezTriples (sizeof(BezTriple)*totvert) - i.e. user-editable keyframes */
+
+ rctf maxrct, totrct; /* bounding boxes */
+
+ short blocktype, adrcode, vartype; /* blocktype= ipo-blocktype; adrcode= type of ipo-curve; vartype= 'format' of data */
+ short totvert; /* total number of BezTriples (i.e. keyframes) on curve */
+ short ipo, extrap; /* interpolation and extrapolation modes */
+ short flag, rt; /* flag= settings; rt= ??? */
+ float ymin, ymax; /* minimum/maximum y-extents for curve */
+ unsigned int bitmask; /* ??? */
+
+ float slide_min, slide_max; /* minimum/maximum values for sliders (in action editor) */
+ float curval; /* value of ipo-curve for current frame */
+
+ IpoDriver *driver; /* pointer to ipo-driver for this curve */
+} IpoCurve;
+
+/* --- ID-Datablock --- */
+
/* IPO Data-Block */
typedef struct Ipo {
ID id;
@@ -47,13 +91,9 @@ typedef struct Ipo {
short muteipo, pad; /* muteipo: either 0 or 1 (whether ipo block is muted) */
} Ipo;
-/* NOTE: IpoCurve struct is defined in DNA_curve_types.h, not in here... */
-
-/* sometimes used */
-typedef short IPO_Channel;
+/* ----------- adrcodes (for matching ipo-curves to data) ------------- */
/* defines: are these duped or new? */
-
#define IPOBUTY 17
#define TOB_IPO 1
@@ -64,7 +104,7 @@ typedef short IPO_Channel;
#define IPO_DISPBITS 2
#define IPO_DISPTIME 3
-/* ******************** */
+/* ********** Object (ID_OB) ********** */
#define OB_TOTIPO 30
#define OB_TOTNAM 30
@@ -110,7 +150,7 @@ typedef short IPO_Channel;
#define OB_ROT_DIFF 100
-/* ******************** */
+/* ********** Material (ID_MA) ********** */
#define MA_TOTIPO 40
#define MA_TOTNAM 26
@@ -142,16 +182,26 @@ typedef short IPO_Channel;
#define MA_FRESTRAI 25
#define MA_ADD 26
-#define MA_MAP1 0x20
-#define MA_MAP2 0x40
-#define MA_MAP3 0x80
-#define MA_MAP4 0x100
-#define MA_MAP5 0x200
-#define MA_MAP6 0x400
-#define MA_MAP7 0x800
-#define MA_MAP8 0x1000
-#define MA_MAP9 0x2000
-#define MA_MAP10 0x4000
+#define MA_MAP1 (1<<5)
+#define MA_MAP2 (1<<6)
+#define MA_MAP3 (1<<7)
+#define MA_MAP4 (1<<8)
+#define MA_MAP5 (1<<9)
+#define MA_MAP6 (1<<10)
+#define MA_MAP7 (1<<11)
+#define MA_MAP8 (1<<12)
+#define MA_MAP9 (1<<13)
+#define MA_MAP10 (1<<14)
+#define MA_MAP11 (1<<15)
+#define MA_MAP12 (1<<16)
+#define MA_MAP13 (1<<17)
+#define MA_MAP14 (1<<18)
+#define MA_MAP15 (1<<19)
+#define MA_MAP16 (1<<20)
+#define MA_MAP17 (1<<21)
+#define MA_MAP18 (1<<22)
+
+/* ********** Texture Slots (MTex) ********** */
#define TEX_TOTNAM 14
@@ -171,7 +221,7 @@ typedef short IPO_Channel;
#define MAP_VARF 13
#define MAP_DISP 14
-/* ******************** */
+/* ********** Texture (ID_TE) ********** */
#define TE_TOTIPO 26
#define TE_TOTNAM 26
@@ -208,21 +258,21 @@ typedef short IPO_Channel;
#define TE_BRIGHT 25
#define TE_CONTRA 26
-/* ******************** */
+/* ******** Sequence (ID_SEQ) ********** */
#define SEQ_TOTIPO 1
#define SEQ_TOTNAM 1
#define SEQ_FAC1 1
-/* ******************** */
+/* ********* Curve (ID_CU) *********** */
#define CU_TOTIPO 1
#define CU_TOTNAM 1
#define CU_SPEED 1
-/* ******************** */
+/* ********* ShapeKey (ID_KE) *********** */
#define KEY_TOTIPO 64
#define KEY_TOTNAM 64
@@ -230,7 +280,7 @@ typedef short IPO_Channel;
#define KEY_SPEED 0
#define KEY_NR 1
-/* ******************** */
+/* ********* World (ID_WO) *********** */
#define WO_TOTIPO 29
#define WO_TOTNAM 16
@@ -255,7 +305,7 @@ typedef short IPO_Channel;
#define WO_STARDIST 15
#define WO_STARSIZE 16
-/* ******************** */
+/* ********** Lamp (ID_LA) ********** */
#define LA_TOTIPO 21
#define LA_TOTNAM 10
@@ -271,9 +321,8 @@ typedef short IPO_Channel;
#define LA_QUAD2 9
#define LA_HALOINT 10
-/* ******************** */
+/* ********* Camera (ID_CA) ************ */
-/* yafray: totipo & totnam +2 because of added curves */
#define CAM_TOTIPO 7
#define CAM_TOTNAM 7
@@ -288,7 +337,7 @@ typedef short IPO_Channel;
#define CAM_SHIFT_X 6
#define CAM_SHIFT_Y 7
-/* ******************** */
+/* ********* Sound (ID_SO) *********** */
#define SND_TOTIPO 4
#define SND_TOTNAM 4
@@ -298,9 +347,9 @@ typedef short IPO_Channel;
#define SND_PANNING 3
#define SND_ATTEN 4
-/* ******************** */
+/* ******* PoseChannel (ID_PO) ********* */
-#define AC_TOTIPO 10 /* __NLA */
+#define AC_TOTIPO 10
#define AC_TOTNAM 10
#define AC_LOC_X 1
@@ -316,28 +365,18 @@ typedef short IPO_Channel;
#define AC_QUAT_Y 27
#define AC_QUAT_Z 28
-/* ******************** */
-#define CO_TOTIPO 2 /* Constraint Ipos */
+/* ******** Constraint (ID_CO) ********** */
+
+#define CO_TOTIPO 2
#define CO_TOTNAM 2
#define CO_ENFORCE 1
#define CO_HEADTAIL 2
-/*
-#define CO_TIME 2
-#define CO_OFFSET_X 3
-#define CO_OFFSET_Y 4
-#define CO_OFFSET_Z 5
-#define CO_ORIENT_X 6
-#define CO_ORIENT_Y 7
-#define CO_ORIENT_Z 8
-#define CO_ROLL 9
-*/
-/* ******************** */
-/* fluidsim ipos NT */
+/* ****** FluidSim (ID_FLUIDSIM) ****** */
-#define FLUIDSIM_TOTIPO 9
-#define FLUIDSIM_TOTNAM 9
+#define FLUIDSIM_TOTIPO 13
+#define FLUIDSIM_TOTNAM 13
#define FLUIDSIM_VISC 1
#define FLUIDSIM_TIME 2
@@ -352,10 +391,17 @@ typedef short IPO_Channel;
#define FLUIDSIM_ACTIVE 9
+#define FLUIDSIM_ATTR_FORCE_STR 10
+#define FLUIDSIM_ATTR_FORCE_RADIUS 11
+#define FLUIDSIM_VEL_FORCE_STR 12
+#define FLUIDSIM_VEL_FORCE_RADIUS 13
+
/* ******************** */
/* particle ipos */
-#define PART_TOTIPO 19
-#define PART_TOTNAM 19
+
+/* ******* Particle (ID_PA) ******** */
+#define PART_TOTIPO 25
+#define PART_TOTNAM 25
#define PART_EMIT_FREQ 1
#define PART_EMIT_LIFE 2
@@ -381,9 +427,18 @@ typedef short IPO_Channel;
#define PART_BB_TILT 19
+#define PART_PD_FSTR 20
+#define PART_PD_FFALL 21
+#define PART_PD_FMAXD 22
+
+#define PART_PD2_FSTR 23
+#define PART_PD2_FFALL 24
+#define PART_PD2_FMAXD 25
+
+
+/* -------------------- Defines: Flags and Types ------------------ */
-/* these are IpoCurve specific */
-/* **************** IPO ********************* */
+/* ----- IPO Curve Defines ------- */
/* icu->vartype */
#define IPO_CHAR 0
@@ -393,6 +448,7 @@ typedef short IPO_Channel;
#define IPO_FLOAT 4
#define IPO_DOUBLE 5
#define IPO_FLOAT_DEGR 6
+
/* very special case, in keys */
#define IPO_BEZTRIPLE 100
#define IPO_BPOINT 101
@@ -407,7 +463,8 @@ typedef short IPO_Channel;
#define IPO_CONST 0
#define IPO_LIN 1
#define IPO_BEZ 2
-#define IPO_MIXED 3 /* not used yet */
+ /* not used yet */
+#define IPO_MIXED 3
/* icu->extrap */
#define IPO_HORIZ 0
@@ -425,6 +482,19 @@ typedef short IPO_Channel;
#define IPO_PROTECT 64
#define IPO_MUTE 128
+/* ---------- IPO Drivers ----------- */
+
+/* offset in driver->name for finding second posechannel for rot-diff */
+#define DRIVER_NAME_OFFS 32
+
+/* driver->type */
+#define IPO_DRIVER_TYPE_NORMAL 0
+#define IPO_DRIVER_TYPE_PYTHON 1
+
+/* driver->flag */
+ /* invalid flag: currently only used for buggy pydriver expressions */
+#define IPO_DRIVER_FLAG_INVALID (1<<0)
+
#endif
diff --git a/source/blender/makesdna/DNA_lamp_types.h b/source/blender/makesdna/DNA_lamp_types.h
index 2afe78289c1..f8f2255c1a7 100644
--- a/source/blender/makesdna/DNA_lamp_types.h
+++ b/source/blender/makesdna/DNA_lamp_types.h
@@ -35,7 +35,7 @@
#include "DNA_scriptlink_types.h"
#ifndef MAX_MTEX
-#define MAX_MTEX 10
+#define MAX_MTEX 18
#endif
struct MTex;
@@ -45,20 +45,21 @@ struct CurveMapping;
typedef struct Lamp {
ID id;
- short type, mode;
+ short type, pad3;
+ int mode;
short colormodel, totex;
float r, g, b, k;
+ float shdwr, shdwg, shdwb, shdwpad;
float energy, dist, spotsize, spotblend;
float haint;
float att1, att2; /* Quad1 and Quad2 attenuation */
- int pad2;
struct CurveMapping *curfalloff;
short falloff_type;
- short pad3;
+ short pad2;
float clipsta, clipend, shadspotsize;
float bias, soft;
@@ -76,6 +77,23 @@ typedef struct Lamp {
/* texact is for buttons */
short texact, shadhalostep;
+ /* sun/sky */
+ short sun_effect_type;
+ short skyblendtype;
+ float horizon_brightness;
+ float spread;
+ float sun_brightness;
+ float sun_size;
+ float backscattered_light;
+ float sun_intensity;
+ float atm_turbidity;
+ float atm_inscattering_factor;
+ float atm_extinction_factor;
+ float atm_distance_factor;
+ float skyblendfac;
+ float sky_exposure;
+ short sky_colorspace, pad4;
+
/* yafray: photonlight params */
int YF_numphotons, YF_numsearch;
short YF_phdepth, YF_useqmc, YF_bufsize, YF_pad;
@@ -84,7 +102,7 @@ typedef struct Lamp {
float YF_glowint, YF_glowofs;
short YF_glowtype, YF_pad2;
- struct MTex *mtex[10];
+ struct MTex *mtex[18]; /* MAX_MTEX */
struct Ipo *ipo;
/* preview */
@@ -122,6 +140,17 @@ typedef struct Lamp {
/* yafray: lamp shadowbuffer flag, softlight */
/* Since it is used with LOCAL lamp, can't use LA_SHAD */
#define LA_YF_SOFT 16384
+#define LA_LAYER_SHADOW 32768
+#define LA_SHAD_TEX (1<<16)
+
+/* layer_shadow */
+#define LA_LAYER_SHADOW_BOTH 0
+#define LA_LAYER_SHADOW_CAST 1
+#define LA_LAYER_SHADOW_RECEIVE 2
+
+/* sun effect type*/
+#define LA_SUN_EFFECT_SKY 1
+#define LA_SUN_EFFECT_AP 2
/* falloff_type */
#define LA_FALLOFF_CONSTANT 0
@@ -165,6 +194,7 @@ typedef struct Lamp {
/* mapto */
#define LAMAP_COL 1
+#define LAMAP_SHAD 2
#endif /* DNA_LAMP_TYPES_H */
diff --git a/source/blender/makesdna/DNA_material_types.h b/source/blender/makesdna/DNA_material_types.h
index 701041319e5..aa847050581 100644
--- a/source/blender/makesdna/DNA_material_types.h
+++ b/source/blender/makesdna/DNA_material_types.h
@@ -36,7 +36,7 @@
#include "DNA_listBase.h"
#ifndef MAX_MTEX
-#define MAX_MTEX 10
+#define MAX_MTEX 18
#endif
struct MTex;
@@ -76,21 +76,23 @@ typedef struct Material {
float aniso_gloss_mir;
float dist_mir;
short fadeto_mir;
- short pad1;
+ short shade_flag; /* like Cubic interpolation */
int mode, mode_l; /* mode_l is the or-ed result of all layer modes */
short flarec, starc, linec, ringc;
float hasize, flaresize, subsize, flareboost;
float strand_sta, strand_end, strand_ease, strand_surfnor;
- float strand_min, strand_pad;
+ float strand_min, strand_widthfade;
char strand_uvname[32];
- float sbias; /* shadow bias */
+ float sbias; /* shadow bias to prevent terminator prob */
+ float lbias; /* factor to multiply lampbias with (0.0 = no mult) */
float shad_alpha; /* in use for irregular shadowbuffer */
+ int septex;
/* for buttons and render*/
char rgbsel, texact, pr_type, use_nodes;
- short pr_back, pr_lamp, septex, ml_flag; /* ml_flag is for disable base material */
+ short pr_back, pr_lamp, pad4, ml_flag; /* ml_flag is for disable base material */
/* shaders */
short diff_shader, spec_shader;
@@ -108,7 +110,7 @@ typedef struct Material {
short ramp_show, pad3;
float rampfac_col, rampfac_spec;
- struct MTex *mtex[10];
+ struct MTex *mtex[18]; /* MAX_MTEX */
struct bNodeTree *nodetree;
struct Ipo *ipo;
struct Group *group; /* light group */
@@ -131,6 +133,8 @@ typedef struct Material {
int YF_dsmp, YF_preset, YF_djit;
ScriptLink scriptlink;
+
+ ListBase gpumaterial; /* runtime */
} Material;
/* **************** MATERIAL ********************* */
@@ -156,6 +160,7 @@ typedef struct Material {
#define MA_SHLESS 4
#define MA_WIRE 8
#define MA_VERTEXCOL 16
+#define MA_HALO_SOFT 16
#define MA_HALO 32
#define MA_ZTRA 64
#define MA_VERTEXCOLP 128
@@ -192,12 +197,16 @@ typedef struct Material {
#define MA_STR_B_UNITS 0x40000000
#define MA_STR_SURFDIFF 0x80000000
-#define MA_MODE_MASK 0x4fffffff /* all valid mode bits */
+#define MA_MODE_MASK 0x6fffffff /* all valid mode bits */
/* ray mirror fadeout */
#define MA_RAYMIR_FADETOSKY 0
#define MA_RAYMIR_FADETOMAT 1
+/* shade_flag */
+#define MA_CUBIC 1
+#define MA_OBCOLOR 2
+
/* diff_shader */
#define MA_DIFF_LAMBERT 0
#define MA_DIFF_ORENNAYAR 1
@@ -311,6 +320,7 @@ typedef struct Material {
#define MA_LAMP 6
#define MA_SKY 7
#define MA_HAIR 10
+#define MA_ATMOS 11
/* pr_back */
#define MA_DARK 1
diff --git a/source/blender/makesdna/DNA_meshdata_types.h b/source/blender/makesdna/DNA_meshdata_types.h
index 819711a7875..fc686a4cc10 100644
--- a/source/blender/makesdna/DNA_meshdata_types.h
+++ b/source/blender/makesdna/DNA_meshdata_types.h
@@ -42,7 +42,7 @@ typedef struct MFace {
typedef struct MEdge {
unsigned int v1, v2;
- char crease, pad;
+ char crease, bweight;
short flag;
} MEdge;
@@ -60,7 +60,7 @@ typedef struct MDeformVert {
typedef struct MVert {
float co[3];
short no[3];
- char flag, mat_nr;
+ char flag, mat_nr, bweight, pad[3];
} MVert;
/* at the moment alpha is abused for vertex painting
@@ -69,6 +69,22 @@ typedef struct MCol {
char a, r, g, b;
} MCol;
+/*bmesh custom data stuff*/
+typedef struct MTexPoly{
+ struct Image *tpage;
+ char flag, transp;
+ short mode,tile,unwrap;
+}MTexPoly;
+
+typedef struct MLoopUV{
+ float uv[2];
+}MLoopUV;
+
+typedef struct MLoopCol{
+ char a, r, g, b;
+ int pad; /*waste!*/
+}MLoopCol;
+
typedef struct MSticky {
float co[2];
} MSticky;
@@ -143,7 +159,7 @@ typedef struct Multires {
MVert *verts;
unsigned char level_count, current, newlvl, edgelvl, pinlvl, renderlvl;
- unsigned char use_col, pad;
+ unsigned char use_col, flag;
/* Special level 1 data that cannot be modified from other levels */
CustomData vdata;
@@ -213,7 +229,7 @@ typedef struct PartialVisibility {
/* mtface->mode */
#define TF_DYNAMIC 1
-#define TF_DEPRECATED 2
+#define TF_ALPHASORT 2
#define TF_TEX 4
#define TF_SHAREDVERT 8
#define TF_LIGHT 16
@@ -229,14 +245,16 @@ typedef struct PartialVisibility {
#define TF_SHADOW 8192
#define TF_BMFONT 16384
-/* mtface->transp */
+/* mtface->transp, values 1-4 are used as flags in the GL, WARNING, TF_SUB cant work with this */
#define TF_SOLID 0
#define TF_ADD 1
#define TF_ALPHA 2
+#define TF_CLIP 4 /* clipmap alpha/binary alpha all or nothing! */
/* sub is not available in the user interface anymore */
#define TF_SUB 3
+
/* mtface->unwrap */
#define TF_DEPRECATED1 1
#define TF_DEPRECATED2 2
@@ -247,4 +265,7 @@ typedef struct PartialVisibility {
#define TF_PIN3 64
#define TF_PIN4 128
+/* multires->flag */
+#define MULTIRES_NO_RENDER 1
+
#endif
diff --git a/source/blender/makesdna/DNA_modifier_types.h b/source/blender/makesdna/DNA_modifier_types.h
index 51f0e961709..ae07434a37f 100644
--- a/source/blender/makesdna/DNA_modifier_types.h
+++ b/source/blender/makesdna/DNA_modifier_types.h
@@ -32,6 +32,13 @@ typedef enum ModifierType {
eModifierType_ParticleSystem,
eModifierType_ParticleInstance,
eModifierType_Explode,
+ eModifierType_Cloth,
+ eModifierType_Collision,
+ eModifierType_Bevel,
+ eModifierType_Shrinkwrap,
+ eModifierType_Fluidsim,
+ eModifierType_Mask,
+ eModifierType_SimpleDeform,
NUM_MODIFIER_TYPES
} ModifierType;
@@ -100,6 +107,24 @@ typedef struct BuildModifierData {
int randomize, seed;
} BuildModifierData;
+/* Mask Modifier */
+typedef struct MaskModifierData {
+ ModifierData modifier;
+
+ struct Object *ob_arm; /* armature to use to in place of hardcoded vgroup */
+ char vgroup[32]; /* name of vertex group to use to mask */
+
+ int mode; /* using armature or hardcoded vgroup */
+ int flag; /* flags for various things */
+} MaskModifierData;
+
+/* Mask Modifier -> mode */
+#define MOD_MASK_MODE_VGROUP 0
+#define MOD_MASK_MODE_ARM 1
+
+/* Mask Modifier -> flag */
+#define MOD_MASK_INV (1<<0)
+
typedef struct ArrayModifierData {
ModifierData modifier;
@@ -173,6 +198,7 @@ typedef struct MirrorModifierData {
#define MOD_MIR_AXIS_X 1<<3
#define MOD_MIR_AXIS_Y 1<<4
#define MOD_MIR_AXIS_Z 1<<5
+#define MOD_MIR_VGROUP 1<<6
typedef struct EdgeSplitModifierData {
ModifierData modifier;
@@ -185,6 +211,27 @@ typedef struct EdgeSplitModifierData {
#define MOD_EDGESPLIT_FROMANGLE 1<<1
#define MOD_EDGESPLIT_FROMFLAG 1<<2
+typedef struct BevelModifierData {
+ ModifierData modifier;
+
+ float value; /* the "raw" bevel value (distance/amount to bevel) */
+ int res; /* the resolution (as originally coded, it is the number of recursive bevels) */
+ int pad;
+ short flags; /* general option flags */
+ short val_flags; /* flags used to interpret the bevel value */
+ short lim_flags; /* flags to tell the tool how to limit the bevel */
+ short e_flags; /* flags to direct how edge weights are applied to verts */
+ float bevel_angle; /* if the BME_BEVEL_ANGLE is set, this will be how "sharp" an edge must be before it gets beveled */
+ char defgrp_name[32]; /* if the BME_BEVEL_VWEIGHT option is set, this will be the name of the vert group */
+} BevelModifierData;
+
+typedef struct BMeshModifierData {
+ ModifierData modifier;
+
+ float pad;
+ int type;
+} BMeshModifierData;
+
typedef struct DisplaceModifierData {
ModifierData modifier;
@@ -304,13 +351,14 @@ typedef struct WaveModifierData {
short flag, pad;
float startx, starty, height, width;
- float narrow, speed, damp;
+ float narrow, speed, damp, falloff;
int texmapping, uvlayer_tmp;
char uvlayer_name[32];
-
+
float timeoffs, lifetime;
+ float pad1;
} WaveModifierData;
typedef struct ArmatureModifierData {
@@ -341,6 +389,35 @@ typedef struct SoftbodyModifierData {
ModifierData modifier;
} SoftbodyModifierData;
+typedef struct ClothModifierData {
+ ModifierData modifier;
+
+ struct Cloth *clothObject; /* The internal data structure for cloth. */
+ struct ClothSimSettings *sim_parms; /* definition is in DNA_cloth_types.h */
+ struct ClothCollSettings *coll_parms; /* definition is in DNA_cloth_types.h */
+ struct PointCache *point_cache; /* definition is in DNA_object_force.h */
+} ClothModifierData;
+
+typedef struct CollisionModifierData {
+ ModifierData modifier;
+
+ struct MVert *x; /* position at the beginning of the frame */
+ struct MVert *xnew; /* position at the end of the frame */
+ struct MVert *xold; /* unsued atm, but was discussed during sprint */
+ struct MVert *current_xnew; /* new position at the actual inter-frame step */
+ struct MVert *current_x; /* position at the actual inter-frame step */
+ struct MVert *current_v; /* (xnew - x) at the actual inter-frame step */
+
+ struct MFace *mfaces; /* object face data */
+
+ unsigned int numverts;
+ unsigned int numfaces;
+ short absorption; /* used for forces, in % */
+ short pad;
+ float time; /* cfra time of modifier */
+ struct BVHTree *bvhtree; /* bounding volume hierarchy for this cloth object */
+} CollisionModifierData;
+
typedef enum {
eBooleanModifierOp_Intersect,
eBooleanModifierOp_Union,
@@ -436,4 +513,80 @@ typedef struct ExplodeModifierData {
float protect;
} ExplodeModifierData;
+typedef struct FluidsimModifierData {
+ ModifierData modifier;
+
+ struct FluidsimSettings *fss; /* definition is is DNA_object_fluidsim.h */
+ struct PointCache *point_cache; /* definition is in DNA_object_force.h */
+} FluidsimModifierData;
+
+typedef struct ShrinkwrapModifierData {
+ ModifierData modifier;
+
+ struct Object *target; /* shrink target */
+ struct Object *auxTarget; /* additional shrink target */
+ char vgroup_name[32]; /* optional vertexgroup name */
+ float keepDist; /* distance offset to keep from mesh/projection point */
+ short shrinkType; /* shrink type projection */
+ short shrinkOpts; /* shrink options */
+ char projAxis; /* axis to project over */
+
+ /*
+ * if using projection over vertex normal this controls the
+ * the level of subsurface that must be done before getting the
+ * vertex coordinates and normal
+ */
+ char subsurfLevels;
+
+ char pad[6];
+
+} ShrinkwrapModifierData;
+
+/* Shrinkwrap->shrinkType */
+#define MOD_SHRINKWRAP_NEAREST_SURFACE 0
+#define MOD_SHRINKWRAP_PROJECT 1
+#define MOD_SHRINKWRAP_NEAREST_VERTEX 2
+
+/* Shrinkwrap->shrinkOpts */
+#define MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR (1<<0) /* allow shrinkwrap to move the vertex in the positive direction of axis */
+#define MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR (1<<1) /* allow shrinkwrap to move the vertex in the negative direction of axis */
+
+#define MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE (1<<3) /* ignore vertex moves if a vertex ends projected on a front face of the target */
+#define MOD_SHRINKWRAP_CULL_TARGET_BACKFACE (1<<4) /* ignore vertex moves if a vertex ends projected on a back face of the target */
+
+#define MOD_SHRINKWRAP_KEEP_ABOVE_SURFACE (1<<5) /* distance is measure to the front face of the target */
+
+#define MOD_SHRINKWRAP_PROJECT_OVER_X_AXIS (1<<0)
+#define MOD_SHRINKWRAP_PROJECT_OVER_Y_AXIS (1<<1)
+#define MOD_SHRINKWRAP_PROJECT_OVER_Z_AXIS (1<<2)
+#define MOD_SHRINKWRAP_PROJECT_OVER_NORMAL 0 /* projection over normal is used if no axis is selected */
+
+
+typedef struct SimpleDeformModifierData {
+ ModifierData modifier;
+
+ struct Object *origin; /* object to control the origin of modifier space coordinates */
+ char vgroup_name[32]; /* optional vertexgroup name */
+ float factor; /* factors to control simple deforms */
+ float limit[2]; /* lower and upper limit */
+
+ char mode; /* deform function */
+ char axis; /* lock axis (for taper and strech) */
+ char originOpts; /* originOptions */
+ char pad;
+
+} SimpleDeformModifierData;
+
+#define MOD_SIMPLEDEFORM_MODE_TWIST 1
+#define MOD_SIMPLEDEFORM_MODE_BEND 2
+#define MOD_SIMPLEDEFORM_MODE_TAPER 3
+#define MOD_SIMPLEDEFORM_MODE_STRETCH 4
+
+#define MOD_SIMPLEDEFORM_LOCK_AXIS_X (1<<0)
+#define MOD_SIMPLEDEFORM_LOCK_AXIS_Y (1<<1)
+
+/* indicates whether simple deform should use the local
+ coordinates or global coordinates of origin */
+#define MOD_SIMPLEDEFORM_ORIGIN_LOCAL (1<<0)
+
#endif
diff --git a/source/blender/makesdna/DNA_node_types.h b/source/blender/makesdna/DNA_node_types.h
index 5f20939fc23..eda37d952c1 100644
--- a/source/blender/makesdna/DNA_node_types.h
+++ b/source/blender/makesdna/DNA_node_types.h
@@ -58,7 +58,7 @@ typedef struct bNodeStack {
#define NS_OSA_VALUES 2
typedef struct bNodeSocket {
- struct bNodeSocket *next, *prev;
+ struct bNodeSocket *next, *prev, *new_sock;
char name[32];
bNodeStack ns; /* custom data for inputs, only UI writes in this */
@@ -92,7 +92,8 @@ typedef struct bNodeSocket {
#define SOCK_IN_USE 4
/* unavailable is for dynamic sockets */
#define SOCK_UNAVAIL 8
-
+ /* flag for selection status */
+#define SOCK_SEL 16
#
#
typedef struct bNodePreview {
@@ -106,6 +107,7 @@ typedef struct bNode {
struct bNode *next, *prev, *new_node;
char name[32];
+ char username[32]; /* custom name defined by user */
short type, flag;
short done, level; /* both for dependency and sorting */
short lasty, menunr; /* lasty: check preview render status, menunr: browse ID blocks */
@@ -142,6 +144,8 @@ typedef struct bNode {
#define NODE_GROUP_EDIT 128
/* free test flag, undefined */
#define NODE_TEST 256
+ /* composite: don't do node but pass on buffer(s) */
+#define NODE_MUTED 512
typedef struct bNodeLink {
struct bNodeLink *next, *prev;
@@ -158,7 +162,8 @@ typedef struct bNodeTree {
ListBase nodes, links;
- bNodeStack **stack; /* stack is only while executing, no read/write in file */
+ bNodeStack *stack; /* stack is only while executing, no read/write in file */
+ struct ListBase *threadstack; /* same as above */
int type, init; /* set init on fileread */
int stacksize; /* amount of elements in stack */
@@ -167,6 +172,10 @@ typedef struct bNodeTree {
ListBase alltypes; /* type definitions */
struct bNodeType *owntype; /* for groups or dynamic trees, no read/write */
+ /* selected input/output socket */
+ bNodeSocket *selin;
+ bNodeSocket *selout;
+
/* callbacks */
void (*timecursor)(int nr);
void (*stats_draw)(char *str);
@@ -191,13 +200,27 @@ typedef struct NodeImageAnim {
} NodeImageAnim;
typedef struct NodeBlurData {
- short sizex, sizey, samples, maxspeed, minspeed, pad1;
- float fac;
+ short sizex, sizey;
+ short samples, maxspeed, minspeed, relative;
+ float fac, percentx, percenty;
short filtertype;
char bokeh, gamma;
- int pad2;
+ short curved;
+ short pad;
+ int image_in_width, image_in_height; /* needed for absolute/relative conversions */
} NodeBlurData;
+typedef struct NodeDBlurData {
+ float center_x, center_y, distance, angle, spin, zoom;
+ short iter;
+ char wrap, pad;
+} NodeDBlurData;
+
+typedef struct NodeBilateralBlurData {
+ float sigma_color, sigma_space;
+ short iter, pad;
+} NodeBilateralBlurData;
+
typedef struct NodeHueSat {
float hue, sat, val;
} NodeHueSat;
@@ -218,6 +241,10 @@ typedef struct NodeTwoXYs {
short x1, x2, y1, y2;
} NodeTwoXYs;
+typedef struct NodeTwoFloats {
+ float x, y;
+} NodeTwoFloats;
+
typedef struct NodeGeometry {
char uvname[32];
char colname[32];
@@ -234,6 +261,10 @@ typedef struct NodeDefocus {
float fstop, maxblur, bthresh, scale;
} NodeDefocus;
+typedef struct NodeScriptDict {
+ void *dict; /* for PyObject *dict */
+ void *node; /* for BPy_Node *node */
+} NodeScriptDict;
/* qdn: glare node */
typedef struct NodeGlare {
diff --git a/source/blender/makesdna/DNA_object_fluidsim.h b/source/blender/makesdna/DNA_object_fluidsim.h
index 9b1e4fb56cb..2914330a2b0 100644
--- a/source/blender/makesdna/DNA_object_fluidsim.h
+++ b/source/blender/makesdna/DNA_object_fluidsim.h
@@ -108,7 +108,7 @@ typedef struct FluidsimSettings {
float surfaceSmoothing;
/* number of surface subdivisions*/
int surfaceSubdivs;
- int unusedDNADummy;
+ int flag; /* GUI flags */
/* particle display - size scaling, and alpha influence */
float particleInfSize, particleInfAlpha;
@@ -117,6 +117,18 @@ typedef struct FluidsimSettings {
/* save fluidsurface normals in mvert.no, and surface vertex velocities (if available) in mvert.co */
struct MVert *meshSurfNormals;
+
+ /* Fluid control settings */
+ float cpsTimeStart;
+ float cpsTimeEnd;
+ float cpsQuality;
+
+ float attractforceStrength;
+ float attractforceRadius;
+ float velocityforceStrength;
+ float velocityforceRadius;
+
+ int lastgoodframe;
} FluidsimSettings;
@@ -128,8 +140,9 @@ typedef struct FluidsimSettings {
#define OB_FLUIDSIM_INFLOW 16
#define OB_FLUIDSIM_OUTFLOW 32
#define OB_FLUIDSIM_PARTICLE 64
+#define OB_FLUIDSIM_CONTROL 128
-#define OB_TYPEFLAG_START 0
+#define OB_TYPEFLAG_START 7
#define OB_FSGEO_THIN (1<<(OB_TYPEFLAG_START+1))
#define OB_FSBND_NOSLIP (1<<(OB_TYPEFLAG_START+2))
#define OB_FSBND_PARTSLIP (1<<(OB_TYPEFLAG_START+3))
@@ -145,6 +158,9 @@ typedef struct FluidsimSettings {
#define OB_FSPART_NEWPART (1<<3)
#define OB_FSPART_FLOAT (1<<4)
+// new fluid bit flags for fss->flags - dg
+#define OB_FLUIDSIM_REVERSE (1 << 0)
+
#ifdef __cplusplus
}
#endif
diff --git a/source/blender/makesdna/DNA_object_force.h b/source/blender/makesdna/DNA_object_force.h
index bbd12fee7c2..21c5242a703 100644
--- a/source/blender/makesdna/DNA_object_force.h
+++ b/source/blender/makesdna/DNA_object_force.h
@@ -67,13 +67,75 @@ typedef struct PartDeflect {
float tex_nabla;
short tex_mode, kink, kink_axis, rt2;
struct Tex *tex; /* Texture of the texture effector */
+ struct RNG *rng; /* random noise generator for e.g. wind */
+ float f_noise; /* noise of force (currently used for wind) */
+ int pad;
} PartDeflect;
+typedef struct PointCache {
+ int flag; /* generic flag */
+ int simframe; /* current frame of simulation (only if SIMULATION_VALID) */
+ int startframe; /* simulation start frame */
+ int endframe; /* simulation end frame */
+ int editframe; /* frame being edited (runtime only) */
+} PointCache;
typedef struct SBVertex {
float vec[4];
} SBVertex;
+typedef struct BulletSoftBody {
+ int flag; /* various boolean options */
+ float linStiff; /* linear stiffness 0..1 */
+ float angStiff; /* angular stiffness 0..1 */
+ float volume; /* volume preservation 0..1 */
+
+ int viterations; /* Velocities solver iterations */
+ int piterations; /* Positions solver iterations */
+ int diterations; /* Drift solver iterations */
+ int citerations; /* Cluster solver iterations */
+
+ float kSRHR_CL; /* Soft vs rigid hardness [0,1] (cluster only) */
+ float kSKHR_CL; /* Soft vs kinetic hardness [0,1] (cluster only) */
+ float kSSHR_CL; /* Soft vs soft hardness [0,1] (cluster only) */
+ float kSR_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
+
+ float kSK_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
+ float kSS_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
+ float kVCF; /* Velocities correction factor (Baumgarte) */
+ float kDP; /* Damping coefficient [0,1] */
+
+ float kDG; /* Drag coefficient [0,+inf] */
+ float kLF; /* Lift coefficient [0,+inf] */
+ float kPR; /* Pressure coefficient [-inf,+inf] */
+ float kVC; /* Volume conversation coefficient [0,+inf] */
+
+ float kDF; /* Dynamic friction coefficient [0,1] */
+ float kMT; /* Pose matching coefficient [0,1] */
+ float kCHR; /* Rigid contacts hardness [0,1] */
+ float kKHR; /* Kinetic contacts hardness [0,1] */
+
+ float kSHR; /* Soft contacts hardness [0,1] */
+ float kAHR; /* Anchors hardness [0,1] */
+ int collisionflags; /* Vertex/Face or Signed Distance Field(SDF) or Clusters, Soft versus Soft or Rigid */
+ int numclusteriterations; /* number of iterations to refine collision clusters*/
+
+} BulletSoftBody;
+
+/* BulletSoftBody.flag */
+#define OB_BSB_SHAPE_MATCHING 2
+#define OB_BSB_UNUSED 4
+#define OB_BSB_BENDING_CONSTRAINTS 8
+#define OB_BSB_AERO_VPOINT 16 /* aero model, Vertex normals are oriented toward velocity*/
+#define OB_BSB_AERO_VTWOSIDE 32 /* aero model, Vertex normals are flipped to match velocity */
+
+/* BulletSoftBody.collisionflags */
+#define OB_BSB_COL_SDF_RS 2 /* SDF based rigid vs soft */
+#define OB_BSB_COL_CL_RS 4 /* Cluster based rigid vs soft */
+#define OB_BSB_COL_CL_SS 8 /* Cluster based soft vs soft */
+#define OB_BSB_COL_VF_SS 16 /* Vertex/Face based soft vs soft */
+
+
typedef struct SoftBody {
struct ParticleSystem *particles; /* particlesystem softbody */
@@ -81,7 +143,7 @@ typedef struct SoftBody {
int totpoint, totspring;
struct BodyPoint *bpoint; /* not saved in file */
struct BodySpring *bspring; /* not saved in file */
- float ctime; /* last time calculated */
+ float pad;
/* part of UI: */
@@ -126,10 +188,15 @@ typedef struct SoftBody {
minloops,
maxloops,
choke,
- pad3,pad4,pad5
+ solver_ID,
+ plastic,springpreload
;
struct SBScratch *scratch; /* scratch pad/cache on live time not saved in file */
+ float shearstiff;
+ float inpush;
+
+ struct PointCache *pointcache;
} SoftBody;
@@ -141,8 +208,8 @@ typedef struct SoftBody {
#define PFIELD_GUIDE 5
#define PFIELD_TEXTURE 6
#define PFIELD_HARMONIC 7
-#define PFIELD_NUCLEAR 8
-#define PFIELD_MDIPOLE 9
+#define PFIELD_CHARGE 8
+#define PFIELD_LENNARDJ 9
/* pd->flag: various settings */
@@ -157,6 +224,7 @@ typedef struct SoftBody {
#define PFIELD_USEMIN 256
#define PFIELD_USEMAXR 512
#define PFIELD_USEMINR 1024
+#define PFIELD_TEX_ROOTCO 2048
/* pd->falloff */
#define PFIELD_FALL_SPHERE 0
@@ -170,21 +238,30 @@ typedef struct SoftBody {
#define PFIELD_TEX_GRAD 1
#define PFIELD_TEX_CURL 2
+/* pointcache->flag */
+#define PTCACHE_BAKED 1
+#define PTCACHE_OUTDATED 2
+#define PTCACHE_SIMULATION_VALID 4
+#define PTCACHE_BAKING 8
+#define PTCACHE_BAKE_EDIT 16
+#define PTCACHE_BAKE_EDIT_ACTIVE 32
+
/* ob->softflag */
#define OB_SB_ENABLE 1
#define OB_SB_GOAL 2
#define OB_SB_EDGES 4
#define OB_SB_QUADS 8
#define OB_SB_POSTDEF 16
-#define OB_SB_REDO 32
-#define OB_SB_BAKESET 64
-#define OB_SB_BAKEDO 128
-#define OB_SB_RESET 256
+// #define OB_SB_REDO 32
+// #define OB_SB_BAKESET 64
+// #define OB_SB_BAKEDO 128
+// #define OB_SB_RESET 256
#define OB_SB_SELF 512
#define OB_SB_FACECOLL 1024
#define OB_SB_EDGECOLL 2048
#define OB_SB_COLLFINAL 4096
-#define OB_SB_PROTECT_CACHE 8192
+//#define OB_SB_PROTECT_CACHE 8192
+#define OB_SB_AERO_ANGLE 16384
/* sb->solverflags */
#define SBSO_MONITOR 1
diff --git a/source/blender/makesdna/DNA_object_types.h b/source/blender/makesdna/DNA_object_types.h
index 5120bee742c..b885bbf084e 100644
--- a/source/blender/makesdna/DNA_object_types.h
+++ b/source/blender/makesdna/DNA_object_types.h
@@ -59,6 +59,27 @@ typedef struct bDeformGroup {
char name[32];
} bDeformGroup;
+/**
+ * The following illustrates the orientation of the
+ * bounding box in local space
+ *
+ *
+ * Z Y
+ * | /
+ * |/
+ * .-----X
+ *
+ *
+ * 2----------6
+ * /| /|
+ * / | / |
+ * 1----------5 |
+ * | | | |
+ * | 3-------|--7
+ * | / | /
+ * |/ |/
+ * 0----------4
+ */
typedef struct BoundBox {
float vec[8][3];
int flag, pad;
@@ -81,6 +102,7 @@ typedef struct Object {
struct Path *path;
struct BoundBox *bb;
struct bAction *action;
+ struct bAction *poselib;
struct bPose *pose;
void *data;
@@ -96,7 +118,7 @@ typedef struct Object {
float loc[3], dloc[3], orig[3];
float size[3], dsize[3];
float rot[3], drot[3];
- float quat[4], dquat[4];
+ /* float quat[4], dquat[4]; (not used yet) */
float obmat[4][4];
float parentinv[4][4]; /* inverse result of parent, so that object doesn't 'stick' to parent */
float constinv[4][4]; /* inverse result of constraints. doesn't include effect of parent or object local transform */
@@ -115,7 +137,7 @@ typedef struct Object {
int dupon, dupoff, dupsta, dupend;
- float sf, ctime;
+ float sf, ctime; /* sf is time-offset, ctime is the objects current time */
/* during realtime */
@@ -134,7 +156,9 @@ typedef struct Object {
float formfactor;
float rdamping, sizefac;
-
+ float margin;
+ int pad3;
+
char dt, dtx;
char totcol; /* copy of mesh or curve or meta */
char actcol; /* currently selected material in the user interface */
@@ -147,10 +171,6 @@ typedef struct Object {
ListBase sensors;
ListBase controllers;
ListBase actuators;
-
- /* now used to store cache particles,
- * should be renamed see effect.c (Campbell) */
- void *sumohandle;
float bbsize[3];
short index; /* custom index, for renderpasses */
@@ -173,7 +193,9 @@ typedef struct Object {
* bit 15: Always ignore activity culling
*/
int gameflag2;
- short softflag; /* softboday settings */
+ struct BulletSoftBody *bsoft; /* settings for game engine bullet soft body */
+
+ short softflag; /* softbody settings */
short recalc; /* dependency flag */
float anisotropicFriction[3];
@@ -192,17 +214,22 @@ typedef struct Object {
short shapenr, shapeflag; /* current shape key for menu or pinned, flag for pinning */
float smoothresh; /* smoothresh is phong interpolation ray_shadow correction in render */
- short recalco, pad4; /* recalco for temp storage of ob->recalc, bad design warning */
+ short recalco; /* recalco for temp storage of ob->recalc, bad design warning */
+ short body_type; /* for now used to temporarily holds the type of collision object */
struct FluidsimSettings *fluidsimSettings; /* if fluidsim enabled, store additional settings */
struct DerivedMesh *derivedDeform, *derivedFinal;
int lastDataMask; /* the custom data layer mask that was last used to calculate derivedDeform and derivedFinal */
- int pad;
+ unsigned int state; /* bit masks of game controllers that are active */
+ unsigned int init_state; /* bit masks of initial state as recorded by the users */
+ int pad2;
/*#ifdef WITH_VERSE*/
void *vnode; /* pointer at object VerseNode */
/*#endif*/
+
+ ListBase gpulamp; /* runtime, for lamps only */
} Object;
/* Warning, this is not used anymore because hooks are now modifiers */
@@ -293,6 +320,9 @@ extern Object workob;
/* for stride edit */
#define OB_DISABLE_PATH 1024
+#define OB_OFFS_PARENTADD 2048
+
+
/* (short) trackflag / upflag */
#define OB_POSX 0
#define OB_POSY 1
@@ -365,6 +395,8 @@ extern Object workob;
#define BA_FROMSET 128
+#define BA_TRANSFORM_CHILD 256 /* child of a transformed object */
+
/* an initial attempt as making selection more specific! */
#define BA_DESELECT 0
#define BA_SELECT 1
@@ -383,6 +415,7 @@ extern Object workob;
#define OB_RECALC_TIME 4
#define OB_RECALC 7
+
/* ob->gameflag */
#define OB_DYNAMIC 1
#define OB_CHILD 2
@@ -402,11 +435,21 @@ extern Object workob;
#define OB_PROP 16384
#define OB_MAINACTOR 32768
+#define OB_COLLISION 65536
+#define OB_SOFT_BODY 0x20000
+
/* ob->gameflag2 */
#define OB_NEVER_DO_ACTIVITY_CULLING 1
#define OB_LIFE (OB_PROP|OB_DYNAMIC|OB_ACTOR|OB_MAINACTOR|OB_CHILD)
+/* ob->body_type */
+#define OB_BODY_TYPE_NO_COLLISION 0
+#define OB_BODY_TYPE_STATIC 1
+#define OB_BODY_TYPE_DYNAMIC 2
+#define OB_BODY_TYPE_RIGID 3
+#define OB_BODY_TYPE_SOFT 4
+
/* ob->scavisflag */
#define OB_VIS_SENS 1
#define OB_VIS_CONT 2
@@ -419,6 +462,9 @@ extern Object workob;
#define OB_ADDCONT 512
#define OB_ADDACT 1024
#define OB_SHOWCONT 2048
+#define OB_SETSTBIT 4096
+#define OB_INITSTBIT 8192
+#define OB_DEBUGSTATE 16384
/* ob->restrictflag */
#define OB_RESTRICT_VIEW 1
@@ -441,9 +487,11 @@ extern Object workob;
#define OB_LOCK_ROTX 8
#define OB_LOCK_ROTY 16
#define OB_LOCK_ROTZ 32
+#define OB_LOCK_ROT 56
#define OB_LOCK_SCALEX 64
#define OB_LOCK_SCALEY 128
#define OB_LOCK_SCALEZ 256
+#define OB_LOCK_SCALE 448
/* ob->softflag in DNA_object_force.h */
diff --git a/source/blender/makesdna/DNA_particle_types.h b/source/blender/makesdna/DNA_particle_types.h
index 115344bd899..7dd69b2151c 100644
--- a/source/blender/makesdna/DNA_particle_types.h
+++ b/source/blender/makesdna/DNA_particle_types.h
@@ -66,6 +66,8 @@ typedef struct ParticleData {
ParticleKey state; /* normally current global coordinates or */
/* in sticky object space if dead & sticky */
+ ParticleKey prev_state; /* previous state */
+
HairKey *hair; /* hair vertices */
ParticleKey *keys; /* keyed states */
@@ -125,18 +127,18 @@ typedef struct ParticleSettings {
/* general values */
float sta, end, lifetime, randlife;
- float timetweak, jitfac, keyed_time;
+ float timetweak, jitfac, keyed_time, eff_hair, rt;
int totpart, userjit, grid_res;
/* initial velocity factors */
float normfac, obfac, randfac, partfac, tanfac, tanphase, reactfac;
- float rotfac, avefac, phasefac;
+ float avefac, phasefac, randrotfac, randphasefac;
/* physical properties */
float mass, size, randsize, reactshape;
/* global physical properties */
float acc[3], dragfac, brownfac, dampfac;
/* length */
- float length, abslength, randlength, pad;
+ float length, abslength, randlength;
/* children */
int child_nbr, ren_child_nbr;
float parents, childsize, childrandsize;
@@ -166,29 +168,30 @@ typedef struct ParticleSettings {
struct Object *bb_ob;
struct Ipo *ipo;
struct PartDeflect *pd;
+ struct PartDeflect *pd2;
} ParticleSettings;
-typedef struct ParticleSystem{
+typedef struct ParticleSystem{ /* note, make sure all (runtime) are NULL's in copy_particlesystem */
struct ParticleSystem *next, *prev;
- ParticleSettings *part;
-
- ParticleData *particles;
+ ParticleSettings *part; /* particle settings */
- ChildParticle *child;
+ ParticleData *particles; /* (parent) particles */
+ ChildParticle *child; /* child particles */
- struct ParticleEdit *edit;
+ struct ParticleEdit *edit; /* particle editmode (runtime) */
- struct ParticleCacheKey **pathcache;
- struct ParticleCacheKey **childcache;
+ struct ParticleCacheKey **pathcache; /* path cache (runtime) */
+ struct ParticleCacheKey **childcache; /* child cache (runtime) */
+ ListBase pathcachebufs, childcachebufs; /* buffers for the above */
- struct SoftBody *soft;
+ struct SoftBody *soft; /* hair softbody */
struct Object *target_ob;
struct Object *keyed_ob;
struct Object *lattice;
- struct ListBase effectors, reactevents;
+ struct ListBase effectors, reactevents; /* runtime */
float imat[4][4]; /* used for duplicators */
float cfra;
@@ -196,13 +199,16 @@ typedef struct ParticleSystem{
int flag, totpart, totchild, totcached, totchildcache, rt;
short recalc, target_psys, keyed_psys, totkeyed, softflag, bakespace;
- char bb_uvname[3][32];
+ char bb_uvname[3][32]; /* billboard uv name */
/* if you change these remember to update array lengths to PSYS_TOT_VG! */
- short vgroup[11], vg_neg, rt3[2];
+ short vgroup[12], vg_neg, rt3; /* vertex groups */
/* temporary storage during render */
void *renderdata;
+
+ /* point cache */
+ struct PointCache *pointcache;
}ParticleSystem;
/* general particle maximums */
@@ -218,13 +224,14 @@ typedef struct ParticleSystem{
#define PART_EMITTER 0
#define PART_REACTOR 1
#define PART_HAIR 2
+#define PART_FLUID 3
/* part->flag */
#define PART_REACT_STA_END 1
#define PART_REACT_MULTIPLE 2
#define PART_LOOP 4
-#define PART_LOOP_INSTANT 8
+//#define PART_LOOP_INSTANT 8
#define PART_HAIR_GEOMETRY 16
@@ -255,10 +262,13 @@ typedef struct ParticleSystem{
#define PART_GRID_INVERT (1<<26)
+#define PART_CHILD_EFFECT (1<<27)
#define PART_CHILD_SEAMS (1<<28)
#define PART_CHILD_RENDER (1<<29)
#define PART_CHILD_GUIDE (1<<30)
+#define PART_SELF_EFFECT (1<<22)
+
/* part->rotfrom */
#define PART_ROT_KEYS 0 /* interpolate directly from keys */
#define PART_ROT_ZINCR 1 /* same as zdir but done incrementally from previous position */
@@ -288,8 +298,6 @@ typedef struct ParticleSystem{
#define PART_KINK_RADIAL 2
#define PART_KINK_WAVE 3
#define PART_KINK_BRAID 4
-#define PART_KINK_ROT 5
-#define PART_KINK_ROLL 6
/* part->draw */
#define PART_DRAW_VEL 1
@@ -352,12 +360,16 @@ typedef struct ParticleSystem{
/* part->rotmode */
#define PART_ROT_NOR 1
#define PART_ROT_VEL 2
-#define PART_ROT_RAND 3
+#define PART_ROT_GLOB_X 3
+#define PART_ROT_GLOB_Y 4
+#define PART_ROT_GLOB_Z 5
+#define PART_ROT_OB_X 6
+#define PART_ROT_OB_Y 7
+#define PART_ROT_OB_Z 8
/* part->avemode */
#define PART_AVE_SPIN 1
#define PART_AVE_RAND 2
-#define PART_AVE_VEL 3
/* part->reactevent */
#define PART_EVENT_DEATH 0
@@ -380,7 +392,7 @@ typedef struct ParticleSystem{
//#define PSYS_BAKING 2
//#define PSYS_BAKE_UI 4
#define PSYS_KEYED_TIME 8
-#define PSYS_ENABLED 16
+#define PSYS_ENABLED 16 /* deprecated */
#define PSYS_FIRST_KEYED 32
#define PSYS_DRAWING 64
//#define PSYS_SOFT_BAKE 128
@@ -388,7 +400,8 @@ typedef struct ParticleSystem{
#define PSYS_HAIR_DONE 512
#define PSYS_KEYED 1024
#define PSYS_EDITED 2048
-#define PSYS_PROTECT_CACHE 4096
+//#define PSYS_PROTECT_CACHE 4096
+#define PSYS_DISABLED 8192
/* pars->flag */
#define PARS_UNEXIST 1
@@ -405,9 +418,10 @@ typedef struct ParticleSystem{
#define PARS_DEAD 1
#define PARS_UNBORN 2
#define PARS_ALIVE 3
+#define PARS_DYING 4
/* psys->vg */
-#define PSYS_TOT_VG 11
+#define PSYS_TOT_VG 12
#define PSYS_VG_DENSITY 0
#define PSYS_VG_VEL 1
@@ -420,6 +434,7 @@ typedef struct ParticleSystem{
#define PSYS_VG_SIZE 8
#define PSYS_VG_TAN 9
#define PSYS_VG_ROT 10
+#define PSYS_VG_EFFECTOR 11
/* part->boidrules */
#define BOID_TOT_RULES 8
diff --git a/source/blender/makesdna/DNA_scene_types.h b/source/blender/makesdna/DNA_scene_types.h
index eef665bc290..6563f56ed4d 100644
--- a/source/blender/makesdna/DNA_scene_types.h
+++ b/source/blender/makesdna/DNA_scene_types.h
@@ -98,6 +98,7 @@ typedef struct FFMpegCodecData {
int rc_buffer_size;
int mux_packet_size;
int mux_rate;
+ IDProperty *properties;
} FFMpegCodecData;
@@ -117,7 +118,11 @@ typedef struct SceneRenderLayer {
struct Group *light_override;
unsigned int lay; /* scene->lay itself has priority over this */
+ unsigned int lay_zmask; /* has to be after lay, this is for Z-masking */
int layflag;
+
+ int pad;
+
int passflag; /* pass_xor has to be after passflag */
int pass_xor;
} SceneRenderLayer;
@@ -131,9 +136,11 @@ typedef struct SceneRenderLayer {
#define SCE_LAY_STRAND 32
/* flags between 32 and 0x8000 are set to 1 already, for future options */
-#define SCE_LAY_ALL_Z 0x8000
-#define SCE_LAY_XOR 0x10000
-#define SCE_LAY_DISABLE 0x20000
+#define SCE_LAY_ALL_Z 0x8000
+#define SCE_LAY_XOR 0x10000
+#define SCE_LAY_DISABLE 0x20000
+#define SCE_LAY_ZMASK 0x40000
+#define SCE_LAY_NEG_ZMASK 0x80000
/* srl->passflag */
#define SCE_PASS_COMBINED 1
@@ -150,6 +157,8 @@ typedef struct SceneRenderLayer {
#define SCE_PASS_INDEXOB 2048
#define SCE_PASS_UV 4096
#define SCE_PASS_RADIO 8192
+#define SCE_PASS_MIST 16384
+
/* note, srl->passflag is treestore element 'nr' in outliner, short still... */
@@ -191,14 +200,6 @@ typedef struct RenderData {
*/
short ysch;
/**
- * Adjustment factors for the aspect ratio in the x direction
- */
- short xasp;
- /**
- * Adjustment factors for the aspect ratio in the x direction
- */
- short yasp;
- /**
* The number of part to use in the x direction
*/
short xparts;
@@ -214,10 +215,12 @@ typedef struct RenderData {
short bufflag;
short quality;
+ short rpad, rpad1, rpad2;
+
/**
* Flags for render settings. Use bit-masking to access the settings.
*/
- short scemode;
+ int scemode;
/**
* Flags for render settings. Use bit-masking to access the settings.
@@ -225,7 +228,7 @@ typedef struct RenderData {
int mode;
/* render engine, octree resolution */
- short renderer, ocres, rpad[2];
+ short renderer, ocres;
/**
* What to do with the sky/background. Picks sky/premul/key
@@ -247,6 +250,15 @@ typedef struct RenderData {
/* information on different layers to be rendered */
ListBase layers;
short actlay, pad;
+
+ /**
+ * Adjustment factors for the aspect ratio in the x direction, was a short in 2.45
+ */
+ float xasp;
+ /**
+ * Adjustment factors for the aspect ratio in the x direction, was a short in 2.45
+ */
+ float yasp;
float frs_sec_base;
@@ -262,8 +274,8 @@ typedef struct RenderData {
/* Bake Render options */
short bake_osa, bake_filter, bake_mode, bake_flag;
- short bake_normal_space, bpad;
- float bake_maxdist;
+ short bake_normal_space, bake_quad_split;
+ float bake_maxdist, bake_biasdist, bake_pad;
/* yafray: global panel params. TODO: move elsewhere */
short GIquality, GIcache, GImethod, GIphotons, GIdirect;
@@ -271,12 +283,12 @@ typedef struct RenderData {
int GIdepth, GIcausdepth, GIpixelspersample;
int GIphotoncount, GImixphotons;
float GIphotonradius;
- int YF_numprocs, YF_raydepth, YF_AApasses, YF_AAsamples;
+ int YF_raydepth, YF_AApasses, YF_AAsamples, yfpad2;
float GIshadowquality, GIrefinement, GIpower, GIindirpower;
float YF_gamma, YF_exposure, YF_raybias, YF_AApixelsize, YF_AAthreshold;
/* paths to backbufffer, output, ftype */
- char backbuf[160], pic[160], ftype[160];
+ char backbuf[160], pic[160];
/* stamps flags. */
int stamp;
@@ -288,8 +300,31 @@ typedef struct RenderData {
/* foreground/background color. */
float fg_stamp[4];
float bg_stamp[4];
+
+ /* render simplify */
+ int simplify_subsurf;
+ int simplify_shadowsamples;
+ float simplify_particles;
+ float simplify_aosss;
+
+ /* cineon */
+ short cineonwhite, cineonblack;
+ float cineongamma;
} RenderData;
+/* control render convert and shading engine */
+typedef struct RenderProfile {
+ struct RenderProfile *next, *prev;
+ char name[32];
+
+ short particle_perc;
+ short subsurf_max;
+ short shadbufsample_max;
+ short pad1;
+
+ float ao_error, pad2;
+
+} RenderProfile;
typedef struct GameFraming {
float col[3];
@@ -314,7 +349,7 @@ typedef struct ImagePaintSettings {
} ImagePaintSettings;
typedef struct ParticleBrushData {
- short size, strength; /* commong settings */
+ short size, strength; /* common settings */
short step, invert; /* for specific brushes only */
} ParticleBrushData;
@@ -330,6 +365,12 @@ typedef struct ParticleEditSettings {
int draw_timed;
} ParticleEditSettings;
+typedef struct TransformOrientation {
+ struct TransformOrientation *next, *prev;
+ char name[36];
+ float mat[3][3];
+} TransformOrientation;
+
typedef struct ToolSettings {
/* Subdivide Settings */
short cornertype;
@@ -363,7 +404,7 @@ typedef struct ToolSettings {
/* Auto-IK */
short autoik_chainlen;
- /* Image Paint (8 byte aligned please!) */
+ /* Image Paint (8 byttse aligned please!) */
struct ImagePaintSettings imapaint;
/* Particle Editing */
@@ -392,12 +433,20 @@ typedef struct ToolSettings {
float skgen_angle_limit;
float skgen_correlation_limit;
float skgen_symmetry_limit;
+ float skgen_retarget_angle_weight;
+ float skgen_retarget_length_weight;
+ float skgen_retarget_distance_weight;
short skgen_options;
char skgen_postpro;
char skgen_postpro_passes;
char skgen_subdivisions[3];
+ char skgen_multi_level;
+ char skgen_optimisation_method;
- char pad3[5];
+ char tpad[6];
+
+ /* Alt+RMB option */
+ char edge_mode;
} ToolSettings;
/* Used by all brushes to store their properties, which can be directly set
@@ -407,25 +456,31 @@ typedef struct BrushData
{
short size;
char strength, dir; /* Not used for smooth brush */
- char airbrush;
char view;
+ char flag;
char pad[2];
} BrushData;
struct SculptSession;
typedef struct SculptData
{
+ /* Note! all pointers in this struct must be duplicated header_info.c's copy_scene function */
+
/* Data stored only from entering sculptmode until exiting sculptmode */
struct SculptSession *session;
/* Pointers to all of sculptmodes's textures */
- struct MTex *mtex[10];
+ struct MTex *mtex[18];
/* Editable brush shape */
struct CurveMapping *cumap;
/* Settings for each brush */
BrushData drawbrush, smoothbrush, pinchbrush, inflatebrush, grabbrush, layerbrush, flattenbrush;
+
+ /* For rotating around a pivot point */
+ float pivot[3];
+
short brush_type;
/* For the Brush Shape */
@@ -444,10 +499,11 @@ typedef struct SculptData
/* Symmetry is separate from the other BrushData because the same
settings are always used for all brush types */
char symm;
-
+
/* Added to store if the 'Rake' setting has been set */
char rake;
- char pad[7];
+ char axislock;
+ char pad[2];
} SculptData;
typedef struct Scene {
@@ -470,7 +526,9 @@ typedef struct Scene {
float editbutsize; /* size of normals */
short selectmode; /* for mesh only! */
short proportional, prop_mode;
- short automerge, pad5, pad6, pad7;
+ short automerge, pad5, pad6;
+
+ short autokey_mode; /* mode for autokeying (defines in DNA_userdef_types.h */
short use_nodes;
@@ -491,9 +549,10 @@ typedef struct Scene {
ScriptLink scriptlink;
ListBase markers;
+ ListBase transform_spaces;
- short jumpframe, pad1;
- short snap_flag, snap_target;
+ short jumpframe;
+ short snap_mode, snap_flag, snap_target;
/* none of the dependancy graph vars is mean to be saved */
struct DagForest *theDag;
@@ -502,6 +561,10 @@ typedef struct Scene {
/* Sculptmode data */
struct SculptData sculptdata;
+
+ /* frame step. */
+ int frame_step;
+ int pad;
} Scene;
@@ -535,10 +598,17 @@ typedef struct Scene {
#define R_GAUSS 0x20000
/* fbuf obsolete... */
#define R_FBUF 0x40000
- /* threads obsolete... is there for old files */
+ /* threads obsolete... is there for old files, now use for autodetect threads */
#define R_THREADS 0x80000
+ /* Use the same flag for autothreads */
+#define R_FIXED_THREADS 0x80000
+
#define R_SPEED 0x100000
#define R_SSS 0x200000
+#define R_NO_OVERWRITE 0x400000 /* skip existing files */
+#define R_TOUCH 0x800000 /* touch files before rendering */
+#define R_SIMPLIFY 0x1000000
+
/* filtertype */
#define R_FILTER_BOX 0
@@ -554,7 +624,7 @@ typedef struct Scene {
#define R_INTERN 0
#define R_YAFRAY 1
-/* scemode */
+/* scemode (int now) */
#define R_DOSEQ 0x0001
#define R_BG_RENDER 0x0002
/* passepartout is camera option now, keep this for backward compatibility */
@@ -569,8 +639,10 @@ typedef struct Scene {
#define R_EXR_TILE_FILE 0x0400
#define R_COMP_FREE 0x0800
#define R_NO_IMAGE_LOAD 0x1000
-#define R_NO_TEX 0x2000
+#define R_NO_TEX 0x2000
#define R_STAMP_INFO 0x4000
+#define R_FULL_SAMPLE 0x8000
+#define R_COMP_RERENDER 0x10000
/* r->stamp */
#define R_STAMP_TIME 0x0001
@@ -598,7 +670,7 @@ typedef struct Scene {
#define R_TARGA 0
#define R_IRIS 1
#define R_HAMX 2
-#define R_FTYPE 3
+#define R_FTYPE 3 /* ftype is nomore */
#define R_JPEG90 4
#define R_MOVIE 5
#define R_IRIZ 7
@@ -623,12 +695,15 @@ typedef struct Scene {
#define R_OPENEXR_HALF 1
#define R_OPENEXR_ZBUF 2
#define R_PREVIEW_JPG 4
+#define R_CINEON_LOG 8
+#define R_TIFF_16BIT 16
/* bake_mode: same as RE_BAKE_xxx defines */
/* bake_flag: */
#define R_BAKE_CLEAR 1
#define R_BAKE_OSA 2
#define R_BAKE_TO_ACTIVE 4
+#define R_BAKE_NORMALIZE 8
/* bake_normal_space */
#define R_BAKE_SPACE_CAMERA 0
@@ -672,10 +747,16 @@ typedef struct Scene {
/* scene->snap_flag */
#define SCE_SNAP 1
+#define SCE_SNAP_ROTATE 2
/* scene->snap_target */
#define SCE_SNAP_TARGET_CLOSEST 0
#define SCE_SNAP_TARGET_CENTER 1
#define SCE_SNAP_TARGET_MEDIAN 2
+#define SCE_SNAP_TARGET_ACTIVE 3
+/* scene->snap_mode */
+#define SCE_SNAP_MODE_VERTEX 0
+#define SCE_SNAP_MODE_EDGE 1
+#define SCE_SNAP_MODE_FACE 2
/* sce->selectmode */
#define SCE_SELECT_VERTEX 1 /* for mesh */
@@ -713,6 +794,9 @@ typedef struct Scene {
#define FFMPEG_MULTIPLEX_AUDIO 1
#define FFMPEG_AUTOSPLIT_OUTPUT 2
+/* Sculpt brush flags */
+#define SCULPT_BRUSH_AIRBRUSH 1
+#define SCULPT_BRUSH_ANCHORED 2
/* SculptData.flags */
#define SCULPT_INPUT_SMOOTH 1
#define SCULPT_DRAW_FAST 2
@@ -734,11 +818,27 @@ typedef struct Scene {
#define SYMM_Y 2
#define SYMM_Z 4
+#define AXISLOCK_X 1
+#define AXISLOCK_Y 2
+#define AXISLOCK_Z 4
+
/* toolsettings->imagepaint_flag */
#define IMAGEPAINT_DRAWING 1
#define IMAGEPAINT_DRAW_TOOL 2
#define IMAGEPAINT_DRAW_TOOL_DRAWING 4
+/* toolsettings->uvcalc_flag */
+#define UVCALC_FILLHOLES 1
+#define UVCALC_NO_ASPECT_CORRECT 2 /* would call this UVCALC_ASPECT_CORRECT, except it should be default with old file */
+#define UVCALC_TRANSFORM_CORRECT 4 /* adjust UV's while transforming to avoid distortion */
+
+/* toolsettings->edge_mode */
+#define EDGE_MODE_SELECT 0
+#define EDGE_MODE_TAG_SEAM 1
+#define EDGE_MODE_TAG_SHARP 2
+#define EDGE_MODE_TAG_CREASE 3
+#define EDGE_MODE_TAG_BEVEL 4
+
/* toolsettings->particle flag */
#define PE_KEEP_LENGTHS 1
#define PE_LOCK_FIRST 2
@@ -771,12 +871,21 @@ typedef struct Scene {
#define RETOPO_ELLIPSE 4
/* toolsettings->skgen_options */
-#define SKGEN_FILTER_INTERNAL 1
-#define SKGEN_FILTER_EXTERNAL 2
-#define SKGEN_SYMMETRY 4
-#define SKGEN_CUT_LENGTH 8
-#define SKGEN_CUT_ANGLE 16
-#define SKGEN_CUT_CORRELATION 32
+#define SKGEN_FILTER_INTERNAL (1 << 0)
+#define SKGEN_FILTER_EXTERNAL (1 << 1)
+#define SKGEN_SYMMETRY (1 << 2)
+#define SKGEN_CUT_LENGTH (1 << 3)
+#define SKGEN_CUT_ANGLE (1 << 4)
+#define SKGEN_CUT_CORRELATION (1 << 5)
+#define SKGEN_HARMONIC (1 << 6)
+#define SKGEN_STICK_TO_EMBEDDING (1 << 7)
+#define SKGEN_ADAPTIVE_DISTANCE (1 << 8)
+#define SKGEN_FILTER_SMART (1 << 9)
+#define SKGEN_DISP_LENGTH (1 << 10)
+#define SKGEN_DISP_WEIGHT (1 << 11)
+#define SKGEN_DISP_ORIG (1 << 12)
+#define SKGEN_DISP_EMBED (1 << 13)
+#define SKGEN_DISP_INDEX (1 << 14)
#define SKGEN_SUB_LENGTH 0
#define SKGEN_SUB_ANGLE 1
diff --git a/source/blender/makesdna/DNA_screen_types.h b/source/blender/makesdna/DNA_screen_types.h
index c5ec847608f..40374f56967 100644
--- a/source/blender/makesdna/DNA_screen_types.h
+++ b/source/blender/makesdna/DNA_screen_types.h
@@ -6,7 +6,7 @@
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
+ * of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -20,7 +20,6 @@
* The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
* All rights reserved.
*
- *
* Contributor(s): Blender Foundation
*
* ***** END GPL LICENSE BLOCK *****
diff --git a/source/blender/makesdna/DNA_scriptlink_types.h b/source/blender/makesdna/DNA_scriptlink_types.h
index 85e0f237d69..95e20dd004d 100644
--- a/source/blender/makesdna/DNA_scriptlink_types.h
+++ b/source/blender/makesdna/DNA_scriptlink_types.h
@@ -58,6 +58,9 @@ typedef struct ScriptLink {
* RENDER script links for clean-up actions */
#define SCRIPT_POSTRENDER 32
+#define SCRIPT_OBJECTUPDATE 64
+#define SCRIPT_OBDATAUPDATE 128
+
/* **************** SPACE HANDLERS ********************* */
/* these are special scriptlinks that can be assigned to
* a given space in a given ScrArea to:
diff --git a/source/blender/makesdna/DNA_sensor_types.h b/source/blender/makesdna/DNA_sensor_types.h
index 90e2b8f9f41..d8a1ffc6c24 100644
--- a/source/blender/makesdna/DNA_sensor_types.h
+++ b/source/blender/makesdna/DNA_sensor_types.h
@@ -82,6 +82,19 @@ typedef struct bPropertySensor {
char maxvalue[32];
} bPropertySensor;
+typedef struct bActuatorSensor {
+ int type;
+ int pad;
+ char name[32];
+} bActuatorSensor;
+
+typedef struct bDelaySensor {
+ short delay;
+ short duration;
+ short flag;
+ short pad;
+} bDelaySensor;
+
typedef struct bCollisionSensor {
char name[32]; /* property name */
char materialName[32]; /* material */
@@ -144,18 +157,18 @@ typedef struct bSensor {
/* just add here, to avoid align errors... */
short invert; /* Whether or not to invert the output. */
- short freq2; /* The negative pulsing frequency? Not used anymore... */
+ short level; /* Whether the sensor is level base (edge by default) */
int pad;
} bSensor;
typedef struct bJoystickSensor {
char name[32];
- short type;
- short pad;
+ char type;
+ char joyindex;
+ short flag;
int axis;
int axisf;
int button;
- int buttonf;
int hat;
int hatf;
int precision;
@@ -197,11 +210,15 @@ typedef struct bJoystickSensor {
#define SENS_RAY 9
#define SENS_MESSAGE 10
#define SENS_JOYSTICK 11
+#define SENS_ACTUATOR 12
+#define SENS_DELAY 13
/* sensor->flag */
#define SENS_SHOW 1
#define SENS_DEL 2
#define SENS_NEW 4
#define SENS_NOT 8
+#define SENS_VISIBLE 16
+#define SENS_PIN 32
/* sensor->pulse */
#define SENS_PULSE_CONT 0
@@ -221,6 +238,9 @@ typedef struct bJoystickSensor {
* */
/* #define SENS_COLLISION_PROPERTY 0 */
#define SENS_COLLISION_MATERIAL 1
+/* ray specific mode */
+/* X-Ray means that the ray will traverse objects that don't have the property/material */
+#define SENS_RAY_XRAY 2
/* Some stuff for the mouse sensor Type: */
#define BL_SENS_MOUSE_LEFT_BUTTON 1
@@ -232,6 +252,8 @@ typedef struct bJoystickSensor {
#define BL_SENS_MOUSE_MOUSEOVER 16
#define BL_SENS_MOUSE_MOUSEOVER_ANY 32
+#define SENS_JOY_ANY_EVENT 1
+
#define SENS_JOY_BUTTON 0
#define SENS_JOY_BUTTON_PRESSED 0
#define SENS_JOY_BUTTON_RELEASED 1
@@ -246,5 +268,9 @@ typedef struct bJoystickSensor {
#define SENS_JOY_HAT 2
#define SENS_JOY_HAT_DIR 0
+
+#define SENS_DELAY_REPEAT 1
+// should match JOYINDEX_MAX in SCA_JoystickDefines.h */
+#define SENS_JOY_MAXINDEX 8
#endif
diff --git a/source/blender/makesdna/DNA_sequence_types.h b/source/blender/makesdna/DNA_sequence_types.h
index cc1213a02a1..7bad8ec3b44 100644
--- a/source/blender/makesdna/DNA_sequence_types.h
+++ b/source/blender/makesdna/DNA_sequence_types.h
@@ -47,19 +47,55 @@ typedef struct StripElem {
typedef struct TStripElem {
struct ImBuf *ibuf;
+ struct ImBuf *ibuf_comp;
struct TStripElem *se1, *se2, *se3;
short ok;
- short pad;
+ short flag;
int nr;
} TStripElem;
+typedef struct StripCrop {
+ int top;
+ int bottom;
+ int left;
+ int right;
+} StripCrop;
+
+typedef struct StripTransform {
+ int xofs;
+ int yofs;
+} StripTransform;
+
+typedef struct StripColorBalance {
+ float lift[3];
+ float gamma[3];
+ float gain[3];
+ int flag;
+ int pad;
+ float exposure;
+ float saturation;
+} StripColorBalance;
+
+typedef struct StripProxy {
+ char dir[160];
+} StripProxy;
+
typedef struct Strip {
struct Strip *next, *prev;
int rt, len, us, done;
+ int startstill, endstill;
StripElem *stripdata;
char dir[160];
int orx, ory;
+ StripProxy *proxy;
+ StripCrop *crop;
+ StripTransform *transform;
+ StripColorBalance *color_balance;
TStripElem *tstripdata;
+ TStripElem *tstripdata_startstill;
+ TStripElem *tstripdata_endstill;
+ struct ImBuf *ibuf_startstill;
+ struct ImBuf *ibuf_endstill;
} Strip;
@@ -93,7 +129,7 @@ typedef struct Sequence {
void *lib; /* needed (to be like ipo), else it will raise libdata warnings, this should never be used */
char name[24]; /* name, not set by default and dosnt need to be unique as with ID's */
- short flag, type; /*flags bitmap (see below) and the type of sequence*/
+ int flag, type; /*flags bitmap (see below) and the type of sequence*/
int len; /* the length of the contense of this strip - before handles are applied */
int start, startofs, endofs;
int startstill, endstill;
@@ -102,6 +138,7 @@ typedef struct Sequence {
float mul, handsize;
/* is sfra needed anymore? - it looks like its only used in one place */
int sfra; /* starting frame according to the timeline of the scene. */
+ int anim_preseek;
Strip *strip;
@@ -125,7 +162,13 @@ typedef struct Sequence {
void *effectdata; /* Struct pointer for effect settings */
- int anim_preseek;
+ int anim_startofs; /* only use part of animation file */
+ int anim_endofs; /* is subtle different to startofs / endofs */
+
+ int blend_mode;
+ float blend_opacity;
+
+ int scenenr; /* for scene selection */
int pad;
} Sequence;
@@ -207,6 +250,18 @@ typedef struct SpeedControlVars {
#define SEQ_FLAG_DELETE 1024
#define SEQ_FLIPX 2048
#define SEQ_FLIPY 4096
+#define SEQ_MAKE_FLOAT 8192
+#define SEQ_LOCK 16384
+#define SEQ_USE_PROXY 32768
+#define SEQ_USE_TRANSFORM 65536
+#define SEQ_USE_CROP 131072
+#define SEQ_USE_COLOR_BALANCE 262144
+#define SEQ_USE_PROXY_CUSTOM_DIR 524288
+#define SEQ_ACTIVE 1048576
+
+#define SEQ_COLOR_BALANCE_INVERSE_GAIN 1
+#define SEQ_COLOR_BALANCE_INVERSE_GAMMA 2
+#define SEQ_COLOR_BALANCE_INVERSE_LIFT 4
/* seq->type WATCH IT: SEQ_EFFECT BIT is used to determine if this is an effect strip!!! */
#define SEQ_IMAGE 0
@@ -232,10 +287,18 @@ typedef struct SpeedControlVars {
#define SEQ_TRANSFORM 27
#define SEQ_COLOR 28
#define SEQ_SPEED 29
+#define SEQ_EFFECT_MAX 29
#define STRIPELEM_FAILED 0
#define STRIPELEM_OK 1
-#define STRIPELEM_META 2
+
+#define STRIPELEM_PREVIEW_DONE 1
+
+#define SEQ_BLEND_REPLACE 0
+/* all other BLEND_MODEs are simple SEQ_EFFECT ids and therefore identical
+ to the table above. (Only those effects that handle _exactly_ two inputs,
+ otherwise, you can't really blend, right :) !)
+*/
#endif
diff --git a/source/blender/makesdna/DNA_space_types.h b/source/blender/makesdna/DNA_space_types.h
index e1b916be814..dc713362d83 100644
--- a/source/blender/makesdna/DNA_space_types.h
+++ b/source/blender/makesdna/DNA_space_types.h
@@ -50,6 +50,7 @@ struct RenderInfo;
struct bNodeTree;
struct uiBlock;
struct FileList;
+struct bGPdata;
/**
* The base structure all the other spaces
@@ -140,11 +141,13 @@ typedef struct SpaceSeq {
View2D v2d;
float xof, yof; /* offset for drawing the image preview */
- short mainb, zoom;
+ short mainb, pad;
short chanshown;
- short pad2;
+ short zebra;
int flag;
- int pad;
+ float zoom;
+
+ struct bGPdata *gpd; /* grease-pencil data */
} SpaceSeq;
typedef struct SpaceFile {
@@ -158,7 +161,7 @@ typedef struct SpaceFile {
int totfile;
char title[24];
- char dir[160];
+ char dir[240];
char file[80];
short type, ofs, flag, sort;
@@ -224,19 +227,19 @@ typedef struct SpaceImage {
short imanr;
short curtile; /* the currently active tile of the image when tile is enabled, is kept in sync with the active faces tile */
int flag;
+ short selectmode;
short imtypenr, lock;
- short showspare, pin;
+ short pin;
float zoom;
char dt_uv; /* UV draw type */
- char sticky; /* sticky selection type */
- char pad[6];
+ char sticky; /* sticky selection type */
+ char dt_uvstretch;
+ char pad[5];
float xof, yof; /* user defined offset, image is centered */
float centx, centy; /* storage for offset while render drawing */
- char *info_str, *info_spare; /* info string for render */
- struct ImBuf *spare;
-
+ struct bGPdata *gpd; /* grease pencil data */
} SpaceImage;
typedef struct SpaceNla {
@@ -263,24 +266,43 @@ typedef struct SpaceText {
struct Text *text;
int top, viewlines;
- short flags, menunr;
-
- int font_id;
+ short flags, menunr;
+ int font_id;
+
int lheight;
int left;
int showlinenrs;
-
int tabnumber;
+
int currtab_set;
int showsyntax;
- int unused_padd;
-
+ int overwrite;
float pix_per_line;
struct rcti txtscroll, txtbar;
+ int wordwrap, doplugins;
+
} SpaceText;
+typedef struct Script {
+ ID id;
+
+ void *py_draw;
+ void *py_event;
+ void *py_button;
+ void *py_browsercallback;
+ void *py_globaldict;
+
+ int flags, lastspace;
+ char scriptname[256]; /* store the script file here so we can re-run it on loading blender, if "Enable Scripts" is on */
+ char scriptarg[256];
+} Script;
+#define SCRIPT_SET_NULL(_script) _script->py_draw = _script->py_event = _script->py_button = _script->py_browsercallback = _script->py_globaldict = NULL; _script->flags = 0;
+#define SCRIPT_RUNNING 0x01
+#define SCRIPT_GUI 0x02
+#define SCRIPT_FILESEL 0x04
+
typedef struct SpaceScript {
SpaceLink *next, *prev;
int spacetype;
@@ -309,6 +331,8 @@ typedef struct SpaceNode {
int spacetype;
float blockscale;
+ short blockhandler[8];
+
View2D v2d;
struct ID *id, *from; /* context, no need to save in file? well... pinning... */
@@ -321,11 +345,13 @@ typedef struct SpaceNode {
struct bNodeTree *nodetree, *edittree;
int treetype, pad; /* treetype: as same nodetree->type */
+ struct bGPdata *gpd; /* grease-pencil data */
} SpaceNode;
/* snode->flag */
#define SNODE_DO_PREVIEW 1
#define SNODE_BACKDRAW 2
+#define SNODE_DISPGP 4
typedef struct SpaceImaSel {
SpaceLink *next, *prev;
@@ -340,7 +366,7 @@ typedef struct SpaceImaSel {
/* specific stuff for drawing */
char title[24];
- char dir[160];
+ char dir[240];
char file[80];
short type, menu, flag, sort;
@@ -404,7 +430,7 @@ typedef struct SpaceImaSel {
/* filesel types */
#define FILE_UNIX 8
-#define FILE_BLENDER 8
+#define FILE_BLENDER 8 /* dont display relative paths */
#define FILE_SPECIAL 9
#define FILE_LOADLIB 1
@@ -450,10 +476,14 @@ typedef struct SpaceImaSel {
#define SI_SHOW 1
/* SpaceImage->dt_uv */
-#define SI_UVDT_DASH 0
-#define SI_UVDT_BLACK 1
-#define SI_UVDT_WHITE 2
-#define SI_UVDT_OUTLINE 3
+#define SI_UVDT_OUTLINE 0
+#define SI_UVDT_DASH 1
+#define SI_UVDT_BLACK 2
+#define SI_UVDT_WHITE 3
+
+/* SpaceImage->dt_uvstretch */
+#define SI_UVDT_STRETCH_ANGLE 0
+#define SI_UVDT_STRETCH_AREA 1
/* SpaceImage->sticky
* Note DISABLE should be 0, however would also need to re-arrange icon order,
@@ -462,6 +492,12 @@ typedef struct SpaceImaSel {
#define SI_STICKY_DISABLE 1
#define SI_STICKY_VERTEX 2
+/* SpaceImage->selectmode */
+#define SI_SELECT_VERTEX 0
+#define SI_SELECT_EDGE 1 /* not implemented */
+#define SI_SELECT_FACE 2
+#define SI_SELECT_ISLAND 3
+
/* SpaceImage->flag */
#define SI_BE_SQUARE 1<<0
#define SI_EDITTILE 1<<1
@@ -469,7 +505,7 @@ typedef struct SpaceImaSel {
#define SI_DRAWTOOL 1<<3
#define SI_DEPRECATED1 1<<4 /* stick UVs to others in the same location */
#define SI_DRAWSHADOW 1<<5
-#define SI_SELACTFACE 1<<6
+#define SI_SELACTFACE 1<<6 /* deprecated */
#define SI_DEPRECATED2 1<<7
#define SI_DEPRECATED3 1<<8 /* stick UV selection to mesh vertex (UVs wont always be touching) */
#define SI_COORDFLOATS 1<<9
@@ -486,7 +522,13 @@ typedef struct SpaceImaSel {
/* this means that the image is drawn until it reaches the view edge,
* in the image view, its unrelated to the 'tile' mode for texface */
#define SI_DRAW_TILE 1<<19
-#define SI_SMOOTH_UV 1<<20
+#define SI_SMOOTH_UV 1<<20
+#define SI_DRAW_STRETCH 1<<21
+#define SI_DISPGP 1<<22
+
+/* SpaceIpo->flag */
+#define SIPO_LOCK_VIEW 1<<0
+#define SIPO_NOTRANSKEYCULL 1<<1
/* SpaceText flags (moved from DNA_text_types.h) */
@@ -520,6 +562,7 @@ typedef struct SpaceImaSel {
#define OOPS_IM 4096
#define OOPS_AR 8192
#define OOPS_GR 16384
+#define OOPS_CA 32768
/* SpaceOops->outlinevis */
#define SO_ALL_SCENES 0
@@ -532,6 +575,7 @@ typedef struct SpaceImaSel {
#define SO_LIBRARIES 7
#define SO_VERSE_SESSION 8
#define SO_VERSE_MS 9
+#define SO_SEQUENCE 10
/* SpaceOops->storeflag */
#define SO_TREESTORE_CLEANUP 1
@@ -578,6 +622,7 @@ typedef struct SpaceImaSel {
#define SNLA_ALLKEYED 1
#define SNLA_ACTIVELAYERS 2
#define SNLA_DRAWTIME 4
+#define SNLA_NOTRANSKEYCULL 8
/* time->flag */
/* show timing in frames instead of in seconds */
@@ -595,16 +640,21 @@ typedef struct SpaceImaSel {
#define TIME_WITH_SEQ_AUDIO 16
#define TIME_SEQ 32
#define TIME_ALL_IMAGE_WIN 64
+#define TIME_CONTINUE_PHYSICS 128
/* sseq->mainb */
#define SEQ_DRAW_SEQUENCE 0
#define SEQ_DRAW_IMG_IMBUF 1
#define SEQ_DRAW_IMG_WAVEFORM 2
#define SEQ_DRAW_IMG_VECTORSCOPE 3
+#define SEQ_DRAW_IMG_HISTOGRAM 4
/* sseq->flag */
-#define SEQ_DRAWFRAMES 1
+#define SEQ_DRAWFRAMES 1
#define SEQ_MARKER_TRANS 2
+#define SEQ_DRAW_COLOR_SEPERATED 4
+#define SEQ_DRAW_SAFE_MARGINS 8
+#define SEQ_DRAW_GPENCIL 16
/* space types, moved from DNA_screen_types.h */
enum {
diff --git a/source/blender/makesdna/DNA_text_types.h b/source/blender/makesdna/DNA_text_types.h
index d1859d22115..48ecccd517a 100644
--- a/source/blender/makesdna/DNA_text_types.h
+++ b/source/blender/makesdna/DNA_text_types.h
@@ -38,25 +38,36 @@ typedef struct TextLine {
struct TextLine *next, *prev;
char *line;
- char *format;
- int len, blen;
+ char *format; /* may be NULL if syntax is off or not yet formatted */
+ int len, blen; /* blen unused */
} TextLine;
+typedef struct TextMarker {
+ struct TextMarker *next, *prev;
+
+ int lineno, start, end, pad1; /* line number and start/end character indices */
+
+ int group, flags; /* see BKE_text.h for flag defines */
+ char color[4], pad[4]; /* draw color of the marker */
+} TextMarker;
+
typedef struct Text {
ID id;
char *name;
-
+
int flags, nlines;
ListBase lines;
TextLine *curl, *sell;
int curc, selc;
+ ListBase markers;
char *undo_buf;
int undo_pos, undo_len;
void *compiled;
+ double mtime;
} Text;
@@ -74,4 +85,12 @@ typedef struct Text {
#define TXT_READONLY 0x0100
#define TXT_FOLLOW 0x0200 /* always follow cursor (console) */
+/* format continuation flags */
+#define TXT_NOCONT 0x00 /* no continuation */
+#define TXT_SNGQUOTSTR 0x01 /* single quotes */
+#define TXT_DBLQUOTSTR 0x02 /* double quotes */
+#define TXT_TRISTR 0x04 /* triplets of quotes: """ or ''' */
+#define TXT_SNGTRISTR 0x05 /*(TXT_TRISTR | TXT_SNGQUOTSTR)*/
+#define TXT_DBLTRISTR 0x06 /*(TXT_TRISTR | TXT_DBLQUOTSTR)*/
+
#endif
diff --git a/source/blender/makesdna/DNA_texture_types.h b/source/blender/makesdna/DNA_texture_types.h
index bee341acf2e..111dc08ee02 100644
--- a/source/blender/makesdna/DNA_texture_types.h
+++ b/source/blender/makesdna/DNA_texture_types.h
@@ -245,6 +245,7 @@ typedef struct TexMapping {
#define TEX_CALCALPHA 32
#define TEX_NORMALMAP 2048
#define TEX_GAUSS_MIP 4096
+#define TEX_FILTER_MIN 8192
/* imaflag unused, only for version check */
#define TEX_FIELDS_ 8
@@ -343,11 +344,13 @@ typedef struct TexMapping {
#define PROJ_Z 3
/* texflag */
-#define MTEX_RGBTOINT 1
-#define MTEX_STENCIL 2
-#define MTEX_NEGATIVE 4
-#define MTEX_ALPHAMIX 8
-#define MTEX_VIEWSPACE 16
+#define MTEX_RGBTOINT 1
+#define MTEX_STENCIL 2
+#define MTEX_NEGATIVE 4
+#define MTEX_ALPHAMIX 8
+#define MTEX_VIEWSPACE 16
+#define MTEX_DUPLI_MAPTO 32
+#define MTEX_OB_DUPLI_ORIG 64
/* blendtype */
#define MTEX_BLEND 0
@@ -360,6 +363,11 @@ typedef struct TexMapping {
#define MTEX_LIGHT 7
#define MTEX_SCREEN 8
#define MTEX_OVERLAY 9
+#define MTEX_BLEND_HUE 10
+#define MTEX_BLEND_SAT 11
+#define MTEX_BLEND_VAL 12
+#define MTEX_BLEND_COLOR 13
+#define MTEX_NUM_BLENDTYPES 14
/* **************** EnvMap ********************* */
diff --git a/source/blender/makesdna/DNA_userdef_types.h b/source/blender/makesdna/DNA_userdef_types.h
index 0f04528130e..fbd962f9372 100644
--- a/source/blender/makesdna/DNA_userdef_types.h
+++ b/source/blender/makesdna/DNA_userdef_types.h
@@ -61,7 +61,6 @@ typedef struct ThemeUI {
char but_drawtype;
char pad[3];
char iconfile[80]; // FILE_MAXFILE length
-
} ThemeUI;
/* try to put them all in one, if needed a special struct can be created as well
@@ -102,16 +101,28 @@ typedef struct ThemeSpace {
char movie[4], image[4], scene[4], audio[4]; // for sequence editor
char effect[4], plugin[4], transition[4], meta[4];
char editmesh_active[4];
+
+ char handle_vertex[4];
+ char handle_vertex_select[4];
+ char handle_vertex_size;
+ char hpad[7];
} ThemeSpace;
+
/* set of colors for use as a custom color set for Objects/Bones wire drawing */
typedef struct ThemeWireColor {
- char unselected[3];
- char selected[3];
- char active[3];
- char pad[7];
+ char solid[4];
+ char select[4];
+ char active[4];
+
+ short flag;
+ short pad;
} ThemeWireColor;
+/* flags for ThemeWireColor */
+#define TH_WIRECOLOR_CONSTCOLS (1<<0)
+#define TH_WIRECOLOR_TEXTCOLS (1<<1)
+
/* A theme */
typedef struct bTheme {
struct bTheme *next, *prev;
@@ -177,7 +188,9 @@ typedef struct UserDef {
char fontname[256]; // FILE_MAXDIR+FILE length
struct ListBase themes;
short undosteps;
- short curssize;
+ short undomemory;
+ short gp_manhattendist, gp_euclideandist, gp_eraser;
+ short gp_settings;
short tb_leftmouse, tb_rightmouse;
struct SolidLight light[3];
short tw_hotspot, tw_flag, tw_handlesize, tw_size;
@@ -192,9 +205,15 @@ typedef struct UserDef {
short recent_files; /* maximum number of recently used files to remember */
short smooth_viewtx; /* miliseconds to spend spinning the view */
short glreslimit;
+ short ndof_pan, ndof_rotate;
+ short curssize, pad;
+// char pad[8];
char versemaster[160];
char verseuser[160];
- float glalphaclip, pad;
+ float glalphaclip;
+
+ short autokey_mode; /* autokeying mode */
+ short autokey_flag; /* flags for autokeying */
struct ColorBand coba_weight; /* from texture.h */
} UserDef;
@@ -213,7 +232,7 @@ extern UserDef U; /* from usiblender.c !!!! */
#define USER_DUPLILINK (1 << 6)
#define USER_FSCOLLUM (1 << 7)
#define USER_MAT_ON_OB (1 << 8)
-#define USER_NO_CAPSLOCK (1 << 9)
+/*#define USER_NO_CAPSLOCK (1 << 9)*/ /* not used anywhere */
#define USER_VIEWMOVE (1 << 10)
#define USER_TOOLTIPS (1 << 11)
#define USER_TWOBUTTONMOUSE (1 << 12)
@@ -224,8 +243,9 @@ extern UserDef U; /* from usiblender.c !!!! */
#define USER_CUSTOM_RANGE (1 << 17)
#define USER_ADD_EDITMODE (1 << 18)
#define USER_ADD_VIEWALIGNED (1 << 19)
-#define USER_ADD_VIEWALIGNED (1 << 19)
-
+#define USER_RELPATHS (1 << 20)
+#define USER_DRAGIMMEDIATE (1 << 21)
+#define USER_DONT_DOSCRIPTLINKS (1 << 22)
/* viewzom */
#define USER_ZOOM_CONT 0
@@ -233,9 +253,8 @@ extern UserDef U; /* from usiblender.c !!!! */
#define USER_ZOOM_DOLLY 2
/* uiflag */
-
-#define USER_KEYINSERTACT (1 << 0)
-#define USER_KEYINSERTOBJ (1 << 1)
+// old flag for #define USER_KEYINSERTACT (1 << 0)
+// old flag for #define USER_KEYINSERTOBJ (1 << 1)
#define USER_WHEELZOOMDIR (1 << 2)
#define USER_FILTERFILEEXTS (1 << 3)
#define USER_DRAWVIEWINFO (1 << 4)
@@ -249,16 +268,30 @@ extern UserDef U; /* from usiblender.c !!!! */
#define USER_LOCKAROUND (1 << 12)
#define USER_GLOBALUNDO (1 << 13)
#define USER_ORBIT_SELECTION (1 << 14)
-#define USER_KEYINSERTAVAI (1 << 15)
+// old flag for #define USER_KEYINSERTAVAI (1 << 15)
+#define USER_ORBIT_ZBUF (1 << 15)
#define USER_HIDE_DOT (1 << 16)
#define USER_SHOW_ROTVIEWICON (1 << 17)
#define USER_SHOW_VIEWPORTNAME (1 << 18)
-#define USER_KEYINSERTNEED (1 << 19)
+// old flag for #define USER_KEYINSERTNEED (1 << 19)
#define USER_ZOOM_TO_MOUSEPOS (1 << 20)
-#define USER_SHOW_FPS (1 << 21)
+#define USER_SHOW_FPS (1 << 21)
+#define USER_MMB_PASTE (1 << 22)
-/* transopts */
+/* Auto-Keying mode */
+ /* AUTOKEY_ON is a bitflag */
+#define AUTOKEY_ON 1
+ /* AUTOKEY_ON + 2**n... (i.e. AUTOKEY_MODE_NORMAL = AUTOKEY_ON + 2) to preserve setting, even when autokey turned off */
+#define AUTOKEY_MODE_NORMAL 3
+#define AUTOKEY_MODE_EDITKEYS 5
+
+/* Auto-Keying flag */
+#define AUTOKEY_FLAG_INSERTAVAIL (1<<0)
+#define AUTOKEY_FLAG_INSERTNEEDED (1<<1)
+#define AUTOKEY_FLAG_AUTOMATKEY (1<<2)
+
+/* transopts */
#define USER_TR_TOOLTIPS (1 << 0)
#define USER_TR_BUTTONS (1 << 1)
#define USER_TR_MENUS (1 << 2)
@@ -269,7 +302,6 @@ extern UserDef U; /* from usiblender.c !!!! */
#define CONVERT_TO_UTF8 (1 << 7)
/* dupflag */
-
#define USER_DUP_MESH (1 << 0)
#define USER_DUP_CURVE (1 << 1)
#define USER_DUP_SURF (1 << 2)
@@ -283,18 +315,20 @@ extern UserDef U; /* from usiblender.c !!!! */
#define USER_DUP_ACT (1 << 10)
/* gameflags */
-
-#define USER_VERTEX_ARRAYS 1
+#define USER_DEPRECATED_FLAG 1
#define USER_DISABLE_SOUND 2
#define USER_DISABLE_MIPMAP 4
/* vrml flag */
-
#define USER_VRML_LAYERS 1
#define USER_VRML_AUTOSCALE 2
#define USER_VRML_TWOSIDED 4
/* tw_flag (transform widget) */
+/* gp_settings (Grease Pencil Settings) */
+#define GP_PAINT_DOSMOOTH (1<<0)
+#define GP_PAINT_DOSIMPLIFY (1<<1)
+
#endif
diff --git a/source/blender/makesdna/DNA_view3d_types.h b/source/blender/makesdna/DNA_view3d_types.h
index 987a12965fb..f1fa8c19199 100644
--- a/source/blender/makesdna/DNA_view3d_types.h
+++ b/source/blender/makesdna/DNA_view3d_types.h
@@ -40,6 +40,7 @@ struct Base;
struct BoundBox;
struct RenderInfo;
struct RetopoViewData;
+struct bGPdata;
/* This is needed to not let VC choke on near and far... old
* proprietary MS extensions... */
@@ -53,9 +54,12 @@ struct RetopoViewData;
#include "DNA_listBase.h"
#include "DNA_image_types.h"
+/* ******************************** */
+
/* The near/far thing is a Win EXCEPTION. Thus, leave near/far in the
* code, and patch for windows. */
-
+
+/* Background Picture in 3D-View */
typedef struct BGpic {
struct Image *ima;
struct ImageUser iuser;
@@ -63,6 +67,9 @@ typedef struct BGpic {
short xim, yim;
} BGpic;
+/* ********************************* */
+
+/* 3D ViewPort Struct */
typedef struct View3D {
struct SpaceLink *next, *prev;
int spacetype;
@@ -78,13 +85,9 @@ typedef struct View3D {
float winmat1[4][4]; // persp(1) storage, for swap matrices
float viewmat1[4][4];
- float viewquat[4], dist, zfac, pad0; /* zfac is initgrabz() result */
+ float viewquat[4], dist, zfac; /* zfac is initgrabz() result */
+ int lay_used; /* used while drawing */
- /**
- * 0 - ortho
- * 1 - do 3d perspective
- * 2 - use the camera
- */
short persp;
short view;
@@ -99,7 +102,7 @@ typedef struct View3D {
/**
* The drawing mode for the 3d display. Set to OB_WIRE, OB_SOLID,
- * OB_SHADED or OB_TEXTURED */
+ * OB_SHADED or OB_TEXTURE */
short drawtype;
short localview;
int lay, layact;
@@ -133,14 +136,22 @@ typedef struct View3D {
short gridsubdiv; /* Number of subdivisions in the grid between each highlighted grid line */
- short pad3;
+ short keyflags; /* flags for display of keyframes */
- short pad2;
+ char ndofmode; /* mode of transform for 6DOF devices -1 not found, 0 normal, 1 fly, 2 ob transform */
+ char ndoffilter; /*filter for 6DOF devices 0 normal, 1 dominant */
void *properties_storage; /* Nkey panel stores stuff here, not in file */
+ struct bGPdata *gpd; /* Grease-Pencil Data (annotation layers) */
+ /* last view */
+ float lviewquat[4];
+ short lpersp, lview;
+
+ short pad5, pad6;
} View3D;
+
/* View3D->flag (short) */
#define V3D_MODE (16+32+64+128+256+512)
#define V3D_DISPIMAGE 1
@@ -160,12 +171,13 @@ typedef struct View3D {
#define V3D_CLIPPING 16384
#define V3D_DRAW_CENTERS 32768
-
/* View3d->flag2 (short) */
+#define V3D_MODE2 (32)
#define V3D_OPP_DIRECTION_NAME 1
#define V3D_FLYMODE 2
#define V3D_DEPRECATED 4 /* V3D_TRANSFORM_SNAP, moved to a scene setting */
#define V3D_SOLID_TEX 8
+#define V3D_DISPGP 16
/* View3D->around */
#define V3D_CENTER 0
@@ -176,9 +188,9 @@ typedef struct View3D {
/* View3d->persp */
-#define V3D_PERSP_ORTHO 0
-#define V3D_PERSP_DO_3D_PERSP 1
-#define V3D_PERSP_USE_THE_CAMERA 2
+#define V3D_ORTHO 0
+#define V3D_PERSP 1
+#define V3D_CAMOB 2
/* View3d->gridflag */
#define V3D_SHOW_FLOOR 1
@@ -196,6 +208,7 @@ typedef struct View3D {
#define V3D_MANIP_LOCAL 1
#define V3D_MANIP_NORMAL 2
#define V3D_MANIP_VIEW 3
+#define V3D_MANIP_CUSTOM 4 /* anything of value 4 or higher is custom */
/* View3d->twflag */
/* USE = user setting, DRAW = based on selection */
@@ -206,3 +219,4 @@ typedef struct View3D {
#endif
+
diff --git a/source/blender/makesdna/DNA_world_types.h b/source/blender/makesdna/DNA_world_types.h
index 4e313570b2b..ab7e25190ad 100644
--- a/source/blender/makesdna/DNA_world_types.h
+++ b/source/blender/makesdna/DNA_world_types.h
@@ -38,7 +38,7 @@ struct Ipo;
struct MTex;
#ifndef MAX_MTEX
-#define MAX_MTEX 10
+#define MAX_MTEX 18
#endif
@@ -101,15 +101,14 @@ typedef struct World {
float aodist, aodistfac, aoenergy, aobias;
short aomode, aosamp, aomix, aocolor;
float ao_adapt_thresh, ao_adapt_speed_fac;
- float pad2[2];
- short ao_samp_method;
- short pad1[3];
+ float ao_approx_error, ao_approx_correction;
+ short ao_samp_method, ao_gather_method, ao_approx_passes, pad1;
float *aosphere, *aotables;
struct Ipo *ipo;
- struct MTex *mtex[10];
+ struct MTex *mtex[18]; /* MAX_MTEX */
/* previews */
struct PreviewImage *preview;
@@ -148,12 +147,17 @@ typedef struct World {
/* aomode (use distances & random sampling modes) */
#define WO_AODIST 1
#define WO_AORNDSMP 2
+#define WO_AOCACHE 4
/* aocolor */
#define WO_AOPLAIN 0
#define WO_AOSKYCOL 1
#define WO_AOSKYTEX 2
+/* ao_gather_method */
+#define WO_AOGATHER_RAYTRACE 0
+#define WO_AOGATHER_APPROX 1
+
/* texco (also in DNA_material_types.h) */
#define TEXCO_ANGMAP 64
#define TEXCO_H_SPHEREMAP 256
diff --git a/source/blender/makesdna/intern/CMakeLists.txt b/source/blender/makesdna/intern/CMakeLists.txt
index d4b222f3644..a85f561da92 100644
--- a/source/blender/makesdna/intern/CMakeLists.txt
+++ b/source/blender/makesdna/intern/CMakeLists.txt
@@ -24,7 +24,7 @@
#
# ***** END GPL LICENSE BLOCK *****
-SET(SRC makesdna.c ../../../../intern/guardedalloc/intern/mallocn.c)
+SET(SRC makesdna.c ../../../../intern/guardedalloc/intern/mallocn.c ../../../../intern/guardedalloc/intern/mmap_win.c)
INCLUDE_DIRECTORIES(../../../../intern/guardedalloc ..)
diff --git a/source/blender/makesdna/intern/SConscript b/source/blender/makesdna/intern/SConscript
index 23d6f84942f..b7d55a0ca1a 100644
--- a/source/blender/makesdna/intern/SConscript
+++ b/source/blender/makesdna/intern/SConscript
@@ -15,31 +15,36 @@ dna = env.Clone()
makesdna_tool.Append(CCFLAGS = '-DBASE_HEADER="\\"source/blender/makesdna/\\"" ')
makesdna_tool.Append (CPPPATH = ['#/intern/guardedalloc',
- '../../makesdna'])
+ '../../makesdna'])
if env['OURPLATFORM'] == 'linuxcross':
- makesdna_tool.Replace(CC='gcc')
- makesdna_tool.Replace(AR='ar')
- makesdna_tool.Replace(LINK='gcc')
+ makesdna_tool.Replace(CC='gcc')
+ makesdna_tool.Replace(AR='ar')
+ makesdna_tool.Replace(LINK='gcc')
if sys.platform != 'cygwin':
- makesdna_tool.Append (CCFLAGS = cflags)
+ makesdna_tool.Append (CCFLAGS = cflags)
makesdna_tool.Append (CPPDEFINES = defines)
-makesdna_tool.Append (LIBPATH = '#'+root_build_dir+'/lib')
+targetdir = root_build_dir+'/lib'
+if not (root_build_dir[0]==os.sep or root_build_dir[1]==':'):
+ targetdir = '#'+targetdir
+makesdna_tool.Append (LIBPATH = targetdir)
if env['BF_PROFILE']:
makesdna_tool.Append (LINKFLAGS = env['BF_PROFILE_FLAGS'])
-if env['OURPLATFORM'] == 'linux2' and root_build_dir[0]==os.sep:
- makesdna = makesdna_tool.Program (target = root_build_dir+'/makesdna', source = source_files, LIBS=['bf_guardedalloc'])
-else:
- makesdna = makesdna_tool.Program (target = '#'+root_build_dir+'/makesdna', source = source_files, LIBS=['bf_guardedalloc'])
+targetdir = root_build_dir + '/makesdna'
+
+if not (root_build_dir[0]==os.sep or root_build_dir[1]==':'):
+ targetdir = '#' + targetdir
+
+makesdna = makesdna_tool.Program (target = targetdir, source = source_files, LIBS=['bf_guardedalloc'])
dna_dict = dna.Dictionary()
dna.Depends ('dna.c', makesdna)
dna.Depends ('dna.c', header_files)
if env['OURPLATFORM'] != 'linuxcross':
- dna.Command ('dna.c', '', root_build_dir+os.sep+"makesdna $TARGET")
+ dna.Command ('dna.c', '', root_build_dir+os.sep+"makesdna $TARGET")
else:
- dna.Command ('dna.c', '', root_build_dir+os.sep+"makesdna.exe $TARGET")
+ dna.Command ('dna.c', '', root_build_dir+os.sep+"makesdna.exe $TARGET")
obj = ['intern/dna.c', 'intern/dna_genfile.c']
Return ('obj')
diff --git a/source/blender/makesdna/intern/makesdna.c b/source/blender/makesdna/intern/makesdna.c
index 87f99896654..dd5aa518e24 100644
--- a/source/blender/makesdna/intern/makesdna.c
+++ b/source/blender/makesdna/intern/makesdna.c
@@ -55,6 +55,8 @@
#include "MEM_guardedalloc.h"
#include "DNA_sdna_types.h"
+#include "BLO_sys_types.h" // for intptr_t support
+
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
@@ -125,6 +127,8 @@ char *includefiles[] = {
"DNA_brush_types.h",
"DNA_customdata_types.h",
"DNA_particle_types.h",
+ "DNA_cloth_types.h",
+ "DNA_gpencil_types.h",
// if you add files here, please add them at the end
// of makesdna.c (this file) as well
"DNA_windowmanager_types.h",
@@ -688,18 +692,18 @@ static int calculate_structlens(int firststruct)
/* 4-8 aligned/ */
if(sizeof(void *) == 4) {
if (len % 4) {
- printf("Align pointer error in struct: %s %s\n", types[structtype], cp);
+ printf("Align pointer error in struct (len4): %s %s\n", types[structtype], cp);
dna_error = 1;
}
} else {
if (len % 8) {
- printf("Align pointer error in struct: %s %s\n", types[structtype], cp);
+ printf("Align pointer error in struct (len8): %s %s\n", types[structtype], cp);
dna_error = 1;
}
}
if (alphalen % 8) {
- printf("Align pointer error in struct: %s %s\n", types[structtype],cp);
+ printf("Align pointer error in struct (alphalen8): %s %s\n", types[structtype],cp);
dna_error = 1;
}
@@ -748,13 +752,13 @@ static int calculate_structlens(int firststruct)
// has_pointer is set or alphalen != len
if (has_pointer || alphalen != len) {
if (alphalen % 8) {
- printf("Sizeerror in struct: %s (add %d bytes)\n", types[structtype], alphalen%8);
+ printf("Sizeerror 8 in struct: %s (add %d bytes)\n", types[structtype], alphalen%8);
dna_error = 1;
}
}
if(len % 4) {
- printf("Sizeerror in struct: %s (add %d bytes)\n", types[structtype], len%4);
+ printf("Sizeerror 4 in struct: %s (add %d bytes)\n", types[structtype], len%4);
dna_error = 1;
}
@@ -954,7 +958,7 @@ int make_structDNA(char *baseDirectory, FILE *file)
/* calculate size of datablock with strings */
cp= names[nr_names-1];
cp+= strlen(names[nr_names-1]) + 1; /* +1: null-terminator */
- len= (long) (cp - (char*) names[0]);
+ len= (intptr_t) (cp - (char*) names[0]);
len= (len+3) & ~3;
dna_write(file, names[0], len);
@@ -967,7 +971,7 @@ int make_structDNA(char *baseDirectory, FILE *file)
/* calculate datablock size */
cp= types[nr_types-1];
cp+= strlen(types[nr_types-1]) + 1; /* +1: null-terminator */
- len= (long) (cp - (char*) types[0]);
+ len= (intptr_t) (cp - (char*) types[0]);
len= (len+3) & ~3;
dna_write(file, types[0], len);
@@ -989,7 +993,7 @@ int make_structDNA(char *baseDirectory, FILE *file)
/* calc datablock size */
sp= structs[nr_structs-1];
sp+= 2+ 2*( sp[1] );
- len= (long) ((char*) sp - (char*) structs[0]);
+ len= (intptr_t) ((char*) sp - (char*) structs[0]);
len= (len+3) & ~3;
dna_write(file, structs[0], len);
@@ -1146,6 +1150,7 @@ int main(int argc, char ** argv)
#include "DNA_brush_types.h"
#include "DNA_customdata_types.h"
#include "DNA_particle_types.h"
+#include "DNA_cloth_types.h"
+#include "DNA_gpencil_types.h"
#include "DNA_windowmanager_types.h"
-
/* end of list */
diff --git a/source/blender/makesrna/intern/makesrna.c b/source/blender/makesrna/intern/makesrna.c
index 43e03662034..de03fcddd15 100644
--- a/source/blender/makesrna/intern/makesrna.c
+++ b/source/blender/makesrna/intern/makesrna.c
@@ -798,8 +798,7 @@ static void make_bad_file(char *file)
int main(int argc, char **argv)
{
FILE *file;
- int return_status = 0;
- extern int totblock;
+ int totblock, return_status = 0;
if (argc!=2 && argc!=3) {
printf("Usage: %s outfile.c [base directory]\n", argv[0]);
@@ -833,6 +832,7 @@ int main(int argc, char **argv)
}
}
+ totblock= MEM_get_memory_blocks_in_use();
if(totblock!=0) {
printf("Error Totblock: %d\n",totblock);
MEM_printmemlist();
diff --git a/source/blender/nodes/CMP_node.h b/source/blender/nodes/CMP_node.h
index 4b7e721ca57..020bbdebfa2 100644
--- a/source/blender/nodes/CMP_node.h
+++ b/source/blender/nodes/CMP_node.h
@@ -66,6 +66,8 @@ extern bNodeType cmp_node_normalize;
extern bNodeType cmp_node_filter;
extern bNodeType cmp_node_blur;
+extern bNodeType cmp_node_dblur;
+extern bNodeType cmp_node_bilateralblur;
extern bNodeType cmp_node_vecblur;
extern bNodeType cmp_node_dilateerode;
extern bNodeType cmp_node_defocus;
@@ -83,6 +85,7 @@ extern bNodeType cmp_node_sepyuva;
extern bNodeType cmp_node_combyuva;
extern bNodeType cmp_node_sepycca;
extern bNodeType cmp_node_combycca;
+extern bNodeType cmp_node_premulkey;
extern bNodeType cmp_node_diff_matte;
extern bNodeType cmp_node_chroma;
diff --git a/source/blender/nodes/CMakeLists.txt b/source/blender/nodes/CMakeLists.txt
index 0be26622536..7f003cb2b42 100644
--- a/source/blender/nodes/CMakeLists.txt
+++ b/source/blender/nodes/CMakeLists.txt
@@ -26,13 +26,14 @@
FILE(GLOB SRC intern/*.c intern/CMP_nodes/*.c intern/SHD_nodes/*.c)
SET(INC
- . ../../../intern/guardedalloc ../include ../blenlib ../makesdna
+ . ../../../intern/guardedalloc ../editors/include ../blenlib ../makesdna
../python ../render/extern/include ../../../intern/decimation/extern
../imbuf ../avi ../../../intern/elbeem/extern
../../../intern/iksolver/extern ../blenloader ../quicktime
- ../blenkernel ../editors/include
+ ../blenkernel ../../../extern/glew/include ../gpu
${SDL_INC}
${ZLIB_INC}
+ ${PYTHON_INC}
)
IF(WITH_VERSE)
diff --git a/source/blender/nodes/Makefile b/source/blender/nodes/Makefile
index 65a0e591848..57f57ebebfe 100644
--- a/source/blender/nodes/Makefile
+++ b/source/blender/nodes/Makefile
@@ -6,7 +6,7 @@
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
+# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
diff --git a/source/blender/nodes/SConscript b/source/blender/nodes/SConscript
index 746be45eb91..5f7f29dab83 100644
--- a/source/blender/nodes/SConscript
+++ b/source/blender/nodes/SConscript
@@ -7,40 +7,44 @@ sources += env.Glob('intern/SHD_nodes/*.c')
incs = '. ./intern '
incs += '#/intern/guardedalloc ../editors/include ../blenlib ../makesdna'
-incs += ' ../python ../render/extern/include '
+incs += ' ../render/extern/include '
incs += ' ../imbuf ../avi '
-incs += ' ../blenloader ../quicktime'
+incs += ' ../blenloader'
incs += ' ../blenkernel ../renderconverter '
-
-
+incs += ' ../gpu #/extern/glew/include '
incs += ' ' + env['BF_OPENGL_INC']
incs += ' ' + env['BF_ZLIB_INC']
-incs += ' ' + env['BF_SDL_INC']
defs = ''
+if env['WITH_BF_PYTHON']:
+ incs += ' ' + env['BF_PYTHON_INC']
+ incs += ' ../python'
+else:
+ defs += 'DISABLE_PYTHON'
+
if env['WITH_BF_INTERNATIONAL']:
- defs += 'WITH_FREETYPE2'
+ defs += ' WITH_FREETYPE2'
if env['WITH_BF_VERSE']:
- defs += ' WITH_VERSE'
- incs += ' ' + env['BF_VERSE_INCLUDE']
+ defs += ' WITH_VERSE'
+ incs += ' ' + env['BF_VERSE_INCLUDE']
if env['WITH_BF_VERSE']:
- defs += ' WITH_VERSE'
+ defs += ' WITH_VERSE'
-if env['WITH_BF_OPENEXR'] == 1:
- defs += ' WITH_OPENEXR'
+if env['WITH_BF_OPENEXR']:
+ defs += ' WITH_OPENEXR'
-if env['WITH_BF_FFMPEG'] == 1:
- defs += ' WITH_FFMPEG'
- incs += ' ' + env['BF_FFMPEG_INC']
+if env['WITH_BF_FFMPEG']:
+ defs += ' WITH_FFMPEG'
+ incs += ' ' + env['BF_FFMPEG_INC']
-if env['WITH_BF_QUICKTIME'] == 1:
- defs += ' WITH_QUICKTIME'
- incs += ' ' + env['BF_QUICKTIME_INC']
+if env['WITH_BF_QUICKTIME']:
+ defs += ' WITH_QUICKTIME'
+ incs += ' ' + env['BF_QUICKTIME_INC']
-defs += ' WITH_CCGSUBSURF'
+defs += ' WITH_CCGSUBSURF '
env.BlenderLib ( libname = 'bf_nodes', sources = sources, includes = Split(incs), defines = Split(defs), libtype=['core','player'], priority = [80, 15] )
diff --git a/source/blender/nodes/SHD_node.h b/source/blender/nodes/SHD_node.h
index 8064a543ca0..d75d7c9f568 100644
--- a/source/blender/nodes/SHD_node.h
+++ b/source/blender/nodes/SHD_node.h
@@ -56,13 +56,13 @@ extern bNodeType sh_node_curve_rgb;
extern bNodeType sh_node_math;
extern bNodeType sh_node_vect_math;
extern bNodeType sh_node_squeeze;
+extern bNodeType node_dynamic_typeinfo;
extern bNodeType sh_node_material_ext;
extern bNodeType sh_node_invert;
extern bNodeType sh_node_seprgb;
extern bNodeType sh_node_combrgb;
extern bNodeType sh_node_hue_sat;
-
#endif
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_alphaOver.c b/source/blender/nodes/intern/CMP_nodes/CMP_alphaOver.c
index f108098750c..4972ff4ae5a 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_alphaOver.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_alphaOver.c
@@ -47,16 +47,16 @@ static void do_alphaover_premul(bNode *node, float *out, float *src, float *over
if(over[3]<=0.0f) {
QUATCOPY(out, src);
}
- else if(*fac==1.0f && over[3]>=1.0f) {
+ else if(fac[0]==1.0f && over[3]>=1.0f) {
QUATCOPY(out, over);
}
else {
- float mul= 1.0f - *fac*over[3];
+ float mul= 1.0f - fac[0]*over[3];
- out[0]= (mul*src[0]) + *fac*over[0];
- out[1]= (mul*src[1]) + *fac*over[1];
- out[2]= (mul*src[2]) + *fac*over[2];
- out[3]= (mul*src[3]) + *fac*over[3];
+ out[0]= (mul*src[0]) + fac[0]*over[0];
+ out[1]= (mul*src[1]) + fac[0]*over[1];
+ out[2]= (mul*src[2]) + fac[0]*over[2];
+ out[3]= (mul*src[3]) + fac[0]*over[3];
}
}
@@ -67,7 +67,7 @@ static void do_alphaover_key(bNode *node, float *out, float *src, float *over, f
if(over[3]<=0.0f) {
QUATCOPY(out, src);
}
- else if(*fac==1.0f && over[3]>=1.0f) {
+ else if(fac[0]==1.0f && over[3]>=1.0f) {
QUATCOPY(out, over);
}
else {
@@ -81,6 +81,31 @@ static void do_alphaover_key(bNode *node, float *out, float *src, float *over, f
}
}
+/* result will be still premul, but the over part is premulled */
+static void do_alphaover_mixed(bNode *node, float *out, float *src, float *over, float *fac)
+{
+
+ if(over[3]<=0.0f) {
+ QUATCOPY(out, src);
+ }
+ else if(fac[0]==1.0f && over[3]>=1.0f) {
+ QUATCOPY(out, over);
+ }
+ else {
+ NodeTwoFloats *ntf= node->storage;
+ float addfac= 1.0f - ntf->x + over[3]*ntf->x;
+ float premul= fac[0]*addfac;
+ float mul= 1.0f - fac[0]*over[3];
+
+ out[0]= (mul*src[0]) + premul*over[0];
+ out[1]= (mul*src[1]) + premul*over[1];
+ out[2]= (mul*src[2]) + premul*over[2];
+ out[3]= (mul*src[3]) + fac[0]*over[3];
+ }
+}
+
+
+
static void node_composit_exec_alphaover(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
{
@@ -97,8 +122,11 @@ static void node_composit_exec_alphaover(void *data, bNode *node, bNodeStack **i
/* make output size of input image */
CompBuf *cbuf= in[1]->data?in[1]->data:in[2]->data;
CompBuf *stackbuf= alloc_compbuf(cbuf->x, cbuf->y, CB_RGBA, 1); /* allocs */
+ NodeTwoFloats *ntf= node->storage;
- if(node->custom1)
+ if(ntf->x != 0.0f)
+ composit3_pixel_processor(node, stackbuf, in[1]->data, in[1]->vec, in[2]->data, in[2]->vec, in[0]->data, in[0]->vec, do_alphaover_mixed, CB_RGBA, CB_RGBA, CB_VAL);
+ else if(node->custom1)
composit3_pixel_processor(node, stackbuf, in[1]->data, in[1]->vec, in[2]->data, in[2]->vec, in[0]->data, in[0]->vec, do_alphaover_key, CB_RGBA, CB_RGBA, CB_VAL);
else
composit3_pixel_processor(node, stackbuf, in[1]->data, in[1]->vec, in[2]->data, in[2]->vec, in[0]->data, in[0]->vec, do_alphaover_premul, CB_RGBA, CB_RGBA, CB_VAL);
@@ -107,6 +135,11 @@ static void node_composit_exec_alphaover(void *data, bNode *node, bNodeStack **i
}
}
+static void node_alphaover_init(bNode* node)
+{
+ node->storage= MEM_callocN(sizeof(NodeTwoFloats), "NodeTwoFloats");
+}
+
bNodeType cmp_node_alphaover= {
/* *next,*prev */ NULL, NULL,
/* type code */ CMP_NODE_ALPHAOVER,
@@ -115,12 +148,12 @@ bNodeType cmp_node_alphaover= {
/* class+opts */ NODE_CLASS_OP_COLOR, NODE_OPTIONS,
/* input sock */ cmp_node_alphaover_in,
/* output sock */ cmp_node_alphaover_out,
- /* storage */ "",
+ /* storage */ "NodeTwoFloats",
/* execfunc */ node_composit_exec_alphaover,
/* butfunc */ NULL,
- /* initfunc */ NULL,
- /* freestoragefunc */ NULL,
- /* copystoragefunc */ NULL,
+ /* initfunc */ node_alphaover_init,
+ /* freestoragefunc */ node_free_standard_storage,
+ /* copystoragefunc */ node_copy_standard_storage,
/* id */ NULL
};
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_bilateralblur.c b/source/blender/nodes/intern/CMP_nodes/CMP_bilateralblur.c
new file mode 100644
index 00000000000..b954e876ea1
--- /dev/null
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_bilateralblur.c
@@ -0,0 +1,272 @@
+/**
+ *
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2006 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Vilem Novak
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#include "../CMP_util.h"
+
+/* **************** BILATERALBLUR ******************** */
+static bNodeSocketType cmp_node_bilateralblur_in[]= {
+ { SOCK_RGBA, 1, "Image", 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 1, "Determinator", 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
+ { -1, 0, "" }
+};
+
+static bNodeSocketType cmp_node_bilateralblur_out[]= {
+ { SOCK_RGBA, 0, "Image", 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
+ { -1, 0, "" }
+};
+
+#define INIT_C3\
+ mean0 = 1; mean1[0] = src[0];mean1[1] = src[1];mean1[2] = src[2];mean1[3] = src[3];
+
+/* finds color distances */
+#define COLOR_DISTANCE_C3(c1, c2)\
+ ((c1[0] - c2[0])*(c1[0] - c2[0]) + \
+ (c1[1] - c2[1])*(c1[1] - c2[1]) + \
+ (c1[2] - c2[2])*(c1[2] - c2[2]) + \
+ (c1[3] - c2[3])*(c1[3] - c2[3]))
+
+/* this is the main kernel function for comparing color distances
+ and adding them weighted to the final color */
+#define KERNEL_ELEMENT_C3(k)\
+ temp_color = src + deltas[k];\
+ ref_color = ref + deltas[k];\
+ w = weight_tab[k] + COLOR_DISTANCE_C3(ref, ref_color )*i2sigma_color;\
+ w = 1./(w*w + 1); \
+ mean0 += w;\
+ mean1[0] += temp_color[0]*w; \
+ mean1[1] += temp_color[1]*w; \
+ mean1[2] += temp_color[2]*w; \
+ mean1[3] += temp_color[3]*w;
+
+/* write blurred values to image */
+#define UPDATE_OUTPUT_C3\
+ mean0 = 1./mean0;\
+ dest[x*pix + 0] = mean1[0]*mean0; \
+ dest[x*pix + 1] = mean1[1]*mean0; \
+ dest[x*pix + 2] = mean1[2]*mean0; \
+ dest[x*pix + 3] = mean1[3]*mean0;
+
+/* initializes deltas for fast access to neighbour pixels */
+#define INIT_3X3_DELTAS( deltas, step, nch ) \
+ ((deltas)[0] = (nch), (deltas)[1] = -(step) + (nch), \
+ (deltas)[2] = -(step), (deltas)[3] = -(step) - (nch), \
+ (deltas)[4] = -(nch), (deltas)[5] = (step) - (nch), \
+ (deltas)[6] = (step), (deltas)[7] = (step) + (nch));
+
+
+/* code of this node was heavily inspired by the smooth function of opencv library.
+The main change is an optional image input */
+static void node_composit_exec_bilateralblur(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
+{
+ NodeBilateralBlurData *nbbd= node->storage;
+ CompBuf *new, *source, *img= in[0]->data , *refimg= in[1]->data;
+ double mean0, w, i2sigma_color, i2sigma_space;
+ double mean1[4];
+ double weight_tab[8];
+ float *src, *dest, *ref, *temp_color, *ref_color;
+ float sigma_color, sigma_space;
+ int imgx, imgy, x, y, pix, i, step;
+ int deltas[8];
+ short found_determinator= 0;
+
+ if(img == NULL || out[0]->hasoutput == 0)
+ return;
+
+ if(img->type != CB_RGBA) {
+ img= typecheck_compbuf(in[0]->data, CB_RGBA);
+ }
+
+ imgx= img->x;
+ imgy= img->y;
+ pix= img->type;
+ step= pix * imgx;
+
+ if(refimg) {
+ if(refimg->x == imgx && refimg->y == imgy) {
+ if(ELEM3(refimg->type, CB_VAL, CB_VEC2, CB_VEC3)) {
+ refimg= typecheck_compbuf(in[1]->data, CB_RGBA);
+ found_determinator= 1;
+ }
+ }
+ }
+ else {
+ refimg= img;
+ }
+
+ /* allocs */
+ source= dupalloc_compbuf(img);
+ new= alloc_compbuf(imgx, imgy, pix, 1);
+
+ /* accept image offsets from other nodes */
+ new->xof= img->xof;
+ new->yof= img->yof;
+
+ /* bilateral code properties */
+ sigma_color= nbbd->sigma_color;
+ sigma_space= nbbd->sigma_space;
+
+ i2sigma_color= 1. / (sigma_color * sigma_color);
+ i2sigma_space= 1. / (sigma_space * sigma_space);
+
+ INIT_3X3_DELTAS(deltas, step, pix);
+
+ weight_tab[0] = weight_tab[2] = weight_tab[4] = weight_tab[6] = i2sigma_space;
+ weight_tab[1] = weight_tab[3] = weight_tab[5] = weight_tab[7] = i2sigma_space * 2;
+
+ /* iterations */
+ for(i= 0; i < nbbd->iter; i++) {
+ src= source->rect;
+ ref= refimg->rect;
+ dest= new->rect;
+ /*goes through image, there are more loops for 1st/last line and all other lines*/
+ /*kernel element accumulates surrounding colors, which are then written with the update_output function*/
+ for(x= 0; x < imgx; x++, src+= pix, ref+= pix) {
+ INIT_C3;
+
+ KERNEL_ELEMENT_C3(6);
+
+ if(x > 0) {
+ KERNEL_ELEMENT_C3(5);
+ KERNEL_ELEMENT_C3(4);
+ }
+
+ if(x < imgx - 1) {
+ KERNEL_ELEMENT_C3(7);
+ KERNEL_ELEMENT_C3(0);
+ }
+
+ UPDATE_OUTPUT_C3;
+ }
+
+ dest+= step;
+
+ for(y= 1; y < imgy - 1; y++, dest+= step, src+= pix, ref+= pix) {
+ x= 0;
+
+ INIT_C3;
+
+ KERNEL_ELEMENT_C3(0);
+ KERNEL_ELEMENT_C3(1);
+ KERNEL_ELEMENT_C3(2);
+ KERNEL_ELEMENT_C3(6);
+ KERNEL_ELEMENT_C3(7);
+
+ UPDATE_OUTPUT_C3;
+
+ src+= pix;
+ ref+= pix;
+
+ for(x= 1; x < imgx - 1; x++, src+= pix, ref+= pix) {
+ INIT_C3;
+
+ KERNEL_ELEMENT_C3(0);
+ KERNEL_ELEMENT_C3(1);
+ KERNEL_ELEMENT_C3(2);
+ KERNEL_ELEMENT_C3(3);
+ KERNEL_ELEMENT_C3(4);
+ KERNEL_ELEMENT_C3(5);
+ KERNEL_ELEMENT_C3(6);
+ KERNEL_ELEMENT_C3(7);
+
+ UPDATE_OUTPUT_C3;
+ }
+
+ INIT_C3;
+
+ KERNEL_ELEMENT_C3(2);
+ KERNEL_ELEMENT_C3(3);
+ KERNEL_ELEMENT_C3(4);
+ KERNEL_ELEMENT_C3(5);
+ KERNEL_ELEMENT_C3(6);
+
+ UPDATE_OUTPUT_C3;
+ }
+
+ for(x= 0; x < imgx; x++, src+= pix, ref+= pix) {
+ INIT_C3;
+
+ KERNEL_ELEMENT_C3(2);
+
+ if(x > 0) {
+ KERNEL_ELEMENT_C3(3);
+ KERNEL_ELEMENT_C3(4);
+ }
+ if(x < imgx - 1) {
+ KERNEL_ELEMENT_C3(1);
+ KERNEL_ELEMENT_C3(0);
+ }
+
+ UPDATE_OUTPUT_C3;
+ }
+
+ if(node->exec & NODE_BREAK) break;
+
+ SWAP(CompBuf, *source, *new);
+ }
+
+ if(node->exec & NODE_BREAK)
+ free_compbuf(source);
+
+ if(img != in[0]->data)
+ free_compbuf(img);
+
+ if(found_determinator == 1) {
+ if(refimg != in[1]->data)
+ free_compbuf(refimg);
+ }
+
+ out[0]->data= source;
+
+ free_compbuf(new);
+}
+
+static void node_composit_init_bilateralblur(bNode* node)
+{
+ NodeBilateralBlurData *nbbd= MEM_callocN(sizeof(NodeBilateralBlurData), "node bilateral blur data");
+ node->storage= nbbd;
+ nbbd->sigma_color= 0.3;
+ nbbd->sigma_space= 5.0;
+}
+
+bNodeType cmp_node_bilateralblur= {
+ /* *next,*prev */ NULL, NULL,
+ /* type code */ CMP_NODE_BILATERALBLUR,
+ /* name */ "Bilateral Blur",
+ /* width+range */ 150, 120, 200,
+ /* class+opts */ NODE_CLASS_OP_FILTER, NODE_OPTIONS,
+ /* input sock */ cmp_node_bilateralblur_in,
+ /* output sock */ cmp_node_bilateralblur_out,
+ /* storage */ "NodeBilateralBlurData",
+ /* execfunc */ node_composit_exec_bilateralblur,
+ /* butfunc */ NULL,
+ /* initfunc */ node_composit_init_bilateralblur,
+ /* freestoragefunc */ node_free_standard_storage,
+ /* copystoragefunc */ node_copy_standard_storage,
+ /* id */ NULL
+
+};
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_blur.c b/source/blender/nodes/intern/CMP_nodes/CMP_blur.c
index 8ef4af4d219..e7e799b6e76 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_blur.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_blur.c
@@ -22,7 +22,8 @@
*
* The Original Code is: all of this file.
*
- * Contributor(s): none yet.
+ * Contributor(s): Campbell Barton, Alfredo de Greef, David Millan Escriva,
+ * Juho Vepsäläinen
*
* ***** END GPL LICENSE BLOCK *****
*/
@@ -397,7 +398,7 @@ static void bokeh_single_image(bNode *node, CompBuf *new, CompBuf *img, float fa
int maxyr= y+rady>imgy-1?imgy-y-1:rady;
float *destd= new->rect + pix*( (y + minyr)*imgx + x + minxr);
- float *dgausd= gausstab + (minyr+rady)*2*radx + minxr+radx;
+ float *dgausd= gausstab + (minyr+rady)*(2*radx+1) + minxr+radx;
if(x<=0) src= srcd;
else if(x<imgx) src+= pix;
@@ -556,16 +557,20 @@ static void blur_with_reference(bNode *node, CompBuf *new, CompBuf *img, CompBuf
static void node_composit_exec_blur(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
{
CompBuf *new, *img= in[0]->data;
+ NodeBlurData *nbd= node->storage;
- if(img==NULL || out[0]->hasoutput==0)
- return;
+ if(img==NULL) return;
+
+ /* store image in size that is needed for absolute/relative conversions on ui level */
+ nbd->image_in_width= img->x;
+ nbd->image_in_height= img->y;
+
+ if(out[0]->hasoutput==0) return;
if (((NodeBlurData *)node->storage)->filtertype == R_FILTER_FAST_GAUSS) {
CompBuf *new, *img = in[0]->data;
/*from eeshlo's original patch, removed to fit in with the existing blur node */
/*const float sx = in[1]->vec[0], sy = in[2]->vec[0];*/
-
- NodeBlurData *nbd= node->storage;
const float sx = ((float)nbd->sizex)/2.0f, sy = ((float)nbd->sizey)/2.0f;
int c;
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_brightness.c b/source/blender/nodes/intern/CMP_nodes/CMP_brightness.c
index c87307434b5..f6363cc7ffa 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_brightness.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_brightness.c
@@ -35,8 +35,8 @@
static bNodeSocketType cmp_node_brightcontrast_in[]= {
{ SOCK_RGBA, 1, "Image", 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
- { SOCK_VALUE, 1, "bright", 0.0f, 0.0f, 0.0f, 0.0f, -100.0f, 100.0f},
- { SOCK_VALUE, 1, "contrast", 0.0f, 0.0f, 0.0f, 0.0f, -100.0f, 100.0f},
+ { SOCK_VALUE, 1, "Bright", 0.0f, 0.0f, 0.0f, 0.0f, -100.0f, 100.0f},
+ { SOCK_VALUE, 1, "Contrast", 0.0f, 0.0f, 0.0f, 0.0f, -100.0f, 100.0f},
{ -1, 0, "" }
};
static bNodeSocketType cmp_node_brightcontrast_out[]= {
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_curves.c b/source/blender/nodes/intern/CMP_nodes/CMP_curves.c
index 17d9821a5ef..01af0e1db1d 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_curves.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_curves.c
@@ -22,7 +22,7 @@
*
* The Original Code is: all of this file.
*
- * Contributor(s): none yet.
+ * Contributor(s): Björn C. Schaefer
*
* ***** END GPL LICENSE BLOCK *****
*/
@@ -123,6 +123,8 @@ bNodeType cmp_node_curve_vec= {
static bNodeSocketType cmp_node_curve_rgb_in[]= {
{ SOCK_VALUE, 1, "Fac", 1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f},
{ SOCK_RGBA, 1, "Image", 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f},
+ { SOCK_RGBA, 1, "Black Level", 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f},
+ { SOCK_RGBA, 1, "White Level", 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f},
{ -1, 0, "" }
};
@@ -157,7 +159,7 @@ static void do_curves_fac(bNode *node, float *out, float *in, float *fac)
static void node_composit_exec_curve_rgb(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
{
- /* stack order input: fac, image */
+ /* stack order input: fac, image, black level, white level */
/* stack order output: image */
if(out[0]->hasoutput==0)
@@ -172,6 +174,8 @@ static void node_composit_exec_curve_rgb(void *data, bNode *node, bNodeStack **i
CompBuf *cbuf= in[1]->data;
CompBuf *stackbuf= alloc_compbuf(cbuf->x, cbuf->y, CB_RGBA, 1); /* allocs */
+ curvemapping_set_black_white(node->storage, in[2]->vec, in[3]->vec);
+
if(in[0]->vec[0] == 1.0)
composit1_pixel_processor(node, stackbuf, in[1]->data, in[1]->vec, do_curves, CB_RGBA);
else
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_defocus.c b/source/blender/nodes/intern/CMP_nodes/CMP_defocus.c
index 53d01ab1d12..6f175671296 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_defocus.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_defocus.c
@@ -235,7 +235,7 @@ static void IIR_gauss_single(CompBuf* buf, float sigma)
#undef YVV
}
-static void defocus_blur(bNode *node, CompBuf *new, CompBuf *img, CompBuf *zbuf, float inpval)
+static void defocus_blur(bNode *node, CompBuf *new, CompBuf *img, CompBuf *zbuf, float inpval, int no_zbuf)
{
NodeDefocus *nqd = node->storage;
CompBuf *wts; // weights buffer
@@ -283,7 +283,7 @@ static void defocus_blur(bNode *node, CompBuf *new, CompBuf *img, CompBuf *zbuf,
// if 'no_zbuf' flag set (which is always set if input is not an image),
// values are instead interpreted directly as blur radius values
- if (nqd->no_zbuf) {
+ if (no_zbuf) {
// to prevent *reaaallly* big radius values and impossible calculation times,
// limit the maximum to half the image width or height, whichever is smaller
float maxr = 0.5f*(float)MIN2(img->x, img->y);
@@ -376,8 +376,10 @@ static void defocus_blur(bNode *node, CompBuf *new, CompBuf *img, CompBuf *zbuf,
// some sort of visual feedback would be nice, or at least this text in the renderwin header
// but for now just print some info in the console every 8 scanlines.
if (((y & 7)==0) || (y==(img->y-1))) {
- printf("\rdefocus: Processing Line %d of %d ... ", y+1, img->y);
- fflush(stdout);
+ if(G.background==0) {
+ printf("\rdefocus: Processing Line %d of %d ... ", y+1, img->y);
+ fflush(stdout);
+ }
}
// esc set by main calling process
if(node->exec & NODE_BREAK)
@@ -698,7 +700,7 @@ static void defocus_blur(bNode *node, CompBuf *new, CompBuf *img, CompBuf *zbuf,
// sampled, simple rejection sampling here, good enough
unsigned int maxsam, s, ui = BLI_rand()*BLI_rand();
float wcor, cpr = BLI_frand();
- if (nqd->no_zbuf)
+ if (no_zbuf)
maxsam = nqd->samples; // no zbuffer input, use sample value directly
else {
// depth adaptive sampling hack, the more out of focus, the more samples taken, 16 minimum.
@@ -772,14 +774,13 @@ static void node_composit_exec_defocus(void *data, bNode *node, bNodeStack **in,
{
CompBuf *new, *old, *zbuf_use = NULL, *img = in[0]->data, *zbuf = in[1]->data;
NodeDefocus *nqd = node->storage;
+ int no_zbuf = nqd->no_zbuf;
if ((img==NULL) || (out[0]->hasoutput==0)) return;
// if image not valid type or fstop==infinite (128), nothing to do, pass in to out
- if (((img->type!=CB_RGBA) && (img->type!=CB_VAL)) || ((nqd->no_zbuf==0) && (nqd->fstop==128.f))) {
- new = alloc_compbuf(img->x, img->y, img->type, 0);
- new->rect = img->rect;
- out[0]->data = new;
+ if (((img->type!=CB_RGBA) && (img->type!=CB_VAL)) || ((no_zbuf==0) && (nqd->fstop==128.f))) {
+ out[0]->data = pass_on_compbuf(img);
return;
}
@@ -793,21 +794,27 @@ static void node_composit_exec_defocus(void *data, bNode *node, bNodeStack **in,
}
zbuf_use = typecheck_compbuf(zbuf, CB_VAL);
}
- else nqd->no_zbuf = 1; // no zbuffer input
+ else no_zbuf = 1; // no zbuffer input
// ok, process
old = img;
if (nqd->gamco) {
- // gamma correct, blender func is simplified, fixed value & RGBA only, should make user param
+ // gamma correct, blender func is simplified, fixed value & RGBA only,
+ // should make user param. also depremul and premul afterwards, gamma
+ // correction can't work with premul alpha
old = dupalloc_compbuf(img);
+ premul_compbuf(old, 1);
gamma_correct_compbuf(old, 0);
+ premul_compbuf(old, 0);
}
new = alloc_compbuf(old->x, old->y, old->type, 1);
- defocus_blur(node, new, old, zbuf_use, in[1]->vec[0]*nqd->scale);
+ defocus_blur(node, new, old, zbuf_use, in[1]->vec[0]*nqd->scale, no_zbuf);
if (nqd->gamco) {
+ premul_compbuf(new, 1);
gamma_correct_compbuf(new, 1);
+ premul_compbuf(new, 0);
free_compbuf(old);
}
if(node->exec & NODE_BREAK) {
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_directionalblur.c b/source/blender/nodes/intern/CMP_nodes/CMP_directionalblur.c
new file mode 100644
index 00000000000..27f535186db
--- /dev/null
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_directionalblur.c
@@ -0,0 +1,143 @@
+/**
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2006 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Alfredo de Greef (eeshlo)
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "../CMP_util.h"
+
+static bNodeSocketType cmp_node_dblur_in[]= {
+ { SOCK_RGBA, 1, "Image", 0.8f, 0.8f, 0.8f, 1.f, 0.f, 1.f},
+ { -1, 0, "" }
+};
+
+static bNodeSocketType cmp_node_dblur_out[]= {
+ { SOCK_RGBA, 0, "Image", 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
+ { -1, 0, "" }
+};
+
+static CompBuf *dblur(bNode *node, CompBuf *img, int iterations, int wrap,
+ float center_x, float center_y, float dist, float angle, float spin, float zoom)
+{
+ if ((dist != 0.f) || (spin != 0.f) || (zoom != 0.f)) {
+ void (*getpix)(CompBuf*, float, float, float*) = wrap ? qd_getPixelLerpWrap : qd_getPixelLerp;
+ const float a= angle * (float)M_PI / 180.f;
+ const float itsc= 1.f / pow(2.f, (float)iterations);
+ float D;
+ float center_x_pix, center_y_pix;
+ float tx, ty;
+ float sc, rot;
+ CompBuf *tmp;
+ int i, j;
+
+ tmp= dupalloc_compbuf(img);
+
+ D= dist * sqrtf(img->x * img->x + img->y * img->y);
+ center_x_pix= center_x * img->x;
+ center_y_pix= center_y * img->y;
+
+ tx= itsc * D * cos(a);
+ ty= -itsc * D * sin(a);
+ sc= itsc * zoom;
+ rot= itsc * spin * (float)M_PI / 180.f;
+
+ /* blur the image */
+ for(i= 0; i < iterations; ++i) {
+ const float cs= cos(rot), ss= sin(rot);
+ const float isc= 1.f / (1.f + sc);
+ unsigned int x, y;
+ float col[4]= {0,0,0,0};
+
+ for(y= 0; y < img->y; ++y) {
+ const float v= isc * (y - center_y_pix) + ty;
+
+ for(x= 0; x < img->x; ++x) {
+ const float u= isc * (x - center_x_pix) + tx;
+ unsigned int p= (x + y * img->x) * img->type;
+
+ getpix(tmp, cs * u + ss * v + center_x_pix, cs * v - ss * u + center_y_pix, col);
+
+ /* mix img and transformed tmp */
+ for(j= 0; j < 4; ++j)
+ img->rect[p + j]= AVG2(img->rect[p + j], col[j]);
+ }
+ }
+
+ /* copy img to tmp */
+ if(i != (iterations - 1))
+ memcpy(tmp->rect, img->rect, sizeof(float) * img->x * img->y * img->type);
+
+ /* double transformations */
+ tx *= 2.f, ty *= 2.f;
+ sc *= 2.f, rot *= 2.f;
+
+ if(node->exec & NODE_BREAK) break;
+ }
+
+ free_compbuf(tmp);
+ }
+
+ return img;
+}
+
+static void node_composit_exec_dblur(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
+{
+ NodeDBlurData *ndbd= node->storage;
+ CompBuf *new, *img= in[0]->data;
+
+ if((img == NULL) || (out[0]->hasoutput == 0)) return;
+
+ if (img->type != CB_RGBA)
+ new = typecheck_compbuf(img, CB_RGBA);
+ else
+ new = dupalloc_compbuf(img);
+
+ out[0]->data= dblur(node, new, ndbd->iter, ndbd->wrap, ndbd->center_x, ndbd->center_y, ndbd->distance, ndbd->angle, ndbd->spin, ndbd->zoom);
+}
+
+static void node_composit_init_dblur(bNode* node)
+{
+ NodeDBlurData *ndbd= MEM_callocN(sizeof(NodeDBlurData), "node dblur data");
+ node->storage= ndbd;
+ ndbd->center_x= 0.5;
+ ndbd->center_y= 0.5;
+}
+
+bNodeType cmp_node_dblur = {
+ /* *next,*prev */ NULL, NULL,
+ /* type code */ CMP_NODE_DBLUR,
+ /* name */ "Directional Blur",
+ /* width+range */ 150, 120, 200,
+ /* class+opts */ NODE_CLASS_OP_FILTER, NODE_OPTIONS,
+ /* input sock */ cmp_node_dblur_in,
+ /* output sock */ cmp_node_dblur_out,
+ /* storage */ "NodeDBlurData",
+ /* execfunc */ node_composit_exec_dblur,
+ /* butfunc */ NULL,
+ /* initfunc */ node_composit_init_dblur,
+ /* freestoragefunc */ node_free_standard_storage,
+ /* copystoragefunc */ node_copy_standard_storage,
+ /* id */ NULL
+};
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_displace.c b/source/blender/nodes/intern/CMP_nodes/CMP_displace.c
index 0ec15d9eb77..f5b6edcea80 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_displace.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_displace.c
@@ -44,18 +44,22 @@ static bNodeSocketType cmp_node_displace_out[]= {
{ -1, 0, "" }
};
+static float *vecbuf_get_pixel(CompBuf *vecbuf, float *veccol, int x, int y)
+{
+ /* the x-xrad stuff is a bit weird, but i seem to need it otherwise
+ * my returned pixels are offset weirdly */
+ return compbuf_get_pixel(vecbuf, veccol, x-vecbuf->xrad, y-vecbuf->yrad, vecbuf->xrad, vecbuf->yrad);
+}
+
static void do_displace(CompBuf *stackbuf, CompBuf *cbuf, CompBuf *vecbuf, float *veccol, float *xscale, float *yscale)
{
ImBuf *ibuf;
- int x, y, sx, sy;
float dx=0.0, dy=0.0;
float dspx, dspy;
- float uv[2];
-
- float *out= stackbuf->rect, *vec=vecbuf->rect, *in= cbuf->rect;
+ float uv[2], col[4], colnext[4], colprev[4];
float *vp, *vpnext, *vpprev;
-
- int row = 3*vecbuf->x;
+ float *out= stackbuf->rect, *vec=vecbuf->rect, *in= cbuf->rect;
+ int x, y, vx, vy, sx, sy;
/* ibuf needed for sampling */
ibuf= IMB_allocImBuf(cbuf->x, cbuf->y, 32, 0, 0);
@@ -65,37 +69,50 @@ static void do_displace(CompBuf *stackbuf, CompBuf *cbuf, CompBuf *vecbuf, float
sx= stackbuf->x;
sy= stackbuf->y;
+
+ QUATCOPY(col, veccol);
+ QUATCOPY(colnext, veccol);
+ QUATCOPY(colprev, veccol);
for(y=0; y<sy; y++) {
for(x= 0; x< sx; x++, out+=4, in+=4, vec+=3) {
- /* the x-xrad stuff is a bit weird, but i seem to need it otherwise
- * my returned pixels are offset weirdly */
- vp = compbuf_get_pixel(vecbuf, veccol, x-vecbuf->xrad, y-vecbuf->yrad, vecbuf->xrad, vecbuf->yrad);
+ vp = vecbuf_get_pixel(vecbuf, col, x, y);
+
+ /* this happens in compbuf_get_pixel, need to make sure the following
+ * check takes them into account */
+ vx= x-vecbuf->xof;
+ vy= y-vecbuf->yof;
/* find the new displaced co-ords, also correcting for translate offset */
- dspx = x - (*xscale * vp[0]);
- dspy = y - (*yscale * vp[1]);
+ dspx = vx - (*xscale * vp[0]);
+ dspy = vy - (*yscale * vp[1]);
/* convert image space to 0.0-1.0 UV space for sampling, correcting for translate offset */
uv[0] = dspx / (float)sx;
uv[1] = dspy / (float)sy;
-
- if(x>0 && x< vecbuf->x-1 && y>0 && y< vecbuf->y-1) {
- vpnext = vp+row;
- vpprev = vp-row;
-
- /* adaptive sampling, X channel */
- dx= 0.5f*(fabs(vp[0]-vp[-3]) + fabs(vp[0]-vp[3]));
-
- dx+= 0.25f*(fabs(vp[0]-vpprev[-3]) + fabs(vp[0]-vpnext[-3]));
- dx+= 0.25f*(fabs(vp[0]-vpprev[+3]) + fabs(vp[0]-vpnext[+3]));
-
- /* adaptive sampling, Y channel */
- dy= 0.5f*(fabs(vp[1]-vp[-row+1]) + fabs(vp[1]-vp[row+1]));
-
- dy+= 0.25f*(fabs(vp[1]-vpprev[+1-3]) + fabs(vp[1]-vpnext[+1-3]));
- dy+= 0.25f*(fabs(vp[1]-vpprev[+1+3]) + fabs(vp[1]-vpnext[+1+3]));
+
+ if(vx>0 && vx< vecbuf->x-1 && vy>0 && vy< vecbuf->y-1) {
+ /* adaptive sampling, X and Y channel.
+ * we call vecbuf_get_pixel for every pixel since the input
+ * might be a procedural, and then we can't use offsets */
+ vpprev = vecbuf_get_pixel(vecbuf, colprev, x-1, y);
+ vpnext = vecbuf_get_pixel(vecbuf, colnext, x+1, y);
+ dx= 0.5f*(fabs(vp[0]-vpprev[0]) + fabs(vp[0]-vpnext[0]));
+
+ vpprev = vecbuf_get_pixel(vecbuf, colprev, x, y-1);
+ vpnext = vecbuf_get_pixel(vecbuf, colnext, x, y+1);
+ dy= 0.5f*(fabs(vp[1]-vpnext[1]) + fabs(vp[1]-vpprev[1]));
+
+ vpprev = vecbuf_get_pixel(vecbuf, colprev, x-1, y-1);
+ vpnext = vecbuf_get_pixel(vecbuf, colnext, x-1, y+1);
+ dx+= 0.25f*(fabs(vp[0]-vpprev[0]) + fabs(vp[0]-vpnext[0]));
+ dy+= 0.25f*(fabs(vp[1]-vpprev[1]) + fabs(vp[1]-vpnext[1]));
+
+ vpprev = vecbuf_get_pixel(vecbuf, colprev, x+1, y-1);
+ vpnext = vecbuf_get_pixel(vecbuf, colnext, x+1, y+1);
+ dx+= 0.25f*(fabs(vp[0]-vpprev[0]) + fabs(vp[0]-vpnext[0]));
+ dy+= 0.25f*(fabs(vp[1]-vpprev[1]) + fabs(vp[1]-vpnext[1]));
/* scaled down to prevent blurriness */
/* 8: magic number, provides a good level of sharpness without getting too aliased */
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_gamma.c b/source/blender/nodes/intern/CMP_nodes/CMP_gamma.c
index 5d0ab729e08..e77de3726cb 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_gamma.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_gamma.c
@@ -34,7 +34,7 @@
static bNodeSocketType cmp_node_gamma_in[]= {
{ SOCK_RGBA, 1, "Image", 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
- { SOCK_VALUE, 1, "Gamma", 1.0f, 0.0f, 0.0f, 0.0f, 0.001f, 2.0f},
+ { SOCK_VALUE, 1, "Gamma", 1.0f, 0.0f, 0.0f, 0.0f, 0.001f, 10.0f},
{ -1, 0, "" }
};
static bNodeSocketType cmp_node_gamma_out[]= {
@@ -46,7 +46,8 @@ static void do_gamma(bNode *node, float *out, float *in, float *fac)
{
int i=0;
for(i=0; i<3; i++) {
- out[i] = pow(in[i],fac[0]);
+ /* check for negative to avoid nan's */
+ out[i] = (in[i] > 0.0f)? pow(in[i],fac[0]): in[i];
}
out[3] = in[3];
}
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_glare.c b/source/blender/nodes/intern/CMP_nodes/CMP_glare.c
index e7b8fd00c93..9ab4038607f 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_glare.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_glare.c
@@ -424,15 +424,18 @@ static void fglow(NodeGlare* ndg, CompBuf* dst, CompBuf* src)
static void node_composit_exec_glare(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
{
- CompBuf *new, *img = in[0]->data;
+ CompBuf *new, *src, *img = in[0]->data;
NodeGlare* ndg = node->storage;
if ((img == NULL) || (out[0]->hasoutput == 0)) return;
- if (img->type != CB_RGBA)
+ if (img->type != CB_RGBA) {
new = typecheck_compbuf(img, CB_RGBA);
- else
+ src = typecheck_compbuf(img, CB_RGBA);
+ } else {
new = dupalloc_compbuf(img);
+ src = dupalloc_compbuf(img);
+ }
{
int x, y;
@@ -448,19 +451,20 @@ static void node_composit_exec_glare(void *data, bNode *node, bNodeStack **in, b
switch (ndg->type) {
case 0:
- star4(ndg, new, img);
+ star4(ndg, new, src);
break;
case 1:
- fglow(ndg, new, img);
+ fglow(ndg, new, src);
break;
case 3:
- ghosts(ndg, new, img);
+ ghosts(ndg, new, src);
break;
case 2:
default:
- streaks(ndg, new, img);
+ streaks(ndg, new, src);
}
+ free_compbuf(src);
out[0]->data = new;
}
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_hueSatVal.c b/source/blender/nodes/intern/CMP_nodes/CMP_hueSatVal.c
index eeddb4ce756..92614d1cc6a 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_hueSatVal.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_hueSatVal.c
@@ -52,9 +52,7 @@ static void do_hue_sat_fac(bNode *node, float *out, float *in, float *fac)
hsv[0]+= (nhs->hue - 0.5f);
if(hsv[0]>1.0) hsv[0]-=1.0; else if(hsv[0]<0.0) hsv[0]+= 1.0;
hsv[1]*= nhs->sat;
- if(hsv[1]>1.0) hsv[1]= 1.0; else if(hsv[1]<0.0) hsv[1]= 0.0;
hsv[2]*= nhs->val;
- if(hsv[2]>1.0) hsv[2]= 1.0; else if(hsv[2]<0.0) hsv[2]= 0.0;
hsv_to_rgb(hsv[0], hsv[1], hsv[2], col, col+1, col+2);
out[0]= mfac*in[0] + *fac*col[0];
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_idMask.c b/source/blender/nodes/intern/CMP_nodes/CMP_idMask.c
index abb9fa98d97..a40579ac3b2 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_idMask.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_idMask.c
@@ -63,8 +63,25 @@ static void do_idmask(CompBuf *stackbuf, CompBuf *cbuf, float idnr)
MEM_freeN(abuf);
}
+/* full sample version */
+static void do_idmask_fsa(CompBuf *stackbuf, CompBuf *cbuf, float idnr)
+{
+ float *rect, *rs;
+ int x;
+
+ rect= cbuf->rect;
+ rs= stackbuf->rect;
+ for(x= cbuf->x*cbuf->y - 1; x>=0; x--)
+ if(rect[x]==idnr)
+ rs[x]= 1.0f;
+
+}
+
+
static void node_composit_exec_idmask(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
{
+ RenderData *rd= data;
+
if(out[0]->hasoutput==0)
return;
@@ -77,7 +94,10 @@ static void node_composit_exec_idmask(void *data, bNode *node, bNodeStack **in,
stackbuf= alloc_compbuf(cbuf->x, cbuf->y, CB_VAL, 1); /* allocs */;
- do_idmask(stackbuf, cbuf, (float)node->custom1);
+ if(rd->scemode & R_FULL_SAMPLE)
+ do_idmask_fsa(stackbuf, cbuf, (float)node->custom1);
+ else
+ do_idmask(stackbuf, cbuf, (float)node->custom1);
out[0]->data= stackbuf;
}
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_image.c b/source/blender/nodes/intern/CMP_nodes/CMP_image.c
index 20308e968d3..be5a1d7241b 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_image.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_image.c
@@ -48,6 +48,7 @@ static bNodeSocketType cmp_node_rlayers_out[]= {
{ SOCK_RGBA, 0, "Refract", 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_RGBA, 0, "Radio", 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_VALUE, 0, "IndexOB", 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_VALUE, 0, "Mist", 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
@@ -78,6 +79,21 @@ static CompBuf *node_composit_get_image(RenderData *rd, Image *ima, ImageUser *i
stackbuf->rect= ibuf->rect_float;
}
+ /*code to respect the premul flag of images; I'm
+ not sure if this is a good idea for multilayer images,
+ since it never worked before for them.
+ if (type==CB_RGBA && ima->flag & IMA_DO_PREMUL) {
+ //premul the image
+ int i;
+ float *pixel = stackbuf->rect;
+
+ for (i=0; i<stackbuf->x*stackbuf->y; i++, pixel += 4) {
+ pixel[0] *= pixel[3];
+ pixel[1] *= pixel[3];
+ pixel[2] *= pixel[3];
+ }
+ }
+ */
return stackbuf;
};
@@ -149,6 +165,8 @@ void outputs_multilayer_get(RenderData *rd, RenderLayer *rl, bNodeStack **out, I
out[RRES_OUT_RADIO]->data= compbuf_multilayer_get(rd, rl, ima, iuser, SCE_PASS_RADIO);
if(out[RRES_OUT_INDEXOB]->hasoutput)
out[RRES_OUT_INDEXOB]->data= compbuf_multilayer_get(rd, rl, ima, iuser, SCE_PASS_INDEXOB);
+ if(out[RRES_OUT_MIST]->hasoutput)
+ out[RRES_OUT_MIST]->data= compbuf_multilayer_get(rd, rl, ima, iuser, SCE_PASS_MIST);
};
@@ -184,11 +202,32 @@ static void node_composit_exec_image(void *data, bNode *node, bNodeStack **in, b
else {
stackbuf= node_composit_get_image(rd, ima, iuser);
- /* put image on stack */
- out[0]->data= stackbuf;
+ if (stackbuf) {
+ /*respect image premul option*/
+ if (stackbuf->type==CB_RGBA && ima->flag & IMA_DO_PREMUL) {
+ int i;
+ float *pixel;
+
+ /*first duplicate stackbuf->rect, since it's just a pointer
+ to the source imbuf, and we don't want to change that.*/
+ stackbuf->rect = MEM_dupallocN(stackbuf->rect);
+
+ /*premul the image*/
+
+ pixel = stackbuf->rect;
+ for (i=0; i<stackbuf->x*stackbuf->y; i++, pixel += 4) {
+ pixel[0] *= pixel[3];
+ pixel[1] *= pixel[3];
+ pixel[2] *= pixel[3];
+ }
+ }
- if(out[2]->hasoutput)
- out[2]->data= node_composit_get_zimage(node, rd);
+ /* put image on stack */
+ out[0]->data= stackbuf;
+
+ if(out[2]->hasoutput)
+ out[2]->data= node_composit_get_zimage(node, rd);
+ }
}
/* alpha and preview for both types */
@@ -205,6 +244,7 @@ static void node_composit_init_image(bNode* node)
{
ImageUser *iuser= MEM_callocN(sizeof(ImageUser), "node image user");
node->storage= iuser;
+ iuser->frames= 1;
iuser->sfra= 1;
iuser->fie_ima= 2;
iuser->ok= 1;
@@ -236,7 +276,7 @@ static CompBuf *compbuf_from_pass(RenderData *rd, RenderLayer *rl, int rectx, in
CompBuf *buf;
int buftype= CB_VEC3;
- if(ELEM(passcode, SCE_PASS_Z, SCE_PASS_INDEXOB))
+ if(ELEM3(passcode, SCE_PASS_Z, SCE_PASS_INDEXOB, SCE_PASS_MIST))
buftype= CB_VAL;
else if(passcode==SCE_PASS_VECTOR)
buftype= CB_VEC4;
@@ -282,7 +322,9 @@ void node_composit_rlayers_out(RenderData *rd, RenderLayer *rl, bNodeStack **out
if(out[RRES_OUT_RADIO]->hasoutput)
out[RRES_OUT_RADIO]->data= compbuf_from_pass(rd, rl, rectx, recty, SCE_PASS_RADIO);
if(out[RRES_OUT_INDEXOB]->hasoutput)
- out[RRES_OUT_INDEXOB]->data= compbuf_from_pass(rd, rl, rectx, recty, SCE_PASS_INDEXOB);
+ out[RRES_OUT_INDEXOB]->data= compbuf_from_pass(rd, rl, rectx, recty, SCE_PASS_INDEXOB);
+ if(out[RRES_OUT_MIST]->hasoutput)
+ out[RRES_OUT_MIST]->data= compbuf_from_pass(rd, rl, rectx, recty, SCE_PASS_MIST);
};
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_math.c b/source/blender/nodes/intern/CMP_nodes/CMP_math.c
index cf2af9bbc11..421c1343df7 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_math.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_math.c
@@ -57,7 +57,7 @@ static void do_math(bNode *node, float *out, float *in, float *in2)
break;
case 3: /* Divide */
{
- if(in[1]==0) /* We don't want to divide by zero. */
+ if(in2[0]==0) /* We don't want to divide by zero. */
out[0]= 0.0;
else
out[0]= in[0] / in2[0];
@@ -131,7 +131,23 @@ static void do_math(bNode *node, float *out, float *in, float *in2)
{
out[0]= (int)(in[0] + 0.5f);
}
- break;
+ break;
+ case 15: /* Less Than */
+ {
+ if( in[0] < in2[0] )
+ out[0]= 1.0f;
+ else
+ out[0]= 0.0f;
+ }
+ break;
+ case 16: /* Greater Than */
+ {
+ if( in[0] > in2[0] )
+ out[0]= 1.0f;
+ else
+ out[0]= 0.0f;
+ }
+ break;
}
}
@@ -142,7 +158,6 @@ static void node_composit_exec_math(void *data, bNode *node, bNodeStack **in, bN
CompBuf *stackbuf;
/* check for inputs and outputs for early out*/
- if(in[0]->hasinput==0 && in[1]->hasinput==0) return;
if(out[0]->hasoutput==0) return;
/* no image-color operation */
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_premulkey.c b/source/blender/nodes/intern/CMP_nodes/CMP_premulkey.c
new file mode 100644
index 00000000000..4fde652c59d
--- /dev/null
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_premulkey.c
@@ -0,0 +1,77 @@
+/**
+* $Id$
+*
+* ***** BEGIN GPL LICENSE BLOCK *****
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 2
+* of the License, or (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software Foundation,
+* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*
+* The Original Code is Copyright (C) 2006 Blender Foundation.
+* All rights reserved.
+*
+* The Original Code is: all of this file.
+*
+* Contributor(s): none yet.
+*
+* ***** END GPL LICENSE BLOCK *****
+
+*/
+
+#include "../CMP_util.h"
+
+/* **************** Premul and Key Alpha Convert ******************** */
+
+static bNodeSocketType cmp_node_premulkey_in[]= {
+ { SOCK_RGBA, 1, "Image", 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
+ { -1, 0, "" }
+};
+static bNodeSocketType cmp_node_premulkey_out[]= {
+ { SOCK_RGBA, 0, "Image", 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
+ { -1, 0, "" }
+};
+
+static void node_composit_exec_premulkey(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
+{
+ if(out[0]->hasoutput==0)
+ return;
+
+ if(in[0]->data) {
+ CompBuf *stackbuf, *cbuf= typecheck_compbuf(in[0]->data, CB_RGBA);
+
+ stackbuf= dupalloc_compbuf(cbuf);
+ premul_compbuf(stackbuf, node->custom1 == 1);
+
+ out[0]->data = stackbuf;
+ if(cbuf != in[0]->data)
+ free_compbuf(cbuf);
+ }
+}
+
+bNodeType cmp_node_premulkey= {
+ /* *next,*prev */ NULL, NULL,
+ /* type code */ CMP_NODE_PREMULKEY,
+ /* name */ "Alpha Convert",
+ /* width+range */ 140, 100, 320,
+ /* class+opts */ NODE_CLASS_CONVERTOR, NODE_OPTIONS,
+ /* input sock */ cmp_node_premulkey_in,
+ /* output sock */ cmp_node_premulkey_out,
+ /* storage */ "",
+ /* execfunc */ node_composit_exec_premulkey,
+ /* butfunc */ NULL,
+ /* initfunc */ NULL,
+ /* freestoragefunc */ NULL,
+ /* copysotragefunc */ NULL,
+ /* id */ NULL
+};
+
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_texture.c b/source/blender/nodes/intern/CMP_nodes/CMP_texture.c
index 31afe74bd11..c1f1948dba1 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_texture.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_texture.c
@@ -42,19 +42,18 @@ static bNodeSocketType cmp_node_texture_out[]= {
};
/* called without rect allocated */
-static void texture_procedural(CompBuf *cbuf, float *col, float xco, float yco)
+static void texture_procedural(CompBuf *cbuf, float *out, float xco, float yco)
{
bNode *node= cbuf->node;
- bNodeSocket *sock= node->inputs.first;
TexResult texres= {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0, NULL};
- float vec[3], *size, nor[3]={0.0f, 0.0f, 0.0f};
- int retval, type= cbuf->type;
+ float vec[3], *size, nor[3]={0.0f, 0.0f, 0.0f}, col[4];
+ int retval, type= cbuf->procedural_type;
- size= sock->next->ns.vec;
+ size= cbuf->procedural_size;
- vec[0]= size[0]*(xco + sock->ns.vec[0]);
- vec[1]= size[1]*(yco + sock->ns.vec[1]);
- vec[2]= size[2]*sock->ns.vec[2];
+ vec[0]= size[0]*(xco + cbuf->procedural_offset[0]);
+ vec[1]= size[1]*(yco + cbuf->procedural_offset[1]);
+ vec[2]= size[2]*cbuf->procedural_offset[2];
retval= multitex_ext((Tex *)node->id, vec, NULL, NULL, 0, &texres);
@@ -80,6 +79,8 @@ static void texture_procedural(CompBuf *cbuf, float *col, float xco, float yco)
else {
VECCOPY(col, nor);
}
+
+ typecheck_compbuf_color(out, col, cbuf->type, cbuf->procedural_type);
}
/* texture node outputs get a small rect, to make sure all other nodes accept it */
@@ -106,6 +107,9 @@ static void node_composit_exec_texture(void *data, bNode *node, bNodeStack **in,
prevbuf->rect_procedural= texture_procedural;
prevbuf->node= node;
+ VECCOPY(prevbuf->procedural_offset, in[0]->vec);
+ VECCOPY(prevbuf->procedural_size, in[1]->vec);
+ prevbuf->procedural_type= CB_RGBA;
composit1_pixel_processor(node, prevbuf, prevbuf, out[0]->vec, do_copy_rgba, CB_RGBA);
generate_preview(node, prevbuf);
free_compbuf(prevbuf);
@@ -115,6 +119,9 @@ static void node_composit_exec_texture(void *data, bNode *node, bNodeStack **in,
stackbuf->rect_procedural= texture_procedural;
stackbuf->node= node;
+ VECCOPY(stackbuf->procedural_offset, in[0]->vec);
+ VECCOPY(stackbuf->procedural_size, in[1]->vec);
+ stackbuf->procedural_type= CB_VAL;
out[0]->data= stackbuf;
}
@@ -123,6 +130,9 @@ static void node_composit_exec_texture(void *data, bNode *node, bNodeStack **in,
stackbuf->rect_procedural= texture_procedural;
stackbuf->node= node;
+ VECCOPY(stackbuf->procedural_offset, in[0]->vec);
+ VECCOPY(stackbuf->procedural_size, in[1]->vec);
+ stackbuf->procedural_type= CB_RGBA;
out[1]->data= stackbuf;
}
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_tonemap.c b/source/blender/nodes/intern/CMP_nodes/CMP_tonemap.c
index 662d8e8dde9..950ad97a397 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_tonemap.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_tonemap.c
@@ -63,7 +63,7 @@ static float avgLogLum(CompBuf *src, float* auto_key, float* Lav, float* Cav)
}
-void static tonemap(NodeTonemap* ntm, CompBuf* dst, CompBuf* src)
+static void tonemap(NodeTonemap* ntm, CompBuf* dst, CompBuf* src)
{
int x, y;
float dr, dg, db, al, igm = (ntm->gamma==0.f) ? 1 : (1.f / ntm->gamma);
@@ -130,13 +130,16 @@ static void node_composit_exec_tonemap(void *data, bNode *node, bNodeStack **in,
if ((img==NULL) || (out[0]->hasoutput==0)) return;
if (img->type != CB_RGBA)
- new = typecheck_compbuf(img, CB_RGBA);
- else
- new = dupalloc_compbuf(img);
+ img = typecheck_compbuf(img, CB_RGBA);
+
+ new = dupalloc_compbuf(img);
tonemap(node->storage, new, img);
out[0]->data = new;
+
+ if(img!=in[0]->data)
+ free_compbuf(img);
}
static void node_composit_init_tonemap(bNode* node)
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_zcombine.c b/source/blender/nodes/intern/CMP_nodes/CMP_zcombine.c
index 29cf8f34d54..daf61609692 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_zcombine.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_zcombine.c
@@ -45,6 +45,19 @@ static bNodeSocketType cmp_node_zcombine_out[]= {
{ -1, 0, "" }
};
+static void do_zcombine(bNode *node, float *out, float *src1, float *z1, float *src2, float *z2)
+{
+ if(*z1 <= *z2) {
+ QUATCOPY(out, src1);
+ }
+ else {
+ QUATCOPY(out, src2);
+
+ if(node->custom1)
+ *z1= *z2;
+ }
+}
+
static void do_zcombine_mask(bNode *node, float *out, float *z1, float *z2)
{
if(*z1 > *z2) {
@@ -67,43 +80,58 @@ static void do_zcombine_add(bNode *node, float *out, float *col1, float *col2, f
static void node_composit_exec_zcombine(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
{
+ RenderData *rd= data;
+ CompBuf *cbuf= in[0]->data;
+ CompBuf *zbuf;
+
/* stack order in: col z col z */
/* stack order out: col z */
- if(out[0]->hasoutput==0)
+ if(out[0]->hasoutput==0 && out[1]->hasoutput==0)
return;
/* no input image; do nothing now */
if(in[0]->data==NULL) {
return;
}
+
+ if(out[1]->hasoutput) {
+ /* copy or make a buffer for for the first z value, here we write result in */
+ if(in[1]->data)
+ zbuf= dupalloc_compbuf(in[1]->data);
+ else {
+ float *zval;
+ int tot= cbuf->x*cbuf->y;
+
+ zbuf= alloc_compbuf(cbuf->x, cbuf->y, CB_VAL, 1);
+ for(zval= zbuf->rect; tot; tot--, zval++)
+ *zval= in[1]->vec[0];
+ }
+ /* lazy coder hack */
+ node->custom1= 1;
+ out[1]->data= zbuf;
+ }
+ else {
+ node->custom1= 0;
+ zbuf= in[1]->data;
+ }
+
+ if(rd->scemode & R_FULL_SAMPLE) {
+ /* make output size of first input image */
+ CompBuf *stackbuf= alloc_compbuf(cbuf->x, cbuf->y, CB_RGBA, 1); // allocs
+
+ composit4_pixel_processor(node, stackbuf, in[0]->data, in[0]->vec, zbuf, in[1]->vec, in[2]->data, in[2]->vec,
+ in[3]->data, in[3]->vec, do_zcombine, CB_RGBA, CB_VAL, CB_RGBA, CB_VAL);
+
+ out[0]->data= stackbuf;
+ }
else {
/* make output size of first input image */
- CompBuf *cbuf= in[0]->data;
CompBuf *stackbuf= alloc_compbuf(cbuf->x, cbuf->y, CB_RGBA, 1); /* allocs */
- CompBuf *zbuf, *mbuf;
+ CompBuf *mbuf;
float *fp;
int x;
char *aabuf;
- if(out[1]->hasoutput) {
- /* copy or make a buffer for for the first z value, here we write result in */
- if(in[1]->data)
- zbuf= dupalloc_compbuf(in[1]->data);
- else {
- float *zval;
- int tot= cbuf->x*cbuf->y;
-
- zbuf= alloc_compbuf(cbuf->x, cbuf->y, CB_VAL, 1);
- for(zval= zbuf->rect; tot; tot--, zval++)
- *zval= in[1]->vec[0];
- }
- /* lazy coder hack */
- node->custom1= 1;
- }
- else {
- node->custom1= 0;
- zbuf= in[1]->data;
- }
/* make a mask based on comparison, optionally write zvalue */
mbuf= alloc_compbuf(cbuf->x, cbuf->y, CB_VAL, 1);
@@ -131,9 +159,8 @@ static void node_composit_exec_zcombine(void *data, bNode *node, bNodeStack **in
MEM_freeN(aabuf);
out[0]->data= stackbuf;
- if(node->custom1)
- out[1]->data= zbuf;
}
+
}
bNodeType cmp_node_zcombine= {
diff --git a/source/blender/nodes/intern/CMP_nodes/Makefile b/source/blender/nodes/intern/CMP_nodes/Makefile
index bf79d14c020..b70b591a588 100644
--- a/source/blender/nodes/intern/CMP_nodes/Makefile
+++ b/source/blender/nodes/intern/CMP_nodes/Makefile
@@ -42,3 +42,5 @@ CPPFLAGS += -I../../../blenlib
CPPFLAGS += -I../../../editors/include
CPPFLAGS += -I../../../imbuf
CPPFLAGS += -I../../../render/extern/include
+CPPFLAGS += -I$(NAN_GLEW)/include
+CPPFLAGS += -I$(OPENGL_HEADERS)
diff --git a/source/blender/nodes/intern/CMP_util.c b/source/blender/nodes/intern/CMP_util.c
index eee33e33ff5..f9805645115 100644
--- a/source/blender/nodes/intern/CMP_util.c
+++ b/source/blender/nodes/intern/CMP_util.c
@@ -122,6 +122,48 @@ void print_compbuf(char *str, CompBuf *cbuf)
}
+/* used for disabling node (similar code in drawnode.c for disable line) */
+void node_compo_pass_on(bNode *node, bNodeStack **nsin, bNodeStack **nsout)
+{
+ CompBuf *valbuf= NULL, *colbuf= NULL, *vecbuf= NULL;
+ bNodeSocket *sock;
+ int a;
+
+ /* connect the first value buffer in with first value out */
+ /* connect the first RGBA buffer in with first RGBA out */
+
+ /* test the inputs */
+ for(a=0, sock= node->inputs.first; sock; sock= sock->next, a++) {
+ if(nsin[a]->data) {
+ CompBuf *cbuf= nsin[a]->data;
+ if(cbuf->type==1 && valbuf==NULL) valbuf= cbuf;
+ if(cbuf->type==3 && vecbuf==NULL) vecbuf= cbuf;
+ if(cbuf->type==4 && colbuf==NULL) colbuf= cbuf;
+ }
+ }
+
+ /* outputs */
+ if(valbuf || colbuf || vecbuf) {
+ for(a=0, sock= node->outputs.first; sock; sock= sock->next, a++) {
+ if(nsout[a]->hasoutput) {
+ if(sock->type==SOCK_VALUE && valbuf) {
+ nsout[a]->data= pass_on_compbuf(valbuf);
+ valbuf= NULL;
+ }
+ if(sock->type==SOCK_VECTOR && vecbuf) {
+ nsout[a]->data= pass_on_compbuf(vecbuf);
+ vecbuf= NULL;
+ }
+ if(sock->type==SOCK_RGBA && colbuf) {
+ nsout[a]->data= pass_on_compbuf(colbuf);
+ colbuf= NULL;
+ }
+ }
+ }
+ }
+}
+
+
CompBuf *get_cropped_compbuf(rcti *drect, float *rectf, int rectx, int recty, int type)
{
CompBuf *cbuf;
@@ -183,17 +225,100 @@ CompBuf *scalefast_compbuf(CompBuf *inbuf, int newx, int newy)
return outbuf;
}
+void typecheck_compbuf_color(float *out, float *in, int outtype, int intype)
+{
+ if(intype == outtype) {
+ memcpy(out, in, sizeof(float)*outtype);
+ }
+ else if(outtype==CB_VAL) {
+ if(intype==CB_VEC2) {
+ *out= 0.5f*(in[0]+in[1]);
+ }
+ else if(intype==CB_VEC3) {
+ *out= 0.333333f*(in[0]+in[1]+in[2]);
+ }
+ else if(intype==CB_RGBA) {
+ *out= in[0]*0.35f + in[1]*0.45f + in[2]*0.2f;
+ }
+ }
+ else if(outtype==CB_VEC2) {
+ if(intype==CB_VAL) {
+ out[0]= in[0];
+ out[1]= in[0];
+ }
+ else if(intype==CB_VEC3) {
+ out[0]= in[0];
+ out[1]= in[1];
+ }
+ else if(intype==CB_RGBA) {
+ out[0]= in[0];
+ out[1]= in[1];
+ }
+ }
+ else if(outtype==CB_VEC3) {
+ if(intype==CB_VAL) {
+ out[0]= in[0];
+ out[1]= in[0];
+ out[2]= in[0];
+ }
+ else if(intype==CB_VEC2) {
+ out[0]= in[0];
+ out[1]= in[1];
+ out[2]= 0.0f;
+ }
+ else if(intype==CB_RGBA) {
+ out[0]= in[0];
+ out[1]= in[1];
+ out[2]= in[2];
+ }
+ }
+ else if(outtype==CB_RGBA) {
+ if(intype==CB_VAL) {
+ out[0]= in[0];
+ out[1]= in[0];
+ out[2]= in[0];
+ out[3]= 1.0f;
+ }
+ else if(intype==CB_VEC2) {
+ out[0]= in[0];
+ out[1]= in[1];
+ out[2]= 0.0f;
+ out[3]= 1.0f;
+ }
+ else if(intype==CB_VEC3) {
+ out[0]= in[0];
+ out[1]= in[1];
+ out[2]= in[2];
+ out[3]= 1.0f;
+ }
+ }
+}
+
CompBuf *typecheck_compbuf(CompBuf *inbuf, int type)
{
- if(inbuf && inbuf->type!=type && inbuf->rect_procedural==NULL) {
- CompBuf *outbuf= alloc_compbuf(inbuf->x, inbuf->y, type, 1);
- float *inrf= inbuf->rect;
- float *outrf= outbuf->rect;
- int x= inbuf->x*inbuf->y;
-
+ if(inbuf && inbuf->type!=type) {
+ CompBuf *outbuf;
+ float *inrf, *outrf;
+ int x;
+
+ outbuf= alloc_compbuf(inbuf->x, inbuf->y, type, 1);
+
/* warning note: xof and yof are applied in pixelprocessor, but should be copied otherwise? */
outbuf->xof= inbuf->xof;
outbuf->yof= inbuf->yof;
+
+ if(inbuf->rect_procedural) {
+ outbuf->rect_procedural= inbuf->rect_procedural;
+ VECCOPY(outbuf->procedural_size, inbuf->procedural_size);
+ VECCOPY(outbuf->procedural_offset, inbuf->procedural_offset);
+ outbuf->procedural_type= inbuf->procedural_type;
+ outbuf->node= inbuf->node;
+ return outbuf;
+ }
+
+ inrf= inbuf->rect;
+ outrf= outbuf->rect;
+ x= inbuf->x*inbuf->y;
if(type==CB_VAL) {
if(inbuf->type==CB_VEC2) {
@@ -460,6 +585,25 @@ CompBuf *valbuf_from_rgbabuf(CompBuf *cbuf, int channel)
return valbuf;
}
+static CompBuf *generate_procedural_preview(CompBuf *cbuf, int newx, int newy)
+{
+ CompBuf *outbuf;
+ float *outfp;
+ int xrad, yrad, x, y;
+
+ outbuf= alloc_compbuf(newx, newy, CB_RGBA, 1);
+
+ outfp= outbuf->rect;
+ xrad= outbuf->xrad;
+ yrad= outbuf->yrad;
+
+ for(y= -yrad; y<-yrad+outbuf->y; y++)
+ for(x= -xrad; x<-xrad+outbuf->x; x++, outfp+=outbuf->type)
+ cbuf->rect_procedural(cbuf, outfp, (float)x/(float)xrad, (float)y/(float)yrad);
+
+ return outbuf;
+}
+
void generate_preview(bNode *node, CompBuf *stackbuf)
{
bNodePreview *preview= node->preview;
@@ -467,7 +611,7 @@ void generate_preview(bNode *node, CompBuf *stackbuf)
if(preview && stackbuf) {
CompBuf *cbuf, *stackbuf_use;
- if(stackbuf->rect==NULL) return;
+ if(stackbuf->rect==NULL && stackbuf->rect_procedural==NULL) return;
stackbuf_use= typecheck_compbuf(stackbuf, CB_RGBA);
@@ -480,7 +624,10 @@ void generate_preview(bNode *node, CompBuf *stackbuf)
preview->xsize= (140*stackbuf->x)/stackbuf->y;
}
- cbuf= scalefast_compbuf(stackbuf_use, preview->xsize, preview->ysize);
+ if(stackbuf_use->rect_procedural)
+ cbuf= generate_procedural_preview(stackbuf_use, preview->xsize, preview->ysize);
+ else
+ cbuf= scalefast_compbuf(stackbuf_use, preview->xsize, preview->ysize);
/* this ensures free-compbuf does the right stuff */
SWAP(float *, cbuf->rect, node->preview->rect);
@@ -575,6 +722,36 @@ void gamma_correct_compbuf(CompBuf *img, int inversed)
}
}
+void premul_compbuf(CompBuf *img, int inversed)
+{
+ float *drect;
+ int x;
+
+ if(img->type!=CB_RGBA) return;
+
+ drect= img->rect;
+ if(inversed) {
+ for(x=img->x*img->y; x>0; x--, drect+=4) {
+ if(fabs(drect[3]) < 1e-5f) {
+ drect[0]= 0.0f;
+ drect[1]= 0.0f;
+ drect[2]= 0.0f;
+ }
+ else {
+ drect[0] /= drect[3];
+ drect[1] /= drect[3];
+ drect[2] /= drect[3];
+ }
+ }
+ }
+ else {
+ for(x=img->x*img->y; x>0; x--, drect+=4) {
+ drect[0] *= drect[3];
+ drect[1] *= drect[3];
+ drect[2] *= drect[3];
+ }
+ }
+}
diff --git a/source/blender/nodes/intern/CMP_util.h b/source/blender/nodes/intern/CMP_util.h
index 44f76b0822e..8443c022d17 100644
--- a/source/blender/nodes/intern/CMP_util.h
+++ b/source/blender/nodes/intern/CMP_util.h
@@ -92,6 +92,8 @@ typedef struct CompBuf {
int xof, yof; /* relative to center of target image */
void (*rect_procedural)(struct CompBuf *, float *, float, float);
+ float procedural_size[3], procedural_offset[3];
+ int procedural_type;
bNode *node; /* only in use for procedural bufs */
struct CompBuf *next, *prev; /* for pass-on, works nicer than reference counting */
@@ -117,10 +119,12 @@ CompBuf *dupalloc_compbuf(CompBuf *cbuf);
CompBuf *pass_on_compbuf(CompBuf *cbuf);
void free_compbuf(CompBuf *cbuf);
void print_compbuf(char *str, CompBuf *cbuf);
+void node_compo_pass_on(struct bNode *node, struct bNodeStack **nsin, struct bNodeStack **nsout);
CompBuf *get_cropped_compbuf(rcti *drect, float *rectf, int rectx, int recty, int type);
CompBuf *scalefast_compbuf(CompBuf *inbuf, int newx, int newy);
CompBuf *typecheck_compbuf(CompBuf *inbuf, int type);
+void typecheck_compbuf_color(float *out, float *in, int outtype, int intype);
float *compbuf_get_pixel(CompBuf *cbuf, float *rectf, int x, int y, int xrad, int yrad);
/* **************************************************** */
@@ -161,6 +165,7 @@ void do_hsva_to_rgba(bNode *node, float *out, float *in);
void do_ycca_to_rgba(bNode *node, float *out, float *in);
void gamma_correct_compbuf(CompBuf *img, int inversed);
+void premul_compbuf(CompBuf *img, int inversed);
void convolve(CompBuf* dst, CompBuf* in1, CompBuf* in2);
extern void node_ID_title_cb(void *node_v, void *unused_v);
diff --git a/source/blender/nodes/intern/Makefile b/source/blender/nodes/intern/Makefile
index 59c57e42bc1..7c9a67b6cc5 100644
--- a/source/blender/nodes/intern/Makefile
+++ b/source/blender/nodes/intern/Makefile
@@ -42,6 +42,8 @@ CPPFLAGS += -I../../blenlib
CPPFLAGS += -I../../editors/include
CPPFLAGS += -I../../imbuf
CPPFLAGS += -I../../render/extern/include
+CPPFLAGS += -I../../gpu
+CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(OPENGL_HEADERS)
DIRS = SHD_nodes CMP_nodes
diff --git a/source/blender/nodes/intern/SHD_nodes/Makefile b/source/blender/nodes/intern/SHD_nodes/Makefile
index ca83c25d277..1369d346fc6 100644
--- a/source/blender/nodes/intern/SHD_nodes/Makefile
+++ b/source/blender/nodes/intern/SHD_nodes/Makefile
@@ -35,6 +35,8 @@ include nan_compile.mk
CFLAGS += $(LEVEL_1_C_WARNINGS)
+CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION)
+CPPFLAGS += -I../../../python
CPPFLAGS += -I../../../blenkernel
CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include
CPPFLAGS += -I../../../makesdna
@@ -42,3 +44,6 @@ CPPFLAGS += -I../../../blenlib
CPPFLAGS += -I../../../editors/include
CPPFLAGS += -I../../../imbuf
CPPFLAGS += -I../../../render/extern/include
+CPPFLAGS += -I../../../gpu
+CPPFLAGS += -I$(NAN_GLEW)/include
+CPPFLAGS += -I$(OPENGL_HEADERS)
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_camera.c b/source/blender/nodes/intern/SHD_nodes/SHD_camera.c
index 63260ff91ed..20136d75540 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_camera.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_camera.c
@@ -46,8 +46,13 @@ static void node_shader_exec_camera(void *data, bNode *node, bNodeStack **in, bN
VECCOPY(out[0]->vec, shi->co); /* get view vector */
out[1]->vec[0]= fabs(shi->co[2]); /* get view z-depth */
out[2]->vec[0]= Normalize(out[0]->vec); /* get view distance */
- }
}
+}
+
+static int gpu_shader_camera(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ return GPU_stack_link(mat, "camera", in, out, GPU_builtin(GPU_VIEW_POSITION));
+}
bNodeType sh_node_camera= {
/* *next,*prev */ NULL, NULL,
@@ -63,6 +68,7 @@ bNodeType sh_node_camera= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_camera
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_curves.c b/source/blender/nodes/intern/SHD_nodes/SHD_curves.c
index b6f1f8d52cd..d277547b636 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_curves.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_curves.c
@@ -56,6 +56,15 @@ static void node_shader_init_curve_vec(bNode* node)
node->storage= curvemapping_add(3, -1.0f, -1.0f, 1.0f, 1.0f);
}
+static int gpu_shader_curve_vec(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ float *array;
+ int size;
+
+ curvemapping_table_RGBA(node->storage, &array, &size);
+ return GPU_stack_link(mat, "curves_vec", in, out, GPU_texture(size, array));
+}
+
bNodeType sh_node_curve_vec= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_CURVE_VEC,
@@ -70,7 +79,8 @@ bNodeType sh_node_curve_vec= {
/* initfunc */ node_shader_init_curve_vec,
/* freestoragefunc */ node_free_curves,
/* copystoragefunc */ node_copy_curves,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_curve_vec
};
@@ -100,6 +110,15 @@ static void node_shader_init_curve_rgb(bNode *node)
node->storage= curvemapping_add(4, 0.0f, 0.0f, 1.0f, 1.0f);
}
+static int gpu_shader_curve_rgb(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ float *array;
+ int size;
+
+ curvemapping_table_RGBA(node->storage, &array, &size);
+ return GPU_stack_link(mat, "curves_rgb", in, out, GPU_texture(size, array));
+}
+
bNodeType sh_node_curve_rgb= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_CURVE_RGB,
@@ -114,6 +133,7 @@ bNodeType sh_node_curve_rgb= {
/* initfunc */ node_shader_init_curve_rgb,
/* freestoragefunc */ node_free_curves,
/* copystoragefunc */ node_copy_curves,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_curve_rgb
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_dynamic.c b/source/blender/nodes/intern/SHD_nodes/SHD_dynamic.c
index 1ba777a0533..4fcfe3a789a 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_dynamic.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_dynamic.c
@@ -27,221 +27,749 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#ifdef USE_PYNODES /* note: won't work without patch */
-
+#ifndef DISABLE_PYTHON
#include <Python.h>
+#include <compile.h>
#include <eval.h>
+#endif
#include "DNA_text_types.h"
#include "BKE_text.h"
+#include "BKE_utildefines.h"
+// XXX
+#if 0
+#ifndef DISABLE_PYTHON
#include "api2_2x/Node.h"
#include "api2_2x/gen_utils.h"
#include "BPY_extern.h"
+#endif
+#endif
#include "../SHD_util.h"
+// XXX
+#if 0
+static void node_dynamic_setup(bNode *node);
+static void node_dynamic_exec_cb(void *data, bNode *node, bNodeStack **in, bNodeStack **out);
+static void node_dynamic_free_storage_cb(bNode *node);
+
+#ifndef DISABLE_PYTHON
static PyObject *init_dynamicdict(void) {
- PyObject *newscriptdict= PyDict_New();
+ PyObject *newscriptdict;
+ PyGILState_STATE gilstate = PyGILState_Ensure();
+
+ newscriptdict= PyDict_New();
+
PyDict_SetItemString(newscriptdict, "__builtins__", PyEval_GetBuiltins());
EXPP_dict_set_item_str(newscriptdict, "__name__", PyString_FromString("__main__"));
+
+ PyGILState_Release(gilstate);
+
return newscriptdict;
}
+#endif
+
+static bNodeType *node_dynamic_find_typeinfo(ListBase *list, ID *id)
+{
+ bNodeType *ntype = list->first;
-static void free_dynamicdict(PyObject *dict) {
- if(dict!=NULL) {
- Py_DECREF(dict);
+ while(ntype) {
+ if (ntype->type == NODE_DYNAMIC && ntype->id == id)
+ break;
+ ntype = ntype->next;
}
+
+ return ntype; /* NULL if doesn't exist */
}
-static void node_dynamic_init(bNode *node) {
- NodeScriptDict *nsd= MEM_callocN(sizeof(NodeScriptDict), "node script dictionary");
- int type= node->custom2;
- node->custom2= 0;
- node->storage= nsd;
- if(type>=NODE_DYNAMIC_MENU) {
- if(type==NODE_DYNAMIC_MENU) {
- nodeMakeDynamicType(node);
- node->custom1= SH_NODE_DYNAMIC_NEW;
- } else {
- node->custom1= SH_NODE_DYNAMIC_ADDEXIST;
+static void node_dynamic_free_typeinfo_sockets(bNodeType *tinfo)
+{
+ bNodeSocketType *sock;
+
+ if (!tinfo) return;
+
+ if (tinfo->inputs) {
+ sock = tinfo->inputs;
+ while (sock->type != -1) {
+ MEM_freeN(sock->name);
+ sock++;
+ }
+ MEM_freeN(tinfo->inputs);
+ tinfo->inputs = NULL;
+ }
+ if (tinfo->outputs) {
+ sock = tinfo->outputs;
+ while (sock->type != -1) {
+ MEM_freeN(sock->name);
+ sock++;
+ }
+ MEM_freeN(tinfo->outputs);
+ tinfo->outputs = NULL;
+ }
+}
+
+static void node_dynamic_free_typeinfo(bNodeType *tinfo)
+{
+ if (!tinfo) return;
+
+ node_dynamic_free_typeinfo_sockets(tinfo);
+
+ if (tinfo->name) { MEM_freeN(tinfo->name); }
+
+ MEM_freeN(tinfo);
+}
+
+static void node_dynamic_free_sockets(bNode *node)
+{
+ BLI_freelistN(&node->inputs);
+ BLI_freelistN(&node->outputs);
+}
+
+/* For now we just remove the socket links. It's the safest
+ * route, since an update in the script may change completely the
+ * inputs and outputs. Trying to recreate the node links would be
+ * nicer for pynode authors, though. */
+static void node_dynamic_update_socket_links(bNode *node, bNodeTree *ntree)
+{
+ if (ntree) {
+ nodeVerifyType(ntree, node);
+ }
+ else {
+ Material *ma;
+
+ for (ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if (ma->nodetree) {
+ bNode *nd;
+ for (nd= ma->nodetree->nodes.first; nd; nd = nd->next) {
+ if (nd == node) nodeVerifyType(ma->nodetree, node);
+ }
+ }
}
- node->id= node->typeinfo->id;
- nodeDynamicParse(node);
- } else {
- if(node->custom1== SH_NODE_DYNAMIC_LOADED) {
- nodeMakeDynamicType(node);
- nodeDynamicParse(node);
- } else if(node->custom1== SH_NODE_DYNAMIC_ADDEXIST)
- nodeDynamicParse(node);
}
}
-static void node_dynamic_free(bNode *node)
+static void node_dynamic_free_storage_cb(bNode *node)
{
- NodeScriptDict *nsd= (NodeScriptDict *)(node->storage);
- BPy_Node *pynode= nsd->node;
- Py_XDECREF(pynode);
- free_dynamicdict((PyObject *)(nsd->dict));
+#ifndef DISABLE_PYTHON
+ NodeScriptDict *nsd;
+ PyObject *pydict;
+ BPy_Node *pynode;
+
+ if (!node->storage) return;
+ nsd = (NodeScriptDict *)(node->storage);
+ pydict = nsd->dict;
+ if (pydict) {
+ Py_DECREF(pydict);
+ }
+ pynode = nsd->node;
+ if (pynode) {
+ Py_DECREF(pynode);
+ }
+#endif
MEM_freeN(node->storage);
+ node->storage = NULL;
}
-static void node_dynamic_copy(bNode *orig_node, bNode *new_node)
+/* Disable pynode when its script fails */
+static void node_dynamic_disable(bNode *node)
{
- NodeScriptDict *nsd= (NodeScriptDict *)(orig_node->storage);
- new_node->storage= MEM_dupallocN(orig_node->storage);
- if(nsd->node)
- Py_INCREF((PyObject *)(nsd->node));
- if(nsd->dict)
- Py_INCREF((PyObject *)(nsd->dict));
+ node->custom1 = 0;
+ node->custom1 = BSET(node->custom1, NODE_DYNAMIC_ERROR);
}
-static void node_dynamic_exec(void *data, bNode *node, bNodeStack **in, bNodeStack **out) {
- BPy_Node *mynode = NULL;
- NodeScriptDict *nsd = NULL;
- PyObject *pyresult = NULL;
- PyObject *args = NULL;
- ShadeInput *shi= ((ShaderCallData *)data)->shi;
+/* Disable all pynodes using the given text (script) id */
+static void node_dynamic_disable_all_by_id(ID *id)
+{
+#ifndef DISABLE_PYTHON
+ Material *ma; /* XXX hardcoded for shaders */
- if(node->custom1==SH_NODE_DYNAMIC_NEW) {
- nodeDynamicParse(node);
- return;
+ for (ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if (ma->nodetree) {
+ bNode *nd;
+ bNodeTree *ntree = ma->nodetree;
+ for (nd= ntree->nodes.first; nd; nd= nd->next) {
+ if (nd->id == id) {
+ nd->custom1 = 0;
+ nd->custom1 = BSET(nd->custom1, NODE_DYNAMIC_ERROR);
+ }
+ }
+ }
}
+#endif
+}
- if(node->custom2<0)
- return;
+static void node_rem_socklist_links(bNodeTree *ntree, ListBase *lb)
+{
+ bNodeLink *link, *next;
+ bNodeSocket *sock;
- if(node->custom1==SH_NODE_DYNAMIC_READY || node->custom1==SH_NODE_DYNAMIC_UPDATED) {
- if(node->custom1== SH_NODE_DYNAMIC_UPDATED)
- node->custom1= SH_NODE_DYNAMIC_READY;
+ if (!lb) return;
- nsd = (NodeScriptDict *)node->storage;
+ for (sock= lb->first; sock; sock= sock->next) {
+ for (link= ntree->links.first; link; link= next) {
+ next= link->next;
+ if (link->fromsock==sock || link->tosock==sock) {
+ nodeRemLink(ntree, link);
+ }
+ }
+ }
+}
- mynode = (BPy_Node *)(nsd->node);
- if(mynode && PyCallable_Check((PyObject *)mynode)) {
- mynode->node= node;
- Node_SetStack(mynode, in, NODE_INPUTSTACK);
- Node_SetStack(mynode, out, NODE_OUTPUTSTACK);
- Node_SetShi(mynode, shi);
- args=Py_BuildValue("()");
- pyresult= PyObject_Call((PyObject *)mynode, args, NULL);
- if(!pyresult) {
- if(PyErr_Occurred()) {
- PyErr_Print();
- node->custom2= -1;
- } else {
- printf("PyObject_Call __call__ failed\n");
+/* XXX hardcoded for shaders */
+static void node_dynamic_rem_all_links(bNodeType *tinfo)
+{
+ Material *ma;
+ int in, out;
+
+ in = tinfo->inputs ? 1 : 0;
+ out = tinfo->outputs ? 1 : 0;
+
+ if (!in && !out) return;
+
+ for (ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if (ma->nodetree) {
+ bNode *nd;
+ bNodeTree *ntree = ma->nodetree;
+ for (nd= ntree->nodes.first; nd; nd= nd->next) {
+ if (nd->typeinfo == tinfo) {
+ if (in)
+ node_rem_socklist_links(ntree, &nd->inputs);
+ if (out)
+ node_rem_socklist_links(ntree, &nd->outputs);
}
}
- Py_XDECREF(pyresult);
- Py_DECREF(args);
}
}
}
-void nodeDynamicParse(struct bNode *node)
+/* node_dynamic_reset: clean a pynode, getting rid of all
+ * data dynamically created for it. */
+static void node_dynamic_reset(bNode *node, int unlink_text)
+{
+ bNodeType *tinfo, *tinfo_default;
+ Material *ma;
+
+ tinfo = node->typeinfo;
+ tinfo_default = node_dynamic_find_typeinfo(&node_all_shaders, NULL);
+
+ if ((tinfo == tinfo_default) && unlink_text) {
+ ID *textID = node->id;
+ /* already at default (empty) state, which happens if this node's
+ * script failed to parse at the first stage: definition. We're here
+ * because its text was removed from Blender. */
+ for (ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if (ma->nodetree) {
+ bNode *nd;
+ for (nd= ma->nodetree->nodes.first; nd; nd = nd->next) {
+ if (nd->id == textID) {
+ nd->id = NULL;
+ nd->custom1 = 0;
+ nd->custom1 = BSET(nd->custom1, NODE_DYNAMIC_NEW);
+ BLI_strncpy(nd->name, "Dynamic", 8);
+ return;
+ }
+ }
+ }
+ }
+ }
+
+ node_dynamic_rem_all_links(tinfo);
+ node_dynamic_free_typeinfo_sockets(tinfo);
+
+ /* reset all other XXX shader nodes sharing this typeinfo */
+ for (ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if (ma->nodetree) {
+ bNode *nd;
+ for (nd= ma->nodetree->nodes.first; nd; nd = nd->next) {
+ if (nd->typeinfo == tinfo) {
+ node_dynamic_free_storage_cb(nd);
+ node_dynamic_free_sockets(nd);
+ //node_dynamic_update_socket_links(nd, ma->nodetree);
+ nd->typeinfo = tinfo_default;
+ if (unlink_text) {
+ nd->id = NULL;
+ nd->custom1 = 0;
+ nd->custom1 = BSET(nd->custom1, NODE_DYNAMIC_NEW);
+ BLI_strncpy(nd->name, "Dynamic", 8);
+ }
+ }
+ }
+ }
+ }
+
+ /* XXX hardcoded for shaders: */
+ if (tinfo->id) { BLI_remlink(&node_all_shaders, tinfo); }
+ node_dynamic_free_typeinfo(tinfo);
+}
+
+/* Special case of the above function: for working pynodes
+ * that were saved on a .blend but fail for some reason when
+ * the file is opened. We need this because pynodes are initialized
+ * before G.main. */
+static void node_dynamic_reset_loaded(bNode *node)
+{
+ bNodeType *tinfo = node->typeinfo;
+
+ node_dynamic_rem_all_links(tinfo);
+ node_dynamic_free_typeinfo_sockets(tinfo);
+ node_dynamic_free_storage_cb(node);
+ /* XXX hardcoded for shaders: */
+ if (tinfo->id) { BLI_remlink(&node_all_shaders, tinfo); }
+
+ node_dynamic_free_typeinfo(tinfo);
+ node->typeinfo = node_dynamic_find_typeinfo(&node_all_shaders, NULL);
+}
+
+int nodeDynamicUnlinkText(ID *txtid) {
+ Material *ma;
+ bNode *nd;
+
+ /* find one node that uses this text */
+ for (ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if (ma->nodetree) {
+ for (nd= ma->nodetree->nodes.first; nd; nd = nd->next) {
+ if ((nd->type == NODE_DYNAMIC) && (nd->id == txtid)) {
+ node_dynamic_reset(nd, 1); /* found, reset all */
+ return 1;
+ }
+ }
+ }
+ }
+ return 0; /* no pynodes used this text */
+}
+
+static void node_dynamic_pyerror_print(bNode *node)
+{
+#ifndef DISABLE_PYTHON
+ PyGILState_STATE gilstate = PyGILState_Ensure();
+
+ fprintf(stderr, "\nError in dynamic node script \"%s\":\n", node->name);
+ if (PyErr_Occurred()) { PyErr_Print(); }
+ else { fprintf(stderr, "Not a valid dynamic node Python script.\n"); }
+
+ PyGILState_Release(gilstate);
+#endif
+}
+
+static void node_dynamic_register_type(bNode *node)
+{
+ nodeRegisterType(&node_all_shaders, node->typeinfo);
+ /* nodeRegisterType copied it to a new one, so we
+ * free the typeinfo itself, but not what it
+ * points to: */
+ MEM_freeN(node->typeinfo);
+ node->typeinfo = node_dynamic_find_typeinfo(&node_all_shaders, node->id);
+ MEM_freeN(node->typeinfo->name);
+ node->typeinfo->name = BLI_strdup(node->name);
+}
+
+#ifndef DISABLE_PYTHON
+/* node_dynamic_get_pynode:
+ * Find the pynode definition from the script */
+static PyObject *node_dynamic_get_pynode(PyObject *dict)
{
- BPy_Node *pynode= NULL;
- PyObject *dict= NULL;
PyObject *key= NULL;
- PyObject *value= NULL;
- PyObject *testinst= NULL;
+ Py_ssize_t pos = 0;
+ PyObject *value = NULL;
+
+ /* script writer specified a node? */
+ value = PyDict_GetItemString(dict, "__node__");
+
+ if (value) {
+ if (PyObject_TypeCheck(value, &PyType_Type)) {
+ Py_INCREF(value);
+ return value;
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "expected class object derived from Scripted node");
+ return NULL;
+ }
+ }
+
+ /* case not, search for it in the script's global dictionary */
+ while (PyDict_Next(dict, &pos, &key, &value)) {
+ /* skip names we know belong to other available objects */
+ if (strcmp("Socket", PyString_AsString(key)) == 0)
+ continue;
+ else if (strcmp("Scripted", PyString_AsString(key)) == 0)
+ continue;
+ /* naive: we grab the first ob of type 'type': */
+ else if (PyObject_TypeCheck(value, &PyType_Type)) {
+ Py_INCREF(value);
+ return value;
+ }
+ }
+
+ PyErr_SetString(PyExc_TypeError,
+ "no PyNode definition found in the script!");
+ return NULL;
+}
+#endif /* DISABLE_PYTHON */
+
+static int node_dynamic_parse(struct bNode *node)
+{
+#ifdef DISABLE_PYTHON
+ return -1;
+#else
+ PyObject *dict= NULL;
+ PyObject *pynode_data= NULL;
+ PyObject *pynode= NULL;
PyObject *args= NULL;
- int pos = 0;
- NodeScriptDict *nsd= NULL;
+ NodeScriptDict *nsd = NULL;
PyObject *pyresult = NULL;
- PyObject *pycompiled = NULL;
- Text *txt = NULL;
- char *buf= NULL;
+ char *buf = NULL;
+ int is_valid_script = 0;
+ PyGILState_STATE gilstate;
+
+ if (!node->id || !node->storage)
+ return 0;
+
+ /* READY, no need to be here */
+ if (BTST(node->custom1, NODE_DYNAMIC_READY))
+ return 0;
+
+ /* for threading */
+ gilstate = PyGILState_Ensure();
+
+ nsd = (NodeScriptDict *)node->storage;
+
+ dict = (PyObject *)(nsd->dict);
+ buf = txt_to_buf((Text *)node->id);
+
+ pyresult = PyRun_String(buf, Py_file_input, dict, dict);
+
+ MEM_freeN(buf);
+
+ if (!pyresult) {
+ if (BTST(node->custom1, NODE_DYNAMIC_LOADED)) {
+ node_dynamic_disable(node);
+ } else {
+ node_dynamic_disable_all_by_id(node->id);
+ }
+ node_dynamic_pyerror_print(node);
+ PyGILState_Release(gilstate);
+ return -1;
+ }
+
+ Py_DECREF(pyresult);
+
+ pynode_data = node_dynamic_get_pynode(dict);
+
+ if (pynode_data) {
+ BPy_NodeSocketLists *socklists = Node_CreateSocketLists(node);
+
+ args = Py_BuildValue("(O)", socklists);
+
+ /* init it to get the input and output sockets */
+ pynode = PyObject_Call(pynode_data, args, NULL);
+
+ Py_DECREF(pynode_data);
+ Py_DECREF(socklists);
+ Py_DECREF(args);
+
+ if (!PyErr_Occurred() && pynode && pytype_is_pynode(pynode)) {
+ InitNode((BPy_Node *)(pynode), node);
+ nsd->node = pynode;
+ node->typeinfo->execfunc = node_dynamic_exec_cb;
+ is_valid_script = 1;
+
+ /* for NEW, LOADED, REPARSE */
+ if (BNTST(node->custom1, NODE_DYNAMIC_ADDEXIST)) {
+ node->typeinfo->pydict = dict;
+ node->typeinfo->pynode = pynode;
+ node->typeinfo->id = node->id;
+ if (BNTST(node->custom1, NODE_DYNAMIC_LOADED))
+ nodeAddSockets(node, node->typeinfo);
+ if (BNTST(node->custom1, NODE_DYNAMIC_REPARSE))
+ node_dynamic_register_type(node);
+ }
+
+ node->custom1 = 0;
+ node->custom1 = BSET(node->custom1, NODE_DYNAMIC_READY);
+ }
+ }
+
+ PyGILState_Release(gilstate);
+
+ if (!is_valid_script) { /* not a valid pynode script */
+ node_dynamic_disable_all_by_id(node->id);
+ node_dynamic_pyerror_print(node);
+ return -1;
+ }
+
+ return 0;
+#endif
+}
+
+/* node_dynamic_setup: prepare for execution (state: NODE_DYNAMIC_READY)
+ * pynodes already linked to a script (node->id != NULL). */
+static void node_dynamic_setup(bNode *node)
+{
+#ifndef DISABLE_PYTHON
+ NodeScriptDict *nsd = NULL;
+ bNodeTree *nodetree = NULL;
+ bNodeType *ntype = NULL;
+ PyGILState_STATE gilstate;
- if(! node->id) {
+ /* Possible cases:
+ * NEW
+ * ADDEXIST
+ * LOADED
+ * REPARSE
+ * ERROR
+ * READY
+ */
+
+ /* NEW, but not linked to a script: link default (empty) typeinfo */
+ if (!node->id) {
+ node->typeinfo = node_dynamic_find_typeinfo(&node_all_shaders,
+ NULL);
return;
}
- if(node->custom1!=SH_NODE_DYNAMIC_READY) {
- txt = (Text *)node->id;
- nsd = (NodeScriptDict *)node->storage;
+ /* READY, no need to be here */
+ if (BTST(node->custom1, NODE_DYNAMIC_READY))
+ return;
+
+ gilstate = PyGILState_Ensure();
+
+ /* ERROR, reset to (empty) defaults */
+ if (BCLR(node->custom1, NODE_DYNAMIC_ERROR) == 0) {
+ node_dynamic_reset(node, 0);
+ PyGILState_Release(gilstate);
+ return;
+ }
+
+ /* User asked to update this pynode, prepare it for reparsing */
+ if (BTST(node->custom1, NODE_DYNAMIC_REPARSE)) {
+ int needs_parsing = 1;
+
+ node->custom1 = BSET(node->custom1, NODE_DYNAMIC_NEW);
+
+ if (BTST(node->custom1, NODE_DYNAMIC_ERROR)) {
+ node->custom1 = BCLR(node->custom1, NODE_DYNAMIC_REPARSE);
+ ntype = node_dynamic_find_typeinfo(&node_all_shaders, node->id);
+
+ if (ntype) {
+ node->typeinfo = ntype;
+ node->custom1 = BSET(node->custom1, NODE_DYNAMIC_ADDEXIST);
+ node->custom1 = BCLR(node->custom1, NODE_DYNAMIC_ERROR);
+ needs_parsing = 0;
+ }
+ else { nodeMakeDynamicType(node); }
+
+ } else {
+ node_dynamic_rem_all_links(node->typeinfo);
+ node_dynamic_free_typeinfo_sockets(node->typeinfo);
+ node_dynamic_update_socket_links(node, NULL);
+ node_dynamic_free_storage_cb(node);
+ }
- if(nsd->dict==NULL && (node->custom1==SH_NODE_DYNAMIC_NEW||node->custom1==SH_NODE_DYNAMIC_LOADED)) {
- nsd->dict= init_dynamicdict();
- } else if(nsd->dict==NULL && node->custom1==SH_NODE_DYNAMIC_ADDEXIST) {
- nsd->dict= node->typeinfo->pydict;
- nsd->node= node->typeinfo->pynode;
- Py_INCREF((PyObject *)(nsd->dict));
- Py_INCREF((PyObject *)(nsd->node));
- node->custom1= SH_NODE_DYNAMIC_READY;
+ if (needs_parsing) {
+ nsd = MEM_callocN(sizeof(NodeScriptDict), "node script dictionary");
+ nsd->dict = init_dynamicdict();
+ node->storage = nsd;
+ /* prepared, now reparse: */
+ node_dynamic_parse(node);
+ PyGILState_Release(gilstate);
return;
}
- dict= (PyObject *)(nsd->dict);
+ }
+ else if (BTST(node->custom1, NODE_DYNAMIC_LOADED)) {
+ /* when loading from a .blend we don't have G.main yet, so we
+ * quickly abuse node->storage in ntreeInitTypes (node.c) to have
+ * our nodetree ptr (needed if a pynode script that worked before
+ * saving the .blend for some reason fails upon loading): */
+ nodetree = (bNodeTree *)node->storage;
+ node->storage = NULL;
+ }
- if(node->custom1!=SH_NODE_DYNAMIC_ADDEXIST) {
- buf = txt_to_buf( txt );
- /*printf("Running script (%s, %d)...", node->name, node->custom1);*/
- pyresult = PyRun_String(buf, Py_file_input, dict, dict);
- /*printf(" done\n");*/
+ if (node->storage)
+ fprintf(stderr, "\nDEBUG: PYNODES ERROR: non NULL node->storage in node_dynamic_setup()\n");
- MEM_freeN(buf);
+ nsd = MEM_callocN(sizeof(NodeScriptDict), "node script dictionary");
+ node->storage = nsd;
+
+ /* NEW, LOADED or REPARSE */
+ if (BNTST(node->custom1, NODE_DYNAMIC_ADDEXIST)) {
+ /* check if there's already a bNodeType linked to this script */
+ /* (XXX hardcoded for shader nodes for now) */
+ ntype = node_dynamic_find_typeinfo(&node_all_shaders, node->id);
- if(!pyresult) {
- if(PyErr_Occurred()) {
- PyErr_Print();
- }
- Py_XDECREF(pyresult);
- return;
+ if (ntype) { /* if so, reuse it */
+ node->typeinfo = ntype;
+ /* so this is actually an ADDEXIST type */
+ node->custom1 = BSET(node->custom1, NODE_DYNAMIC_ADDEXIST);
+ }
+ else { /* create bNodeType for this pynode */
+ nodeMakeDynamicType(node);
+ nsd->dict = init_dynamicdict();
+ if ((node_dynamic_parse(node) == -1) && nodetree) {
+ node_dynamic_reset_loaded(node);
}
+ PyGILState_Release(gilstate);
+ return;
+ }
+ }
- Py_DECREF(pyresult);
+ /* ADDEXIST: new pynode linked to an already registered dynamic type,
+ * we just reuse existing py dict and pynode */
+ nsd->dict = node->typeinfo->pydict;
+ nsd->node = node->typeinfo->pynode;
- while(PyDict_Next( (PyObject *)(nsd->dict), &pos, &key, &value) ) {
- if(PyObject_TypeCheck(value, &PyType_Type)==1) {
- BPy_DefinitionMap *outputdef= Node_CreateOutputDefMap(node);
- BPy_DefinitionMap *inputdef= Node_CreateInputDefMap(node);
-
- args= Py_BuildValue("(OO)", inputdef, outputdef);
- testinst= PyObject_Call(value, args, NULL);
-
- Py_DECREF(outputdef);
- Py_DECREF(inputdef);
- if(testinst && PyObject_TypeCheck(testinst, &Node_Type)==1) {
- Py_INCREF(testinst);
- Py_INCREF(dict);
- InitNode((BPy_Node *)(testinst), node);
- nsd->node= testinst;
- node->typeinfo->execfunc= node_dynamic_exec;
- if(node->custom1== SH_NODE_DYNAMIC_NEW || node->custom1== SH_NODE_DYNAMIC_LOADED) {
- node->typeinfo->pynode= testinst;
- node->typeinfo->pydict= nsd->dict;
- node->typeinfo->id= node->id;
- nodeAddSockets(node, node->typeinfo);
- nodeRegisterType(&node_all_shaders, node->typeinfo);
- node->custom1= SH_NODE_DYNAMIC_READY;
- }
- break;
- }
- Py_DECREF(args);
- }
- }
+ Py_INCREF((PyObject *)(nsd->dict));
+ Py_INCREF((PyObject *)(nsd->node));
+
+ if (BTST(node->custom1, NODE_DYNAMIC_NEW)) {
+ nodeAddSockets(node, node->typeinfo);
+ node->custom1 = BCLR(node->custom1, NODE_DYNAMIC_NEW);
+ }
+
+ node->custom1 = BCLR(node->custom1, NODE_DYNAMIC_ADDEXIST);
+ node->custom1 = BSET(node->custom1, NODE_DYNAMIC_READY);
+
+ PyGILState_Release(gilstate);
+#endif /* DISABLE_PYTHON */
+ return;
+}
+
+/* node_dynamic_init_cb callback: called when a pynode is created.
+ * The pynode type is passed via node->custom2. It can be:
+ * 0: for loaded empty nodes
+ * NODE_DYNAMIC_MENU: for the default Dynamic node type
+ * > NODE_DYNAMIC_MENU: for the new types defined by scripts
+*/
+static void node_dynamic_init_cb(bNode *node) {
+ int type = node->custom2;
+
+ node->custom2 = 0;
+
+ if (type >= NODE_DYNAMIC_MENU) {
+ node->custom1 = 0;
+
+ if (type == NODE_DYNAMIC_MENU) {
+ node->custom1 = BSET(node->custom1, NODE_DYNAMIC_NEW);
+ return;
}
+
+ node->custom1 = BSET(node->custom1, NODE_DYNAMIC_ADDEXIST);
+ node->id = node->typeinfo->id;
}
+
+ node_dynamic_setup(node);
+}
+
+/* node_dynamic_copy_cb: pynode copy callback */
+static void node_dynamic_copy_cb(bNode *orig_node, bNode *new_node)
+{
+#ifdef DISABLE_PYTHON
+ return;
+#else
+ NodeScriptDict *nsd;
+ PyGILState_STATE gilstate;
+
+ if (!orig_node->storage) return;
+
+ nsd = (NodeScriptDict *)(orig_node->storage);
+ new_node->storage = MEM_dupallocN(orig_node->storage);
+
+ gilstate = PyGILState_Ensure();
+
+ if (nsd->node)
+ Py_INCREF((PyObject *)(nsd->node));
+ if (nsd->dict)
+ Py_INCREF((PyObject *)(nsd->dict));
+
+ PyGILState_Release(gilstate);
+#endif
}
+/* node_dynamic_exec_cb: the execution callback called per pixel
+ * during rendering. */
+static void node_dynamic_exec_cb(void *data, bNode *node, bNodeStack **in, bNodeStack **out) {
+#ifdef DISABLE_PYTHON
+ return;
+#else
+ BPy_Node *mynode = NULL;
+ NodeScriptDict *nsd = NULL;
+ PyObject *pyresult = NULL;
+ PyObject *args = NULL;
+ ShadeInput *shi;
+ PyGILState_STATE gilstate;
+
+ if (!node->id)
+ return;
+
+ /*if (G.scene->r.threads > 1)
+ return;*/
+
+ if (BTST2(node->custom1, NODE_DYNAMIC_NEW, NODE_DYNAMIC_REPARSE)) {
+ node_dynamic_setup(node);
+ return;
+ }
+
+ if (BTST(node->custom1, NODE_DYNAMIC_ERROR)) {
+ if (node->storage) node_dynamic_setup(node);
+ return;
+ }
+
+ if (BTST(node->custom1, NODE_DYNAMIC_READY)) {
+ nsd = (NodeScriptDict *)node->storage;
+ mynode = (BPy_Node *)(nsd->node);
+
+
+ if (mynode && PyCallable_Check((PyObject *)mynode)) {
+
+ gilstate = PyGILState_Ensure();
+
+ mynode->node = node;
+ shi = ((ShaderCallData *)data)->shi;
+
+ Node_SetStack(mynode, in, NODE_INPUTSTACK);
+ Node_SetStack(mynode, out, NODE_OUTPUTSTACK);
+ Node_SetShi(mynode, shi);
+
+ args=Py_BuildValue("()");
+ pyresult= PyObject_Call((PyObject *)mynode, args, NULL);
+ Py_DECREF(args);
-bNodeType sh_node_dynamic = {
+ if (!pyresult) {
+ PyGILState_Release(gilstate);
+ node_dynamic_disable_all_by_id(node->id);
+ node_dynamic_pyerror_print(node);
+ node_dynamic_setup(node);
+ return;
+ }
+ Py_DECREF(pyresult);
+ PyGILState_Release(gilstate);
+ }
+ }
+#endif
+}
+
+bNodeType node_dynamic_typeinfo = {
/* next, prev */ NULL, NULL,
- /* type code */ SH_NODE_DYNAMIC,
+ /* type code */ NODE_DYNAMIC,
/* name */ "Dynamic",
/* width+range */ 150, 60, 300,
/* class+opts */ NODE_CLASS_OP_DYNAMIC, NODE_OPTIONS,
/* input sock */ NULL,
/* output sock */ NULL,
/* storage */ "NodeScriptDict",
- /* execfunc */ node_dynamic_exec,
+ /* execfunc */ node_dynamic_exec_cb,
/* butfunc */ NULL,
- /* initfunc */ node_dynamic_init,
- /* freefunc */ node_dynamic_free,
- /* copyfunc */ node_dynamic_copy,
+ /* initfunc */ node_dynamic_init_cb,
+ /* freefunc */ node_dynamic_free_storage_cb,
+ /* copyfunc */ node_dynamic_copy_cb,
/* id */ NULL
};
-#endif /* USE_PYNODES */
+#else
+
+bNodeType node_dynamic_typeinfo = {NULL};
+
+#endif
+
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_geom.c b/source/blender/nodes/intern/SHD_nodes/SHD_geom.c
index 24395059c60..bc345759b98 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_geom.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_geom.c
@@ -29,6 +29,7 @@
#include "../SHD_util.h"
+#include "DNA_customdata_types.h"
/* **************** GEOMETRY ******************** */
@@ -124,6 +125,18 @@ static void node_shader_init_geometry(bNode *node)
node->storage= MEM_callocN(sizeof(NodeGeometry), "NodeGeometry");
}
+static int gpu_shader_geom(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ NodeGeometry *ngeo= (NodeGeometry*)node->storage;
+ GPUNodeLink *orco = GPU_attribute(CD_ORCO, "");
+ GPUNodeLink *mtface = GPU_attribute(CD_MTFACE, ngeo->uvname);
+ GPUNodeLink *mcol = GPU_attribute(CD_MCOL, ngeo->colname);
+
+ return GPU_stack_link(mat, "geom", in, out,
+ GPU_builtin(GPU_VIEW_POSITION), GPU_builtin(GPU_VIEW_NORMAL),
+ GPU_builtin(GPU_INVERSE_VIEW_MATRIX), orco, mtface, mcol);
+}
+
/* node type definition */
bNodeType sh_node_geom= {
/* *next,*prev */ NULL, NULL,
@@ -139,6 +152,7 @@ bNodeType sh_node_geom= {
/* initfunc */ node_shader_init_geometry,
/* freestoragefunc */ node_free_standard_storage,
/* copystoragefunc */ node_copy_standard_storage,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_geom
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_hueSatVal.c b/source/blender/nodes/intern/SHD_nodes/SHD_hueSatVal.c
index 8c07a2d1dc8..1b7b2dfb8e7 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_hueSatVal.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_hueSatVal.c
@@ -54,9 +54,7 @@ static void do_hue_sat_fac(bNode *node, float *out, float *hue, float *sat, floa
hsv[0]+= (*hue - 0.5f);
if(hsv[0]>1.0) hsv[0]-=1.0; else if(hsv[0]<0.0) hsv[0]+= 1.0;
hsv[1]*= *sat;
- if(hsv[1]>1.0) hsv[1]= 1.0; else if(hsv[1]<0.0) hsv[1]= 0.0;
hsv[2]*= *val;
- if(hsv[2]>1.0) hsv[2]= 1.0; else if(hsv[2]<0.0) hsv[2]= 0.0;
hsv_to_rgb(hsv[0], hsv[1], hsv[2], col, col+1, col+2);
out[0]= mfac*in[0] + *fac*col[0];
@@ -73,6 +71,12 @@ static void node_shader_exec_hue_sat(void *data, bNode *node, bNodeStack **in, b
do_hue_sat_fac(node, out[0]->vec, in[0]->vec, in[1]->vec, in[2]->vec, in[4]->vec, in[3]->vec);
}
+
+static int gpu_shader_hue_sat(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ return GPU_stack_link(mat, "hue_sat", in, out);
+}
+
bNodeType sh_node_hue_sat= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_HUE_SAT,
@@ -87,7 +91,8 @@ bNodeType sh_node_hue_sat= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_hue_sat
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_invert.c b/source/blender/nodes/intern/SHD_nodes/SHD_invert.c
index 4d1ce282fce..72ee1483ecf 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_invert.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_invert.c
@@ -64,6 +64,11 @@ bNodeStack **out)
VECCOPY(out[0]->vec, col);
}
+static int gpu_shader_invert(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ return GPU_stack_link(mat, "invert", in, out);
+}
+
bNodeType sh_node_invert= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_INVERT,
@@ -78,6 +83,7 @@ bNodeType sh_node_invert= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_invert
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_mapping.c b/source/blender/nodes/intern/SHD_nodes/SHD_mapping.c
index 589954c8f7b..c081929a2fc 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_mapping.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_mapping.c
@@ -69,6 +69,20 @@ static void node_shader_init_mapping(bNode *node)
node->storage= add_mapping();
}
+static int gpu_shader_mapping(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ TexMapping *texmap= node->storage;
+ float domin= (texmap->flag & TEXMAP_CLIP_MIN) != 0;
+ float domax= (texmap->flag & TEXMAP_CLIP_MAX) != 0;
+ GPUNodeLink *tmat = GPU_uniform((float*)texmap->mat);
+ GPUNodeLink *tmin = GPU_uniform(texmap->min);
+ GPUNodeLink *tmax = GPU_uniform(texmap->max);
+ GPUNodeLink *tdomin = GPU_uniform(&domin);
+ GPUNodeLink *tdomax = GPU_uniform(&domax);
+
+ return GPU_stack_link(mat, "mapping", in, out, tmat, tmin, tmax, tdomin, tdomax);
+}
+
bNodeType sh_node_mapping= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_MAPPING,
@@ -83,7 +97,8 @@ bNodeType sh_node_mapping= {
/* initfunc */ node_shader_init_mapping,
/* freestoragefunc */ node_free_standard_storage,
/* copystoragefunc */ node_copy_standard_storage,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_mapping
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_material.c b/source/blender/nodes/intern/SHD_nodes/SHD_material.c
index bdceb134c0d..c0a2534ac4a 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_material.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_material.c
@@ -54,7 +54,6 @@ static bNodeSocketType sh_node_material_ext_in[]= {
{ SOCK_VALUE, 1, "Refl", 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
{ SOCK_VECTOR, 1, "Normal", 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f},
{ SOCK_RGBA, 1, "Mirror", 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 1, "AmbCol", 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
{ SOCK_VALUE, 1, "Ambient", 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
{ SOCK_VALUE, 1, "Emit", 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
{ SOCK_VALUE, 1, "SpecTra", 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
@@ -117,8 +116,6 @@ static void node_shader_exec_material(void *data, bNode *node, bNodeStack **in,
if (node->type == SH_NODE_MATERIAL_EXT) {
if(in[MAT_IN_MIR]->hasinput)
nodestack_get_vec(&shi->mirr, SOCK_VECTOR, in[MAT_IN_MIR]);
- if(in[MAT_IN_AMBCOL]->hasinput)
- nodestack_get_vec(&shi->ambr, SOCK_VECTOR, in[MAT_IN_AMBCOL]);
if(in[MAT_IN_AMB]->hasinput)
nodestack_get_vec(&shi->amb, SOCK_VALUE, in[MAT_IN_AMB]);
if(in[MAT_IN_EMIT]->hasinput)
@@ -185,6 +182,77 @@ static void node_shader_init_material(bNode* node)
node->custom1= SH_NODE_MAT_DIFF|SH_NODE_MAT_SPEC;
}
+static int gpu_shader_material(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ if(node->id) {
+ GPUShadeInput shi;
+ GPUShadeResult shr;
+
+ GPU_shadeinput_set(mat, (Material*)node->id, &shi);
+
+ /* write values */
+ if(in[MAT_IN_COLOR].hasinput)
+ shi.rgb = in[MAT_IN_COLOR].link;
+
+ if(in[MAT_IN_SPEC].hasinput)
+ shi.specrgb = in[MAT_IN_SPEC].link;
+
+ if(in[MAT_IN_REFL].hasinput)
+ shi.refl = in[MAT_IN_REFL].link;
+
+ /* retrieve normal */
+ if(in[MAT_IN_NORMAL].hasinput) {
+ GPUNodeLink *tmp;
+ shi.vn = in[MAT_IN_NORMAL].link;
+ GPU_link(mat, "vec_math_normalize", shi.vn, &shi.vn, &tmp);
+ }
+
+ /* custom option to flip normal */
+ if(node->custom1 & SH_NODE_MAT_NEG)
+ GPU_link(mat, "vec_math_negate", shi.vn, &shi.vn);
+
+ if (node->type == SH_NODE_MATERIAL_EXT) {
+ if(in[MAT_IN_AMB].hasinput)
+ shi.amb= in[MAT_IN_AMB].link;
+ if(in[MAT_IN_EMIT].hasinput)
+ shi.emit= in[MAT_IN_EMIT].link;
+ if(in[MAT_IN_ALPHA].hasinput)
+ shi.alpha= in[MAT_IN_ALPHA].link;
+ }
+
+ GPU_shaderesult_set(&shi, &shr); /* clears shr */
+
+ /* write to outputs */
+ if(node->custom1 & SH_NODE_MAT_DIFF) {
+ if(node->custom1 & SH_NODE_MAT_SPEC)
+ out[MAT_OUT_COLOR].link= shr.combined;
+ else
+ out[MAT_OUT_COLOR].link= shr.diff;
+ }
+ else if(node->custom1 & SH_NODE_MAT_SPEC) {
+ out[MAT_OUT_COLOR].link= shr.spec;
+ }
+ else
+ GPU_link(mat, "set_rgb_zero", &out[MAT_OUT_COLOR].link);
+
+ GPU_link(mat, "mtex_alpha_to_col", out[MAT_OUT_COLOR].link, shr.alpha, &out[MAT_OUT_COLOR].link);
+
+ out[MAT_OUT_ALPHA].link = shr.alpha; //
+
+ if(node->custom1 & SH_NODE_MAT_NEG)
+ GPU_link(mat, "vec_math_negate", shi.vn, &shi.vn);
+ out[MAT_OUT_NORMAL].link = shi.vn;
+
+ if (node->type == SH_NODE_MATERIAL_EXT) {
+ out[MAT_OUT_DIFFUSE].link = shr.diff;
+ out[MAT_OUT_SPEC].link = shr.spec;
+ }
+
+ return 1;
+ }
+
+ return 0;
+}
bNodeType sh_node_material= {
/* *next,*prev */ NULL, NULL,
@@ -200,8 +268,8 @@ bNodeType sh_node_material= {
/* initfunc */ node_shader_init_material,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
-
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_material
};
bNodeType sh_node_material_ext= {
@@ -218,7 +286,7 @@ bNodeType sh_node_material_ext= {
/* initfunc */ node_shader_init_material,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
-
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_material
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_math.c b/source/blender/nodes/intern/SHD_nodes/SHD_math.c
index 95162e508d5..050c2cdcc95 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_math.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_math.c
@@ -174,10 +174,66 @@ bNodeStack **out)
else
out[0]->vec[0]= (int)(in[1]->vec[0] + 0.5f);
}
- break;
+ break;
+ case 15: /* Less Than */
+ {
+ if( in[0]->vec[0] < in[1]->vec[0] )
+ out[0]->vec[0]= 1.0f;
+ else
+ out[0]->vec[0]= 0.0f;
+ }
+ break;
+ case 16: /* Greater Than */
+ {
+ if( in[0]->vec[0] > in[1]->vec[0] )
+ out[0]->vec[0]= 1.0f;
+ else
+ out[0]->vec[0]= 0.0f;
+ }
+ break;
}
}
+static int gpu_shader_math(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ static char *names[] = {"math_add", "math_subtract", "math_multiply",
+ "math_divide", "math_sine", "math_cosine", "math_tangnet", "math_asin",
+ "math_acos", "math_atan", "math_pow", "math_log", "math_min", "math_max",
+ "math_round", "math_less_than", "math_greater_than"};
+
+ switch (node->custom1) {
+ case 0:
+ case 1:
+ case 2:
+ case 3:
+ case 10:
+ case 11:
+ case 12:
+ case 13:
+ case 15:
+ case 16:
+ GPU_stack_link(mat, names[node->custom1], NULL, out,
+ GPU_socket(&in[0]), GPU_socket(&in[1]));
+ break;
+ case 4:
+ case 5:
+ case 6:
+ case 7:
+ case 8:
+ case 9:
+ case 14:
+ if(in[0].hasinput || !in[1].hasinput)
+ GPU_stack_link(mat, names[node->custom1], NULL, out, GPU_socket(&in[0]));
+ else
+ GPU_stack_link(mat, names[node->custom1], NULL, out, GPU_socket(&in[1]));
+ break;
+ default:
+ return 0;
+ }
+
+ return 1;
+}
+
bNodeType sh_node_math= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_MATH,
@@ -192,6 +248,7 @@ bNodeType sh_node_math= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_math
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_mixRgb.c b/source/blender/nodes/intern/SHD_nodes/SHD_mixRgb.c
index dba70253fda..2da1dee5623 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_mixRgb.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_mixRgb.c
@@ -60,6 +60,17 @@ static void node_shader_exec_mix_rgb(void *data, bNode *node, bNodeStack **in, b
VECCOPY(out[0]->vec, col);
}
+static int gpu_shader_mix_rgb(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ static char *names[] = {"mix_blend", "mix_add", "mix_mult", "mix_sub",
+ "mix_screen", "mix_div", "mix_diff", "mix_dark", "mix_light",
+ "mix_overlay", "mix_dodge", "mix_burn", "mix_hue", "mix_sat",
+ "mix_val", "mix_color"};
+
+ return GPU_stack_link(mat, names[node->custom1], in, out);
+}
+
+
bNodeType sh_node_mix_rgb= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_MIX_RGB,
@@ -74,6 +85,7 @@ bNodeType sh_node_mix_rgb= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_mix_rgb
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_normal.c b/source/blender/nodes/intern/SHD_nodes/SHD_normal.c
index f1ffd3446af..9d4ea1ccf67 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_normal.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_normal.c
@@ -57,6 +57,14 @@ static void node_shader_exec_normal(void *data, bNode *node, bNodeStack **in, bN
out[1]->vec[0]= -INPR(out[0]->vec, vec);
}
+static int gpu_shader_normal(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ bNodeSocket *sock= node->outputs.first;
+ GPUNodeLink *vec = GPU_uniform(sock->ns.vec);
+
+ return GPU_stack_link(mat, "normal", in, out, vec);
+}
+
bNodeType sh_node_normal= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_NORMAL,
@@ -71,6 +79,7 @@ bNodeType sh_node_normal= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_normal
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_output.c b/source/blender/nodes/intern/SHD_nodes/SHD_output.c
index 0a9a30c452b..76856cfd2e8 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_output.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_output.c
@@ -62,6 +62,19 @@ static void node_shader_exec_output(void *data, bNode *node, bNodeStack **in, bN
}
}
+static int gpu_shader_output(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ GPUNodeLink *outlink;
+
+ /*if(in[1].hasinput)
+ GPU_material_enable_alpha(mat);*/
+
+ GPU_stack_link(mat, "output_node", in, out, &outlink);
+ GPU_material_output_link(mat, outlink);
+
+ return 1;
+}
+
bNodeType sh_node_output= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_OUTPUT,
@@ -76,7 +89,8 @@ bNodeType sh_node_output= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_output
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_rgb.c b/source/blender/nodes/intern/SHD_nodes/SHD_rgb.c
index 4e56e26d3ad..1aa1a2ffc33 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_rgb.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_rgb.c
@@ -42,6 +42,14 @@ static void node_shader_exec_rgb(void *data, bNode *node, bNodeStack **in, bNode
VECCOPY(out[0]->vec, sock->ns.vec);
}
+static int gpu_shader_rgb(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ bNodeSocket *sock= node->outputs.first;
+ GPUNodeLink *vec = GPU_uniform(sock->ns.vec);
+
+ return GPU_stack_link(mat, "set_rgba", in, out, vec);
+}
+
bNodeType sh_node_rgb= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_RGB,
@@ -56,6 +64,7 @@ bNodeType sh_node_rgb= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_rgb
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_sepcombRGB.c b/source/blender/nodes/intern/SHD_nodes/SHD_sepcombRGB.c
index 2b52a8e2229..6d5df2a1321 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_sepcombRGB.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_sepcombRGB.c
@@ -48,6 +48,11 @@ static void node_shader_exec_seprgb(void *data, bNode *node, bNodeStack **in, bN
out[2]->vec[0] = in[0]->vec[2];
}
+static int gpu_shader_seprgb(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ return GPU_stack_link(mat, "separate_rgb", in, out);
+}
+
bNodeType sh_node_seprgb= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_SEPRGB,
@@ -62,7 +67,8 @@ bNodeType sh_node_seprgb= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_seprgb
};
@@ -86,6 +92,11 @@ static void node_shader_exec_combrgb(void *data, bNode *node, bNodeStack **in, b
out[0]->vec[2] = in[2]->vec[0];
}
+static int gpu_shader_combrgb(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ return GPU_stack_link(mat, "combine_rgb", in, out);
+}
+
bNodeType sh_node_combrgb= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_COMBRGB,
@@ -100,6 +111,7 @@ bNodeType sh_node_combrgb= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_combrgb
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_squeeze.c b/source/blender/nodes/intern/SHD_nodes/SHD_squeeze.c
index 30abad666c4..d3480a6ae9d 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_squeeze.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_squeeze.c
@@ -54,6 +54,11 @@ bNodeStack **out)
out[0]->vec[0] = 1.0f / (1.0f + pow(2.71828183,-((vec[0]-vec[2])*vec[1]))) ;
}
+static int gpu_shader_squeeze(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ return GPU_stack_link(mat, "squeeze", in, out);
+}
+
bNodeType sh_node_squeeze= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_SQUEEZE,
@@ -68,6 +73,7 @@ bNodeType sh_node_squeeze= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_squeeze
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_texture.c b/source/blender/nodes/intern/SHD_nodes/SHD_texture.c
index ace11a20d42..31dbde940fd 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_texture.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_texture.c
@@ -27,6 +27,8 @@
* ***** END GPL LICENSE BLOCK *****
*/
+#include "DNA_texture_types.h"
+
#include "../SHD_util.h"
/* **************** TEXTURE ******************** */
@@ -110,6 +112,18 @@ static void node_shader_exec_texture(void *data, bNode *node, bNodeStack **in, b
}
}
+static int gpu_shader_texture(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ Tex *tex = (Tex*)node->id;
+
+ if(tex && tex->type == TEX_IMAGE && tex->ima) {
+ GPUNodeLink *texlink = GPU_image(tex->ima, NULL);
+ return GPU_stack_link(mat, "texture_image", in, out, texlink);
+ }
+ else
+ return 0;
+}
+
bNodeType sh_node_texture= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_TEXTURE,
@@ -124,7 +138,8 @@ bNodeType sh_node_texture= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_texture
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_valToRgb.c b/source/blender/nodes/intern/SHD_nodes/SHD_valToRgb.c
index cf7e33d9dca..301c0cb7031 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_valToRgb.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_valToRgb.c
@@ -59,6 +59,15 @@ static void node_shader_init_valtorgb(bNode *node)
node->storage= add_colorband(1);
}
+static int gpu_shader_valtorgb(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ float *array;
+ int size;
+
+ colorband_table_RGBA(node->storage, &array, &size);
+ return GPU_stack_link(mat, "valtorgb", in, out, GPU_texture(size, array));
+}
+
bNodeType sh_node_valtorgb= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_VALTORGB,
@@ -73,7 +82,8 @@ bNodeType sh_node_valtorgb= {
/* initfunc */ node_shader_init_valtorgb,
/* freestoragefunc */ node_free_standard_storage,
/* copystoragefunc */ node_copy_standard_storage,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_valtorgb
};
@@ -96,6 +106,11 @@ static void node_shader_exec_rgbtobw(void *data, bNode *node, bNodeStack **in, b
out[0]->vec[0]= in[0]->vec[0]*0.35f + in[0]->vec[1]*0.45f + in[0]->vec[2]*0.2f;
}
+static int gpu_shader_rgbtobw(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ return GPU_stack_link(mat, "rgbtobw", in, out);
+}
+
bNodeType sh_node_rgbtobw= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_RGBTOBW,
@@ -110,7 +125,8 @@ bNodeType sh_node_rgbtobw= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_rgbtobw
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_value.c b/source/blender/nodes/intern/SHD_nodes/SHD_value.c
index 57ef7226066..768ef3cda3d 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_value.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_value.c
@@ -42,7 +42,13 @@ static void node_shader_exec_value(void *data, bNode *node, bNodeStack **in, bNo
out[0]->vec[0]= sock->ns.vec[0];
}
+static int gpu_shader_value(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ bNodeSocket *sock= node->outputs.first;
+ GPUNodeLink *vec = GPU_uniform(sock->ns.vec);
+ return GPU_stack_link(mat, "set_value", in, out, vec);
+}
bNodeType sh_node_value= {
/* *next,*prev */ NULL, NULL,
@@ -58,7 +64,8 @@ bNodeType sh_node_value= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_value
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_vectMath.c b/source/blender/nodes/intern/SHD_nodes/SHD_vectMath.c
index 8d0a4b3abe3..96db8db18a6 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_vectMath.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_vectMath.c
@@ -99,6 +99,34 @@ static void node_shader_exec_vect_math(void *data, bNode *node, bNodeStack **in,
}
+static int gpu_shader_vect_math(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ static char *names[] = {"vec_math_add", "vec_math_subtract",
+ "vec_math_average", "vec_math_dot", "vec_math_cross",
+ "vec_math_normalize"};
+
+ switch (node->custom1) {
+ case 0:
+ case 1:
+ case 2:
+ case 3:
+ case 4:
+ GPU_stack_link(mat, names[node->custom1], NULL, out,
+ GPU_socket(&in[0]), GPU_socket(&in[1]));
+ break;
+ case 5:
+ if(in[0].hasinput || !in[1].hasinput)
+ GPU_stack_link(mat, names[node->custom1], NULL, out, GPU_socket(&in[0]));
+ else
+ GPU_stack_link(mat, names[node->custom1], NULL, out, GPU_socket(&in[1]));
+ break;
+ default:
+ return 0;
+ }
+
+ return 1;
+}
+
bNodeType sh_node_vect_math= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_VECT_MATH,
@@ -113,6 +141,7 @@ bNodeType sh_node_vect_math= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_vect_math
};
diff --git a/source/blender/nodes/intern/SHD_util.c b/source/blender/nodes/intern/SHD_util.c
index c9f58fbce49..f673834d2b7 100644
--- a/source/blender/nodes/intern/SHD_util.c
+++ b/source/blender/nodes/intern/SHD_util.c
@@ -164,7 +164,7 @@ void nodeShaderSynchronizeID(bNode *node, int copyto)
case MAT_IN_MIR:
VECCOPY(&ma->mirr, sock->ns.vec); break;
case MAT_IN_AMB:
- VECCOPY(&ma->ambr, sock->ns.vec); break;
+ ma->amb= sock->ns.vec[0]; break;
case MAT_IN_EMIT:
ma->emit= sock->ns.vec[0]; break;
case MAT_IN_SPECTRA:
@@ -188,7 +188,7 @@ void nodeShaderSynchronizeID(bNode *node, int copyto)
case MAT_IN_MIR:
VECCOPY(sock->ns.vec, &ma->mirr); break;
case MAT_IN_AMB:
- VECCOPY(sock->ns.vec, &ma->ambr); break;
+ sock->ns.vec[0]= ma->amb; break;
case MAT_IN_EMIT:
sock->ns.vec[0]= ma->emit; break;
case MAT_IN_SPECTRA:
diff --git a/source/blender/nodes/intern/SHD_util.h b/source/blender/nodes/intern/SHD_util.h
index fcab420f3f2..0d9783fdd4b 100644
--- a/source/blender/nodes/intern/SHD_util.h
+++ b/source/blender/nodes/intern/SHD_util.h
@@ -72,6 +72,8 @@
#include "RE_pipeline.h"
#include "RE_shader_ext.h"
+#include "GPU_material.h"
+
//XXX #include "butspace.h"
//XXX #include "wm_event_types.h"
@@ -100,13 +102,12 @@ typedef struct ShaderCallData {
#define MAT_IN_REFL 2
#define MAT_IN_NORMAL 3
#define MAT_IN_MIR 4
-#define MAT_IN_AMBCOL 5
-#define MAT_IN_AMB 6
-#define MAT_IN_EMIT 7
-#define MAT_IN_SPECTRA 8
-#define MAT_IN_RAY_MIRROR 9
-#define MAT_IN_ALPHA 10
-#define MAT_IN_TRANSLUCENCY 11
+#define MAT_IN_AMB 5
+#define MAT_IN_EMIT 6
+#define MAT_IN_SPECTRA 7
+#define MAT_IN_RAY_MIRROR 8
+#define MAT_IN_ALPHA 9
+#define MAT_IN_TRANSLUCENCY 10
/* output socket defines */
#define MAT_OUT_COLOR 0
diff --git a/source/blender/python/BPY_extern.h b/source/blender/python/BPY_extern.h
index 8da2f126de0..1761ce14ed6 100644
--- a/source/blender/python/BPY_extern.h
+++ b/source/blender/python/BPY_extern.h
@@ -6,11 +6,7 @@
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
-<<<<<<< .mine
* of the License, or (at your option) any later version.
-=======
- * of the License, or (at your option) any later version.
->>>>>>> .r13159
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -35,6 +31,7 @@
#define BPY_EXTERN_H
extern char bprogname[]; /* holds a copy of argv[0], from creator.c */
+extern char btempdir[]; /* use this to store a valid temp directory */
struct Text; /* defined in DNA_text_types.h */
struct ID; /* DNA_ID.h */
@@ -44,13 +41,14 @@ struct ScriptLink; /* DNA_scriptlink_types.h */
struct ListBase; /* DNA_listBase.h */
struct SpaceText; /* DNA_space_types.h */
struct SpaceScript; /* DNA_space_types.h */
-struct Script; /* BPI_script.h */
struct ScrArea; /* DNA_screen_types.h */
struct bScreen; /* DNA_screen_types.h */
struct bConstraint; /* DNA_constraint_types.h */
struct bPythonConstraint; /* DNA_constraint_types.h */
struct bConstraintOb; /* DNA_constraint_types.h */
struct bConstraintTarget; /* DNA_constraint_types.h*/
+struct Script; /* DNA_screen_types.h */
+struct BPyMenu;
#ifdef __cplusplus
extern "C" {
#endif
@@ -79,24 +77,30 @@ extern "C" {
void BPY_pyconstraint_target(struct bPythonConstraint *con, struct bConstraintTarget *ct);
void BPY_pyconstraint_update(struct Object *owner, struct bConstraint *con);
int BPY_is_pyconstraint(struct Text *text);
+ void BPY_free_pyconstraint_links(struct Text *text);
void BPY_start_python( int argc, char **argv );
void BPY_end_python( void );
void BPY_post_start_python( void );
void init_syspath( int first_time );
void syspath_append( char *dir );
-
+ void BPY_rebuild_syspath( void );
+ int BPY_path_update( void );
+
int BPY_Err_getLinenumber( void );
const char *BPY_Err_getFilename( void );
int BPY_txt_do_python_Text( struct Text *text );
int BPY_menu_do_python( short menutype, int event );
- void BPY_run_python_script( char *filename );
+ int BPY_menu_do_shortcut( short menutype, unsigned short key, unsigned short modifiers );
+ int BPY_menu_invoke( struct BPyMenu *pym, short menutype );
+ void BPY_run_python_script( const char *filename );
+ int BPY_run_script(struct Script *script);
void BPY_free_compiled_text( struct Text *text );
void BPY_clear_bad_scriptlinks( struct Text *byebye );
int BPY_has_onload_script( void );
- void BPY_do_all_scripts( short event );
+ void BPY_do_all_scripts( short event, short anim );
int BPY_check_all_scriptlinks( struct Text *text );
void BPY_do_pyscript( struct ID *id, short event );
void BPY_free_scriptlink( struct ScriptLink *slink );
@@ -108,7 +112,7 @@ extern "C" {
int BPY_has_spacehandler(struct Text *text, struct ScrArea *sa);
void BPY_screen_free_spacehandlers(struct bScreen *sc);
int BPY_do_spacehandlers(struct ScrArea *sa, unsigned short event,
- unsigned short space_event);
+ short eventValue, unsigned short space_event);
void BPY_pydriver_update(void);
float BPY_pydriver_eval(struct IpoDriver *driver);
@@ -124,7 +128,10 @@ extern "C" {
unsigned short event, short val, char ascii );
void BPY_clear_script( struct Script *script );
void BPY_free_finished_script( struct Script *script );
-
+ void BPY_scripts_clear_pyobjects( void );
+
+ void error_pyscript( void );
+
/* void BPY_Err_Handle(struct Text *text); */
/* void BPY_clear_bad_scriptlink(struct ID *id, struct Text *byebye); */
/* void BPY_clear_bad_scriptlist(struct ListBase *, struct Text *byebye); */
diff --git a/source/blender/python/Makefile b/source/blender/python/Makefile
index d0eb6ddbae5..c830fbb3ccf 100644
--- a/source/blender/python/Makefile
+++ b/source/blender/python/Makefile
@@ -1,12 +1,12 @@
#
-# $Id: Makefile
+# $Id: Makefile 14444 2008-04-16 22:40:48Z hos $
#
# ***** BEGIN GPL LICENSE BLOCK *****
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
+# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
diff --git a/source/blender/quicktime/SConscript b/source/blender/quicktime/SConscript
index d9ab68251dd..49ecfc94a5d 100644
--- a/source/blender/quicktime/SConscript
+++ b/source/blender/quicktime/SConscript
@@ -2,7 +2,7 @@
Import ('env')
source_files = ['apple/quicktime_import.c',
- 'apple/quicktime_export.c']
+ 'apple/quicktime_export.c']
incs = ['.',
'../quicktime',
@@ -20,10 +20,10 @@ incs = ['.',
incs.append(env['BF_QUICKTIME_INC'])
if env['OURPLATFORM'] in ['win32-vc', 'darwin']:
- types = ['core', 'player']
- priorities = [115, 200]
+ types = ['core', 'player']
+ priorities = [115, 200]
else:
- types = ['core']
- priorities = [115]
+ types = ['core']
+ priorities = [115]
env.BlenderLib ('bf_quicktime', sources=source_files, includes=incs, defines=['WITH_QUICKTIME'], libtype=types, priority=priorities)
diff --git a/source/blender/quicktime/apple/quicktime_export.c b/source/blender/quicktime/apple/quicktime_export.c
index 06c5d9132bc..ca025a0b8a3 100644
--- a/source/blender/quicktime/apple/quicktime_export.c
+++ b/source/blender/quicktime/apple/quicktime_export.c
@@ -307,6 +307,7 @@ static void QT_EndCreateMyVideoTrack(void)
static void QT_StartAddVideoSamplesToMedia (const Rect *trackFrame, int rectx, int recty)
{
+ SCTemporalSettings gTemporalSettings;
OSErr err = noErr;
qtexport->ibuf = IMB_allocImBuf (rectx, recty, 32, IB_rect, 0);
@@ -325,7 +326,18 @@ static void QT_StartAddVideoSamplesToMedia (const Rect *trackFrame, int rectx, i
SCDefaultPixMapSettings (qtdata->theComponent, qtexport->thePixMap, true);
- SCSetInfo(qtdata->theComponent, scTemporalSettingsType, &qtdata->gTemporalSettings);
+ // workaround for crash with H.264, which requires an upgrade to
+ // the new callback based api for proper encoding, but that's not
+ // really compatible with rendering out frames sequentially
+ gTemporalSettings = qtdata->gTemporalSettings;
+ if(qtdata->gSpatialSettings.codecType == kH264CodecType) {
+ if(gTemporalSettings.temporalQuality != codecMinQuality) {
+ fprintf(stderr, "Only minimum quality compression supported for QuickTime H.264.\n");
+ gTemporalSettings.temporalQuality = codecMinQuality;
+ }
+ }
+
+ SCSetInfo(qtdata->theComponent, scTemporalSettingsType, &gTemporalSettings);
SCSetInfo(qtdata->theComponent, scSpatialSettingsType, &qtdata->gSpatialSettings);
SCSetInfo(qtdata->theComponent, scDataRateSettingsType, &qtdata->aDataRateSetting);
@@ -415,7 +427,7 @@ void makeqtstring (char *string) {
if (string==0) return;
strcpy(string, G.scene->r.pic);
- BLI_convertstringcode(string, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(string, G.sce);
BLI_make_existing_file(string);
@@ -569,13 +581,13 @@ static void check_renderbutton_framerate(void) {
CheckError( err, "SCSetInfo error" );
if(qtdata->gTemporalSettings.frameRate == 1571553) { // 23.98 fps
- qtdata->kVideoTimeScale = 2400;
+ qtdata->kVideoTimeScale = 24000;
qtdata->duration = 1001;
} else if (qtdata->gTemporalSettings.frameRate == 1964113) { // 29.97 fps
- qtdata->kVideoTimeScale = 3000;
+ qtdata->kVideoTimeScale = 30000;
qtdata->duration = 1001;
} else if (qtdata->gTemporalSettings.frameRate == 3928227) { // 59.94 fps
- qtdata->kVideoTimeScale = 6000;
+ qtdata->kVideoTimeScale = 60000;
qtdata->duration = 1001;
} else {
qtdata->kVideoTimeScale = (qtdata->gTemporalSettings.frameRate >> 16) * 100;
@@ -644,13 +656,13 @@ int get_qtcodec_settings(void)
G.scene->r.frs_sec = 24;
G.scene->r.frs_sec_base = 1.001;
} else if (qtdata->gTemporalSettings.frameRate == 1964113) { // 29.97 fps
- qtdata->kVideoTimeScale = 3000;
+ qtdata->kVideoTimeScale = 30000;
qtdata->duration = 1001;
G.scene->r.frs_sec = 30;
G.scene->r.frs_sec_base = 1.001;
} else if (qtdata->gTemporalSettings.frameRate == 3928227) { // 59.94 fps
- qtdata->kVideoTimeScale = 6000;
+ qtdata->kVideoTimeScale = 60000;
qtdata->duration = 1001;
G.scene->r.frs_sec = 60;
@@ -658,7 +670,7 @@ int get_qtcodec_settings(void)
} else {
double fps = qtdata->gTemporalSettings.frameRate;
- qtdata->kVideoTimeScale = 600;
+ qtdata->kVideoTimeScale = 60000;
qtdata->duration = qtdata->kVideoTimeScale / (qtdata->gTemporalSettings.frameRate / 65536);
if ((qtdata->gTemporalSettings.frameRate & 0xffff) == 0) {
diff --git a/source/blender/radiosity/CMakeLists.txt b/source/blender/radiosity/CMakeLists.txt
index 9ffa0e61d6a..e76f7409f99 100644
--- a/source/blender/radiosity/CMakeLists.txt
+++ b/source/blender/radiosity/CMakeLists.txt
@@ -27,9 +27,9 @@
FILE(GLOB SRC intern/source/*.c)
SET(INC
- extern/include ../blenlib ../blenkernel ../makesdna ../include
+ extern/include ../blenlib ../blenkernel ../makesdna ../editors/include
../../../intern/guardedalloc ../render/extern/include
- ../render/intern/include ../editors/include
+ ../render/intern/include ../blenloader ../../../extern/glew/include
)
BLENDERLIB_NOLIST(blender_radiosity "${SRC}" "${INC}")
diff --git a/source/blender/radiosity/SConscript b/source/blender/radiosity/SConscript
index 9939690b664..528b4e29c04 100644
--- a/source/blender/radiosity/SConscript
+++ b/source/blender/radiosity/SConscript
@@ -5,7 +5,7 @@ sources = env.Glob('intern/source/*.c')
incs = 'extern/include ../blenlib ../blenkernel ../makesdna ../editors/include'
incs += ' #/intern/guardedalloc ../render/extern/include'
-incs += ' ../render/intern/include'
+incs += ' ../render/intern/include ../blenloader #/extern/glew/include'
incs += ' ' + env['BF_OPENGL_INC']
diff --git a/source/blender/radiosity/intern/source/Makefile b/source/blender/radiosity/intern/source/Makefile
index bd4ebce742f..44b38de9bae 100644
--- a/source/blender/radiosity/intern/source/Makefile
+++ b/source/blender/radiosity/intern/source/Makefile
@@ -36,6 +36,7 @@ include nan_compile.mk
CFLAGS += $(LEVEL_1_C_WARNINGS)
+CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(OPENGL_HEADERS)
# not very neat....
@@ -44,6 +45,7 @@ CPPFLAGS += -I../../../blenlib
CPPFLAGS += -I../../../makesdna
CPPFLAGS += -I../../../imbuf
CPPFLAGS += -I../../../
+CPPFLAGS += -I../../../blenloader
CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include
# first /include is my own includes, second are the external includes
diff --git a/source/blender/radiosity/intern/source/radfactors.c b/source/blender/radiosity/intern/source/radfactors.c
index 0065d993b15..1a400ff57a8 100644
--- a/source/blender/radiosity/intern/source/radfactors.c
+++ b/source/blender/radiosity/intern/source/radfactors.c
@@ -51,9 +51,9 @@
#include "RE_render_ext.h" /* for `RE_zbufferall_radio and RE_zbufferall_radio */
/* locals */
-void rad_setmatrices(RadView *vw);
-void clearsubflagelem(RNode *rn);
-void setsubflagelem(RNode *rn);
+static void rad_setmatrices(RadView *vw);
+static void clearsubflagelem(RNode *rn);
+static void setsubflagelem(RNode *rn);
RadView hemitop, hemiside;
@@ -252,7 +252,7 @@ void rad_make_hocos(RadView *vw)
/* } */
}
-void rad_setmatrices(RadView *vw) /* for hemi's */
+static void rad_setmatrices(RadView *vw) /* for hemi's */
{
float up1[3], len, twist;
@@ -626,7 +626,7 @@ void minmaxradelemfilt(RNode *rn, float *min, float *max, float *errmin, float *
}
}
-void setsubflagelem(RNode *rn)
+static void setsubflagelem(RNode *rn)
{
if(rn->down1) {
@@ -638,7 +638,7 @@ void setsubflagelem(RNode *rn)
}
}
-void clearsubflagelem(RNode *rn)
+static void clearsubflagelem(RNode *rn)
{
if(rn->down1) {
@@ -739,11 +739,9 @@ void subdivideshootElements(int it)
}
}
if(rn) {
- min[0]= min[1]= min[2]= 1.0e10;
- max[0]= max[1]= max[2]= -1.0e10;
+ INIT_MINMAX(min, max);
/* errmin and max are the filtered colors */
- errmin[0]= errmin[1]= errmin[2]= 1.0e10;
- errmax[0]= errmax[1]= errmax[2]= -1.0e10;
+ INIT_MINMAX(errmin, errmax);
minmaxradelemfilt(rp->first, min, max, errmin, errmax);
/* if small difference between colors: no subdiv */
diff --git a/source/blender/radiosity/intern/source/radnode.c b/source/blender/radiosity/intern/source/radnode.c
index ca37d021639..fa23ca5da57 100644
--- a/source/blender/radiosity/intern/source/radnode.c
+++ b/source/blender/radiosity/intern/source/radnode.c
@@ -48,15 +48,17 @@
#include "radio.h"
+#include "BLO_sys_types.h" // for intptr_t support
+
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
/* locals */
-void *malloc_fast(int size);
-void *calloc_fast(int size);
-void free_fast(void *poin, int siz);
-void deleteTriNodes(RNode *node);
+static void *malloc_fast(int size);
+static void *calloc_fast(int size);
+static void free_fast(void *poin, int siz);
+static void deleteTriNodes(RNode *node);
/* lower because of local type define */
/* void check_mallocgroup(MallocGroup *mg); */
@@ -118,7 +120,7 @@ void check_mallocgroup(MallocGroup *mg)
printf("fastmalloc: shouldnt be here\n");
}
-void *malloc_fast(int size)
+static void *malloc_fast(int size)
{
MallocGroup *mg;
void *retval;
@@ -152,7 +154,7 @@ void *malloc_fast(int size)
return mg->data;
}
-void *calloc_fast(int size)
+static void *calloc_fast(int size)
{
void *poin;
@@ -162,17 +164,17 @@ void *calloc_fast(int size)
return poin;
}
-void free_fast(void *poin, int size)
+static void free_fast(void *poin, int size)
{
MallocGroup *mg;
- long val;
+ intptr_t val;
mg= MallocBase.last;
while(mg) {
if(mg->size==size) {
- if( ((long)poin) >= ((long)mg->data) ) {
- if( ((long)poin) < ((long)(mg->data+MAL_GROUPSIZE*size)) ) {
- val= ((long)poin) - ((long)mg->data);
+ if( ((intptr_t)poin) >= ((intptr_t)mg->data) ) {
+ if( ((intptr_t)poin) < ((intptr_t)(mg->data+MAL_GROUPSIZE*size)) ) {
+ val= ((intptr_t)poin) - ((intptr_t)mg->data);
val/= size;
mg->curfree= val;
mg->flags[val]= 0;
@@ -954,7 +956,7 @@ int comparelevel(RNode *node, RNode *nb, int level)
return 1;
}
-void deleteTriNodes(RNode *node) /* both children of node */
+static void deleteTriNodes(RNode *node) /* both children of node */
{
RNode *n1, *n2;
diff --git a/source/blender/radiosity/intern/source/radpreprocess.c b/source/blender/radiosity/intern/source/radpreprocess.c
index 345a5911ac8..eec75942da0 100644
--- a/source/blender/radiosity/intern/source/radpreprocess.c
+++ b/source/blender/radiosity/intern/source/radpreprocess.c
@@ -64,6 +64,8 @@
#include "radio.h"
+#include "BLO_sys_types.h" // for intptr_t support
+
void setparelem(RNode *rn, RPatch *par);
void splitconnected()
@@ -171,7 +173,7 @@ int vergedge(const void *v1,const void *v2)
void addedge(float *v1, float *v2, EdSort *es)
{
- if( ((long)v1)<((long)v2) ) {
+ if( ((intptr_t)v1)<((intptr_t)v2) ) {
es->v1= v1;
es->v2= v2;
}
@@ -279,7 +281,7 @@ void setedgepointers()
MEM_freeN(esblock);
}
-int materialIndex(Material *ma)
+static int materialIndex(Material *ma)
{
int i = 0;
for(i=0;i< RG.totmat; i++)
diff --git a/source/blender/radiosity/intern/source/radrender.c b/source/blender/radiosity/intern/source/radrender.c
index 9a97690de54..0233ffbcf9f 100644
--- a/source/blender/radiosity/intern/source/radrender.c
+++ b/source/blender/radiosity/intern/source/radrender.c
@@ -76,22 +76,23 @@ static float maxenergy;
/* find the face with maximum energy to become shooter */
/* nb: _rr means rad-render version of existing radio call */
-static VlakRen *findshoot_rr(Render *re)
+static void findshoot_rr(Render *re, VlakRen **shoot_p, RadFace **shootrf_p)
{
- RadFace *rf;
+ RadFace *rf, *shootrf, **radface;
ObjectRen *obr;
VlakRen *vlr=NULL, *shoot;
float energy;
int a;
shoot= NULL;
+ shootrf= NULL;
maxenergy= 0.0;
for(obr=re->objecttable.first; obr; obr=obr->next) {
for(a=0; a<obr->totvlak; a++) {
if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak; else vlr++;
- if(vlr->radface) {
- rf= vlr->radface;
+ if((radface=RE_vlakren_get_radface(obr, vlr, 0)) && *radface) {
+ rf= *radface;
rf->flag &= ~RAD_SHOOT;
energy= rf->unshot[0]*rf->area;
@@ -100,26 +101,32 @@ static VlakRen *findshoot_rr(Render *re)
if(energy>maxenergy) {
shoot= vlr;
+ shootrf= rf;
maxenergy= energy;
}
}
}
}
- if(shoot) {
+ if(shootrf) {
maxenergy/= RG.totenergy;
- if(maxenergy<RG.convergence) return NULL;
- shoot->radface->flag |= RAD_SHOOT;
+ if(maxenergy<RG.convergence) {
+ *shoot_p= NULL;
+ *shootrf_p= NULL;
+ return;
+ }
+ shootrf->flag |= RAD_SHOOT;
}
- return shoot;
+ *shoot_p= shoot;
+ *shootrf_p= shootrf;
}
-static void backface_test_rr(Render *re, VlakRen *shoot)
+static void backface_test_rr(Render *re, VlakRen *shoot, RadFace *shootrf)
{
ObjectRen *obr;
VlakRen *vlr=NULL;
- RadFace *rf;
+ RadFace *rf, **radface;
float tvec[3];
int a;
@@ -127,9 +134,9 @@ static void backface_test_rr(Render *re, VlakRen *shoot)
for(obr=re->objecttable.first; obr; obr=obr->next) {
for(a=0; a<obr->totvlak; a++) {
if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak; else vlr++;
- if(vlr->radface && vlr!=shoot) {
- rf= vlr->radface;
- VecSubf(tvec, shoot->radface->cent, rf->cent);
+ if(vlr != shoot && (radface=RE_vlakren_get_radface(obr, vlr, 0)) && *radface) {
+ rf= *radface;
+ VecSubf(tvec, shootrf->cent, rf->cent);
if(tvec[0]*rf->norm[0]+ tvec[1]*rf->norm[1]+ tvec[2]*rf->norm[2] < 0.0)
rf->flag |= RAD_BACKFACE;
@@ -142,7 +149,7 @@ static void clear_backface_test_rr(Render *re)
{
ObjectRen *obr;
VlakRen *vlr=NULL;
- RadFace *rf;
+ RadFace *rf, **radface;
int a;
/* backface flag clear */
@@ -150,8 +157,8 @@ static void clear_backface_test_rr(Render *re)
for(a=0; a<obr->totvlak; a++) {
if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak; else vlr++;
- if(vlr->radface) {
- rf= vlr->radface;
+ if((radface=RE_vlakren_get_radface(obr, vlr, 0)) && *radface) {
+ rf= *radface;
rf->flag &= ~RAD_BACKFACE;
}
}
@@ -161,11 +168,11 @@ static void clear_backface_test_rr(Render *re)
extern RadView hemitop, hemiside; // radfactors.c
/* hemi-zbuffering, delivers formfactors array */
-static void makeformfactors_rr(Render *re, VlakRen *shoot)
+static void makeformfactors_rr(Render *re, VlakRen *shoot, RadFace *shootrf)
{
ObjectRen *obr;
VlakRen *vlr=NULL;
- RadFace *rf;
+ RadFace *rf, **radface;
float len, vec[3], up[3], side[3], tar[5][3], *fp;
int a;
@@ -174,25 +181,25 @@ static void makeformfactors_rr(Render *re, VlakRen *shoot)
/* set up hemiview */
/* first: upvector for hemitop, we use diagonal hemicubes to prevent aliasing */
- VecSubf(vec, shoot->v1->co, shoot->radface->cent);
- Crossf(up, shoot->radface->norm, vec);
+ VecSubf(vec, shoot->v1->co, shootrf->cent);
+ Crossf(up, shootrf->norm, vec);
len= Normalize(up);
VECCOPY(hemitop.up, up);
- VECCOPY(hemiside.up, shoot->radface->norm);
+ VECCOPY(hemiside.up, shootrf->norm);
- Crossf(side, shoot->radface->norm, up);
+ Crossf(side, shootrf->norm, up);
/* five targets */
- VecAddf(tar[0], shoot->radface->cent, shoot->radface->norm);
- VecAddf(tar[1], shoot->radface->cent, up);
- VecSubf(tar[2], shoot->radface->cent, up);
- VecAddf(tar[3], shoot->radface->cent, side);
- VecSubf(tar[4], shoot->radface->cent, side);
+ VecAddf(tar[0], shootrf->cent, shootrf->norm);
+ VecAddf(tar[1], shootrf->cent, up);
+ VecSubf(tar[2], shootrf->cent, up);
+ VecAddf(tar[3], shootrf->cent, side);
+ VecSubf(tar[4], shootrf->cent, side);
/* camera */
- VECCOPY(hemiside.cam, shoot->radface->cent);
- VECCOPY(hemitop.cam, shoot->radface->cent);
+ VECCOPY(hemiside.cam, shootrf->cent);
+ VECCOPY(hemitop.cam, shootrf->cent);
/* do it! */
VECCOPY(hemitop.tar, tar[0]);
@@ -210,10 +217,10 @@ static void makeformfactors_rr(Render *re, VlakRen *shoot)
for(a=0; a<obr->totvlak; a++) {
if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak; else vlr++;
- if(vlr->radface) {
- rf= vlr->radface;
+ if((radface=RE_vlakren_get_radface(obr, vlr, 0)) && *radface) {
+ rf= *radface;
if(*fp!=0.0 && rf->area!=0.0) {
- *fp *= shoot->radface->area/rf->area;
+ *fp *= shootrf->area/rf->area;
if(*fp>1.0) *fp= 1.0001;
}
fp++;
@@ -223,17 +230,17 @@ static void makeformfactors_rr(Render *re, VlakRen *shoot)
}
/* based at RG.formfactors array, distribute shoot energy over other faces */
-static void applyformfactors_rr(Render *re, VlakRen *shoot)
+static void applyformfactors_rr(Render *re, VlakRen *shoot, RadFace *shootrf)
{
ObjectRen *obr;
VlakRen *vlr=NULL;
- RadFace *rf;
+ RadFace *rf, **radface;
float *fp, *ref, unr, ung, unb, r, g, b;
int a;
- unr= shoot->radface->unshot[0];
- ung= shoot->radface->unshot[1];
- unb= shoot->radface->unshot[2];
+ unr= shootrf->unshot[0];
+ ung= shootrf->unshot[1];
+ unb= shootrf->unshot[2];
fp= RG.formfactors;
@@ -241,8 +248,8 @@ static void applyformfactors_rr(Render *re, VlakRen *shoot)
for(a=0; a<obr->totvlak; a++) {
if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak; else vlr++;
- if(vlr->radface) {
- rf= vlr->radface;
+ if((radface=RE_vlakren_get_radface(obr, vlr, 0)) && *radface) {
+ rf= *radface;
if(*fp!= 0.0) {
ref= &(vlr->mat->r);
@@ -266,7 +273,7 @@ static void applyformfactors_rr(Render *re, VlakRen *shoot)
}
}
/* shoot energy has been shot */
- shoot->radface->unshot[0]= shoot->radface->unshot[1]= shoot->radface->unshot[2]= 0.0;
+ shootrf->unshot[0]= shootrf->unshot[1]= shootrf->unshot[2]= 0.0;
}
@@ -274,29 +281,30 @@ static void applyformfactors_rr(Render *re, VlakRen *shoot)
static void progressiverad_rr(Render *re)
{
VlakRen *shoot;
+ RadFace *shootrf;
float unshot[3];
int it= 0;
- shoot= findshoot_rr(re);
+ findshoot_rr(re, &shoot, &shootrf);
while( shoot ) {
/* backfaces receive no energy, but are zbuffered... */
- backface_test_rr(re, shoot);
+ backface_test_rr(re, shoot, shootrf);
/* ...unless it's two sided */
- if(shoot->radface->flag & RAD_TWOSIDED) {
- VECCOPY(unshot, shoot->radface->unshot);
- VecMulf(shoot->radface->norm, -1.0);
- makeformfactors_rr(re, shoot);
- applyformfactors_rr(re, shoot);
- VecMulf(shoot->radface->norm, -1.0);
- VECCOPY(shoot->radface->unshot, unshot);
+ if(shootrf->flag & RAD_TWOSIDED) {
+ VECCOPY(unshot, shootrf->unshot);
+ VecMulf(shootrf->norm, -1.0);
+ makeformfactors_rr(re, shoot, shootrf);
+ applyformfactors_rr(re, shoot, shootrf);
+ VecMulf(shootrf->norm, -1.0);
+ VECCOPY(shootrf->unshot, unshot);
}
/* hemi-zbuffers */
- makeformfactors_rr(re, shoot);
+ makeformfactors_rr(re, shoot, shootrf);
/* based at RG.formfactors array, distribute shoot energy over other faces */
- applyformfactors_rr(re, shoot);
+ applyformfactors_rr(re, shoot, shootrf);
it++;
re->timecursor(it);
@@ -306,7 +314,7 @@ static void progressiverad_rr(Render *re)
if(re->test_break()) break;
if(RG.maxiter && RG.maxiter<=it) break;
- shoot= findshoot_rr(re);
+ findshoot_rr(re, &shoot, &shootrf);
}
printf(" Unshot energy:%f\n", 1000.0*maxenergy);
@@ -319,7 +327,7 @@ static void initradfaces(Render *re)
{
ObjectRen *obr;
VlakRen *vlr= NULL;
- RadFace *rf;
+ RadFace *rf, **radface;
int a, b;
/* globals */
@@ -356,9 +364,18 @@ printf(" Rad elems: %d emittors %d\n", RG.totelem, RG.totpatch);
if(vlr->mat->mode & MA_RADIO) {
/* during render, vlr->n gets flipped/corrected, we cannot have that */
- if(vlr->v4) CalcNormFloat4(vlr->v1->co, vlr->v2->co, vlr->v3->co, vlr->v4->co, rf->norm);
- else CalcNormFloat(vlr->v1->co, vlr->v2->co, vlr->v3->co, rf->norm);
-
+ if (obr->ob->transflag & OB_NEG_SCALE){
+ /* The object has negative scale that will cause the normals to flip.
+ To counter this unwanted normal flip, swap vertex 2 and 4 for a quad
+ or vertex 2 and 3 (see flip_face) for a triangle in the call to CalcNormFloat4
+ in order to flip the normals back to the way they were in the original mesh. */
+ if(vlr->v4) CalcNormFloat4(vlr->v1->co, vlr->v4->co, vlr->v3->co, vlr->v2->co, rf->norm);
+ else CalcNormFloat(vlr->v1->co, vlr->v3->co, vlr->v2->co, rf->norm);
+ }else{
+ if(vlr->v4) CalcNormFloat4(vlr->v1->co, vlr->v2->co, vlr->v3->co, vlr->v4->co, rf->norm);
+ else CalcNormFloat(vlr->v1->co, vlr->v2->co, vlr->v3->co, rf->norm);
+ }
+
rf->totrad[0]= vlr->mat->emit*vlr->mat->r;
rf->totrad[1]= vlr->mat->emit*vlr->mat->g;
rf->totrad[2]= vlr->mat->emit*vlr->mat->b;
@@ -385,7 +402,8 @@ printf(" Rad elems: %d emittors %d\n", RG.totelem, RG.totpatch);
// uncommented; this isnt satisfying, but i leave it in the code for now (ton)
// if(vlr->mat->translucency!=0.0) rf->flag |= RAD_TWOSIDED;
- vlr->radface= rf++;
+ radface=RE_vlakren_get_radface(obr, vlr, 1);
+ *radface= rf++;
}
}
}
@@ -420,7 +438,7 @@ static void make_vertex_rad_values(Render *re)
ObjectRen *obr;
VertRen *v1=NULL;
VlakRen *vlr=NULL;
- RadFace *rf;
+ RadFace *rf, **radface;
float *col;
int a;
@@ -432,8 +450,8 @@ static void make_vertex_rad_values(Render *re)
for(a=0; a<obr->totvlak; a++) {
if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak; else vlr++;
- if(vlr->radface) {
- rf= vlr->radface;
+ if((radface=RE_vlakren_get_radface(obr, vlr, 0)) && *radface) {
+ rf= *radface;
/* apply correction */
rf->totrad[0]= RG.radfactor*pow( rf->totrad[0], RG.igamma);
diff --git a/source/blender/readblenfile/intern/BLO_readblenfile.c b/source/blender/readblenfile/intern/BLO_readblenfile.c
index 6e5bf149c7a..ec71611b31d 100644
--- a/source/blender/readblenfile/intern/BLO_readblenfile.c
+++ b/source/blender/readblenfile/intern/BLO_readblenfile.c
@@ -159,7 +159,7 @@ blo_read_runtime(
} else {
//printf("starting to read runtime from %s at datastart %d\n", path, datastart);
lseek(fd, datastart, SEEK_SET);
- bfd = blo_read_blendafterruntime(fd, actualsize-datastart, error_r);
+ bfd = blo_read_blendafterruntime(fd, path, actualsize-datastart, error_r);
fd= -1; // file was closed in blo_read_blendafterruntime()
}
diff --git a/source/blender/render/CMakeLists.txt b/source/blender/render/CMakeLists.txt
index b543dff49ff..0b659554d1a 100644
--- a/source/blender/render/CMakeLists.txt
+++ b/source/blender/render/CMakeLists.txt
@@ -29,7 +29,7 @@ FILE(GLOB SRC intern/source/*.c)
SET(INC
intern/include ../../../intern/guardedalloc ../blenlib ../makesdna
extern/include ../blenkernel ../radiosity/extern/include ../imbuf
- ../quicktime ../include ../../kernel/gen_messaging ../yafray
+ ../quicktime ../include ../../kernel/gen_messaging ../yafray ../blenloader
)
IF(WITH_OPENEXR)
diff --git a/source/blender/render/SConscript b/source/blender/render/SConscript
index d06331a5b48..7f799a78834 100644
--- a/source/blender/render/SConscript
+++ b/source/blender/render/SConscript
@@ -6,26 +6,26 @@ sources = env.Glob('intern/source/*.c')
incs = 'intern/include #/intern/guardedalloc ../blenlib ../makesdna'
incs += ' extern/include ../blenkernel ../radiosity/extern/include ../imbuf'
-incs += ' ../quicktime ../editors/include ../../kernel/gen_messaging'
+incs += ' ../include ../blenloader'
defs = []
-if env['WITH_BF_YAFRAY'] == 1:
- incs += ' ../yafray'
+if env['WITH_BF_YAFRAY']:
+ incs += ' ../yafray'
else:
- defs.append('DISABLE_YAFRAY')
+ defs.append('DISABLE_YAFRAY')
-if env['WITH_BF_QUICKTIME'] == 1:
- defs.append('WITH_QUICKTIME')
- incs += ' ' + env['BF_QUICKTIME_INC']
+if env['WITH_BF_QUICKTIME']:
+ defs.append('WITH_QUICKTIME')
+ incs += ' ../quicktime ' + env['BF_QUICKTIME_INC']
-if env['WITH_BF_FFMPEG'] == 1:
- defs.append('WITH_FFMPEG')
+if env['WITH_BF_FFMPEG']:
+ defs.append('WITH_FFMPEG')
if env['WITH_BF_OPENEXR']:
- defs.append('WITH_OPENEXR')
+ defs.append('WITH_OPENEXR')
if env['OURPLATFORM']=='linux2':
- cflags='-pthread'
+ cflags='-pthread'
env.BlenderLib ( libname = 'bf_render', sources = sources, includes = Split(incs), defines=defs, libtype='core', priority=55, compileflags=cflags )
diff --git a/source/blender/render/extern/include/RE_pipeline.h b/source/blender/render/extern/include/RE_pipeline.h
index d202ea1eed5..60557403143 100644
--- a/source/blender/render/extern/include/RE_pipeline.h
+++ b/source/blender/render/extern/include/RE_pipeline.h
@@ -38,6 +38,7 @@ struct Scene;
struct RenderData;
struct NodeBlurData;
struct Object;
+struct bNodeTree;
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* this include is what is exposed of render to outside world */
@@ -73,7 +74,7 @@ typedef struct RenderLayer {
/* copy of RenderData */
char name[RE_MAXNAME];
- unsigned int lay;
+ unsigned int lay, lay_zmask;
int layflag, passflag, pass_xor;
struct Material *mat_override;
@@ -88,10 +89,11 @@ typedef struct RenderLayer {
} RenderLayer;
typedef struct RenderResult {
+ struct RenderResult *next, *prev;
/* target image size */
int rectx, recty;
- short crop, pad;
+ short crop, sample_nr;
/* optional, 32 bits version of picture, used for ogl render and image curves */
int *rect32;
@@ -113,7 +115,6 @@ typedef struct RenderResult {
volatile RenderLayer *renlay;
/* optional saved endresult on disk */
- char exrfile[FILE_MAXDIR];
void *exrhandle;
/* for render results in Image, verify validity for sequences */
@@ -121,6 +122,7 @@ typedef struct RenderResult {
} RenderResult;
+
typedef struct RenderStats {
int totface, totvert, totstrand, tothalo, totlamp, totpart;
short curfield, curblur, curpart, partsdone, convertdone;
@@ -151,7 +153,7 @@ struct RenderLayer *RE_GetRenderLayer(struct RenderResult *rr, const char *name)
float *RE_RenderLayerGetPass(struct RenderLayer *rl, int passtype);
/* obligatory initialize call, disprect is optional */
-void RE_InitState (struct Render *re, struct RenderData *rd, int winx, int winy, rcti *disprect);
+void RE_InitState (struct Render *re, struct Render *source, struct RenderData *rd, int winx, int winy, rcti *disprect);
/* use this to change disprect of active render */
void RE_SetDispRect (struct Render *re, rcti *disprect);
@@ -175,17 +177,23 @@ void RE_DataBase_ApplyWindow(struct Render *re);
/* override the scene setting for amount threads, commandline */
void RE_set_max_threads(int threads);
+/* set the render threads based on the commandline and autothreads setting */
+void RE_init_threadcount(Render *re);
+
/* the main processor, assumes all was set OK! */
void RE_TileProcessor(struct Render *re, int firsttile, int threaded);
/* only RE_NewRender() needed, main Blender render calls */
void RE_BlenderFrame(struct Render *re, struct Scene *scene, int frame);
-void RE_BlenderAnim(struct Render *re, struct Scene *scene, int sfra, int efra);
+void RE_BlenderAnim(struct Render *re, struct Scene *scene, int sfra, int efra, int tfra);
void RE_ReadRenderResult(struct Scene *scene, struct Scene *scenode);
void RE_WriteRenderResult(RenderResult *rr, char *filename, int compress);
struct RenderResult *RE_MultilayerConvert(void *exrhandle, int rectx, int recty);
+/* do a full sample buffer compo */
+void RE_MergeFullSample(struct Render *re, struct Scene *sce, struct bNodeTree *ntree);
+
/* ancient stars function... go away! */
void RE_make_stars(struct Render *re, void (*initfunc)(void),
void (*vertexfunc)(float*), void (*termfunc)(void));
@@ -206,11 +214,14 @@ float RE_filter_value(int type, float x);
void RE_zbuf_accumulate_vecblur(struct NodeBlurData *nbd, int xsize, int ysize, float *newrect, float *imgrect, float *vecbufrect, float *zbufrect);
/* shaded view or baking options */
-#define RE_BAKE_LIGHT 0
-#define RE_BAKE_ALL 1
-#define RE_BAKE_AO 2
-#define RE_BAKE_NORMALS 3
-#define RE_BAKE_TEXTURE 4
+#define RE_BAKE_LIGHT 0
+#define RE_BAKE_ALL 1
+#define RE_BAKE_AO 2
+#define RE_BAKE_NORMALS 3
+#define RE_BAKE_TEXTURE 4
+#define RE_BAKE_DISPLACEMENT 5
+#define RE_BAKE_SHADOW 6
+
void RE_Database_Baking(struct Render *re, struct Scene *scene, int type, struct Object *actob);
void RE_DataBase_GetView(struct Render *re, float mat[][4]);
diff --git a/source/blender/render/extern/include/RE_raytrace.h b/source/blender/render/extern/include/RE_raytrace.h
index 39bf2be4256..8f429f7dd90 100644
--- a/source/blender/render/extern/include/RE_raytrace.h
+++ b/source/blender/render/extern/include/RE_raytrace.h
@@ -70,7 +70,7 @@ typedef struct Isect {
int ob_last;
short isect; /* which half of quad */
- short mode; /* RE_RAYSHADOW, RE_RAYMIRROR, RE_RAYSHADOW_TRA */
+ short mode; /* RE_RAY_SHADOW, RE_RAY_MIRROR, RE_RAY_SHADOW_TRA */
int lay; /* -1 default, set for layer lamps */
/* only used externally */
@@ -89,7 +89,7 @@ typedef struct Isect {
/* function callbacks for face type abstraction */
typedef void (*RayCoordsFunc)(RayFace *face,
float **v1, float **v2, float **v3, float **v4);
-typedef int (*RayCheckFunc)(Isect *is, RayFace *face);
+typedef int (*RayCheckFunc)(Isect *is, int ob, RayFace *face);
typedef float *(*RayObjectTransformFunc)(void *userdata, int ob);
/* tree building and freeing */
diff --git a/source/blender/render/extern/include/RE_shader_ext.h b/source/blender/render/extern/include/RE_shader_ext.h
index 5b81052f5d2..888474ffa18 100644
--- a/source/blender/render/extern/include/RE_shader_ext.h
+++ b/source/blender/render/extern/include/RE_shader_ext.h
@@ -47,7 +47,7 @@ typedef struct ShadeResult
{
float combined[4];
float col[4];
- float alpha;
+ float alpha, mist, z;
float diff[3]; /* no ramps, shadow, etc */
float spec[3];
float shad[3];
@@ -64,6 +64,7 @@ struct ShadeInputCopy {
struct Material *mat;
struct VlakRen *vlr;
+ struct StrandRen *strand;
struct ObjectInstanceRen *obi;
struct ObjectRen *obr;
int facenr;
@@ -96,6 +97,7 @@ typedef struct ShadeInput
struct Material *mat;
struct VlakRen *vlr;
+ struct StrandRen *strand;
struct ObjectInstanceRen *obi;
struct ObjectRen *obr;
int facenr;
@@ -132,7 +134,8 @@ typedef struct ShadeInput
/* texture coordinates */
float lo[3], gl[3], ref[3], orn[3], winco[3], sticky[3], vcol[4], rad[3];
float refcol[4], displace[3];
- float strand, tang[3], stress, winspeed[4];
+ float strandco, tang[3], nmaptang[3], stress, winspeed[4];
+ float duplilo[3], dupliuv[3];
ShadeInputUV uv[8]; /* 8 = MAX_MTFACE */
ShadeInputCol col[8]; /* 8 = MAX_MCOL */
@@ -154,6 +157,8 @@ typedef struct ShadeInput
int xs, ys; /* pixel to be rendered */
int mask; /* subsample mask */
+ float scanco[3]; /* original scanline coordinate without jitter */
+
int samplenr; /* sample counter, to detect if we should do shadow again */
int depth; /* 1 or larger on raytrace shading */
@@ -166,6 +171,7 @@ typedef struct ShadeInput
/* from initialize, part or renderlayer */
short do_preview; /* for nodes, in previewrender */
short thread, sample; /* sample: ShadeSample array index */
+
unsigned int lay;
int layflag, passflag, combinedflag;
struct Group *light_override;
diff --git a/source/blender/render/intern/include/occlusion.h b/source/blender/render/intern/include/occlusion.h
new file mode 100644
index 00000000000..646ad30b318
--- /dev/null
+++ b/source/blender/render/intern/include/occlusion.h
@@ -0,0 +1,49 @@
+/*
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2008 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Brecht Van Lommel.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef OCCLUSION_H
+#define OCCLUSION_H
+
+struct Render;
+struct ShadeInput;
+struct ShadeResult;
+struct RenderPart;
+struct ShadeSample;
+struct DerivedMesh;
+struct ObjectRen;
+
+void make_occ_tree(struct Render *re);
+void free_occ(struct Render *re);
+void sample_occ(struct Render *re, struct ShadeInput *shi);
+
+void cache_occ_samples(struct Render *re, struct RenderPart *pa, struct ShadeSample *ssamp);
+void free_occ_samples(struct Render *re, struct RenderPart *pa);
+
+#endif
+
diff --git a/source/blender/render/intern/include/pixelblending.h b/source/blender/render/intern/include/pixelblending.h
index 04c5a3977a3..f7f4bc76eae 100644
--- a/source/blender/render/intern/include/pixelblending.h
+++ b/source/blender/render/intern/include/pixelblending.h
@@ -35,6 +35,8 @@
*/
void add_filt_fmask(unsigned int mask, float *col, float *rowbuf, int row_w);
void add_filt_fmask_pixsize(unsigned int mask, float *in, float *rowbuf, int row_w, int pixsize);
+void add_filt_fmask_coord(float filt[][3], float *col, float *rowbuf, int row_w, int col_h, int x, int y);
+void mask_array(unsigned int mask, float filt[][3]);
/**
* Alpha-over blending for floats.
diff --git a/source/blender/render/intern/include/pixelshading.h b/source/blender/render/intern/include/pixelshading.h
index d2235784a59..c6b11b4af9a 100644
--- a/source/blender/render/intern/include/pixelshading.h
+++ b/source/blender/render/intern/include/pixelshading.h
@@ -45,7 +45,7 @@
* mask is pixel coverage in bits
* @return pointer to the object
*/
-void shadeHaloFloat(HaloRen *har,
+int shadeHaloFloat(HaloRen *har,
float *col, int zz,
float dist, float xn,
float yn, short flarec);
@@ -55,7 +55,8 @@ void shadeHaloFloat(HaloRen *har,
*/
void shadeSkyPixel(float *collector, float fx, float fy);
void shadeSkyView(float *colf, float *rco, float *view, float *dxyview);
-
+void shadeAtmPixel(struct SunSky *sunsky, float *collector, float fx, float fy, float distance);
+void shadeSunView(float *colf, float *view);
/* ------------------------------------------------------------------------- */
#endif
diff --git a/source/blender/render/intern/include/render_types.h b/source/blender/render/intern/include/render_types.h
index 7fbbd0f5abc..1768b052b54 100644
--- a/source/blender/render/intern/include/render_types.h
+++ b/source/blender/render/intern/include/render_types.h
@@ -42,6 +42,9 @@
#include "RE_pipeline.h"
#include "RE_shader_ext.h" /* TexResult, ShadeResult, ShadeInput */
+#include "sunsky.h"
+
+#include "BLO_sys_types.h" // for intptr_t support
struct Object;
struct MemArena;
@@ -64,8 +67,10 @@ typedef struct SampleTables
typedef struct QMCSampler
{
+ struct QMCSampler *next, *prev;
int type;
int tot;
+ int used;
double *samp2d;
double offs[BLENDER_MAX_THREADS][2];
} QMCSampler;
@@ -79,17 +84,18 @@ typedef struct RenderPart
{
struct RenderPart *next, *prev;
- /* result of part rendering */
- RenderResult *result;
+ RenderResult *result; /* result of part rendering */
+ ListBase fullresult; /* optional full sample buffers */
int *recto; /* object table for objects */
int *rectp; /* polygon index table */
int *rectz; /* zbuffer */
- long *rectdaps; /* delta acum buffer for pixel structs */
+ int *rectmask; /* negative zmask */
+ intptr_t *rectdaps; /* delta acum buffer for pixel structs */
int *rectbacko; /* object table for backside sss */
int *rectbackp; /* polygon index table for backside sss */
int *rectbackz; /* zbuffer for backside sss */
- long *rectall; /* buffer for all faces for sss */
+ intptr_t *rectall; /* buffer for all faces for sss */
rcti disprect; /* part coordinates within total picture */
int rectx, recty; /* the size */
@@ -113,6 +119,8 @@ struct Render
RenderResult *result;
/* if render with single-layer option, other rendered layers are stored here */
RenderResult *pushedresult;
+ /* a list of RenderResults, for fullsample */
+ ListBase fullresult;
/* window size, display rect, viewplane */
int winx, winy;
@@ -147,7 +155,10 @@ struct Render
/* samples */
SampleTables *samples;
float jit[32][2];
- QMCSampler *qsa;
+ ListBase *qmcsamplers;
+
+ /* shadow counter, detect shadow-reuse for shaders */
+ int shadowsamplenr[BLENDER_MAX_THREADS];
/* scene, and its full copy of renderdata and world */
Scene *scene;
@@ -158,6 +169,10 @@ struct Render
/* octree tables and variables for raytrace */
void *raytree;
+
+ /* occlusion tree */
+ void *occlusiontree;
+ ListBase strandsurface;
/* use this instead of R.r.cfra */
float cfra;
@@ -170,11 +185,9 @@ struct Render
ListBase lampren; /* storage, for free */
ListBase objecttable;
- struct RenderBuckets *strandbuckets;
struct ObjectInstanceRen *objectinstance;
ListBase instancetable;
- struct GHash *objecthash;
int totinstance;
struct Image *backbuf, *bakebuf;
@@ -215,7 +228,7 @@ struct ISBData;
typedef struct ShadSampleBuf {
struct ShadSampleBuf *next, *prev;
- long *zbuf;
+ intptr_t *zbuf;
char *cbuf;
} ShadSampleBuf;
@@ -241,7 +254,9 @@ typedef struct ObjectRen {
struct ObjectRen *next, *prev;
struct Object *ob, *par;
struct Scene *sce;
- int index, psysindex;
+ int index, psysindex, flag, lay;
+
+ float boundbox[2][3];
int totvert, totvlak, totstrand, tothalo;
int vertnodeslen, vlaknodeslen, strandnodeslen, blohalen;
@@ -249,11 +264,13 @@ typedef struct ObjectRen {
struct VlakTableNode *vlaknodes;
struct StrandTableNode *strandnodes;
struct HaloRen **bloha;
- ListBase strandbufs;
+ struct StrandBuffer *strandbuf;
char (*mtface)[32];
char (*mcol)[32];
- int actmtface, actmcol;
+ int actmtface, actmcol, bakemtface;
+
+ float obmat[4][4]; /* only used in convertblender.c, for instancing */
} ObjectRen;
typedef struct ObjectInstanceRen {
@@ -261,11 +278,14 @@ typedef struct ObjectInstanceRen {
ObjectRen *obr;
Object *ob, *par;
- int index, psysindex;
+ int index, psysindex, lay;
- float mat[4][4], imat[3][3];
+ float mat[4][4], nmat[3][3]; /* nmat is inverse mat tranposed */
short flag;
+ float dupliorco[3], dupliuv[2];
+ float (*duplitexmat)[4];
+
float *vectors;
int totvector;
} ObjectInstanceRen;
@@ -302,13 +322,10 @@ typedef struct RadFace {
typedef struct VlakRen {
struct VertRen *v1, *v2, *v3, *v4; /* keep in order for ** addressing */
- unsigned int lay;
float n[3];
struct Material *mat;
char puno;
char flag, ec;
- RadFace *radface;
- ObjectRen *obr;
int index;
} VlakRen;
@@ -328,22 +345,43 @@ typedef struct HaloRen
struct Material *mat;
} HaloRen;
+/* ------------------------------------------------------------------------- */
+
typedef struct StrandVert {
float co[3];
float strandco;
} StrandVert;
+typedef struct StrandSurface {
+ struct StrandSurface *next, *prev;
+ ObjectRen obr;
+ int (*face)[4];
+ float (*co)[3];
+ /* for occlusion caching */
+ float (*col)[3];
+ /* for speedvectors */
+ float (*prevco)[3], (*nextco)[3];
+ int totvert, totface;
+} StrandSurface;
+
+typedef struct StrandBound {
+ int start, end;
+ float boundbox[2][3];
+} StrandBound;
+
typedef struct StrandBuffer {
struct StrandBuffer *next, *prev;
struct StrandVert *vert;
- int totvert;
+ struct StrandBound *bound;
+ int totvert, totbound;
struct ObjectRen *obr;
struct Material *ma;
+ struct StrandSurface *surface;
unsigned int lay;
int overrideuv;
int flag, maxdepth;
- float adaptcos, minwidth;
+ float adaptcos, minwidth, widthfade;
float winmat[4][4];
int winx, winy;
@@ -380,8 +418,10 @@ typedef struct LampRen {
float xs, ys, dist;
float co[3];
- short type, mode;
+ short type;
+ int mode;
float r, g, b, k;
+ float shdwr, shdwg, shdwb;
float energy, haint;
int lay;
float spotsi,spotbl;
@@ -420,9 +460,11 @@ typedef struct LampRen {
float area_size, area_sizey, area_sizez;
float adapt_thresh;
+ /* sun/sky */
+ struct SunSky *sunsky;
+
struct ShadBuf *shb;
float *jitter;
- QMCSampler *qsa;
float imat[3][3];
float spottexfac;
@@ -463,6 +505,9 @@ typedef struct LampRen {
#define R_LAMPHALO 8
#define R_GLOB_NOPUNOFLIP 16
#define R_NEED_TANGENT 32
+#define R_SKIP_MULTIRES 64
+#define R_BAKE_TRACE 128
+#define R_BAKING 256
/* vlakren->flag (vlak = face in dutch) char!!! */
#define R_SMOOTH 1
@@ -481,10 +526,14 @@ typedef struct LampRen {
#define R_STRAND_BSPLINE 1
#define R_STRAND_B_UNITS 2
+/* objectren->flag */
+#define R_INSTANCEABLE 1
+
/* objectinstance->flag */
#define R_DUPLI_TRANSFORMED 1
#define R_ENV_TRANSFORMED 2
#define R_TRANSFORMED (1|2)
+#define R_NEED_VECTORS 4
#endif /* RENDER_TYPES_H */
diff --git a/source/blender/render/intern/include/rendercore.h b/source/blender/render/intern/include/rendercore.h
index ab009a980a5..4b28529a147 100644
--- a/source/blender/render/intern/include/rendercore.h
+++ b/source/blender/render/intern/include/rendercore.h
@@ -37,8 +37,8 @@
/* vector defines */
-#define CROSS(dest, a, b) dest[0]= a[1] * b[2] - a[2] * b[1]; dest[1]= a[2] * b[0] - a[0] * b[2]; dest[2]= a[0] * b[1] - a[1] * b[0]
-#define VECMUL(dest, f) dest[0]*= f; dest[1]*= f; dest[2]*= f
+#define CROSS(dest, a, b) { dest[0]= a[1] * b[2] - a[2] * b[1]; dest[1]= a[2] * b[0] - a[0] * b[2]; dest[2]= a[0] * b[1] - a[1] * b[0]; }
+#define VECMUL(dest, f) { dest[0]*= f; dest[1]*= f; dest[2]*= f; }
struct HaloRen;
struct ShadeInput;
@@ -47,13 +47,14 @@ struct World;
struct RenderPart;
struct RenderLayer;
struct ObjectRen;
+struct ListBase;
/* ------------------------------------------------------------------------- */
typedef struct PixStr
{
struct PixStr *next;
- int obi, facenr, z;
+ int obi, facenr, z, maskz;
unsigned short mask;
short shadfac;
} PixStr;
@@ -87,6 +88,9 @@ void zbufshadeDA_tile(struct RenderPart *pa);
void zbufshade_sss_tile(struct RenderPart *pa);
+int get_sample_layers(struct RenderPart *pa, struct RenderLayer *rl, struct RenderLayer **rlpp);
+
+
/* -------- ray.c ------- */
extern void freeraytree(Render *re);
@@ -97,9 +101,7 @@ extern void ray_trace(ShadeInput *, ShadeResult *);
extern void ray_ao(ShadeInput *, float *);
extern void init_jitter_plane(LampRen *lar);
extern void init_ao_sphere(struct World *wrld);
-extern void init_lamp_hammersley(LampRen *lar);
-extern void free_lamp_qmcsampler(LampRen *lar);
-extern void init_render_hammersley(Render *re);
+extern void init_render_qmcsampler(Render *re);
extern void free_render_qmcsampler(Render *re);
#endif /* RENDER_EXT_H */
diff --git a/source/blender/render/intern/include/renderdatabase.h b/source/blender/render/intern/include/renderdatabase.h
index c919a54008e..dc28eae1cc2 100644
--- a/source/blender/render/intern/include/renderdatabase.h
+++ b/source/blender/render/intern/include/renderdatabase.h
@@ -42,6 +42,7 @@ struct CustomData;
struct StrandBuffer;
struct StrandRen;
struct ObjectInstanceRen;
+struct RadFace;
#define RE_QUAD_MASK 0x7FFFFFF
#define RE_QUAD_OFFS 0x8000000
@@ -63,6 +64,8 @@ typedef struct VlakTableNode {
struct MCol *mcol;
int totmtface, totmcol;
float *surfnor;
+ float *tangent;
+ struct RadFace **radface;
} VlakTableNode;
typedef struct StrandTableNode {
@@ -70,6 +73,7 @@ typedef struct StrandTableNode {
float *winspeed;
float *surfnor;
float *simplify;
+ int *face;
struct MCol *mcol;
float *uv;
int totuv, totmcol;
@@ -82,6 +86,7 @@ void free_renderdata_vlaknodes(struct VlakTableNode *vlaknodes);
void set_normalflags(struct Render *re, struct ObjectRen *obr);
void project_renderdata(struct Render *re, void (*projectfunc)(float *, float mat[][4], float *), int do_pano, float xoffs, int do_buckets);
+int clip_render_object(float boundbox[][3], float *bounds, float mat[][4]);
/* functions are not exported... so wrong names */
@@ -93,8 +98,8 @@ struct HaloRen *RE_inithalo(struct Render *re, struct ObjectRen *obr, struct Mat
struct HaloRen *RE_inithalo_particle(struct Render *re, struct ObjectRen *obr, struct DerivedMesh *dm, struct Material *ma, float *vec, float *vec1, float *orco, float *uvco, float hasize, float vectsize, int seed);
struct StrandBuffer *RE_addStrandBuffer(struct ObjectRen *obr, int totvert);
-struct ObjectRen *RE_addRenderObject(struct Render *re, struct Object *ob, struct Object *par, int index, int psysindex);
-void RE_addRenderInstance(struct Render *re, struct ObjectRen *obr, struct Object *ob, struct Object *par, int index, int psysindex, float mat[][4]);
+struct ObjectRen *RE_addRenderObject(struct Render *re, struct Object *ob, struct Object *par, int index, int psysindex, int lay);
+struct ObjectInstanceRen *RE_addRenderInstance(struct Render *re, struct ObjectRen *obr, struct Object *ob, struct Object *par, int index, int psysindex, float mat[][4], int lay);
void RE_makeRenderInstances(struct Render *re);
void RE_instanceTransformNormal(struct ObjectInstanceRen *obi, float *nor, float *tnor);
@@ -108,12 +113,15 @@ float *RE_vertren_get_winspeed(struct ObjectInstanceRen *obi, struct VertRen *ve
struct MTFace *RE_vlakren_get_tface(struct ObjectRen *obr, VlakRen *ren, int n, char **name, int verify);
struct MCol *RE_vlakren_get_mcol(struct ObjectRen *obr, VlakRen *ren, int n, char **name, int verify);
float *RE_vlakren_get_surfnor(struct ObjectRen *obr, VlakRen *ren, int verify);
+float *RE_vlakren_get_nmap_tangent(struct ObjectRen *obr, VlakRen *ren, int verify);
+RadFace **RE_vlakren_get_radface(struct ObjectRen *obr, VlakRen *ren, int verify);
int RE_vlakren_get_normal(struct Render *re, struct ObjectInstanceRen *obi, struct VlakRen *vlr, float *nor);
float *RE_strandren_get_surfnor(struct ObjectRen *obr, struct StrandRen *strand, int verify);
float *RE_strandren_get_uv(struct ObjectRen *obr, struct StrandRen *strand, int n, char **name, int verify);
struct MCol *RE_strandren_get_mcol(struct ObjectRen *obr, struct StrandRen *strand, int n, char **name, int verify);
float *RE_strandren_get_simplify(struct ObjectRen *obr, struct StrandRen *strand, int verify);
+int *RE_strandren_get_face(struct ObjectRen *obr, struct StrandRen *strand, int verify);
float *RE_strandren_get_winspeed(struct ObjectInstanceRen *obi, struct StrandRen *strand, int verify);
struct VertRen *RE_vertren_copy(struct ObjectRen *obr, struct VertRen *ver);
diff --git a/source/blender/render/intern/include/shadbuf.h b/source/blender/render/intern/include/shadbuf.h
index a96baab8294..7015b4bc1bf 100644
--- a/source/blender/render/intern/include/shadbuf.h
+++ b/source/blender/render/intern/include/shadbuf.h
@@ -54,7 +54,7 @@ void threaded_makeshadowbufs(struct Render *re);
* @param inp The inproduct between viewvector and ?
*
*/
-float testshadowbuf(struct ShadBuf *shb, float *rco, float *dxco, float *dyco, float inp);
+float testshadowbuf(struct Render *re, struct ShadBuf *shb, float *rco, float *dxco, float *dyco, float inp, float mat_bias);
/**
* Determines the shadow factor for lamp <lar>, between <p1>
diff --git a/source/blender/render/intern/include/shading.h b/source/blender/render/intern/include/shading.h
index 6ca63a2976d..54311d2515a 100644
--- a/source/blender/render/intern/include/shading.h
+++ b/source/blender/render/intern/include/shading.h
@@ -40,13 +40,13 @@ struct ObjectInstanceRen obi;
/* needed to calculate shadow and AO for an entire pixel */
typedef struct ShadeSample {
- int tot; /* amount of shi in use, can be 1 for not FULL_OSA */
+ int tot; /* amount of shi in use, can be 1 for not FULL_OSA */
+
+ RenderLayer *rlpp[RE_MAX_OSA]; /* fast lookup from sample to renderlayer (fullsample buf) */
/* could be malloced once */
ShadeInput shi[RE_MAX_OSA];
ShadeResult shr[RE_MAX_OSA];
-
- int samplenr; /* counter, detect shadow-reuse for shaders */
} ShadeSample;
@@ -56,7 +56,8 @@ void shade_material_loop(struct ShadeInput *shi, struct ShadeResult *shr);
void shade_input_set_triangle_i(struct ShadeInput *shi, struct ObjectInstanceRen *obi, struct VlakRen *vlr, short i1, short i2, short i3);
void shade_input_set_triangle(struct ShadeInput *shi, volatile int obi, volatile int facenr, int normal_flip);
void shade_input_copy_triangle(struct ShadeInput *shi, struct ShadeInput *from);
-void shade_input_set_viewco(struct ShadeInput *shi, float x, float y, float z);
+void shade_input_calc_viewco(struct ShadeInput *shi, float x, float y, float z, float *view, float *dxyview, float *co, float *dxco, float *dyco);
+void shade_input_set_viewco(struct ShadeInput *shi, float x, float y, float sx, float sy, float z);
void shade_input_set_uv(struct ShadeInput *shi);
void shade_input_set_normals(struct ShadeInput *shi);
void shade_input_flip_normals(struct ShadeInput *shi);
@@ -69,6 +70,7 @@ void shade_input_initialize(struct ShadeInput *shi, struct RenderPart *pa, struc
void shade_sample_initialize(struct ShadeSample *ssamp, struct RenderPart *pa, struct RenderLayer *rl);
void shade_samples_do_AO(struct ShadeSample *ssamp);
+void shade_samples_fill_with_ps(struct ShadeSample *ssamp, struct PixStr *ps, int x, int y);
int shade_samples(struct ShadeSample *ssamp, struct PixStr *ps, int x, int y);
void vlr_set_uv_indices(struct VlakRen *vlr, int *i1, int *i2, int *i3);
diff --git a/source/blender/render/intern/include/sss.h b/source/blender/render/intern/include/sss.h
index 660fb544227..9ffdcaf206a 100644
--- a/source/blender/render/intern/include/sss.h
+++ b/source/blender/render/intern/include/sss.h
@@ -59,7 +59,7 @@ void sss_add_points(Render *re, float (*co)[3], float (*color)[3], float *area,
void free_sss(struct Render *re);
int sample_sss(struct Render *re, struct Material *mat, float *co, float *col);
-int has_sss_tree(struct Render *re, struct Material *mat);
+int sss_pass_done(struct Render *re, struct Material *mat);
#endif /*SSS_H*/
diff --git a/source/blender/render/intern/include/strand.h b/source/blender/render/intern/include/strand.h
index c6ec72125ad..09988125830 100644
--- a/source/blender/render/intern/include/strand.h
+++ b/source/blender/render/intern/include/strand.h
@@ -41,6 +41,9 @@ struct RenderBuckets;
struct RenderPrimitiveIterator;
struct ZSpan;
struct ObjectInstanceRen;
+struct StrandSurface;
+struct DerivedMesh;
+struct ObjectRen;
typedef struct StrandPoint {
/* position within segment */
@@ -61,6 +64,7 @@ typedef struct StrandPoint {
float co1[3], co2[3];
float hoco1[4], hoco2[4];
float zco1[3], zco2[3];
+ int clip1, clip2;
/* screen space */
float hoco[4];
@@ -81,9 +85,20 @@ typedef struct StrandSegment {
int shaded;
} StrandSegment;
+struct StrandShadeCache;
+typedef struct StrandShadeCache StrandShadeCache;
+
void strand_eval_point(StrandSegment *sseg, StrandPoint *spoint);
-void render_strand_segment(struct Render *re, float winmat[][4], struct StrandPart *spart, struct ZSpan *zspan, StrandSegment *sseg);
-void project_strands(Render *re, void (*projectfunc)(float *, float mat[][4], float *), int do_pano, int do_buckets);
+void render_strand_segment(struct Render *re, float winmat[][4], struct StrandPart *spart, struct ZSpan *zspan, int totzspan, StrandSegment *sseg);
+void strand_minmax(struct StrandRen *strand, float *min, float *max);
+
+struct StrandSurface *cache_strand_surface(struct Render *re, struct ObjectRen *obr, struct DerivedMesh *dm, float mat[][4], int timeoffset);
+void free_strand_surface(struct Render *re);
+
+struct StrandShadeCache *strand_shade_cache_create(void);
+void strand_shade_cache_free(struct StrandShadeCache *cache);
+void strand_shade_segment(struct Render *re, struct StrandShadeCache *cache, struct StrandSegment *sseg, struct ShadeSample *ssamp, float t, float s, int addpassflag);
+void strand_shade_unref(struct StrandShadeCache *cache, struct StrandVert *svert);
struct RenderBuckets *init_buckets(struct Render *re);
void add_buckets_primitive(struct RenderBuckets *buckets, float *min, float *max, void *prim);
diff --git a/source/blender/render/intern/include/sunsky.h b/source/blender/render/intern/include/sunsky.h
new file mode 100644
index 00000000000..f61338bcf27
--- /dev/null
+++ b/source/blender/render/intern/include/sunsky.h
@@ -0,0 +1,144 @@
+ /**
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * Contributor(s): zaghaghi
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+/**
+ * This feature comes from Preetham paper on "A Practical Analytic Model for Daylight"
+ * and example code from Brian Smits, another author of that paper in
+ * http://www.cs.utah.edu/vissim/papers/sunsky/code/
+ * */
+#ifndef SUNSKY_H_
+#define SUNSKY_H_
+
+#define SPECTRUM_MAX_COMPONENTS 100
+#define SPECTRUM_START 350.0
+#define SPECTRUM_END 800.0
+
+typedef struct SunSky
+{
+ short effect_type, skyblendtype, sky_colorspace;
+ float turbidity;
+ float theta, phi;
+
+ float toSun[3];
+
+ /*float sunSpectralRaddata[SPECTRUM_MAX_COMPONENTS];*/
+ float sunSolidAngle;
+
+ float zenith_Y, zenith_x, zenith_y;
+
+ float perez_Y[5], perez_x[5], perez_y[5];
+
+ /* suggested by glome in
+ * http://projects.blender.org/tracker/?func=detail&atid=127&aid=8063&group_id=9*/
+ float horizon_brightness;
+ float spread;
+ float sun_brightness;
+ float sun_size;
+ float backscattered_light;
+ float skyblendfac;
+ float sky_exposure;
+
+ float atm_HGg;
+
+ float atm_SunIntensity;
+ float atm_InscatteringMultiplier;
+ float atm_ExtinctionMultiplier;
+ float atm_BetaRayMultiplier;
+ float atm_BetaMieMultiplier;
+ float atm_DistanceMultiplier;
+
+ float atm_BetaRay[3];
+ float atm_BetaDashRay[3];
+ float atm_BetaMie[3];
+ float atm_BetaDashMie[3];
+ float atm_BetaRM[3];
+}SunSky;
+
+/**
+ * InitSunSky:
+ * this function compute some sun,sky parameters according to input parameters and also initiate some other sun, sky parameters
+ * parameters:
+ * sunSky, is a structure that contains informtion about sun, sky and atmosphere, in this function, most of its values initiated
+ * turb, is atmosphere turbidity
+ * toSun, contains sun direction
+ * horizon_brighness, controls the brightness of the horizon colors
+ * spread, controls colors spreed at horizon
+ * sun_brightness, controls sun's brightness
+ * sun_size, controls sun's size
+ * back_scatter, controls back scatter light
+ * */
+void InitSunSky(struct SunSky *sunsky, float turb, float *toSun, float horizon_brightness,
+ float spread,float sun_brightness, float sun_size, float back_scatter,
+ float skyblendfac, short skyblendtype, float sky_exposure, float sky_colorspace);
+
+/**
+ * GetSkyXYZRadiance:
+ * this function compute sky radiance according to a view parameters `theta' and `phi'and sunSky values
+ * parameters:
+ * sunSky, sontains sun and sky parameters
+ * theta, is sun's theta
+ * phi, is sun's phi
+ * color_out, is computed color that shows sky radiance in XYZ color format
+ * */
+void GetSkyXYZRadiance(struct SunSky* sunsky, float theta, float phi, float color_out[3]);
+
+/**
+ * GetSkyXYZRadiancef:
+ * this function compute sky radiance according to a view direction `varg' and sunSky values
+ * parameters:
+ * sunSky, sontains sun and sky parameters
+ * varg, shows direction
+ * color_out, is computed color that shows sky radiance in XYZ color format
+ * */
+void GetSkyXYZRadiancef(struct SunSky* sunsky, const float varg[3], float color_out[3]);
+
+/**
+ * InitAtmosphere:
+ * this function intiate sunSky structure with user input parameters.
+ * parameters:
+ * sunSky, contains information about sun, and in this function some atmosphere parameters will initiated
+ * sun_intens, shows sun intensity value
+ * mief, Mie scattering factor this factor currently call with 1.0
+ * rayf, Rayleigh scattering factor, this factor currently call with 1.0
+ * inscattf, inscatter light factor that range from 0.0 to 1.0, 0.0 means no inscatter light and 1.0 means full inscatter light
+ * extincf, extinction light factor that range from 0.0 to 1.0, 0.0 means no extinction and 1.0 means full extinction
+ * disf, is distance factor, multiplyed to pixle's z value to compute each pixle's distance to camera,
+ * */
+void InitAtmosphere(struct SunSky *sunSky, float sun_intens, float mief, float rayf, float inscattf, float extincf, float disf);
+
+/**
+ * AtmospherePixleShader:
+ * this function apply atmosphere effect on a pixle color `rgb' at distance `s'
+ * parameters:
+ * sunSky, contains information about sun parameters and user values
+ * view, is camera view vector
+ * s, is distance
+ * rgb, contains rendered color value for a pixle
+ * */
+void AtmospherePixleShader( struct SunSky* sunSky, float view[3], float s, float rgb[3]);
+
+/**
+ * ClipColor:
+ * clip a color to range [0,1];
+ * */
+void ClipColor(float c[3]);
+
+#endif /*SUNSKY_H_*/
diff --git a/source/blender/render/intern/include/texture.h b/source/blender/render/intern/include/texture.h
index 8e56c4a852f..be5471e07c4 100644
--- a/source/blender/render/intern/include/texture.h
+++ b/source/blender/render/intern/include/texture.h
@@ -55,7 +55,7 @@ struct ImBuf;
void do_halo_tex(struct HaloRen *har, float xn, float yn, float *colf);
void do_sky_tex(float *rco, float *lo, float *dxyview, float *hor, float *zen, float *blend, int skyflag);
void do_material_tex(struct ShadeInput *shi);
-void do_lamp_tex(LampRen *la, float *lavec, struct ShadeInput *shi, float *colf);
+void do_lamp_tex(LampRen *la, float *lavec, struct ShadeInput *shi, float *colf, int effect);
void init_render_textures(Render *re);
diff --git a/source/blender/render/intern/include/zbuf.h b/source/blender/render/intern/include/zbuf.h
index 4d30c1e0dfb..b6d0c656f63 100644
--- a/source/blender/render/intern/include/zbuf.h
+++ b/source/blender/render/intern/include/zbuf.h
@@ -36,6 +36,8 @@ struct LampRen;
struct VlakRen;
struct ListBase;
struct ZSpan;
+struct APixstrand;
+struct StrandShadeCache;
void fillrect(int *rect, int x, int y, int val);
@@ -48,12 +50,11 @@ void projectverto(float *v1, float winmat[][4], float *adr);
int testclip(float *v);
void zbuffer_shadow(struct Render *re, float winmat[][4], struct LampRen *lar, int *rectz, int size, float jitx, float jity);
-void zbuffer_solid(struct RenderPart *pa, unsigned int layer, short layflag, void (*fillfunc)(struct RenderPart*, struct ZSpan*, int, void*), void *data);
+void zbuffer_solid(struct RenderPart *pa, struct RenderLayer *rl, void (*fillfunc)(struct RenderPart*, struct ZSpan*, int, void*), void *data);
-unsigned short *zbuffer_transp_shade(struct RenderPart *pa, struct RenderLayer *rl, float *pass);
-unsigned short *zbuffer_strands_shade(struct Render *re, struct RenderPart *pa, struct RenderLayer *rl, float *pass);
-void convert_zbuf_to_distbuf(struct RenderPart *pa, struct RenderLayer *rl);
+unsigned short *zbuffer_transp_shade(struct RenderPart *pa, struct RenderLayer *rl, float *pass, struct ListBase *psmlist);
void zbuffer_sss(RenderPart *pa, unsigned int lay, void *handle, void (*func)(void*, int, int, int, int, int));
+int zbuffer_strands_abuf(struct Render *re, struct RenderPart *pa, struct RenderLayer *rl, struct APixstrand *apixbuf, struct ListBase *apsmbase, struct StrandShadeCache *cache);
typedef struct APixstr {
unsigned short mask[4]; /* jitter mask */
@@ -64,10 +65,20 @@ typedef struct APixstr {
struct APixstr *next;
} APixstr;
+typedef struct APixstrand {
+ unsigned short mask[4]; /* jitter mask */
+ int z[4]; /* distance */
+ int p[4]; /* index */
+ int obi[4]; /* object instance */
+ int seg[4]; /* for strands, segment number */
+ float u[4], v[4]; /* for strands, u,v coordinate in segment */
+ struct APixstrand *next;
+} APixstrand;
+
typedef struct APixstrMain
{
struct APixstrMain *next, *prev;
- struct APixstr *ps;
+ void *ps;
} APixstrMain;
/* span fill in method, is also used to localize data for zbuffering */
@@ -84,12 +95,15 @@ typedef struct ZSpan {
int *rectz1; /* seconday z buffer for shadowbuffer (2nd closest z) */
int *rectp; /* polygon index buffer */
int *recto; /* object buffer */
+ int *rectmask; /* negative zmask buffer */
APixstr *apixbuf, *curpstr; /* apixbuf for transparent */
+ APixstrand *curpstrand; /* same for strands */
struct ListBase *apsmbase;
int polygon_offset; /* offset in Z */
float shad_alpha; /* copy from material, used by irregular shadbuf */
int mask, apsmcounter; /* in use by apixbuf */
+ int apstrandmcounter;
float clipcrop; /* for shadow, was in R global before */
diff --git a/source/blender/render/intern/source/convertblender.c b/source/blender/render/intern/source/convertblender.c
index d8ad518da14..a9bc2131d77 100644
--- a/source/blender/render/intern/source/convertblender.c
+++ b/source/blender/render/intern/source/convertblender.c
@@ -54,6 +54,7 @@
#include "DNA_meshdata_types.h"
#include "DNA_meta_types.h"
#include "DNA_modifier_types.h"
+#include "DNA_node_types.h"
#include "DNA_object_types.h"
#include "DNA_object_force.h"
#include "DNA_object_fluidsim.h"
@@ -99,6 +100,7 @@
#include "envmap.h"
//XXX #include "multires.h"
+#include "occlusion.h"
#include "render_types.h"
#include "rendercore.h"
#include "renderdatabase.h"
@@ -106,9 +108,12 @@
#include "radio.h"
#include "shadbuf.h"
#include "shading.h"
+#include "strand.h"
#include "texture.h"
#include "sss.h"
+#include "strand.h"
#include "zbuf.h"
+#include "sunsky.h"
#ifndef DISABLE_YAFRAY /* disable yafray */
@@ -198,6 +203,7 @@ void RE_make_stars(Render *re, void (*initfunc)(void),
else stargrid *= 1.0; /* then it draws fewer */
if(re) MTC_Mat4Invert(mat, re->viewmat);
+ else MTC_Mat4One(mat);
/* BOUNDING BOX CALCULATION
* bbox goes from z = loc_near_var | loc_far_var,
@@ -228,7 +234,7 @@ void RE_make_stars(Render *re, void (*initfunc)(void),
}
if(re) /* add render object for stars */
- obr= RE_addRenderObject(re, NULL, NULL, 0, 0);
+ obr= RE_addRenderObject(re, NULL, NULL, 0, 0, 0);
for (x = sx, fx = sx * stargrid; x <= ex; x++, fx += stargrid) {
for (y = sy, fy = sy * stargrid; y <= ey ; y++, fy += stargrid) {
@@ -447,34 +453,8 @@ static void calc_edge_stress(Render *re, ObjectRen *obr, Mesh *me)
MEM_freeN(accum);
}
-void tangent_from_uv(float *uv1, float *uv2, float *uv3, float *co1, float *co2, float *co3, float *n, float *tang)
-{
- float tangv[3], ct[3], e1[3], e2[3], s1, t1, s2, t2, det;
-
- s1= uv2[0] - uv1[0];
- s2= uv3[0] - uv1[0];
- t1= uv2[1] - uv1[1];
- t2= uv3[1] - uv1[1];
- det= 1.0f / (s1 * t2 - s2 * t1);
-
- /* normals in render are inversed... */
- VecSubf(e1, co1, co2);
- VecSubf(e2, co1, co3);
- tang[0] = (t2*e1[0] - t1*e2[0])*det;
- tang[1] = (t2*e1[1] - t1*e2[1])*det;
- tang[2] = (t2*e1[2] - t1*e2[2])*det;
- tangv[0] = (s1*e2[0] - s2*e1[0])*det;
- tangv[1] = (s1*e2[1] - s2*e1[1])*det;
- tangv[2] = (s1*e2[2] - s2*e1[2])*det;
- Crossf(ct, tang, tangv);
-
- /* check flip */
- if ((ct[0]*n[0] + ct[1]*n[1] + ct[2]*n[2]) < 0.0f)
- VecMulf(tang, -1.0f);
-}
-
/* gets tangent from tface or orco */
-static void calc_tangent_vector(ObjectRen *obr, VlakRen *vlr)
+static void calc_tangent_vector(ObjectRen *obr, VertexTangent **vtangents, MemArena *arena, VlakRen *vlr, int do_nmap_tangent, int do_tangent)
{
MTFace *tface= RE_vlakren_get_tface(obr, vlr, obr->actmtface, NULL, 0);
VertRen *v1=vlr->v1, *v2=vlr->v2, *v3=vlr->v3, *v4=vlr->v4;
@@ -500,30 +480,55 @@ static void calc_tangent_vector(ObjectRen *obr, VlakRen *vlr)
tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, vlr->n, tang);
- tav= RE_vertren_get_tangent(obr, v1, 1);
- VECADD(tav, tav, tang);
- tav= RE_vertren_get_tangent(obr, v2, 1);
- VECADD(tav, tav, tang);
- tav= RE_vertren_get_tangent(obr, v3, 1);
- VECADD(tav, tav, tang);
-
- if(v4) {
- tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, vlr->n, tang);
-
+ if(do_tangent) {
tav= RE_vertren_get_tangent(obr, v1, 1);
VECADD(tav, tav, tang);
- tav= RE_vertren_get_tangent(obr, v3, 1);
+ tav= RE_vertren_get_tangent(obr, v2, 1);
VECADD(tav, tav, tang);
- tav= RE_vertren_get_tangent(obr, v4, 1);
+ tav= RE_vertren_get_tangent(obr, v3, 1);
VECADD(tav, tav, tang);
}
+
+ if(do_nmap_tangent) {
+ sum_or_add_vertex_tangent(arena, &vtangents[v1->index], tang, uv1);
+ sum_or_add_vertex_tangent(arena, &vtangents[v2->index], tang, uv2);
+ sum_or_add_vertex_tangent(arena, &vtangents[v3->index], tang, uv3);
+ }
+
+ if(v4) {
+ tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, vlr->n, tang);
+
+ if(do_tangent) {
+ tav= RE_vertren_get_tangent(obr, v1, 1);
+ VECADD(tav, tav, tang);
+ tav= RE_vertren_get_tangent(obr, v3, 1);
+ VECADD(tav, tav, tang);
+ tav= RE_vertren_get_tangent(obr, v4, 1);
+ VECADD(tav, tav, tang);
+ }
+
+ if(do_nmap_tangent) {
+ sum_or_add_vertex_tangent(arena, &vtangents[v1->index], tang, uv1);
+ sum_or_add_vertex_tangent(arena, &vtangents[v3->index], tang, uv3);
+ sum_or_add_vertex_tangent(arena, &vtangents[v4->index], tang, uv4);
+ }
+ }
}
-static void calc_vertexnormals(Render *re, ObjectRen *obr, int do_tangent)
+static void calc_vertexnormals(Render *re, ObjectRen *obr, int do_tangent, int do_nmap_tangent)
{
+ MemArena *arena= NULL;
+ VertexTangent **vtangents= NULL;
int a;
+ if(do_nmap_tangent) {
+ arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
+ BLI_memarena_use_calloc(arena);
+
+ vtangents= MEM_callocN(sizeof(VertexTangent*)*obr->totvert, "VertexTangent");
+ }
+
/* clear all vertex normals */
for(a=0; a<obr->totvert; a++) {
VertRen *ver= RE_findOrAddVert(obr, a);
@@ -596,10 +601,10 @@ static void calc_vertexnormals(Render *re, ObjectRen *obr, int do_tangent)
v3->n[2] +=fac3*vlr->n[2];
}
- if(do_tangent) {
+ if(do_nmap_tangent || do_tangent) {
/* tangents still need to be calculated for flat faces too */
/* weighting removed, they are not vertexnormals */
- calc_tangent_vector(obr, vlr);
+ calc_tangent_vector(obr, vtangents, arena, vlr, do_nmap_tangent, do_tangent);
}
}
@@ -618,6 +623,30 @@ static void calc_vertexnormals(Render *re, ObjectRen *obr, int do_tangent)
if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
}
}
+
+ if(do_nmap_tangent) {
+ VertRen *v1=vlr->v1, *v2=vlr->v2, *v3=vlr->v3, *v4=vlr->v4;
+ MTFace *tface= RE_vlakren_get_tface(obr, vlr, obr->actmtface, NULL, 0);
+
+ if(tface) {
+ float *vtang, *ftang= RE_vlakren_get_nmap_tangent(obr, vlr, 1);
+
+ vtang= find_vertex_tangent(vtangents[v1->index], tface->uv[0]);
+ VECCOPY(ftang, vtang);
+ Normalize(ftang);
+ vtang= find_vertex_tangent(vtangents[v2->index], tface->uv[1]);
+ VECCOPY(ftang+3, vtang);
+ Normalize(ftang+3);
+ vtang= find_vertex_tangent(vtangents[v3->index], tface->uv[2]);
+ VECCOPY(ftang+6, vtang);
+ Normalize(ftang+6);
+ if(v4) {
+ vtang= find_vertex_tangent(vtangents[v4->index], tface->uv[3]);
+ VECCOPY(ftang+9, vtang);
+ Normalize(ftang+9);
+ }
+ }
+ }
}
/* normalize vertex normals */
@@ -636,94 +665,12 @@ static void calc_vertexnormals(Render *re, ObjectRen *obr, int do_tangent)
}
}
}
-}
-// NT same as calc_vertexnormals, but dont modify the existing vertex normals
-// only recalculate other render data. If this is at some point used for other things than fluidsim,
-// this could be made on option for the normal calc_vertexnormals
-static void calc_fluidsimnormals(Render *re, ObjectRen *obr, int do_tangent)
-{
- int a;
-
- /* dont clear vertex normals here */
- // OFF for(a=0; a<obr->totvert; a++) { VertRen *ver= RE_findOrAddVert(obr, a); ver->n[0]=ver->n[1]=ver->n[2]= 0.0; }
- /* calculate cos of angles and point-masses, use as weight factor to add face normal to vertex */
- for(a=0; a<obr->totvlak; a++) {
- VlakRen *vlr= RE_findOrAddVlak(obr, a);
- if(vlr->flag & ME_SMOOTH) {
- VertRen *v1= vlr->v1;
- VertRen *v2= vlr->v2;
- VertRen *v3= vlr->v3;
- VertRen *v4= vlr->v4;
- float n1[3], n2[3], n3[3], n4[3];
- float fac1, fac2, fac3, fac4=0.0f;
-
- if(re->flag & R_GLOB_NOPUNOFLIP)
- vlr->flag |= R_NOPUNOFLIP;
-
- VecSubf(n1, v2->co, v1->co);
- Normalize(n1);
- VecSubf(n2, v3->co, v2->co);
- Normalize(n2);
- if(v4==NULL) {
- VecSubf(n3, v1->co, v3->co);
- Normalize(n3);
- fac1= saacos(-n1[0]*n3[0]-n1[1]*n3[1]-n1[2]*n3[2]);
- fac2= saacos(-n1[0]*n2[0]-n1[1]*n2[1]-n1[2]*n2[2]);
- fac3= saacos(-n2[0]*n3[0]-n2[1]*n3[1]-n2[2]*n3[2]);
- }
- else {
- VecSubf(n3, v4->co, v3->co);
- Normalize(n3);
- VecSubf(n4, v1->co, v4->co);
- Normalize(n4);
- fac1= saacos(-n4[0]*n1[0]-n4[1]*n1[1]-n4[2]*n1[2]);
- fac2= saacos(-n1[0]*n2[0]-n1[1]*n2[1]-n1[2]*n2[2]);
- fac3= saacos(-n2[0]*n3[0]-n2[1]*n3[1]-n2[2]*n3[2]);
- fac4= saacos(-n3[0]*n4[0]-n3[1]*n4[1]-n3[2]*n4[2]);
-
- if(!(vlr->flag & R_NOPUNOFLIP)) {
- if( check_vnormal(vlr->n, v4->n) ) fac4= -fac4;
- }
- }
-
- //if(do_tangent)
- // calc_tangent_vector(obr, vlr, fac1, fac2, fac3, fac4);
- }
- if(do_tangent) {
- /* tangents still need to be calculated for flat faces too */
- /* weighting removed, they are not vertexnormals */
- calc_tangent_vector(obr, vlr);
- }
- }
-
- /* do solid faces */
- for(a=0; a<obr->totvlak; a++) {
- VlakRen *vlr= RE_findOrAddVlak(obr, a);
- if((vlr->flag & ME_SMOOTH)==0) {
- float *f1= vlr->v1->n;
- if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
- f1= vlr->v2->n;
- if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
- f1= vlr->v3->n;
- if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
- if(vlr->v4) {
- f1= vlr->v4->n;
- if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
- }
- }
- }
-
- /* normalize vertex normals */
- for(a=0; a<obr->totvert; a++) {
- VertRen *ver= RE_findOrAddVert(obr, a);
- Normalize(ver->n);
- if(do_tangent) {
- float *tav= RE_vertren_get_tangent(obr, ver, 0);
- if(tav) Normalize(tav);
- }
- }
+ if(arena)
+ BLI_memarena_free(arena);
+ if(vtangents)
+ MEM_freeN(vtangents);
}
/* ------------------------------------------------------------------------- */
@@ -926,6 +873,8 @@ static float *get_object_orco(Render *re, Object *ob)
orco = make_orco_curve(ob);
} else if (ob->type==OB_SURF) {
orco = make_orco_surf(ob);
+ } else if (ob->type==OB_MBALL) {
+ orco = make_orco_mball(ob);
}
if (orco)
@@ -951,6 +900,26 @@ static void free_mesh_orco_hash(Render *re)
}
}
+static void flag_render_node_material(Render *re, bNodeTree *ntree)
+{
+ bNode *node;
+
+ for(node=ntree->nodes.first; node; node= node->next) {
+ if(node->id) {
+ if(GS(node->id->name)==ID_MA) {
+ Material *ma= (Material *)node->id;
+
+ if(ma->mode & MA_ZTRA)
+ re->flag |= R_ZTRA;
+
+ ma->flag |= MA_IS_USED;
+ }
+ else if(node->type==NODE_GROUP)
+ flag_render_node_material(re, (bNodeTree *)node->id);
+ }
+ }
+}
+
static Material *give_render_material(Render *re, Object *ob, int nr)
{
extern Material defmaterial; /* material.c */
@@ -959,14 +928,17 @@ static Material *give_render_material(Render *re, Object *ob, int nr)
ma= give_current_material(ob, nr);
if(ma==NULL)
ma= &defmaterial;
- else
- if(ma->mode & MA_ZTRA)
- re->flag |= R_ZTRA;
if(re->r.mode & R_SPEED) ma->texco |= NEED_UV;
+ if(ma->mode & MA_ZTRA)
+ re->flag |= R_ZTRA;
+
/* for light groups */
ma->flag |= MA_IS_USED;
+
+ if(ma->nodetree && ma->use_nodes)
+ flag_render_node_material(re, ma->nodetree);
return ma;
}
@@ -977,7 +949,7 @@ static Material *give_render_material(Render *re, Object *ob, int nr)
/* future thread problem... */
static void static_particle_strand(Render *re, ObjectRen *obr, Material *ma, float *orco, float *surfnor,
- float *uvco, int totuv, float *vec, float *vec1, float ctime,
+ float *uvco, int totuv, MCol *mcol, int totcol, float *vec, float *vec1, float ctime,
int first, int line, int adapt, float adapt_angle, float adapt_pix, int override_uv)
{
static VertRen *v1= NULL, *v2= NULL;
@@ -1040,7 +1012,6 @@ static void static_particle_strand(Render *re, ObjectRen *obr, Material *ma, flo
if(line) {
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
vlr->flag= flag;
- vlr->obr= obr;
vlr->v1= RE_findOrAddVert(obr, obr->totvert++);
vlr->v2= RE_findOrAddVert(obr, obr->totvert++);
vlr->v3= RE_findOrAddVert(obr, obr->totvert++);
@@ -1074,7 +1045,6 @@ static void static_particle_strand(Render *re, ObjectRen *obr, Material *ma, flo
vlr->mat= ma;
vlr->ec= ME_V2V3;
- vlr->lay= obr->ob->lay;
if(surfnor) {
float *snor= RE_vlakren_get_surfnor(obr, vlr, 1);
@@ -1101,6 +1071,14 @@ static void static_particle_strand(Render *re, ObjectRen *obr, Material *ma, flo
mtf->uv[2][1]=mtf->uv[3][1]=1.0f;
}
}
+ if(mcol){
+ for(i=0; i<totcol; i++){
+ MCol *mc;
+ mc=RE_vlakren_get_mcol(obr,vlr,i,NULL,1);
+ mc[0]=mc[1]=mc[2]=mc[3]=mcol[i];
+ mc[0]=mc[1]=mc[2]=mc[3]=mcol[i];
+ }
+ }
}
/* first two vertices of a strand */
else if(first) {
@@ -1130,7 +1108,6 @@ static void static_particle_strand(Render *re, ObjectRen *obr, Material *ma, flo
if(adapt==0 || second){
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
vlr->flag= flag;
- vlr->obr= obr;
vlr->v1= v1;
vlr->v2= v2;
vlr->v3= RE_findOrAddVert(obr, obr->totvert++);
@@ -1160,7 +1137,6 @@ static void static_particle_strand(Render *re, ObjectRen *obr, Material *ma, flo
if(Inpf(anor,nor)<adapt_angle && w>adapt_pix){
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
vlr->flag= flag;
- vlr->obr= obr;
vlr->v1= v1;
vlr->v2= v2;
vlr->v3= RE_findOrAddVert(obr, obr->totvert++);
@@ -1193,7 +1169,6 @@ static void static_particle_strand(Render *re, ObjectRen *obr, Material *ma, flo
vlr->mat= ma;
vlr->ec= ME_V2V3;
- vlr->lay= obr->ob->lay;
if(surfnor) {
float *snor= RE_vlakren_get_surfnor(obr, vlr, 1);
@@ -1220,6 +1195,14 @@ static void static_particle_strand(Render *re, ObjectRen *obr, Material *ma, flo
mtf->uv[2][1]=mtf->uv[3][1]=(vlr->v3->accum+1.0f)/2.0f;
}
}
+ if(mcol){
+ for(i=0; i<totcol; i++){
+ MCol *mc;
+ mc=RE_vlakren_get_mcol(obr,vlr,i,NULL,1);
+ mc[0]=mc[1]=mc[2]=mc[3]=mcol[i];
+ mc[0]=mc[1]=mc[2]=mc[3]=mcol[i];
+ }
+ }
}
}
@@ -1230,7 +1213,6 @@ static void static_particle_wire(ObjectRen *obr, Material *ma, float *vec, float
if(line) {
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
- vlr->obr= obr;
vlr->v1= RE_findOrAddVert(obr, obr->totvert++);
vlr->v2= RE_findOrAddVert(obr, obr->totvert++);
vlr->v3= vlr->v2;
@@ -1246,7 +1228,6 @@ static void static_particle_wire(ObjectRen *obr, Material *ma, float *vec, float
vlr->mat= ma;
vlr->ec= ME_V1V2;
- vlr->lay= obr->ob->lay;
}
else if(first) {
@@ -1255,7 +1236,6 @@ static void static_particle_wire(ObjectRen *obr, Material *ma, float *vec, float
}
else {
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
- vlr->obr= obr;
vlr->v1= v1;
vlr->v2= RE_findOrAddVert(obr, obr->totvert++);
vlr->v3= vlr->v2;
@@ -1270,7 +1250,6 @@ static void static_particle_wire(ObjectRen *obr, Material *ma, float *vec, float
vlr->mat= ma;
vlr->ec= ME_V1V2;
- vlr->lay= obr->ob->lay;
}
}
@@ -1287,7 +1266,6 @@ static void particle_billboard(Render *re, ObjectRen *obr, Material *ma, Object
onevec[align]=1.0f;
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
- vlr->obr= obr;
vlr->v1= RE_findOrAddVert(obr, obr->totvert++);
vlr->v2= RE_findOrAddVert(obr, obr->totvert++);
vlr->v3= RE_findOrAddVert(obr, obr->totvert++);
@@ -1370,7 +1348,6 @@ static void particle_billboard(Render *re, ObjectRen *obr, Material *ma, Object
vlr->mat= ma;
vlr->ec= ME_V2V3;
- vlr->lay= obr->ob->lay;
if(uv_split>1){
uvdx=uvdy=1.0f/(float)uv_split;
@@ -1456,7 +1433,8 @@ static void particle_billboard(Render *re, ObjectRen *obr, Material *ma, Object
}
static void render_new_particle(Render *re, ObjectRen *obr, DerivedMesh *dm, Material *ma, int path, int first, int line,
float time, float *loc, float *loc1, float *orco, float *surfnor, int totuv, float *uvco,
- float size, int seed, int override_uv, int adapt, float adapt_angle, float adapt_pix)
+ int totcol, MCol *mcol, float size, int seed, int override_uv,
+ int adapt, float adapt_angle, float adapt_pix)
{
HaloRen *har=0;
if(path){
@@ -1467,19 +1445,18 @@ static void render_new_particle(Render *re, ObjectRen *obr, DerivedMesh *dm, Mat
if(har) har->lay= obr->ob->lay;
}
else
- static_particle_strand(re, obr, ma, orco, surfnor, uvco, totuv, loc, loc1, time, first, line, adapt, adapt_angle, adapt_pix, override_uv);
+ static_particle_strand(re, obr, ma, orco, surfnor, uvco, totuv, mcol, totcol, loc, loc1, time, first, line, adapt, adapt_angle, adapt_pix, override_uv);
}
else{
har= RE_inithalo_particle(re, obr, dm, ma, loc, NULL, orco, uvco, size, 0.0, seed);
if(har) har->lay= obr->ob->lay;
}
}
-static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem *psys)
+static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem *psys, int timeoffset)
{
Object *ob= obr->ob;
Object *tob=0, *bb_ob=re->scene->camera;
Material *ma=0;
- CustomDataLayer *layer;
MTFace *mtface;
ParticleSystemModifierData *psmd;
ParticleSystem *tpsys=0;
@@ -1490,21 +1467,25 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
ParticleCacheKey *cache=0;
StrandBuffer *strandbuf=0;
StrandVert *svert=0;
+ StrandBound *sbound= 0;
StrandRen *strand=0;
RNG *rng= 0;
+ MCol *mcol= 0;
float loc[3],loc1[3],loc0[3],vel[3],mat[4][4],nmat[3][3],co[3],nor[3],time;
float *orco=0,*surfnor=0,*uvco=0, strandlen=0.0f, curlen=0.0f;
float hasize, pa_size, pa_time, r_tilt, cfra=bsystem_time(ob,(float)CFRA,0.0);
- float loc_tex[3], size_tex[3], adapt_angle=0.0, adapt_pix=0.0, random;
- float simplify[2];
- int i, a, k, max_k=0, totpart, totuv=0, override_uv=-1, dosimplify = 0;
- int path_possible=0, keys_possible=0, baked_keys=0, totchild=psys->totchild;
- int seed, path_nbr=0, path=0, orco1=0, adapt=0, uv[3]={0,0,0};
+ float adapt_angle=0.0, adapt_pix=0.0, random, simplify[2];
+ int i, a, k, max_k=0, totpart, totuv=0, totcol=0, override_uv=-1, dosimplify = 0, dosurfacecache = 0;
+ int path_possible=0, keys_possible=0, baked_keys=0, totchild=0;
+ int seed, path_nbr=0, path=0, orco1=0, adapt=0, uv[3]={0,0,0}, num;
+ int totface, *origindex = 0;
char **uv_name=0;
/* 1. check that everything is ok & updated */
if(psys==NULL)
return 0;
+
+ totchild=psys->totchild;
part=psys->part;
pars=psys->particles;
@@ -1547,6 +1528,7 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
RE_set_customdata_names(obr, &psmd->dm->faceData);
totuv=CustomData_number_of_layers(&psmd->dm->faceData,CD_MTFACE);
+ totcol=CustomData_number_of_layers(&psmd->dm->faceData,CD_MCOL);
if(ma->texco & TEXCO_UV && totuv) {
uvco = MEM_callocN(totuv*2*sizeof(float),"particle_uvs");
@@ -1557,6 +1539,9 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
}
}
+ if(totcol)
+ mcol = MEM_callocN(totcol*sizeof(MCol),"particle_mcols");
+
if(part->draw_as==PART_DRAW_BB){
int first_uv=CustomData_get_layer_index(&psmd->dm->faceData,CD_MTFACE);
@@ -1607,8 +1592,6 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
totpart=psys->totpart;
- mesh_get_texspace(ob->data, loc_tex, NULL, size_tex);
-
if(psys->pathcache){
path_possible=1;
keys_possible=1;
@@ -1645,12 +1628,37 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
strandbuf->overrideuv= override_uv;
strandbuf->minwidth= ma->strand_min;
+ if(ma->strand_widthfade == 0.0f)
+ strandbuf->widthfade= 0.0f;
+ else if(ma->strand_widthfade >= 1.0f)
+ strandbuf->widthfade= 2.0f - ma->strand_widthfade;
+ else
+ strandbuf->widthfade= 1.0f/MAX2(ma->strand_widthfade, 1e-5f);
+
if(part->flag & PART_HAIR_BSPLINE)
strandbuf->flag |= R_STRAND_BSPLINE;
if(ma->mode & MA_STR_B_UNITS)
strandbuf->flag |= R_STRAND_B_UNITS;
svert= strandbuf->vert;
+
+ if(re->r.mode & R_SPEED)
+ dosurfacecache= 1;
+ else if((re->wrld.mode & WO_AMB_OCC) && (re->wrld.ao_gather_method == WO_AOGATHER_APPROX))
+ if(ma->amb != 0.0f)
+ dosurfacecache= 1;
+
+ totface= psmd->dm->getNumFaces(psmd->dm);
+ origindex= psmd->dm->getFaceDataArray(psmd->dm, CD_ORIGINDEX);
+ if(origindex) {
+ for(a=0; a<totface; a++)
+ strandbuf->totbound= MAX2(strandbuf->totbound, origindex[a]);
+ strandbuf->totbound++;
+ }
+ strandbuf->totbound++;
+ strandbuf->bound= MEM_callocN(sizeof(StrandBound)*strandbuf->totbound, "StrandBound");
+ sbound= strandbuf->bound;
+ sbound->start= sbound->end= 0;
}
}
}
@@ -1669,7 +1677,7 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
psys->lattice=psys_get_lattice(ob,psys);
/* 3. start creating renderable things */
- for(a=0,pa=pars; a<totpart+totchild; a++, pa++) {
+ for(a=0,pa=pars; a<totpart+totchild; a++, pa++, seed++) {
random = rng_getFloat(rng);
if(a<totpart){
@@ -1694,20 +1702,43 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
/* get orco */
if(tpsys && (part->from==PART_FROM_PARTICLE || part->phystype==PART_PHYS_NO)){
tpa=tpsys->particles+pa->num;
- psys_particle_on_emitter(ob, psmd,tpart->from,tpa->num, -1,tpa->fuv,tpa->foffset,co,nor,0,0,orco,0);
+ psys_particle_on_emitter(psmd,tpart->from,tpa->num,pa->num_dmcache,tpa->fuv,tpa->foffset,co,nor,0,0,orco,0);
}
else
- psys_particle_on_emitter(ob, psmd,part->from,pa->num,-1,pa->fuv,pa->foffset,co,nor,0,0,orco,0);
+ psys_particle_on_emitter(psmd,part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,nor,0,0,orco,0);
+
+ num= pa->num_dmcache;
+
+ if(num == DMCACHE_NOTFOUND)
+ if(pa->num < psmd->dm->getNumFaces(psmd->dm))
+ num= pa->num;
if(uvco && ELEM(part->from,PART_FROM_FACE,PART_FROM_VOLUME)){
- layer=psmd->dm->faceData.layers + CustomData_get_layer_index(&psmd->dm->faceData,CD_MFACE);
for(i=0; i<totuv; i++){
- MFace *mface=psmd->dm->getFaceData(psmd->dm,pa->num,CD_MFACE);
-
- mtface=(MTFace*)CustomData_get_layer_n(&psmd->dm->faceData,CD_MTFACE,i);
- mtface+=pa->num;
-
- psys_interpolate_uvs(mtface,mface->v4,pa->fuv,uvco+2*i);
+ if(num != DMCACHE_NOTFOUND) {
+ MFace *mface=psmd->dm->getFaceData(psmd->dm,num,CD_MFACE);
+ mtface=(MTFace*)CustomData_get_layer_n(&psmd->dm->faceData,CD_MTFACE,i);
+ mtface+=num;
+
+ psys_interpolate_uvs(mtface,mface->v4,pa->fuv,uvco+2*i);
+ }
+ else {
+ uvco[2*i]= 0.0f;
+ uvco[2*i + 1]= 0.0f;
+ }
+ }
+ }
+ if(mcol && ELEM(part->from,PART_FROM_FACE,PART_FROM_VOLUME)){
+ for(i=0; i<totcol; i++){
+ if(num != DMCACHE_NOTFOUND) {
+ MFace *mface=psmd->dm->getFaceData(psmd->dm,num,CD_MFACE);
+ MCol *mc=(MCol*)CustomData_get_layer_n(&psmd->dm->faceData,CD_MCOL,i);
+ mc+=num*4;
+
+ psys_interpolate_mcol(mc,mface->v4,pa->fuv,mcol+i);
+ }
+ else
+ memset(&mcol[i], 0, sizeof(MCol));
}
}
@@ -1744,14 +1775,22 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
r_tilt=2.0f*cpa->rand[2];
+ num= cpa->num;
+
/* get orco */
- psys_particle_on_emitter(ob, psmd,
- (part->childtype == PART_CHILD_FACES)? PART_FROM_FACE: PART_FROM_PARTICLE,
- cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co,nor,0,0,orco,0);
+ if(part->childtype == PART_CHILD_FACES) {
+ psys_particle_on_emitter(psmd,
+ PART_FROM_FACE, cpa->num,DMCACHE_ISCHILD,
+ cpa->fuv,cpa->foffset,co,nor,0,0,orco,0);
+ }
+ else {
+ ParticleData *par = psys->particles + cpa->parent;
+ psys_particle_on_emitter(psmd, part->from,
+ par->num,DMCACHE_ISCHILD,par->fuv,
+ par->foffset,co,nor,0,0,orco,0);
+ }
if(uvco){
- layer=psmd->dm->faceData.layers + CustomData_get_layer_index(&psmd->dm->faceData,CD_MFACE);
-
if(part->from!=PART_FROM_PARTICLE && part->childtype==PART_CHILD_FACES){
for(i=0; i<totuv; i++){
if(part->childtype==PART_CHILD_FACES){
@@ -1768,30 +1807,77 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
}
}
else if(ELEM(part->from,PART_FROM_FACE,PART_FROM_VOLUME)){
- for(i=0; i<totuv; i++){
- ParticleData *parent = psys->particles+cpa->parent;
- MFace *mface=psmd->dm->getFaceData(psmd->dm,parent->num,CD_MFACE);
+ ParticleData *parent = psys->particles + cpa->parent;
+ num= parent->num_dmcache;
- mtface=(MTFace*)CustomData_get_layer_n(&psmd->dm->faceData,CD_MTFACE,i);
- mtface+=parent->num;
-
- psys_interpolate_uvs(mtface,mface->v4,parent->fuv,uvco+2*i);
+ if(num == DMCACHE_NOTFOUND)
+ if(parent->num < psmd->dm->getNumFaces(psmd->dm))
+ num= parent->num;
+
+ for(i=0; i<totuv; i++) {
+ if(num != DMCACHE_NOTFOUND) {
+ MFace *mface=psmd->dm->getFaceData(psmd->dm,num,CD_MFACE);
+ mtface=(MTFace*)CustomData_get_layer_n(&psmd->dm->faceData,CD_MTFACE,i);
+ mtface+=num;
+ psys_interpolate_uvs(mtface,mface->v4,parent->fuv,uvco+2*i);
+ }
+ else {
+ uvco[2*i]= 0.0f;
+ uvco[2*i + 1]= 0.0f;
+ }
+ }
+ }
+ }
+
+ if(mcol){
+ if(part->from!=PART_FROM_PARTICLE && part->childtype==PART_CHILD_FACES){
+ for(i=0; i<totcol; i++){
+ if(part->childtype==PART_CHILD_FACES){
+ MFace *mface=psmd->dm->getFaceData(psmd->dm,cpa->num,CD_MFACE);
+ MCol *mc=(MCol*)CustomData_get_layer_n(&psmd->dm->faceData,CD_MCOL,i);
+ mc+=cpa->num*4;
+
+ psys_interpolate_mcol(mc,mface->v4,cpa->fuv,mcol+i);
+ }
+ else
+ memset(&mcol[i], 0, sizeof(MCol));
+ }
+ }
+ else if(ELEM(part->from,PART_FROM_FACE,PART_FROM_VOLUME)){
+ ParticleData *parent = psys->particles + cpa->parent;
+ num= parent->num_dmcache;
+
+ if(num == DMCACHE_NOTFOUND)
+ if(parent->num < psmd->dm->getNumFaces(psmd->dm))
+ num= parent->num;
+
+ for(i=0; i<totcol; i++){
+ if(num != DMCACHE_NOTFOUND) {
+ MFace *mface=psmd->dm->getFaceData(psmd->dm,num,CD_MFACE);
+ MCol *mc=(MCol*)CustomData_get_layer_n(&psmd->dm->faceData,CD_MCOL,i);
+ mc+=num*4;
+
+ psys_interpolate_mcol(mc,mface->v4,parent->fuv,mcol+i);
+ }
+ else
+ memset(&mcol[i], 0, sizeof(MCol));
}
}
}
dosimplify= psys_render_simplify_params(psys, cpa, simplify);
- if(path_nbr) {
+ if(path_nbr && psys->childcache) {
cache = psys->childcache[a-totpart];
max_k = (int)cache->steps;
}
- }
- if(orco) {
- orco[0] = (orco[0]-loc_tex[0])/size_tex[0];
- orco[1] = (orco[1]-loc_tex[1])/size_tex[1];
- orco[2] = (orco[2]-loc_tex[2])/size_tex[2];
+ if(strandbuf) {
+ if(origindex[cpa->num]+1 > sbound - strandbuf->bound) {
+ sbound= strandbuf->bound + origindex[cpa->num]+1;
+ sbound->start= sbound->end= obr->totstrand;
+ }
+ }
}
/* surface normal shading setup */
@@ -1820,8 +1906,13 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
VECCOPY(snor, surfnor);
}
- if(uvco){
- for(i=0; i<totuv; i++){
+ if(dosurfacecache && num >= 0) {
+ int *facenum= RE_strandren_get_face(obr, strand, 1);
+ *facenum= num;
+ }
+
+ if(uvco) {
+ for(i=0; i<totuv; i++) {
if(i != override_uv) {
float *uv= RE_strandren_get_uv(obr, strand, i, NULL, 1);
@@ -1830,6 +1921,14 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
}
}
}
+ if(mcol) {
+ for(i=0; i<totcol; i++) {
+ MCol *mc= RE_strandren_get_mcol(obr, strand, i, NULL, 1);
+ *mc = mcol[i];
+ }
+ }
+
+ sbound->end++;
}
/* strandco computation setup */
@@ -1879,7 +1978,7 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
VECADDFAC(loc1,loc,vel,part->draw_line[1]);
render_new_particle(re,obr,psmd->dm,ma,1,0,1,0.0f,loc0,loc1,
- orco,surfnor,totuv,uvco,hasize,seed,override_uv,0,0,0);
+ orco,surfnor,totuv,uvco,totcol,mcol,hasize,seed,override_uv,0,0,0);
}
else if(part->draw_as==PART_DRAW_BB) {
VECCOPY(vel,state.vel);
@@ -1899,13 +1998,13 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
VECSUB(loc0,loc1,loc);
VECADD(loc0,loc1,loc0);
render_new_particle(re,obr,psmd->dm,ma,path,1,0,0.0f,loc1,loc0,
- orco,surfnor,totuv,uvco,hasize,seed,override_uv,
+ orco,surfnor,totuv,uvco,totcol,mcol,hasize,seed,override_uv,
adapt,adapt_angle,adapt_pix);
}
if(path_nbr==0 || k)
render_new_particle(re,obr,psmd->dm,ma,path,0,0,time,loc,loc1,
- orco,surfnor,totuv,uvco,hasize,seed,override_uv,
+ orco,surfnor,totuv,uvco,totcol,mcol,hasize,seed,override_uv,
adapt,adapt_angle,adapt_pix);
VECCOPY(loc1,loc);
@@ -1919,6 +2018,9 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
break;
}
+ if(dosurfacecache)
+ strandbuf->surface= cache_strand_surface(re, obr, psmd->dm, mat, timeoffset);
+
/* 4. clean up */
if(ma) do_mat_ipo(ma);
@@ -1927,6 +2029,9 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
if(uvco)
MEM_freeN(uvco);
+
+ if(mcol)
+ MEM_freeN(mcol);
if(uv_name)
MEM_freeN(uv_name);
@@ -1944,7 +2049,7 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
}
if(path && (ma->mode_l & MA_TANGENT_STR)==0)
- calc_vertexnormals(re, obr, 0);
+ calc_vertexnormals(re, obr, 0, 0);
return 1;
}
@@ -2005,7 +2110,8 @@ static void make_render_halos(Render *re, ObjectRen *obr, Mesh *me, int totvert,
static int verghalo(const void *a1, const void *a2)
{
- const HaloRen *har1= a1, *har2= a2;
+ const HaloRen *har1= *(const HaloRen**)a1;
+ const HaloRen *har2= *(const HaloRen**)a2;
if(har1->zs < har2->zs) return 1;
else if(har1->zs > har2->zs) return -1;
@@ -2053,11 +2159,11 @@ static short test_for_displace(Render *re, Object *ob)
return 0;
}
-static void displace_render_vert(Render *re, ObjectRen *obr, ShadeInput *shi, VertRen *vr, int vindex, float *scale)
+static void displace_render_vert(Render *re, ObjectRen *obr, ShadeInput *shi, VertRen *vr, int vindex, float *scale, float mat[][4], float imat[][3])
{
MTFace *tface;
short texco= shi->mat->texco;
- float sample=0;
+ float sample=0, displace[3];
char *name;
int i;
@@ -2066,6 +2172,15 @@ static void displace_render_vert(Render *re, ObjectRen *obr, ShadeInput *shi, Ve
/* vertex normal is used for textures type 'col' and 'var' */
VECCOPY(shi->vn, vr->n);
+ if(mat)
+ Mat4MulVecfl(mat, shi->co);
+
+ if(imat) {
+ shi->vn[0]= imat[0][0]*vr->n[0]+imat[0][1]*vr->n[1]+imat[0][2]*vr->n[2];
+ shi->vn[1]= imat[1][0]*vr->n[0]+imat[1][1]*vr->n[1]+imat[1][2]*vr->n[2];
+ shi->vn[2]= imat[2][0]*vr->n[0]+imat[2][1]*vr->n[1]+imat[2][2]*vr->n[2];
+ }
+
if (texco & TEXCO_UV) {
shi->totuv= 0;
shi->actuv= obr->actmtface;
@@ -2111,11 +2226,18 @@ static void displace_render_vert(Render *re, ObjectRen *obr, ShadeInput *shi, Ve
//printf("no=%f, %f, %f\nbefore co=%f, %f, %f\n", vr->n[0], vr->n[1], vr->n[2],
//vr->co[0], vr->co[1], vr->co[2]);
+
+ displace[0]= shi->displace[0] * scale[0];
+ displace[1]= shi->displace[1] * scale[1];
+ displace[2]= shi->displace[2] * scale[2];
+ if(mat)
+ Mat3MulVecfl(imat, displace);
+
/* 0.5 could become button once? */
- vr->co[0] += shi->displace[0] * scale[0] ;
- vr->co[1] += shi->displace[1] * scale[1] ;
- vr->co[2] += shi->displace[2] * scale[2] ;
+ vr->co[0] += displace[0];
+ vr->co[1] += displace[1];
+ vr->co[2] += displace[2];
//printf("after co=%f, %f, %f\n", vr->co[0], vr->co[1], vr->co[2]);
@@ -2133,28 +2255,36 @@ static void displace_render_vert(Render *re, ObjectRen *obr, ShadeInput *shi, Ve
return;
}
-static void displace_render_face(Render *re, VlakRen *vlr, float *scale)
+static void displace_render_face(Render *re, ObjectRen *obr, VlakRen *vlr, float *scale, float mat[][4], float imat[][3])
{
ShadeInput shi;
+ /* Warning, This is not that nice, and possibly a bit slow,
+ however some variables were not initialized properly in, unless using shade_input_initialize(...), we need to do a memset */
+ memset(&shi, 0, sizeof(ShadeInput));
+ /* end warning! - Campbell */
+
/* set up shadeinput struct for multitex() */
- shi.osatex= 0; /* signal not to use dx[] and dy[] texture AA vectors */
+
+ /* memset above means we dont need this */
+ /*shi.osatex= 0;*/ /* signal not to use dx[] and dy[] texture AA vectors */
+
shi.vlr= vlr; /* current render face */
shi.mat= vlr->mat; /* current input material */
/* Displace the verts, flag is set when done */
if (!vlr->v1->flag)
- displace_render_vert(re, vlr->obr, &shi, vlr->v1,0, scale);
+ displace_render_vert(re, obr, &shi, vlr->v1,0, scale, mat, imat);
if (!vlr->v2->flag)
- displace_render_vert(re, vlr->obr, &shi, vlr->v2, 1, scale);
+ displace_render_vert(re, obr, &shi, vlr->v2, 1, scale, mat, imat);
if (!vlr->v3->flag)
- displace_render_vert(re, vlr->obr, &shi, vlr->v3, 2, scale);
+ displace_render_vert(re, obr, &shi, vlr->v3, 2, scale, mat, imat);
if (vlr->v4) {
if (!vlr->v4->flag)
- displace_render_vert(re, vlr->obr, &shi, vlr->v4, 3, scale);
+ displace_render_vert(re, obr, &shi, vlr->v4, 3, scale, mat, imat);
/* closest in displace value. This will help smooth edges. */
if ( fabs(vlr->v1->accum - vlr->v3->accum) > fabs(vlr->v2->accum - vlr->v4->accum))
@@ -2171,7 +2301,7 @@ static void displace_render_face(Render *re, VlakRen *vlr, float *scale)
}
}
-static void do_displacement(Render *re, ObjectRen *obr)
+static void do_displacement(Render *re, ObjectRen *obr, float mat[][4], float imat[][3])
{
VertRen *vr;
VlakRen *vlr;
@@ -2196,11 +2326,11 @@ static void do_displacement(Render *re, ObjectRen *obr)
for(i=0; i<obr->totvlak; i++){
vlr=RE_findOrAddVlak(obr, i);
- displace_render_face(re, vlr, scale);
+ displace_render_face(re, obr, vlr, scale, mat, imat);
}
/* Recalc vertex normals */
- calc_vertexnormals(re, obr, 0);
+ calc_vertexnormals(re, obr, 0, 0);
}
/* ------------------------------------------------------------------------- */
@@ -2214,8 +2344,8 @@ static void init_render_mball(Render *re, ObjectRen *obr)
VertRen *ver;
VlakRen *vlr, *vlr1;
Material *ma;
- float *data, *nors, mat[4][4], imat[3][3], xn, yn, zn;
- int a, need_orco, *index;
+ float *data, *nors, *orco, mat[4][4], imat[3][3], xn, yn, zn;
+ int a, need_orco, vlakindex, *index;
if (ob!=find_basis_mball(ob))
return;
@@ -2237,8 +2367,9 @@ static void init_render_mball(Render *re, ObjectRen *obr)
data= dl->verts;
nors= dl->nors;
+ orco= get_object_orco(re, ob);
- for(a=0; a<dl->nr; a++, data+=3, nors+=3) {
+ for(a=0; a<dl->nr; a++, data+=3, nors+=3, orco+=3) {
ver= RE_findOrAddVert(obr, obr->totvert++);
VECCOPY(ver->co, data);
@@ -2256,14 +2387,13 @@ static void init_render_mball(Render *re, ObjectRen *obr)
Normalize(ver->n);
//if(ob->transflag & OB_NEG_SCALE) VecMulf(ver->n. -1.0);
- if(need_orco) ver->orco= data;
+ if(need_orco) ver->orco= orco;
}
index= dl->index;
for(a=0; a<dl->parts; a++, index+=4) {
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
- vlr->obr= obr;
vlr->v1= RE_findOrAddVert(obr, index[0]);
vlr->v2= RE_findOrAddVert(obr, index[1]);
vlr->v3= RE_findOrAddVert(obr, index[2]);
@@ -2277,12 +2407,13 @@ static void init_render_mball(Render *re, ObjectRen *obr)
vlr->mat= ma;
vlr->flag= ME_SMOOTH+R_NOPUNOFLIP;
vlr->ec= 0;
- vlr->lay= ob->lay;
/* mball -too bad- always has triangles, because quads can be non-planar */
if(index[3] && index[3]!=index[2]) {
vlr1= RE_findOrAddVlak(obr, obr->totvlak++);
+ vlakindex= vlr1->index;
*vlr1= *vlr;
+ vlr1->index= vlakindex;
vlr1->v2= vlr1->v3;
vlr1->v3= RE_findOrAddVert(obr, index[3]);
if(ob->transflag & OB_NEG_SCALE)
@@ -2292,14 +2423,8 @@ static void init_render_mball(Render *re, ObjectRen *obr)
}
}
- if(need_orco) {
- /* store displist and scale */
- make_orco_mball(ob);
- }
- else {
- /* enforce display lists remade */
- freedisplist(&ob->disp);
- }
+ /* enforce display lists remade */
+ freedisplist(&ob->disp);
/* this enforces remake for real, orco displist is small (in scale) */
ob->recalc |= OB_RECALC_DATA;
@@ -2316,7 +2441,7 @@ static int dl_surf_to_renderdata(ObjectRen *obr, DispList *dl, Material **matar,
VertRen *v1, *v2, *v3, *v4, *ver;
VlakRen *vlr, *vlr1, *vlr2, *vlr3;
Curve *cu= ob->data;
- float *data, n1[3], flen;
+ float *data, n1[3];
int u, v, orcoret= 0;
int p1, p2, p3, p4, a;
int sizeu, nsizeu, sizev, nsizev;
@@ -2386,13 +2511,12 @@ static int dl_surf_to_renderdata(ObjectRen *obr, DispList *dl, Material **matar,
v4= RE_findOrAddVert(obr, p4);
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
- vlr->obr= obr;
vlr->v1= v1; vlr->v2= v2; vlr->v3= v3; vlr->v4= v4;
- flen= CalcNormFloat4(vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co, n1);
+ CalcNormFloat4(vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co, n1);
+
VECCOPY(vlr->n, n1);
- vlr->lay= ob->lay;
vlr->mat= matar[ dl->col];
vlr->ec= ME_V1V2+ME_V2V3;
vlr->flag= dl->rt;
@@ -2524,7 +2648,7 @@ static void init_render_surf(Render *re, ObjectRen *obr)
freedisplist(&displist);
}
-static void init_render_curve(Render *re, ObjectRen *obr, int only_verts)
+static void init_render_curve(Render *re, ObjectRen *obr, int timeoffset)
{
Object *ob= obr->ob;
Curve *cu;
@@ -2539,7 +2663,8 @@ static void init_render_curve(Render *re, ObjectRen *obr, int only_verts)
int frontside, need_orco=0;
cu= ob->data;
- if(cu->nurb.first==NULL) return;
+ if(ob->type==OB_FONT && cu->str==NULL) return;
+ else if(ob->type==OB_CURVE && cu->nurb.first==NULL) return;
/* no modifier call here, is in makedisp */
@@ -2602,13 +2727,12 @@ static void init_render_curve(Render *re, ObjectRen *obr, int only_verts)
}
}
- if(only_verts==0) {
+ if(timeoffset==0) {
startvlak= obr->totvlak;
index= dl->index;
for(a=0; a<dl->parts; a++, index+=3) {
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
- vlr->obr = obr;
vlr->v1= RE_findOrAddVert(obr, startvert+index[0]);
vlr->v2= RE_findOrAddVert(obr, startvert+index[1]);
vlr->v3= RE_findOrAddVert(obr, startvert+index[2]);
@@ -2627,7 +2751,6 @@ static void init_render_curve(Render *re, ObjectRen *obr, int only_verts)
vlr->flag |= R_NOPUNOFLIP;
}
vlr->ec= 0;
- vlr->lay= ob->lay;
}
}
}
@@ -2657,14 +2780,16 @@ static void init_render_curve(Render *re, ObjectRen *obr, int only_verts)
}
}
- if(dl->bevelSplitFlag || only_verts==0) {
+ if(dl->bevelSplitFlag || timeoffset==0) {
startvlak= obr->totvlak;
for(a=0; a<dl->parts; a++) {
frontside= (a >= dl->nr/2);
-
- DL_SURFINDEX(dl->flag & DL_CYCL_U, dl->flag & DL_CYCL_V, dl->nr, dl->parts);
+
+ if (surfindex_displist(dl, a, &b, &p1, &p2, &p3, &p4)==0)
+ break;
+
p1+= startvert;
p2+= startvert;
p3+= startvert;
@@ -2672,7 +2797,6 @@ static void init_render_curve(Render *re, ObjectRen *obr, int only_verts)
for(; b<dl->nr; b++) {
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
- vlr->obr= obr;
vlr->v1= RE_findOrAddVert(obr, p2);
vlr->v2= RE_findOrAddVert(obr, p1);
vlr->v3= RE_findOrAddVert(obr, p3);
@@ -2681,7 +2805,6 @@ static void init_render_curve(Render *re, ObjectRen *obr, int only_verts)
if(a==0) vlr->ec+= ME_V1V2;
vlr->flag= dl->rt;
- vlr->lay= ob->lay;
/* this is not really scientific: the vertices
* 2, 3 en 4 seem to give better vertexnormals than 1 2 3:
@@ -2875,7 +2998,7 @@ static void use_mesh_edge_lookup(ObjectRen *obr, DerivedMesh *dm, MEdge *medge,
}
}
-static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
+static void init_render_mesh(Render *re, ObjectRen *obr, int timeoffset)
{
Object *ob= obr->ob;
Mesh *me;
@@ -2889,9 +3012,9 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
CustomDataMask mask;
float xn, yn, zn, imat[3][3], mat[4][4]; //nor[3],
float *orco=0;
- int a, a1, ok, need_orco=0, need_stress=0, need_tangent=0, vertofs;
+ int need_orco=0, need_stress=0, need_nmap_tangent=0, need_tangent=0;
+ int a, a1, ok, vertofs;
int end, do_autosmooth=0, totvert = 0;
- int useFluidmeshNormals= 0; // NT fluidsim, use smoothed normals?
int use_original_normals= 0;
me= ob->data;
@@ -2912,11 +3035,19 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
if(ma->texco & TEXCO_STRESS)
need_stress= 1;
/* normalmaps, test if tangents needed, separated from shading */
- if ((ma->mode_l & MA_TANGENT_V) || (ma->mode_l & MA_NORMAP_TANG)) {
+ if(ma->mode_l & MA_TANGENT_V) {
need_tangent= 1;
if(me->mtface==NULL)
need_orco= 1;
}
+ if(ma->mode_l & MA_NORMAP_TANG) {
+ if(me->mtface==NULL) {
+ need_orco= 1;
+ need_tangent= 1;
+ }
+ need_nmap_tangent= 1;
+ }
+
/* radio faces need autosmooth, to separate shared vertices in corners */
if(re->r.mode & R_RADIO)
if(ma->mode & MA_RADIO)
@@ -2926,23 +3057,32 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
if(re->flag & R_NEED_TANGENT) {
/* exception for tangent space baking */
- need_tangent= 1;
- if(me->mtface==NULL)
+ if(me->mtface==NULL) {
need_orco= 1;
+ need_tangent= 1;
+ }
+ need_nmap_tangent= 1;
}
/* check autosmooth and displacement, we then have to skip only-verts optimize */
do_autosmooth |= (me->flag & ME_AUTOSMOOTH);
if(do_autosmooth)
- only_verts= 0;
+ timeoffset= 0;
if(test_for_displace(re, ob ) )
- only_verts= 0;
+ timeoffset= 0;
mask= CD_MASK_BAREMESH|CD_MASK_MTFACE|CD_MASK_MCOL;
- if(!only_verts)
+ if(!timeoffset)
if(need_orco)
mask |= CD_MASK_ORCO;
+ if(me->mr) {
+ if(re->flag & R_SKIP_MULTIRES)
+ me->mr->flag |= MULTIRES_NO_RENDER;
+ else
+ me->mr->flag &= ~MULTIRES_NO_RENDER;
+ }
+
dm= mesh_create_derived_render(ob, mask);
if(dm==NULL) return; /* in case duplicated object fails? */
@@ -2954,12 +3094,6 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
}
}
- if((ob->fluidsimFlag & OB_FLUIDSIM_ENABLE) &&
- (ob->fluidsimSettings->type & OB_FLUIDSIM_DOMAIN)&&
- (ob->fluidsimSettings->meshSurface) ) {
- useFluidmeshNormals = 1;
- }
-
mvert= dm->getVertArray(dm);
totvert= dm->getNumVerts(dm);
@@ -2982,17 +3116,6 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
if(do_autosmooth==0) /* autosmooth on original unrotated data to prevent differences between frames */
MTC_Mat4MulVecfl(mat, ver->co);
- if(useFluidmeshNormals) {
- /* normals are inverted in render */
- xn = -mvert->no[0]/ 32767.0;
- yn = -mvert->no[1]/ 32767.0;
- zn = -mvert->no[2]/ 32767.0;
- /* transfor to cam space */
- ver->n[0]= imat[0][0]*xn+imat[0][1]*yn+imat[0][2]*zn;
- ver->n[1]= imat[1][0]*xn+imat[1][1]*yn+imat[1][2]*zn;
- ver->n[2]= imat[2][0]*xn+imat[2][1]*yn+imat[2][2]*zn;
- } // useFluidmeshNormals
-
if(orco) {
ver->orco= orco;
orco+=3;
@@ -3005,7 +3128,7 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
}
}
- if(!only_verts) {
+ if(!timeoffset) {
/* store customdata names, because DerivedMesh is freed */
RE_set_customdata_names(obr, &dm->faceData);
@@ -3052,7 +3175,6 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
flag= mface->flag & ME_SMOOTH;
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
- vlr->obr= obr;
vlr->v1= RE_findOrAddVert(obr, vertofs+v1);
vlr->v2= RE_findOrAddVert(obr, vertofs+v2);
vlr->v3= RE_findOrAddVert(obr, vertofs+v3);
@@ -3082,7 +3204,6 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
vlr->flag |= R_NOPUNOFLIP;
}
vlr->ec= 0; /* mesh edges rendered separately */
- vlr->lay= ob->lay;
if(len==0) obr->totvlak--;
else {
@@ -3133,7 +3254,6 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
MVert *v1 = &mvert[medge->v2];
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
- vlr->obr= obr;
vlr->v1= RE_findOrAddVert(obr, vertofs+medge->v1);
vlr->v2= RE_findOrAddVert(obr, vertofs+medge->v2);
vlr->v3= vlr->v2;
@@ -3154,7 +3274,6 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
vlr->mat= ma;
vlr->flag= 0;
vlr->ec= ME_V1V2;
- vlr->lay= ob->lay;
}
}
if(edgetable)
@@ -3163,22 +3282,20 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
}
}
- if(!only_verts) {
+ if(!timeoffset) {
if (test_for_displace(re, ob ) ) {
- calc_vertexnormals(re, obr, 0);
- do_displacement(re, obr);
+ calc_vertexnormals(re, obr, 0, 0);
+ if(do_autosmooth)
+ do_displacement(re, obr, mat, imat);
+ else
+ do_displacement(re, obr, NULL, NULL);
}
if(do_autosmooth) {
autosmooth(re, obr, mat, me->smoothresh);
}
- if(useFluidmeshNormals) {
- // do not recalculate, only init render data
- calc_fluidsimnormals(re, obr, need_tangent);
- } else {
- calc_vertexnormals(re, obr, need_tangent);
- }
+ calc_vertexnormals(re, obr, need_tangent, need_nmap_tangent);
if(need_stress)
calc_edge_stress(re, obr, me);
@@ -3209,8 +3326,6 @@ static void initshadowbuf(Render *re, LampRen *lar, float mat[][4])
/* percentage render: keep track of min and max */
shb->size= (lar->bufsize*re->r.size)/100;
- if(lar->buffers>1) shb->size/= 2;
-
if(shb->size<512) shb->size= 512;
else if(shb->size > lar->bufsize) shb->size= lar->bufsize;
@@ -3282,6 +3397,7 @@ static GroupObject *add_render_lamp(Render *re, Object *ob)
LampRen *lar;
GroupObject *go;
float mat[4][4], angle, xn, yn;
+ float vec[3];
int c;
/* previewrender sets this to zero... prevent accidents */
@@ -3341,6 +3457,9 @@ static GroupObject *add_render_lamp(Render *re, Object *ob)
lar->r= lar->energy*la->r;
lar->g= lar->energy*la->g;
lar->b= lar->energy*la->b;
+ lar->shdwr= la->shdwr;
+ lar->shdwg= la->shdwg;
+ lar->shdwb= la->shdwb;
lar->k= la->k;
// area
@@ -3353,12 +3472,20 @@ static GroupObject *add_render_lamp(Render *re, Object *ob)
lar->area_sizez= la->area_sizez;
lar->area_shape= la->area_shape;
+
+ /* Annoying, lamp UI does this, but the UI might not have been used? - add here too.
+ * make sure this matches buttons_shading.c's logic */
+ if(ELEM4(la->type, LA_AREA, LA_SPOT, LA_SUN, LA_LOCAL) && (la->mode & LA_SHAD_RAY))
+ if (ELEM3(la->type, LA_SPOT, LA_SUN, LA_LOCAL))
+ if (la->ray_samp_method == LA_SAMP_CONSTANT) la->ray_samp_method = LA_SAMP_HALTON;
+
lar->ray_samp_method= la->ray_samp_method;
lar->ray_samp_type= la->ray_samp_type;
lar->adapt_thresh= la->adapt_thresh;
+ lar->sunsky = NULL;
- if( ELEM3(lar->type, LA_SPOT, LA_SUN, LA_LOCAL)) {
+ if( ELEM(lar->type, LA_SPOT, LA_LOCAL)) {
lar->ray_totsamp= lar->ray_samp*lar->ray_samp;
lar->area_shape = LA_AREA_SQUARE;
lar->area_sizey= lar->area_size;
@@ -3388,6 +3515,27 @@ static GroupObject *add_render_lamp(Render *re, Object *ob)
area_lamp_vectors(lar);
init_jitter_plane(lar); // subsamples
}
+ else if(lar->type==LA_SUN){
+ lar->ray_totsamp= lar->ray_samp*lar->ray_samp;
+ lar->area_shape = LA_AREA_SQUARE;
+ lar->area_sizey= lar->area_size;
+
+ if((la->sun_effect_type & LA_SUN_EFFECT_SKY) ||
+ (la->sun_effect_type & LA_SUN_EFFECT_AP)){
+ lar->sunsky = (struct SunSky*)MEM_callocN(sizeof(struct SunSky), "sunskyren");
+ lar->sunsky->effect_type = la->sun_effect_type;
+
+ VECCOPY(vec,ob->obmat[2]);
+ Normalize(vec);
+
+ InitSunSky(lar->sunsky, la->atm_turbidity, vec, la->horizon_brightness,
+ la->spread, la->sun_brightness, la->sun_size, la->backscattered_light,
+ la->skyblendfac, la->skyblendtype, la->sky_exposure, la->sky_colorspace);
+
+ InitAtmosphere(lar->sunsky, la->sun_intensity, 1.0, 1.0, la->atm_inscattering_factor, la->atm_extinction_factor,
+ la->atm_distance_factor);
+ }
+ }
else lar->ray_totsamp= 0;
#ifndef DISABLE_YAFRAY
@@ -3465,7 +3613,10 @@ static GroupObject *add_render_lamp(Render *re, Object *ob)
for(c=0; c<MAX_MTEX; c++) {
if(la->mtex[c] && la->mtex[c]->tex) {
- lar->mode |= LA_TEXTURE;
+ if (la->mtex[c]->mapto & LAMAP_COL)
+ lar->mode |= LA_TEXTURE;
+ if (la->mtex[c]->mapto & LAMAP_SHAD)
+ lar->mode |= LA_SHAD_TEX;
if(G.rendering) {
if(re->osa) {
@@ -3485,9 +3636,6 @@ static GroupObject *add_render_lamp(Render *re, Object *ob)
if(re->r.mode & R_SHADOW) {
- if ((lar->mode & LA_SHAD_RAY) && (lar->ray_samp_method == LA_SAMP_HAMMERSLEY)) {
- init_lamp_hammersley(lar);
- }
if(la->type==LA_AREA && (lar->mode & LA_SHAD_RAY) && (lar->ray_samp_method == LA_SAMP_CONSTANT)) {
init_jitter_plane(lar);
}
@@ -3501,16 +3649,24 @@ static GroupObject *add_render_lamp(Render *re, Object *ob)
/* this is the way used all over to check for shadow */
if(lar->shb || (lar->mode & LA_SHAD_RAY)) {
+ LampShadowSample *ls;
LampShadowSubSample *lss;
- int a, b, tot= re->r.threads*re->r.osa;
+ int a, b;
+
+ memset(re->shadowsamplenr, 0, sizeof(re->shadowsamplenr));
lar->shadsamp= MEM_mallocN(re->r.threads*sizeof(LampShadowSample), "lamp shadow sample");
- lss= lar->shadsamp[0].s;
+ ls= lar->shadsamp;
+
/* shadfacs actually mean light, let's put them to 1 to prevent unitialized accidents */
- for(a=0; a<tot; a++, lss++) {
- for(b=0; b<4; b++) {
+ for(a=0; a<re->r.threads; a++, ls++) {
+ lss= ls->s;
+ for(b=0; b<re->r.osa; b++, lss++) {
lss->samplenr= -1; /* used to detect whether we store or read */
- lss->shadfac[b]= 1.0f;
+ lss->shadfac[0]= 1.0f;
+ lss->shadfac[1]= 1.0f;
+ lss->shadfac[2]= 1.0f;
+ lss->shadfac[3]= 1.0f;
}
}
}
@@ -3611,13 +3767,18 @@ void init_render_world(Render *re)
if(re->osa)
while(re->wrld.aosamp*re->wrld.aosamp < re->osa)
re->wrld.aosamp++;
- if(!(re->r.mode & R_RAYTRACE))
+ if(!(re->r.mode & R_RAYTRACE) && (re->wrld.ao_gather_method == WO_AOGATHER_RAYTRACE))
re->wrld.mode &= ~WO_AMB_OCC;
}
else {
memset(&re->wrld, 0, sizeof(World));
- re->wrld.exp= 0.0;
- re->wrld.range= 1.0;
+ re->wrld.exp= 0.0f;
+ re->wrld.range= 1.0f;
+
+ /* for mist pass */
+ re->wrld.miststa= re->clipsta;
+ re->wrld.mistdist= re->clipend-re->clipsta;
+ re->wrld.misi= 1.0f;
}
re->wrld.linfac= 1.0 + pow((2.0*re->wrld.exp + 0.5), -10);
@@ -3679,7 +3840,7 @@ static void set_phong_threshold(ObjectRen *obr)
}
/* per face check if all samples should be taken.
- if raytrace, do always for raytraced material, or when material full_osa set */
+ if raytrace or multisample, do always for raytraced material, or when material full_osa set */
static void set_fullsample_flag(Render *re, ObjectRen *obr)
{
VlakRen *vlr;
@@ -3693,7 +3854,8 @@ static void set_fullsample_flag(Render *re, ObjectRen *obr)
for(a=obr->totvlak-1; a>=0; a--) {
vlr= RE_findOrAddVlak(obr, a);
- if(vlr->mat->mode & MA_FULL_OSA) vlr->flag |= R_FULL_OSA;
+ if(vlr->mat->mode & MA_FULL_OSA)
+ vlr->flag |= R_FULL_OSA;
else if(trace) {
if(vlr->mat->mode & MA_SHLESS);
else if(vlr->mat->mode & (MA_RAYTRANSP|MA_RAYMIRROR))
@@ -3705,6 +3867,57 @@ static void set_fullsample_flag(Render *re, ObjectRen *obr)
}
}
+/* split quads for pradictable baking
+ * dir 1 == (0,1,2) (0,2,3), 2 == (1,3,0) (1,2,3)
+ */
+static void split_quads(ObjectRen *obr, int dir)
+{
+ VlakRen *vlr, *vlr1;
+ int a;
+
+ for(a=obr->totvlak-1; a>=0; a--) {
+ vlr= RE_findOrAddVlak(obr, a);
+
+ /* test if rendering as a quad or triangle, skip wire */
+ if(vlr->v4 && (vlr->flag & R_STRAND)==0 && (vlr->mat->mode & MA_WIRE)==0) {
+
+ if(vlr->v4) {
+
+ vlr1= RE_vlakren_copy(obr, vlr);
+ vlr1->flag |= R_FACE_SPLIT;
+
+ if( dir==2 ) vlr->flag |= R_DIVIDE_24;
+ else vlr->flag &= ~R_DIVIDE_24;
+
+ /* new vertex pointers */
+ if (vlr->flag & R_DIVIDE_24) {
+ vlr1->v1= vlr->v2;
+ vlr1->v2= vlr->v3;
+ vlr1->v3= vlr->v4;
+
+ vlr->v3 = vlr->v4;
+
+ vlr1->flag |= R_DIVIDE_24;
+ }
+ else {
+ vlr1->v1= vlr->v1;
+ vlr1->v2= vlr->v3;
+ vlr1->v3= vlr->v4;
+
+ vlr1->flag &= ~R_DIVIDE_24;
+ }
+ vlr->v4 = vlr1->v4 = NULL;
+
+ /* new normals */
+ CalcNormFloat(vlr->v3->co, vlr->v2->co, vlr->v1->co, vlr->n);
+ CalcNormFloat(vlr1->v3->co, vlr1->v2->co, vlr1->v1->co, vlr1->n);
+ }
+ /* clear the flag when not divided */
+ else vlr->flag &= ~R_DIVIDE_24;
+ }
+ }
+}
+
static void check_non_flat_quads(ObjectRen *obr)
{
VlakRen *vlr, *vlr1;
@@ -3767,6 +3980,7 @@ static void check_non_flat_quads(ObjectRen *obr)
xn= nor[0]*vlr->n[0] + nor[1]*vlr->n[1] + nor[2]*vlr->n[2];
if(ABS(xn) < 0.999995 ) { // checked on noisy fractal grid
+
float d1, d2;
vlr1= RE_vlakren_copy(obr, vlr);
@@ -3778,10 +3992,10 @@ static void check_non_flat_quads(ObjectRen *obr)
CalcNormFloat(vlr->v2->co, vlr->v3->co, vlr->v4->co, nor);
d2= nor[0]*vlr->v2->n[0] + nor[1]*vlr->v2->n[1] + nor[2]*vlr->v2->n[2];
-
+
if( fabs(d1) < fabs(d2) ) vlr->flag |= R_DIVIDE_24;
else vlr->flag &= ~R_DIVIDE_24;
-
+
/* new vertex pointers */
if (vlr->flag & R_DIVIDE_24) {
vlr1->v1= vlr->v2;
@@ -3812,26 +4026,67 @@ static void check_non_flat_quads(ObjectRen *obr)
}
}
-static void finalize_render_object(Render *re, ObjectRen *obr, int only_verts)
+static void finalize_render_object(Render *re, ObjectRen *obr, int timeoffset)
{
Object *ob= obr->ob;
+ VertRen *ver= NULL;
+ StrandRen *strand= NULL;
+ StrandBound *sbound= NULL;
+ float min[3], max[3], smin[3], smax[3];
+ int a, b;
if(obr->totvert || obr->totvlak || obr->tothalo || obr->totstrand) {
/* the exception below is because displace code now is in init_render_mesh call,
I will look at means to have autosmooth enabled for all object types
and have it as general postprocess, like displace */
if(ob->type!=OB_MESH && test_for_displace(re, ob))
- do_displacement(re, obr);
+ do_displacement(re, obr, NULL, NULL);
- if(!only_verts) {
+ if(!timeoffset) {
/* phong normal interpolation can cause error in tracing
* (terminator problem) */
ob->smoothresh= 0.0;
if((re->r.mode & R_RAYTRACE) && (re->r.mode & R_SHADOW))
set_phong_threshold(obr);
-
- check_non_flat_quads(obr);
+
+ if (re->flag & R_BAKING && re->r.bake_quad_split != 0) {
+ /* Baking lets us define a quad split order */
+ split_quads(obr, re->r.bake_quad_split);
+ } else {
+ check_non_flat_quads(obr);
+ }
+
set_fullsample_flag(re, obr);
+
+ /* compute bounding boxes for clipping */
+ INIT_MINMAX(min, max);
+ for(a=0; a<obr->totvert; a++) {
+ if((a & 255)==0) ver= obr->vertnodes[a>>8].vert;
+ else ver++;
+
+ DO_MINMAX(ver->co, min, max);
+ }
+
+ if(obr->strandbuf) {
+ sbound= obr->strandbuf->bound;
+ for(b=0; b<obr->strandbuf->totbound; b++, sbound++) {
+ INIT_MINMAX(smin, smax);
+
+ for(a=sbound->start; a<sbound->end; a++) {
+ strand= RE_findOrAddStrand(obr, a);
+ strand_minmax(strand, smin, smax);
+ }
+
+ VECCOPY(sbound->boundbox[0], smin);
+ VECCOPY(sbound->boundbox[1], smax);
+
+ DO_MINMAX(smin, min, max);
+ DO_MINMAX(smax, min, max);
+ }
+ }
+
+ VECCOPY(obr->boundbox[0], min);
+ VECCOPY(obr->boundbox[1], max);
}
}
}
@@ -3845,7 +4100,128 @@ static int render_object_type(int type)
return ELEM5(type, OB_FONT, OB_CURVE, OB_SURF, OB_MESH, OB_MBALL);
}
-static void init_render_object_data(Render *re, ObjectRen *obr, int only_verts)
+static void find_dupli_instances(Render *re, ObjectRen *obr)
+{
+ ObjectInstanceRen *obi;
+ float imat[4][4], obmat[4][4], obimat[4][4], nmat[3][3];
+ int first = 1;
+
+ Mat4MulMat4(obmat, obr->obmat, re->viewmat);
+ Mat4Invert(imat, obmat);
+
+ /* for objects instanced by dupliverts/faces/particles, we go over the
+ * list of instances to find ones that instance obr, and setup their
+ * matrices and obr pointer */
+ for(obi=re->instancetable.last; obi; obi=obi->prev) {
+ if(!obi->obr && obi->ob == obr->ob && obi->psysindex == obr->psysindex) {
+ obi->obr= obr;
+
+ /* compute difference between object matrix and
+ * object matrix with dupli transform, in viewspace */
+ Mat4CpyMat4(obimat, obi->mat);
+ Mat4MulMat4(obi->mat, imat, obimat);
+
+ Mat3CpyMat4(nmat, obi->mat);
+ Mat3Inv(obi->nmat, nmat);
+ Mat3Transp(obi->nmat);
+
+ if(!first) {
+ re->totvert += obr->totvert;
+ re->totvlak += obr->totvlak;
+ re->tothalo += obr->tothalo;
+ re->totstrand += obr->totstrand;
+ }
+ else
+ first= 0;
+ }
+ }
+}
+
+static void assign_dupligroup_dupli(Render *re, ObjectInstanceRen *obi, ObjectRen *obr)
+{
+ float imat[4][4], obmat[4][4], obimat[4][4], nmat[3][3];
+
+ Mat4MulMat4(obmat, obr->obmat, re->viewmat);
+ Mat4Invert(imat, obmat);
+
+ obi->obr= obr;
+
+ /* compute difference between object matrix and
+ * object matrix with dupli transform, in viewspace */
+ Mat4CpyMat4(obimat, obi->mat);
+ Mat4MulMat4(obi->mat, imat, obimat);
+
+ Mat3CpyMat4(nmat, obi->mat);
+ Mat3Inv(obi->nmat, nmat);
+ Mat3Transp(obi->nmat);
+
+ re->totvert += obr->totvert;
+ re->totvlak += obr->totvlak;
+ re->tothalo += obr->tothalo;
+ re->totstrand += obr->totstrand;
+}
+
+static ObjectRen *find_dupligroup_dupli(Render *re, Object *ob, int psysindex)
+{
+ ObjectRen *obr;
+
+ /* if the object is itself instanced, we don't want to create an instance
+ * for it */
+ if(ob->transflag & OB_RENDER_DUPLI)
+ return NULL;
+
+ /* try to find an object that was already created so we can reuse it
+ * and save memory */
+ for(obr=re->objecttable.first; obr; obr=obr->next)
+ if(obr->ob == ob && obr->psysindex == psysindex && (obr->flag & R_INSTANCEABLE))
+ return obr;
+
+ return NULL;
+}
+
+static void set_dupli_tex_mat(Render *re, ObjectInstanceRen *obi, DupliObject *dob)
+{
+ /* For duplis we need to have a matrix that transform the coordinate back
+ * to it's original position, without the dupli transforms. We also check
+ * the matrix is actually needed, to save memory on lots of dupliverts for
+ * example */
+ static Object *lastob= NULL;
+ static int needtexmat= 0;
+
+ /* init */
+ if(!re) {
+ lastob= NULL;
+ needtexmat= 0;
+ return;
+ }
+
+ /* check if we actually need it */
+ if(lastob != dob->ob) {
+ Material ***material;
+ short a, *totmaterial;
+
+ lastob= dob->ob;
+ needtexmat= 0;
+
+ totmaterial= give_totcolp(dob->ob);
+ material= give_matarar(dob->ob);
+
+ if(totmaterial && material)
+ for(a= 0; a<*totmaterial; a++)
+ if((*material)[a] && (*material)[a]->texco & TEXCO_OBJECT)
+ needtexmat= 1;
+ }
+
+ if(needtexmat) {
+ float imat[4][4];
+
+ obi->duplitexmat= BLI_memarena_alloc(re->memArena, sizeof(float)*4*4);
+ Mat4Invert(imat, dob->mat);
+ MTC_Mat4MulSerie(obi->duplitexmat, re->viewmat, dob->omat, imat, re->viewinv, 0, 0, 0, 0);
+ }
+}
+
+static void init_render_object_data(Render *re, ObjectRen *obr, int timeoffset)
{
Object *ob= obr->ob;
ParticleSystem *psys;
@@ -3863,20 +4239,20 @@ static void init_render_object_data(Render *re, ObjectRen *obr, int only_verts)
for(psys=ob->particlesystem.first, i=0; i<obr->psysindex-1; i++)
psys= psys->next;
- render_new_particle_system(re, obr, psys);
+ render_new_particle_system(re, obr, psys, timeoffset);
}
else {
if ELEM(ob->type, OB_FONT, OB_CURVE)
- init_render_curve(re, obr, only_verts);
+ init_render_curve(re, obr, timeoffset);
else if(ob->type==OB_SURF)
init_render_surf(re, obr);
else if(ob->type==OB_MESH)
- init_render_mesh(re, obr, only_verts);
+ init_render_mesh(re, obr, timeoffset);
else if(ob->type==OB_MBALL)
init_render_mball(re, obr);
}
- finalize_render_object(re, obr, only_verts);
+ finalize_render_object(re, obr, timeoffset);
re->totvert += obr->totvert;
re->totvlak += obr->totvlak;
@@ -3884,11 +4260,14 @@ static void init_render_object_data(Render *re, ObjectRen *obr, int only_verts)
re->totstrand += obr->totstrand;
}
-static void add_render_object(Render *re, Object *ob, Object *par, int index, int only_verts)
+static void add_render_object(Render *re, Object *ob, Object *par, DupliObject *dob, int timeoffset, int vectorlay)
{
ObjectRen *obr;
+ ObjectInstanceRen *obi;
ParticleSystem *psys;
- int show_emitter, allow_render= 1, psysindex;
+ int show_emitter, allow_render= 1, index, psysindex;
+
+ index= (dob)? dob->index: 0;
/* the emitter has to be processed first (render levels of modifiers) */
/* so here we only check if the emitter should be rendered */
@@ -3896,7 +4275,7 @@ static void add_render_object(Render *re, Object *ob, Object *par, int index, in
show_emitter= 0;
for(psys=ob->particlesystem.first; psys; psys=psys->next) {
show_emitter += psys->part->draw & PART_DRAW_EMITTER;
- psys_render_set(ob, psys, re->viewmat, re->winmat, re->winx, re->winy);
+ psys_render_set(ob, psys, re->viewmat, re->winmat, re->winx, re->winy, timeoffset);
}
/* if no psys has "show emitter" selected don't render emitter */
@@ -3906,32 +4285,52 @@ static void add_render_object(Render *re, Object *ob, Object *par, int index, in
/* one render object for the data itself */
if(allow_render) {
- obr= RE_addRenderObject(re, ob, par, index, 0);
- init_render_object_data(re, obr, only_verts);
+ obr= RE_addRenderObject(re, ob, par, index, 0, ob->lay);
+ if((dob && !dob->animated) || (ob->transflag & OB_RENDER_DUPLI)) {
+ obr->flag |= R_INSTANCEABLE;
+ Mat4CpyMat4(obr->obmat, ob->obmat);
+ }
+ if(obr->lay & vectorlay)
+ obr->flag |= R_NEED_VECTORS;
+ init_render_object_data(re, obr, timeoffset);
/* only add instance for objects that have not been used for dupli */
- if(!(ob->transflag & OB_RENDER_DUPLI))
- RE_addRenderInstance(re, obr, ob, par, index, 0, NULL);
+ if(!(ob->transflag & OB_RENDER_DUPLI)) {
+ obi= RE_addRenderInstance(re, obr, ob, par, index, 0, NULL, ob->lay);
+ if(dob) set_dupli_tex_mat(re, obi, dob);
+ }
+ else
+ find_dupli_instances(re, obr);
}
/* and one render object per particle system */
if(ob->particlesystem.first) {
psysindex= 1;
for(psys=ob->particlesystem.first; psys; psys=psys->next, psysindex++) {
- obr= RE_addRenderObject(re, ob, par, index, psysindex);
- init_render_object_data(re, obr, only_verts);
+ obr= RE_addRenderObject(re, ob, par, index, psysindex, ob->lay);
+ if((dob && !dob->animated) || (ob->transflag & OB_RENDER_DUPLI)) {
+ obr->flag |= R_INSTANCEABLE;
+ Mat4CpyMat4(obr->obmat, ob->obmat);
+ }
+ if(obr->lay & vectorlay)
+ obr->flag |= R_NEED_VECTORS;
+ init_render_object_data(re, obr, timeoffset);
psys_render_restore(ob, psys);
/* only add instance for objects that have not been used for dupli */
- if(!(ob->transflag & OB_RENDER_DUPLI))
- RE_addRenderInstance(re, obr, ob, par, index, psysindex, NULL);
+ if(!(ob->transflag & OB_RENDER_DUPLI)) {
+ obi= RE_addRenderInstance(re, obr, ob, par, index, psysindex, NULL, ob->lay);
+ if(dob) set_dupli_tex_mat(re, obi, dob);
+ }
+ else
+ find_dupli_instances(re, obr);
}
}
}
/* par = pointer to duplicator parent, needed for object lookup table */
/* index = when duplicater copies same object (particle), the counter */
-static void init_render_object(Render *re, Object *ob, Object *par, int index, int only_verts)
+static void init_render_object(Render *re, Object *ob, Object *par, DupliObject *dob, int timeoffset, int vectorlay)
{
static double lasttime= 0.0;
double time;
@@ -3940,7 +4339,7 @@ static void init_render_object(Render *re, Object *ob, Object *par, int index, i
if(ob->type==OB_LAMP)
add_render_lamp(re, ob);
else if(render_object_type(ob->type))
- add_render_object(re, ob, par, index, only_verts);
+ add_render_object(re, ob, par, dob, timeoffset, vectorlay);
else {
MTC_Mat4MulMat4(mat, ob->obmat, re->viewmat);
MTC_Mat4Invert(ob->imat, mat);
@@ -3965,6 +4364,14 @@ void RE_Database_Free(Render *re)
{
Object *ob = NULL;
LampRen *lar;
+
+ /* statistics for debugging render memory usage */
+ if((G.f & G_DEBUG) && (G.rendering)) {
+ if((re->r.scemode & R_PREVIEWBUTS)==0) {
+ BKE_image_print_memlist();
+ MEM_printmemlist_stats();
+ }
+ }
/* FREE */
@@ -3972,7 +4379,7 @@ void RE_Database_Free(Render *re)
freeshadowbuf(lar);
if(lar->jitter) MEM_freeN(lar->jitter);
if(lar->shadsamp) MEM_freeN(lar->shadsamp);
- if(lar->qsa) free_lamp_qmcsampler(lar);
+ if(lar->sunsky) MEM_freeN(lar->sunsky);
curvemapping_free(lar->curfalloff);
}
@@ -4010,13 +4417,14 @@ void RE_Database_Free(Render *re)
re->wrld.aotables= NULL;
re->scene->world->aotables= NULL;
}
- if((re->r.mode & R_RAYTRACE) && (re->wrld.mode & WO_AMB_OCC) &&
- (re->wrld.ao_samp_method == WO_AOSAMP_HAMMERSLEY) && (re->qsa))
+ if(re->r.mode & R_RAYTRACE)
free_render_qmcsampler(re);
if(re->r.mode & R_RAYTRACE) freeraytree(re);
free_sss(re);
+ free_occ(re);
+ free_strand_surface(re);
re->totvlak=re->totvert=re->totstrand=re->totlamp=re->tothalo= 0;
re->i.convertdone= 0;
@@ -4045,16 +4453,15 @@ static int allow_render_object(Object *ob, int nolamps, int onlyselected, Object
for(psys=ob->particlesystem.first; psys; psys=psys->next){
part=psys->part;
- if((part->draw_as==PART_DRAW_OB && part->dup_ob) || (part->draw_as==PART_DRAW_GR && part->dup_group))
- if(part->draw & PART_DRAW_EMITTER)
- allow= 1;
+ if(part->draw & PART_DRAW_EMITTER)
+ allow= 1;
}
}
if(!allow)
return 0;
}
- else if(ob->transflag & OB_DUPLI)
+ else if((ob->transflag & OB_DUPLI) && !(ob->transflag & OB_DUPLIFRAMES))
return 0;
if(nolamps && (ob->type==OB_LAMP))
@@ -4066,19 +4473,128 @@ static int allow_render_object(Object *ob, int nolamps, int onlyselected, Object
return 1;
}
-static int allow_render_dupli_instance(Render *re, Object *ob, Object *obd)
+static int allow_render_dupli_instance(Render *re, DupliObject *dob, Object *obd)
{
+ ParticleSystem *psys;
+ Material *ma;
+ short a, *totmaterial;
+
+ /* don't allow objects with halos. we need to have
+ * all halo's to sort them globally in advance */
+ totmaterial= give_totcolp(obd);
+
+ if(totmaterial) {
+ for(a= 0; a<*totmaterial; a++) {
+ ma= give_current_material(obd, a);
+ if(ma && (ma->mode & MA_HALO))
+ return 0;
+ }
+ }
+
+ for(psys=obd->particlesystem.first; psys; psys=psys->next)
+ if(!ELEM5(psys->part->draw_as, PART_DRAW_BB, PART_DRAW_LINE, PART_DRAW_PATH, PART_DRAW_OB, PART_DRAW_GR))
+ return 0;
+
+ /* don't allow lamp, animated duplis, or radio render */
return (render_object_type(obd->type) &&
- (!(ob->transflag & OB_DUPLIGROUP)) &&
+ (!(dob->type == OB_DUPLIGROUP) || !dob->animated) &&
!(re->r.mode & R_RADIO));
}
-static void database_init_objects(Render *re, unsigned int lay, int nolamps, int onlyselected, Object *actob, int only_verts)
+static void dupli_render_particle_set(Render *re, Object *ob, int timeoffset, int level, int enable)
+{
+ /* ugly function, but we need to set particle systems to their render
+ * settings before calling object_duplilist, to get render level duplis */
+ Group *group;
+ GroupObject *go;
+ ParticleSystem *psys;
+ DerivedMesh *dm;
+
+ if(level >= MAX_DUPLI_RECUR)
+ return;
+
+ if(ob->transflag & OB_DUPLIPARTS) {
+ for(psys=ob->particlesystem.first; psys; psys=psys->next) {
+ if(ELEM(psys->part->draw_as, PART_DRAW_OB, PART_DRAW_GR)) {
+ if(enable)
+ psys_render_set(ob, psys, re->viewmat, re->winmat, re->winx, re->winy, timeoffset);
+ else
+ psys_render_restore(ob, psys);
+ }
+ }
+
+ if(level == 0 && enable) {
+ /* this is to make sure we get render level duplis in groups:
+ * the derivedmesh must be created before init_render_mesh,
+ * since object_duplilist does dupliparticles before that */
+ dm = mesh_create_derived_render(ob, CD_MASK_BAREMESH|CD_MASK_MTFACE|CD_MASK_MCOL);
+ dm->release(dm);
+
+ for(psys=ob->particlesystem.first; psys; psys=psys->next)
+ psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated;
+ }
+ }
+
+ if(ob->dup_group==NULL) return;
+ group= ob->dup_group;
+
+ for(go= group->gobject.first; go; go= go->next)
+ dupli_render_particle_set(re, go->ob, timeoffset, level+1, enable);
+}
+
+static int get_vector_renderlayers(Scene *sce)
+{
+ SceneRenderLayer *srl;
+ int lay= 0;
+
+ for(srl= sce->r.layers.first; srl; srl= srl->next)
+ if(srl->passflag & SCE_PASS_VECTOR)
+ lay |= srl->lay;
+
+ return lay;
+}
+
+static void add_group_render_dupli_obs(Render *re, Group *group, int nolamps, int onlyselected, Object *actob, int timeoffset, int vectorlay, int level)
+{
+ GroupObject *go;
+ Object *ob;
+
+ /* simple preventing of too deep nested groups */
+ if(level>MAX_DUPLI_RECUR) return;
+
+ /* recursively go into dupligroups to find objects with OB_RENDER_DUPLI
+ * that were not created yet */
+ for(go= group->gobject.first; go; go= go->next) {
+ ob= go->ob;
+
+ if(ob->flag & OB_DONE) {
+ if(ob->transflag & OB_RENDER_DUPLI) {
+ if(allow_render_object(ob, nolamps, onlyselected, actob)) {
+ init_render_object(re, ob, NULL, 0, timeoffset, vectorlay);
+ ob->transflag &= ~OB_RENDER_DUPLI;
+
+ if(ob->dup_group)
+ add_group_render_dupli_obs(re, ob->dup_group, nolamps, onlyselected, actob, timeoffset, vectorlay, level+1);
+ }
+ }
+ }
+ }
+}
+
+static void database_init_objects(Render *re, unsigned int renderlay, int nolamps, int onlyselected, Object *actob, int timeoffset)
{
Base *base;
Object *ob;
+ Group *group;
+ ObjectInstanceRen *obi;
Scene *sce;
float mat[4][4];
+ int lay, vectorlay, redoimat= 0;
+
+ /* for duplis we need the Object texture mapping to work as if
+ * untransformed, set_dupli_tex_mat sets the matrix to allow that
+ * NULL is just for init */
+ set_dupli_tex_mat(NULL, NULL, NULL);
for(SETLOOPER(re->scene, base)) {
ob= base->object;
@@ -4092,76 +4608,149 @@ static void database_init_objects(Render *re, unsigned int lay, int nolamps, int
for(SETLOOPER(re->scene, base)) {
ob= base->object;
-
+
+ /* in the prev/next pass for making speed vectors, avoid creating
+ * objects that are not on a renderlayer with a vector pass, can
+ * save a lot of time in complex scenes */
+ vectorlay= get_vector_renderlayers(sce);
+ lay= (timeoffset)? renderlay & vectorlay: renderlay;
+
/* if the object has been restricted from rendering in the outliner, ignore it */
if(ob->restrictflag & OB_RESTRICT_RENDER) continue;
/* OB_DONE means the object itself got duplicated, so was already converted */
if(ob->flag & OB_DONE) {
- if(ob->transflag & OB_RENDER_DUPLI)
- if(allow_render_object(ob, nolamps, onlyselected, actob))
- init_render_object(re, ob, NULL, 0, only_verts);
+ /* OB_RENDER_DUPLI means instances for it were already created, now
+ * it still needs to create the ObjectRen containing the data */
+ if(ob->transflag & OB_RENDER_DUPLI) {
+ if(allow_render_object(ob, nolamps, onlyselected, actob)) {
+ init_render_object(re, ob, NULL, 0, timeoffset, vectorlay);
+ ob->transflag &= ~OB_RENDER_DUPLI;
+ }
+ }
}
else if((base->lay & lay) || (ob->type==OB_LAMP && (base->lay & re->scene->lay)) ) {
if((ob->transflag & OB_DUPLI) && (ob->type!=OB_MBALL)) {
DupliObject *dob;
ListBase *lb;
+ redoimat= 1;
+
+ /* create list of duplis generated by this object, particle
+ * system need to have render settings set for dupli particles */
+ dupli_render_particle_set(re, ob, timeoffset, 0, 1);
lb= object_duplilist(sce, ob);
+ dupli_render_particle_set(re, ob, timeoffset, 0, 0);
+
for(dob= lb->first; dob; dob= dob->next) {
Object *obd= dob->ob;
Mat4CpyMat4(obd->obmat, dob->mat);
/* group duplis need to set ob matrices correct, for deform. so no_draw is part handled */
- if(dob->no_draw)
+ if(!(obd->transflag & OB_RENDER_DUPLI) && dob->no_draw)
continue;
if(obd->restrictflag & OB_RESTRICT_RENDER)
continue;
-
+
if(obd->type==OB_MBALL)
continue;
if(!allow_render_object(obd, nolamps, onlyselected, actob))
continue;
- if(allow_render_dupli_instance(re, ob, obd)) {
+ if(allow_render_dupli_instance(re, dob, obd)) {
ParticleSystem *psys;
+ ObjectRen *obr = NULL;
int psysindex;
- float imat[4][4], mat[4][4];
-
- /* compute difference between object matrix and
- * object matrix with dupli transform, in viewspace */
- Mat4Invert(imat, dob->omat);
- MTC_Mat4MulSerie(mat, re->viewmat, dob->mat, imat, re->viewinv, 0, 0, 0, 0);
-
- RE_addRenderInstance(re, NULL, obd, ob, dob->index, 0, mat);
+ float mat[4][4];
+
+ /* instances instead of the actual object are added in two cases, either
+ * this is a duplivert/face/particle, or it is a non-animated object in
+ * a dupligroup that has already been created before */
+ if(dob->type != OB_DUPLIGROUP || (obr=find_dupligroup_dupli(re, obd, 0))) {
+ Mat4MulMat4(mat, dob->mat, re->viewmat);
+ obi= RE_addRenderInstance(re, NULL, obd, ob, dob->index, 0, mat, obd->lay);
+
+ /* fill in instance variables for texturing */
+ set_dupli_tex_mat(re, obi, dob);
+ if(dob->type != OB_DUPLIGROUP) {
+ VECCOPY(obi->dupliorco, dob->orco);
+ obi->dupliuv[0]= dob->uv[0];
+ obi->dupliuv[1]= dob->uv[1];
+ }
+ else {
+ /* for the second case, setup instance to point to the already
+ * created object, and possibly setup instances if this object
+ * itself was duplicated. for the first case find_dupli_instances
+ * will be called later. */
+ assign_dupligroup_dupli(re, obi, obr);
+ if(obd->transflag & OB_RENDER_DUPLI)
+ find_dupli_instances(re, obr);
+ }
+ }
+ else
+ /* can't instance, just create the object */
+ init_render_object(re, obd, ob, dob, timeoffset, vectorlay);
+ /* same logic for particles, each particle system has it's own object, so
+ * need to go over them separately */
psysindex= 1;
- for(psys=obd->particlesystem.first; psys; psys=psys->next)
- RE_addRenderInstance(re, NULL, obd, ob, dob->index, psysindex++, mat);
+ for(psys=obd->particlesystem.first; psys; psys=psys->next) {
+ if(dob->type != OB_DUPLIGROUP || (obr=find_dupligroup_dupli(re, ob, psysindex))) {
+ obi= RE_addRenderInstance(re, NULL, obd, ob, dob->index, psysindex++, mat, obd->lay);
+
+ set_dupli_tex_mat(re, obi, dob);
+ if(dob->type != OB_DUPLIGROUP) {
+ VECCOPY(obi->dupliorco, dob->orco);
+ obi->dupliuv[0]= dob->uv[0];
+ obi->dupliuv[1]= dob->uv[1];
+ }
+ else {
+ assign_dupligroup_dupli(re, obi, obr);
+ if(obd->transflag & OB_RENDER_DUPLI)
+ find_dupli_instances(re, obr);
+ }
+ }
+ }
- obd->flag |= OB_DONE;
- obd->transflag |= OB_RENDER_DUPLI;
+ if(dob->type != OB_DUPLIGROUP) {
+ obd->flag |= OB_DONE;
+ obd->transflag |= OB_RENDER_DUPLI;
+ }
}
else
- init_render_object(re, obd, ob, dob->index, only_verts);
+ init_render_object(re, obd, ob, dob, timeoffset, vectorlay);
if(re->test_break()) break;
}
free_object_duplilist(lb);
if(allow_render_object(ob, nolamps, onlyselected, actob))
- init_render_object(re, ob, NULL, 0, only_verts);
+ init_render_object(re, ob, NULL, 0, timeoffset, vectorlay);
}
else if(allow_render_object(ob, nolamps, onlyselected, actob))
- init_render_object(re, ob, NULL, 0, only_verts);
+ init_render_object(re, ob, NULL, 0, timeoffset, vectorlay);
}
if(re->test_break()) break;
}
+ /* objects in groups with OB_RENDER_DUPLI set still need to be created,
+ * since they may not be part of the scene */
+ for(group= G.main->group.first; group; group=group->id.next)
+ add_group_render_dupli_obs(re, group, nolamps, onlyselected, actob, timeoffset, renderlay, 0);
+
+ /* imat objects has to be done again, since groups can mess it up */
+ if(redoimat) {
+ for(SETLOOPER(re->scene, base)) {
+ ob= base->object;
+ MTC_Mat4MulMat4(mat, ob->obmat, re->viewmat);
+ MTC_Mat4Invert(ob->imat, mat);
+ }
+ }
+
if(!re->test_break())
RE_makeRenderInstances(re);
}
@@ -4202,14 +4791,16 @@ void RE_Database_FromScene(Render *re, Scene *scene, int use_camera_view)
Mat4Ortho(re->scene->camera->obmat);
Mat4Invert(mat, re->scene->camera->obmat);
RE_SetView(re, mat);
+ re->scene->camera->recalc= OB_RECALC_OB; /* force correct matrix for scaled cameras */
}
init_render_world(re); /* do first, because of ambient. also requires re->osa set correct */
- if(re->wrld.mode & WO_AMB_OCC) {
- if (re->wrld.ao_samp_method == WO_AOSAMP_HAMMERSLEY)
- init_render_hammersley(re);
- else if (re->wrld.ao_samp_method == WO_AOSAMP_CONSTANT)
- init_ao_sphere(&re->wrld);
+ if(re->r.mode & R_RAYTRACE) {
+ init_render_qmcsampler(re);
+
+ if(re->wrld.mode & WO_AMB_OCC)
+ if (re->wrld.ao_samp_method == WO_AOSAMP_CONSTANT)
+ init_ao_sphere(&re->wrld);
}
/* still bad... doing all */
@@ -4270,10 +4861,17 @@ void RE_Database_FromScene(Render *re, Scene *scene, int use_camera_view)
if(!re->test_break())
project_renderdata(re, projectverto, re->r.mode & R_PANORAMA, 0, 1);
+
+ /* Occlusion */
+ if((re->wrld.mode & WO_AMB_OCC) && !re->test_break())
+ if(re->wrld.ao_gather_method == WO_AOGATHER_APPROX)
+ if(re->r.renderer==R_INTERN)
+ if(re->r.mode & R_SHADOW)
+ make_occ_tree(re);
/* SSS */
if((re->r.mode & R_SSS) && !re->test_break())
- if (re->r.renderer==R_INTERN)
+ if(re->r.renderer==R_INTERN)
make_sss_tree(re);
}
@@ -4334,7 +4932,7 @@ static void database_fromscene_vectors(Render *re, Scene *scene, int timeoffset)
}
/* MAKE RENDER DATA */
- database_init_objects(re, lay, 0, 0, 0, 1);
+ database_init_objects(re, lay, 0, 0, 0, timeoffset);
if(!re->test_break())
project_renderdata(re, projectverto, re->r.mode & R_PANORAMA, 0, 1);
@@ -4429,14 +5027,49 @@ static void calculate_speedvector(float *vectors, int step, float winsq, float w
}
}
+static float *calculate_strandsurface_speedvectors(Render *re, ObjectInstanceRen *obi, StrandSurface *mesh)
+{
+ float winsq= re->winx*re->winy, winroot= sqrt(winsq), (*winspeed)[4];
+ float ho[4], prevho[4], nextho[4], winmat[4][4], vec[2];
+ int a;
+
+ if(mesh->co && mesh->prevco && mesh->nextco) {
+ if(obi->flag & R_TRANSFORMED)
+ Mat4MulMat4(winmat, obi->mat, re->winmat);
+ else
+ Mat4CpyMat4(winmat, re->winmat);
+
+ winspeed= MEM_callocN(sizeof(float)*4*mesh->totvert, "StrandSurfWin");
+
+ for(a=0; a<mesh->totvert; a++) {
+ projectvert(mesh->co[a], winmat, ho);
+
+ projectvert(mesh->prevco[a], winmat, prevho);
+ speedvector_project(NULL, vec, mesh->prevco[a], prevho);
+ calculate_speedvector(vec, 0, winsq, winroot, mesh->co[a], ho, winspeed[a]);
+
+ projectvert(mesh->nextco[a], winmat, nextho);
+ speedvector_project(NULL, vec, mesh->nextco[a], nextho);
+ calculate_speedvector(vec, 1, winsq, winroot, mesh->co[a], ho, winspeed[a]);
+ }
+
+ return (float*)winspeed;
+ }
+
+ return NULL;
+}
+
static void calculate_speedvectors(Render *re, ObjectInstanceRen *obi, float *vectors, int step)
{
ObjectRen *obr= obi->obr;
VertRen *ver= NULL;
StrandRen *strand= NULL;
- float *speed, ho[4], winmat[4][4];
+ StrandBuffer *strandbuf;
+ StrandSurface *mesh= NULL;
+ float *speed, (*winspeed)[4]=NULL, ho[4], winmat[4][4];
+ float *co1, *co2, *co3, *co4, w[4];
float winsq= re->winx*re->winy, winroot= sqrt(winsq);
- int a;
+ int a, *face, *index;
if(obi->flag & R_TRANSFORMED)
Mat4MulMat4(winmat, obi->mat, re->winmat);
@@ -4455,13 +5088,42 @@ static void calculate_speedvectors(Render *re, ObjectInstanceRen *obi, float *ve
}
if(obr->strandnodes) {
- for(a=0; a<obr->totstrand; a++, vectors+=2) {
- if((a & 255)==0) strand= obr->strandnodes[a>>8].strand;
- else strand++;
+ strandbuf= obr->strandbuf;
+ mesh= (strandbuf)? strandbuf->surface: NULL;
+
+ /* compute speed vectors at surface vertices */
+ if(mesh)
+ winspeed= (float(*)[4])calculate_strandsurface_speedvectors(re, obi, mesh);
+
+ if(winspeed) {
+ for(a=0; a<obr->totstrand; a++, vectors+=2) {
+ if((a & 255)==0) strand= obr->strandnodes[a>>8].strand;
+ else strand++;
+
+ index= RE_strandren_get_face(obr, strand, 0);
+ if(index && *index < mesh->totface) {
+ speed= RE_strandren_get_winspeed(obi, strand, 1);
+
+ /* interpolate speed vectors from strand surface */
+ face= mesh->face[*index];
+
+ co1= mesh->co[face[0]];
+ co2= mesh->co[face[1]];
+ co3= mesh->co[face[2]];
+ co4= (face[3])? mesh->co[face[3]]: NULL;
+
+ InterpWeightsQ3Dfl(co1, co2, co3, co4, strand->vert->co, w);
+
+ speed[0]= speed[1]= speed[2]= speed[3]= 0.0f;
+ QUATADDFAC(speed, speed, winspeed[face[0]], w[0]);
+ QUATADDFAC(speed, speed, winspeed[face[1]], w[1]);
+ QUATADDFAC(speed, speed, winspeed[face[2]], w[2]);
+ if(face[3])
+ QUATADDFAC(speed, speed, winspeed[face[3]], w[3]);
+ }
+ }
- speed= RE_strandren_get_winspeed(obi, strand, 1);
- projectvert(strand->vert->co, winmat, ho);
- calculate_speedvector(vectors, step, winsq, winroot, strand->vert->co, ho, speed);
+ MEM_freeN(winspeed);
}
}
}
@@ -4471,36 +5133,54 @@ static int load_fluidsimspeedvectors(Render *re, ObjectInstanceRen *obi, float *
ObjectRen *obr= obi->obr;
Object *fsob= obr->ob;
VertRen *ver= NULL;
- float *speed, div, zco[2];
+ float *speed, div, zco[2], avgvel[4] = {0.0, 0.0, 0.0, 0.0};
float zmulx= re->winx/2, zmuly= re->winy/2, len;
float winsq= re->winx*re->winy, winroot= sqrt(winsq);
int a, j;
float hoco[4], ho[4], fsvec[4], camco[4];
float mat[4][4], winmat[4][4];
float imat[4][4];
- MVert *vverts;
-
+ FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(fsob, eModifierType_Fluidsim);
+ FluidsimSettings *fss = fluidmd->fss;
+ float *velarray = NULL;
+
/* only one step needed */
if(step) return 1;
+ if(fluidmd)
+ fss = fluidmd->fss;
+ else
+ return 0;
+
Mat4CpyMat4(mat, re->viewmat);
MTC_Mat4Invert(imat, mat);
/* set first vertex OK */
- if( (!fsob->fluidsimSettings) || (!fsob->fluidsimSettings->meshSurfNormals) ) return 0;
- vverts = fsob->fluidsimSettings->meshSurfNormals;
- //fprintf(stderr, "GZ_VEL obj '%s', calc load_fluidsimspeedvectors\n",fsob->id.name); // NT DEBUG
-
- if( obr->totvert != fsob->fluidsimSettings->meshSurface->totvert ) {
+ if(!fss->meshSurfNormals) return 0;
+
+ if( obr->totvert != GET_INT_FROM_POINTER(fss->meshSurface) ) {
//fprintf(stderr, "load_fluidsimspeedvectors - modified fluidsim mesh, not using speed vectors (%d,%d)...\n", obr->totvert, fsob->fluidsimSettings->meshSurface->totvert); // DEBUG
return 0;
}
+
+ velarray = (float *)fss->meshSurfNormals;
if(obi->flag & R_TRANSFORMED)
Mat4MulMat4(winmat, obi->mat, re->winmat);
else
Mat4CpyMat4(winmat, re->winmat);
+ /* (bad) HACK calculate average velocity */
+ /* better solution would be fixing getVelocityAt() in intern/elbeem/intern/solver_util.cpp
+ so that also small drops/little water volumes return a velocity != 0.
+ But I had no luck in fixing that function - DG */
+ for(a=0; a<obr->totvert; a++) {
+ for(j=0;j<3;j++) avgvel[j] += velarray[3*a + j];
+
+ }
+ for(j=0;j<3;j++) avgvel[j] /= (float)(obr->totvert);
+
+
for(a=0; a<obr->totvert; a++, vectors+=2) {
if((a & 255)==0)
ver= obr->vertnodes[a>>8].vert;
@@ -4510,8 +5190,16 @@ static int load_fluidsimspeedvectors(Render *re, ObjectInstanceRen *obi, float *
// get fluid velocity
fsvec[3] = 0.;
//fsvec[0] = fsvec[1] = fsvec[2] = fsvec[3] = 0.; fsvec[2] = 2.; // NT fixed test
- for(j=0;j<3;j++) fsvec[j] = vverts[a].co[j];
-
+ for(j=0;j<3;j++) fsvec[j] = velarray[3*a + j];
+
+ /* (bad) HACK insert average velocity if none is there (see previous comment) */
+ if((fsvec[0] == 0.0) && (fsvec[1] == 0.0) && (fsvec[2] == 0.0))
+ {
+ fsvec[0] = avgvel[0];
+ fsvec[1] = avgvel[1];
+ fsvec[2] = avgvel[2];
+ }
+
// transform (=rotate) to cam space
camco[0]= imat[0][0]*fsvec[0] + imat[0][1]*fsvec[1] + imat[0][2]*fsvec[2];
camco[1]= imat[1][0]*fsvec[0] + imat[1][1]*fsvec[1] + imat[1][2]*fsvec[2];
@@ -4552,7 +5240,6 @@ static void copy_dbase_object_vectors(Render *re, ListBase *lb)
ObjectInstanceRen *obi, *obilb;
ObjectRen *obr;
VertRen *ver= NULL;
- StrandRen *strand= NULL;
float *vec, ho[4], winmat[4][4];
int a, totvector;
@@ -4563,7 +5250,7 @@ static void copy_dbase_object_vectors(Render *re, ListBase *lb)
memcpy(obilb, obi, sizeof(ObjectInstanceRen));
BLI_addtail(lb, obilb);
- obilb->totvector= totvector= obr->totvert + obr->totstrand;
+ obilb->totvector= totvector= obr->totvert;
if(totvector > 0) {
vec= obilb->vectors= MEM_mallocN(2*sizeof(float)*totvector, "vector array");
@@ -4580,14 +5267,6 @@ static void copy_dbase_object_vectors(Render *re, ListBase *lb)
projectvert(ver->co, winmat, ho);
speedvector_project(NULL, vec, ver->co, ho);
}
-
- for(a=0; a<obr->totstrand; a++, vec+=2) {
- if((a & 255)==0) strand= obr->strandnodes[a>>8].strand;
- else strand++;
-
- projectvert(strand->vert->co, winmat, ho);
- speedvector_project(NULL, vec, strand->vert->co, ho);
- }
}
}
}
@@ -4605,8 +5284,10 @@ static void free_dbase_object_vectors(ListBase *lb)
void RE_Database_FromScene_Vectors(Render *re, Scene *sce)
{
ObjectInstanceRen *obi, *oldobi;
+ StrandSurface *mesh;
ListBase *table;
ListBase oldtable= {NULL, NULL}, newtable= {NULL, NULL};
+ ListBase strandsurface;
int step;
re->i.infostr= "Calculating previous vectors";
@@ -4621,7 +5302,10 @@ void RE_Database_FromScene_Vectors(Render *re, Scene *sce)
copy_dbase_object_vectors(re, &oldtable);
/* free dbase and make the future one */
+ strandsurface= re->strandsurface;
+ memset(&re->strandsurface, 0, sizeof(ListBase));
RE_Database_Free(re);
+ re->strandsurface= strandsurface;
if(!re->test_break()) {
/* creates entire dbase */
@@ -4633,7 +5317,10 @@ void RE_Database_FromScene_Vectors(Render *re, Scene *sce)
copy_dbase_object_vectors(re, &newtable);
/* free dbase and make the real one */
+ strandsurface= re->strandsurface;
+ memset(&re->strandsurface, 0, sizeof(ListBase));
RE_Database_Free(re);
+ re->strandsurface= strandsurface;
if(!re->test_break())
RE_Database_FromScene(re, sce, 1);
@@ -4647,10 +5334,14 @@ void RE_Database_FromScene_Vectors(Render *re, Scene *sce)
table= &oldtable;
oldobi= table->first;
- for(obi= re->instancetable.first; obi && oldobi; obi= obi->next, oldobi= oldobi->next) {
+ for(obi= re->instancetable.first; obi && oldobi; obi= obi->next) {
int ok= 1;
+ FluidsimModifierData *fluidmd;
+
+ if(!(obi->obr->flag & R_NEED_VECTORS))
+ continue;
- obi->totvector= obi->obr->totvert + obi->obr->totstrand;
+ obi->totvector= obi->obr->totvert;
/* find matching object in old table */
if(oldobi->ob!=obi->ob || oldobi->par!=obi->par || oldobi->index!=obi->index || oldobi->psysindex!=obi->psysindex) {
@@ -4669,25 +5360,38 @@ void RE_Database_FromScene_Vectors(Render *re, Scene *sce)
}
// NT check for fluidsim special treatment
- if((obi->ob->fluidsimFlag & OB_FLUIDSIM_ENABLE) && (obi->ob->fluidsimSettings->type & OB_FLUIDSIM_DOMAIN)) {
+ fluidmd = (FluidsimModifierData *)modifiers_findByType(obi->ob, eModifierType_Fluidsim);
+ if(fluidmd && fluidmd->fss && (fluidmd->fss->type & OB_FLUIDSIM_DOMAIN)) {
// use preloaded per vertex simulation data , only does calculation for step=1
// NOTE/FIXME - velocities and meshes loaded unnecessarily often during the database_fromscene_vectors calls...
load_fluidsimspeedvectors(re, obi, oldobi->vectors, step);
- } else {
+ }
+ else {
/* check if both have same amounts of vertices */
- if(obi->totvector!=oldobi->totvector) {
+ if(obi->totvector==oldobi->totvector)
+ calculate_speedvectors(re, obi, oldobi->vectors, step);
+ else
printf("Warning: object %s has different amount of vertices or strands on other frame\n", obi->ob->id.name+2);
- continue;
- }
-
- calculate_speedvectors(re, obi, oldobi->vectors, step);
} // not fluidsim
+
+ oldobi= oldobi->next;
}
}
}
free_dbase_object_vectors(&oldtable);
free_dbase_object_vectors(&newtable);
+
+ for(mesh=re->strandsurface.first; mesh; mesh=mesh->next) {
+ if(mesh->prevco) {
+ MEM_freeN(mesh->prevco);
+ mesh->prevco= NULL;
+ }
+ if(mesh->nextco) {
+ MEM_freeN(mesh->nextco);
+ mesh->nextco= NULL;
+ }
+ }
re->i.infostr= NULL;
re->stats_draw(&re->i);
@@ -4705,6 +5409,8 @@ void RE_Database_FromScene_Vectors(Render *re, Scene *sce)
RE_BAKE_NORMALS:for baking, no lamps and only selected objects
RE_BAKE_AO: for baking, no lamps, but all objects
RE_BAKE_TEXTURE:for baking, no lamps, only selected objects
+ RE_BAKE_DISPLACEMENT:for baking, no lamps, only selected objects
+ RE_BAKE_SHADOW: for baking, only shadows, but all objects
*/
void RE_Database_Baking(Render *re, Scene *scene, int type, Object *actob)
{
@@ -4716,21 +5422,31 @@ void RE_Database_Baking(Render *re, Scene *scene, int type, Object *actob)
/* renderdata setup and exceptions */
re->r= scene->r;
- re->r.mode &= ~R_OSA;
+
+ RE_init_threadcount(re);
+
re->flag |= R_GLOB_NOPUNOFLIP;
+ re->flag |= R_BAKING;
re->excludeob= actob;
+ if(type == RE_BAKE_LIGHT)
+ re->flag |= R_SKIP_MULTIRES;
+ if(actob)
+ re->flag |= R_BAKE_TRACE;
if(type==RE_BAKE_NORMALS && re->r.bake_normal_space==R_BAKE_SPACE_TANGENT)
re->flag |= R_NEED_TANGENT;
- if(!actob && ELEM3(type, RE_BAKE_LIGHT, RE_BAKE_NORMALS, RE_BAKE_TEXTURE)) {
+ if(!actob && ELEM4(type, RE_BAKE_LIGHT, RE_BAKE_NORMALS, RE_BAKE_TEXTURE, RE_BAKE_DISPLACEMENT)) {
re->r.mode &= ~R_SHADOW;
re->r.mode &= ~R_RAYTRACE;
}
+ if(!actob && (type==RE_BAKE_SHADOW)) {
+ re->r.mode |= R_SHADOW;
+ }
+
/* setup render stuff */
- if(type!=RE_BAKE_LIGHT)
- re->memArena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
+ re->memArena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
re->totvlak=re->totvert=re->totstrand=re->totlamp=re->tothalo= 0;
re->lights.first= re->lights.last= NULL;
@@ -4752,11 +5468,12 @@ void RE_Database_Baking(Render *re, Scene *scene, int type, Object *actob)
}
init_render_world(re); /* do first, because of ambient. also requires re->osa set correct */
- if(re->wrld.mode & WO_AMB_OCC) {
- if (re->wrld.ao_samp_method == WO_AOSAMP_HAMMERSLEY)
- init_render_hammersley(re);
- else if (re->wrld.ao_samp_method == WO_AOSAMP_CONSTANT)
- init_ao_sphere(&re->wrld);
+ if(re->r.mode & R_RAYTRACE) {
+ init_render_qmcsampler(re);
+
+ if(re->wrld.mode & WO_AMB_OCC)
+ if (re->wrld.ao_samp_method == WO_AOSAMP_CONSTANT)
+ init_ao_sphere(&re->wrld);
}
/* still bad... doing all */
@@ -4765,8 +5482,8 @@ void RE_Database_Baking(Render *re, Scene *scene, int type, Object *actob)
set_node_shader_lamp_loop(shade_material_loop);
/* MAKE RENDER DATA */
- nolamps= !ELEM(type, RE_BAKE_LIGHT, RE_BAKE_ALL);
- onlyselected= ELEM(type, RE_BAKE_NORMALS, RE_BAKE_TEXTURE);
+ nolamps= !ELEM3(type, RE_BAKE_LIGHT, RE_BAKE_ALL, RE_BAKE_SHADOW);
+ onlyselected= ELEM3(type, RE_BAKE_NORMALS, RE_BAKE_TEXTURE, RE_BAKE_DISPLACEMENT);
database_init_objects(re, lay, nolamps, onlyselected, actob, 0);
@@ -4781,6 +5498,12 @@ void RE_Database_Baking(Render *re, Scene *scene, int type, Object *actob)
if(!re->test_break())
if(re->r.mode & R_RAYTRACE)
makeraytree(re);
+
+ /* occlusion */
+ if((re->wrld.mode & WO_AMB_OCC) && !re->test_break())
+ if(re->wrld.ao_gather_method == WO_AOGATHER_APPROX)
+ if(re->r.mode & R_SHADOW)
+ make_occ_tree(re);
}
/* ------------------------------------------------------------------------- */
@@ -4813,7 +5536,7 @@ void RE_make_sticky(void)
}
re= RE_NewRender("_make sticky_");
- RE_InitState(re, &G.scene->r, G.scene->r.xsch, G.scene->r.ysch, NULL);
+ RE_InitState(re, NULL, &G.scene->r, G.scene->r.xsch, G.scene->r.ysch, NULL);
/* use renderdata and camera to set viewplane */
RE_SetCamera(re, G.scene->camera);
diff --git a/source/blender/render/intern/source/envmap.c b/source/blender/render/intern/source/envmap.c
index b1b907aebb6..13fa9b17b71 100644
--- a/source/blender/render/intern/source/envmap.c
+++ b/source/blender/render/intern/source/envmap.c
@@ -127,7 +127,7 @@ static Render *envmap_render_copy(Render *re, EnvMap *env)
envre->r.size= 100;
envre->r.yasp= envre->r.xasp= 1;
- RE_InitState(envre, &envre->r, cuberes, cuberes, NULL);
+ RE_InitState(envre, NULL, &envre->r, cuberes, cuberes, NULL);
envre->scene= re->scene; /* unsure about this... */
/* view stuff in env render */
@@ -150,14 +150,15 @@ static Render *envmap_render_copy(Render *re, EnvMap *env)
envre->tothalo= re->tothalo;
envre->totstrand= re->totstrand;
envre->totlamp= re->totlamp;
+ envre->sortedhalos= re->sortedhalos;
envre->lights= re->lights;
envre->objecttable= re->objecttable;
- envre->strandbuckets= re->strandbuckets;
envre->customdata_names= re->customdata_names;
envre->raytree= re->raytree;
envre->totinstance= re->totinstance;
envre->instancetable= re->instancetable;
envre->objectinstance= re->objectinstance;
+ envre->qmcsamplers= re->qmcsamplers;
return envre;
}
@@ -171,13 +172,14 @@ static void envmap_free_render_copy(Render *envre)
envre->totstrand= 0;
envre->totlamp= 0;
envre->totinstance= 0;
+ envre->sortedhalos= NULL;
envre->lights.first= envre->lights.last= NULL;
envre->objecttable.first= envre->objecttable.last= NULL;
- envre->strandbuckets= NULL;
envre->customdata_names.first= envre->customdata_names.last= NULL;
envre->raytree= NULL;
envre->instancetable.first= envre->instancetable.last= NULL;
envre->objectinstance= NULL;
+ envre->qmcsamplers= NULL;
RE_FreeRender(envre);
}
@@ -223,7 +225,7 @@ static void env_rotate_scene(Render *re, float mat[][4], int mode)
ObjectInstanceRen *obi;
LampRen *lar = NULL;
HaloRen *har = NULL;
- float imat[3][3], pmat[4][4], smat[4][4], tmat[4][4], cmat[3][3];
+ float imat[3][3], pmat[4][4], smat[4][4], tmat[4][4], cmat[3][3], tmpmat[4][4];
int a;
if(mode==0) {
@@ -237,15 +239,18 @@ static void env_rotate_scene(Render *re, float mat[][4], int mode)
for(obi=re->instancetable.first; obi; obi=obi->next) {
/* append or set matrix depending on dupli */
- if(obi->flag & R_DUPLI_TRANSFORMED)
- Mat4MulMat4(obi->mat, tmat, obi->mat);
+ if(obi->flag & R_DUPLI_TRANSFORMED) {
+ Mat4CpyMat4(tmpmat, obi->mat);
+ Mat4MulMat4(obi->mat, tmpmat, tmat);
+ }
else if(mode==1)
Mat4CpyMat4(obi->mat, tmat);
else
Mat4One(obi->mat);
Mat3CpyMat4(cmat, obi->mat);
- Mat3Inv(obi->imat, cmat);
+ Mat3Inv(obi->nmat, cmat);
+ Mat3Transp(obi->nmat);
/* indicate the renderer has to use transform matrices */
if(mode==0)
@@ -313,12 +318,13 @@ static void env_layerflags(Render *re, unsigned int notlay)
notlay= ~notlay;
for(obr=re->objecttable.first; obr; obr=obr->next) {
- for(a=0; a<obr->totvlak; a++) {
- if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak;
- else vlr++;
+ if((obr->lay & notlay)==0) {
+ for(a=0; a<obr->totvlak; a++) {
+ if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak;
+ else vlr++;
- if((vlr->lay & notlay)==0)
vlr->flag |= R_HIDDEN;
+ }
}
}
}
@@ -433,12 +439,19 @@ static void render_envmap(Render *re, EnvMap *env)
if(re->test_break()==0) {
RenderLayer *rl= envre->result->layers.first;
+ int y;
+ char *alpha;
ibuf= IMB_allocImBuf(envre->rectx, envre->recty, 24, IB_rect, 0);
ibuf->rect_float= rl->rectf;
IMB_rect_from_float(ibuf);
ibuf->rect_float= NULL;
-
+
+ /* envmap renders without alpha */
+ alpha= ((char *)ibuf->rect)+3;
+ for(y= ibuf->x*ibuf->y - 1; y>=0; y--, alpha+=4)
+ *alpha= 255;
+
env->cube[part]= ibuf;
}
@@ -715,7 +728,7 @@ int envmaptex(Tex *tex, float *texvec, float *dxt, float *dyt, int osatex, TexRe
fac= (texres->ta+texr1.ta+texr2.ta);
if(fac!=0.0) {
fac= 1.0/fac;
-
+
texres->tr= fac*(texres->ta*texres->tr + texr1.ta*texr1.tr + texr2.ta*texr2.tr );
texres->tg= fac*(texres->ta*texres->tg + texr1.ta*texr1.tg + texr2.ta*texr2.tg );
texres->tb= fac*(texres->ta*texres->tb + texr1.ta*texr1.tb + texr2.ta*texr2.tb );
diff --git a/source/blender/render/intern/source/imagetexture.c b/source/blender/render/intern/source/imagetexture.c
index 23b5e597070..b9a2acb8b1c 100644
--- a/source/blender/render/intern/source/imagetexture.c
+++ b/source/blender/render/intern/source/imagetexture.c
@@ -32,6 +32,7 @@
#include <string.h>
#include <fcntl.h>
#include <math.h>
+#include <float.h>
#ifndef WIN32
#include <unistd.h>
#else
@@ -93,10 +94,10 @@ static void ibuf_get_color(float *col, struct ImBuf *ibuf, int x, int y)
else {
char *rect = (char *)( ibuf->rect+ ofs);
- col[0] = ((float)rect[0])/255.0f;
- col[1] = ((float)rect[1])/255.0f;
- col[2] = ((float)rect[2])/255.0f;
- col[3] = ((float)rect[3])/255.0f;
+ col[0] = ((float)rect[0])*(1.0f/255.0f);
+ col[1] = ((float)rect[1])*(1.0f/255.0f);
+ col[2] = ((float)rect[2])*(1.0f/255.0f);
+ col[3] = ((float)rect[3])*(1.0f/255.0f);
}
}
@@ -245,7 +246,7 @@ int imagewrap(Tex *tex, Image *ima, ImBuf *ibuf, float *texvec, TexResult *texre
if(tex->flag & TEX_NEGALPHA) texres->ta= 1.0f-texres->ta;
/* de-premul, this is being premulled in shade_input_do_shade() */
- if(texres->ta!=1.0f && texres->ta!=0.0f) {
+ if(texres->ta!=1.0f && texres->ta>FLT_EPSILON) {
fx= 1.0f/texres->ta;
texres->tr*= fx;
texres->tg*= fx;
@@ -576,10 +577,10 @@ static void boxsample(ImBuf *ibuf, float minx, float miny, float maxx, float max
if(texres->talpha==0) texres->ta= 1.0;
if(alphaclip!=1.0) {
- /* this is for later investigation, premul or not? */
- /* texres->tr*= alphaclip; */
- /* texres->tg*= alphaclip; */
- /* texres->tb*= alphaclip; */
+ /* premul it all */
+ texres->tr*= alphaclip;
+ texres->tg*= alphaclip;
+ texres->tb*= alphaclip;
texres->ta*= alphaclip;
}
}
@@ -615,6 +616,7 @@ void ibuf_sample(ImBuf *ibuf, float fx, float fy, float dx, float dy, float *res
return;
}
+ memset(&texres, 0, sizeof(texres));
boxsample(ibuf, fx, fy, fx+dx, fy+dy, &texres, 0, 1);
result[0]= texres.tr;
result[1]= texres.tg;
@@ -699,10 +701,22 @@ int imagewraposa(Tex *tex, Image *ima, ImBuf *ibuf, float *texvec, float *dxt, f
maxy= MAX3(dxt[1],dyt[1],dxt[1]+dyt[1] );
/* tex_sharper has been removed */
- minx= tex->filtersize*(maxx-minx)/2.0f;
- miny= tex->filtersize*(maxy-miny)/2.0f;
+ minx= (maxx-minx)/2.0f;
+ miny= (maxy-miny)/2.0f;
- if(tex->filtersize!=1.0f) {
+ if(tex->imaflag & TEX_FILTER_MIN) {
+ /* make sure the filtersize is minimal in pixels (normal, ref map can have miniature pixel dx/dy) */
+ float addval= (0.5f * tex->filtersize) / (float) MIN2(ibuf->x, ibuf->y);
+
+ if(addval > minx)
+ minx= addval;
+ if(addval > miny)
+ miny= addval;
+ }
+ else if(tex->filtersize!=1.0f) {
+ minx*= tex->filtersize;
+ miny*= tex->filtersize;
+
dxt[0]*= tex->filtersize;
dxt[1]*= tex->filtersize;
dyt[0]*= tex->filtersize;
@@ -977,7 +991,7 @@ int imagewraposa(Tex *tex, Image *ima, ImBuf *ibuf, float *texvec, float *dxt, f
}
/* de-premul, this is being premulled in shade_input_do_shade() */
- if(texres->ta!=1.0f && texres->ta!=0.0f) {
+ if(texres->ta!=1.0f && texres->ta>FLT_EPSILON) {
fx= 1.0f/texres->ta;
texres->tr*= fx;
texres->tg*= fx;
diff --git a/source/blender/render/intern/source/initrender.c b/source/blender/render/intern/source/initrender.c
index 3ea8c6edffa..40c0edb6e5f 100644
--- a/source/blender/render/intern/source/initrender.c
+++ b/source/blender/render/intern/source/initrender.c
@@ -257,7 +257,7 @@ void make_sample_tables(Render *re)
{
static int firsttime= 1;
SampleTables *st;
- float flweight[32], fmask[256];
+ float flweight[32];
float weight[32], totw, val, *fpx1, *fpx2, *fpy1, *fpy2, *m3, *m4;
int i, j, a;
@@ -300,11 +300,6 @@ void make_sample_tables(Render *re)
st->centLut[a]= -0.45+((float)a)/16.0;
}
- val= 1.0/((float)re->osa);
- for(a=0; a<256; a++) {
- fmask[a]= ((float)st->cmask[a])*val;
- }
-
/* calculate totw */
totw= 0.0;
for(j= -1; j<2; j++) {
@@ -459,7 +454,10 @@ void RE_SetCamera(Render *re, Object *camera)
if(cam->type==CAM_ORTHO) re->r.mode |= R_ORTHO;
- /* solve this too... all time depending stuff is in convertblender.c? */
+ /* solve this too... all time depending stuff is in convertblender.c?
+ * Need to update the camera early because it's used for projection matrices
+ * and other stuff BEFORE the animation update loop is done
+ * */
if(cam->ipo) {
calc_ipo(cam->ipo, frame_to_float(re->r.cfra));
execute_ipo(&cam->id, cam->ipo);
@@ -603,24 +601,20 @@ void initparts(Render *re)
/* mininum part size, but for exr tile saving it was checked already */
if(!(re->r.scemode & R_EXR_TILE_FILE)) {
if(re->r.mode & R_PANORAMA) {
- if(re->rectx/xparts < 8)
+ if(ceil(re->rectx/(float)xparts) < 8)
xparts= 1 + re->rectx/8;
}
else
- if(re->rectx/xparts < 64)
+ if(ceil(re->rectx/(float)xparts) < 64)
xparts= 1 + re->rectx/64;
- if(re->recty/yparts < 64)
+ if(ceil(re->recty/(float)yparts) < 64)
yparts= 1 + re->recty/64;
}
/* part size */
- partx= re->rectx/xparts;
- party= re->recty/yparts;
-
- /* if remainder pixel, add one, then parts are more equal in size for large panoramas */
- if(re->rectx % partx)
- partx++;
+ partx= ceil(re->rectx/(float)xparts);
+ party= ceil(re->recty/(float)yparts);
re->xparts= xparts;
re->yparts= yparts;
diff --git a/source/blender/render/intern/source/occlusion.c b/source/blender/render/intern/source/occlusion.c
new file mode 100644
index 00000000000..d2d2cf3fb77
--- /dev/null
+++ b/source/blender/render/intern/source/occlusion.c
@@ -0,0 +1,1763 @@
+/*
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2008 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Brecht Van Lommel.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_material_types.h"
+
+#include "BLI_arithb.h"
+#include "BLI_blenlib.h"
+#include "BLI_memarena.h"
+#include "BLI_threads.h"
+
+#include "BKE_global.h"
+#include "BKE_scene.h"
+#include "BKE_utildefines.h"
+
+#include "RE_shader_ext.h"
+
+/* local includes */
+#include "occlusion.h"
+#include "render_types.h"
+#include "rendercore.h"
+#include "renderdatabase.h"
+#include "pixelshading.h"
+#include "shading.h"
+#include "zbuf.h"
+
+/* ------------------------- Declarations --------------------------- */
+
+#define INVALID_INDEX ((int)(~0))
+#define INVPI 0.31830988618379069f
+#define TOTCHILD 8
+#define CACHE_STEP 3
+
+typedef struct OcclusionCacheSample {
+ float co[3], n[3], col[3], intensity, dist2;
+ int x, y, filled;
+} OcclusionCacheSample;
+
+typedef struct OcclusionCache {
+ OcclusionCacheSample *sample;
+ int x, y, w, h, step;
+} OcclusionCache;
+
+typedef struct OccFace {
+ int obi;
+ int facenr;
+} OccFace;
+
+typedef struct OccNode {
+ float co[3], area;
+ float sh[9], dco;
+ float occlusion;
+ int childflag;
+ union {
+ //OccFace face;
+ int face;
+ struct OccNode *node;
+ } child[TOTCHILD];
+} OccNode;
+
+typedef struct OcclusionTree {
+ MemArena *arena;
+
+ float (*co)[3]; /* temporary during build */
+
+ OccFace *face; /* instance and face indices */
+ float *occlusion; /* occlusion for faces */
+
+ OccNode *root;
+
+ OccNode **stack[BLENDER_MAX_THREADS];
+ int maxdepth;
+
+ int totface;
+
+ float error;
+ float distfac;
+
+ int dothreadedbuild;
+ int totbuildthread;
+
+ OcclusionCache *cache;
+} OcclusionTree;
+
+typedef struct OcclusionThread {
+ Render *re;
+ StrandSurface *mesh;
+ float (*facecol)[3];
+ int begin, end;
+ int thread;
+} OcclusionThread;
+
+typedef struct OcclusionBuildThread {
+ OcclusionTree *tree;
+ int begin, end, depth;
+ OccNode *node;
+} OcclusionBuildThread;
+
+/* ------------------------- Shading --------------------------- */
+
+extern Render R; // meh
+
+#if 0
+static void occ_shade(ShadeSample *ssamp, ObjectInstanceRen *obi, VlakRen *vlr, float *rad)
+{
+ ShadeInput *shi= ssamp->shi;
+ ShadeResult *shr= ssamp->shr;
+ float l, u, v, *v1, *v2, *v3;
+
+ /* init */
+ if(vlr->v4) {
+ shi->u= u= 0.5f;
+ shi->v= v= 0.5f;
+ }
+ else {
+ shi->u= u= 1.0f/3.0f;
+ shi->v= v= 1.0f/3.0f;
+ }
+
+ /* setup render coordinates */
+ v1= vlr->v1->co;
+ v2= vlr->v2->co;
+ v3= vlr->v3->co;
+
+ /* renderco */
+ l= 1.0f-u-v;
+
+ shi->co[0]= l*v3[0]+u*v1[0]+v*v2[0];
+ shi->co[1]= l*v3[1]+u*v1[1]+v*v2[1];
+ shi->co[2]= l*v3[2]+u*v1[2]+v*v2[2];
+
+ shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 2);
+
+ /* set up view vector */
+ VECCOPY(shi->view, shi->co);
+ Normalize(shi->view);
+
+ /* cache for shadow */
+ shi->samplenr++;
+
+ shi->xs= 0; // TODO
+ shi->ys= 0;
+
+ shade_input_set_normals(shi);
+
+ /* no normal flip */
+ if(shi->flippednor)
+ shade_input_flip_normals(shi);
+
+ /* not a pretty solution, but fixes common cases */
+ if(shi->obr->ob && shi->obr->ob->transflag & OB_NEG_SCALE) {
+ VecMulf(shi->vn, -1.0f);
+ VecMulf(shi->vno, -1.0f);
+ }
+
+ /* init material vars */
+ // note, keep this synced with render_types.h
+ memcpy(&shi->r, &shi->mat->r, 23*sizeof(float));
+ shi->har= shi->mat->har;
+
+ /* render */
+ shade_input_set_shade_texco(shi);
+ shade_material_loop(shi, shr); /* todo: nodes */
+
+ VECCOPY(rad, shr->combined);
+}
+
+static void occ_build_shade(Render *re, OcclusionTree *tree)
+{
+ ShadeSample ssamp;
+ ObjectInstanceRen *obi;
+ VlakRen *vlr;
+ int a;
+
+ R= *re;
+
+ /* setup shade sample with correct passes */
+ memset(&ssamp, 0, sizeof(ShadeSample));
+ ssamp.shi[0].lay= re->scene->lay;
+ ssamp.shi[0].passflag= SCE_PASS_DIFFUSE|SCE_PASS_RGBA;
+ ssamp.shi[0].combinedflag= ~(SCE_PASS_SPEC);
+ ssamp.tot= 1;
+
+ for(a=0; a<tree->totface; a++) {
+ obi= &R.objectinstance[tree->face[a].obi];
+ vlr= RE_findOrAddVlak(obi->obr, tree->face[a].vlr);
+
+ occ_shade(&ssamp, obi, vlr, tree->rad[a]);
+ }
+}
+#endif
+
+/* ------------------------- Spherical Harmonics --------------------------- */
+
+/* Use 2nd order SH => 9 coefficients, stored in this order:
+ 0 = (0,0),
+ 1 = (1,-1), 2 = (1,0), 3 = (1,1),
+ 4 = (2,-2), 5 = (2,-1), 6 = (2,0), 7 = (2,1), 8 = (2,2) */
+
+static void sh_copy(float *shresult, float *sh)
+{
+ memcpy(shresult, sh, sizeof(float)*9);
+}
+
+static void sh_mul(float *sh, float f)
+{
+ int i;
+
+ for(i=0; i<9; i++)
+ sh[i] *= f;
+}
+
+static void sh_add(float *shresult, float *sh1, float *sh2)
+{
+ int i;
+
+ for(i=0; i<9; i++)
+ shresult[i]= sh1[i] + sh2[i];
+}
+
+static void sh_from_disc(float *n, float area, float *shresult)
+{
+ /* See formula (3) in:
+ "An Efficient Representation for Irradiance Environment Maps" */
+ float sh[9], x, y, z;
+
+ x= n[0];
+ y= n[1];
+ z= n[2];
+
+ sh[0]= 0.282095f;
+
+ sh[1]= 0.488603f*y;
+ sh[2]= 0.488603f*z;
+ sh[3]= 0.488603f*x;
+
+ sh[4]= 1.092548f*x*y;
+ sh[5]= 1.092548f*y*z;
+ sh[6]= 0.315392f*(3.0f*z*z - 1.0f);
+ sh[7]= 1.092548f*x*z;
+ sh[8]= 0.546274f*(x*x - y*y);
+
+ sh_mul(sh, area);
+ sh_copy(shresult, sh);
+}
+
+static float sh_eval(float *sh, float *v)
+{
+ /* See formula (13) in:
+ "An Efficient Representation for Irradiance Environment Maps" */
+ static const float c1 = 0.429043f, c2 = 0.511664f, c3 = 0.743125f;
+ static const float c4 = 0.886227f, c5 = 0.247708f;
+ float x, y, z, sum;
+
+ x= v[0];
+ y= v[1];
+ z= v[2];
+
+ sum= c1*sh[8]*(x*x - y*y);
+ sum += c3*sh[6]*z*z;
+ sum += c4*sh[0];
+ sum += -c5*sh[6];
+ sum += 2.0f*c1*(sh[4]*x*y + sh[7]*x*z + sh[5]*y*z);
+ sum += 2.0f*c2*(sh[3]*x + sh[1]*y + sh[2]*z);
+
+ return sum;
+}
+
+/* ------------------------------ Building --------------------------------- */
+
+static void occ_face(const OccFace *face, float *co, float *normal, float *area)
+{
+ ObjectInstanceRen *obi;
+ VlakRen *vlr;
+ float v1[3], v2[3], v3[3], v4[3];
+
+ obi= &R.objectinstance[face->obi];
+ vlr= RE_findOrAddVlak(obi->obr, face->facenr);
+
+ if(co) {
+ if(vlr->v4)
+ VecLerpf(co, vlr->v1->co, vlr->v3->co, 0.5f);
+ else
+ CalcCent3f(co, vlr->v1->co, vlr->v2->co, vlr->v3->co);
+
+ if(obi->flag & R_TRANSFORMED)
+ Mat4MulVecfl(obi->mat, co);
+ }
+
+ if(normal) {
+ normal[0]= -vlr->n[0];
+ normal[1]= -vlr->n[1];
+ normal[2]= -vlr->n[2];
+
+ if(obi->flag & R_TRANSFORMED)
+ Mat3MulVecfl(obi->nmat, normal);
+ }
+
+ if(area) {
+ VECCOPY(v1, vlr->v1->co);
+ VECCOPY(v2, vlr->v2->co);
+ VECCOPY(v3, vlr->v3->co);
+ if(vlr->v4) VECCOPY(v4, vlr->v4->co);
+
+ if(obi->flag & R_TRANSFORMED) {
+ Mat4MulVecfl(obi->mat, v1);
+ Mat4MulVecfl(obi->mat, v2);
+ Mat4MulVecfl(obi->mat, v3);
+ if(vlr->v4) Mat4MulVecfl(obi->mat, v4);
+ }
+
+ /* todo: correct area for instances */
+ if(vlr->v4)
+ *area= AreaQ3Dfl(v1, v2, v3, v4);
+ else
+ *area= AreaT3Dfl(v1, v2, v3);
+ }
+}
+
+static void occ_sum_occlusion(OcclusionTree *tree, OccNode *node)
+{
+ OccNode *child;
+ float occ, area, totarea;
+ int a, b;
+
+ occ= 0.0f;
+ totarea= 0.0f;
+
+ for(b=0; b<TOTCHILD; b++) {
+ if(node->childflag & (1<<b)) {
+ a= node->child[b].face;
+ occ_face(&tree->face[a], 0, 0, &area);
+ occ += area*tree->occlusion[a];
+ totarea += area;
+ }
+ else if(node->child[b].node) {
+ child= node->child[b].node;
+ occ_sum_occlusion(tree, child);
+
+ occ += child->area*child->occlusion;
+ totarea += child->area;
+ }
+ }
+
+ if(totarea != 0.0f)
+ occ /= totarea;
+
+ node->occlusion= occ;
+}
+
+static int occ_find_bbox_axis(OcclusionTree *tree, int begin, int end, float *min, float *max)
+{
+ float len, maxlen= -1.0f;
+ int a, axis = 0;
+
+ INIT_MINMAX(min, max);
+
+ for(a=begin; a<end; a++)
+ DO_MINMAX(tree->co[a], min, max)
+
+ for(a=0; a<3; a++) {
+ len= max[a] - min[a];
+
+ if(len > maxlen) {
+ maxlen= len;
+ axis= a;
+ }
+ }
+
+ return axis;
+}
+
+static void occ_node_from_face(OccFace *face, OccNode *node)
+{
+ float n[3];
+
+ occ_face(face, node->co, n, &node->area);
+ node->dco= 0.0f;
+ sh_from_disc(n, node->area, node->sh);
+}
+
+static void occ_build_dco(OcclusionTree *tree, OccNode *node, float *co, float *dco)
+{
+ OccNode *child;
+ float dist, d[3], nco[3];
+ int b;
+
+ for(b=0; b<TOTCHILD; b++) {
+ if(node->childflag & (1<<b)) {
+ occ_face(tree->face+node->child[b].face, nco, 0, 0);
+ }
+ else if(node->child[b].node) {
+ child= node->child[b].node;
+ occ_build_dco(tree, child, co, dco);
+ VECCOPY(nco, child->co);
+ }
+
+ VECSUB(d, nco, co);
+ dist= INPR(d, d);
+ if(dist > *dco)
+ *dco= dist;
+ }
+}
+
+static void occ_build_split(OcclusionTree *tree, int begin, int end, int *split)
+{
+ float min[3], max[3], mid;
+ int axis, a, enda;
+
+ /* split in middle of boundbox. this seems faster than median split
+ * on complex scenes, possibly since it avoids two distant faces to
+ * be in the same node better? */
+ axis= occ_find_bbox_axis(tree, begin, end, min, max);
+ mid= 0.5f*(min[axis]+max[axis]);
+
+ a= begin;
+ enda= end;
+ while(a<enda) {
+ if(tree->co[a][axis] > mid) {
+ enda--;
+ SWAP(OccFace, tree->face[a], tree->face[enda]);
+ SWAP(float, tree->co[a][0], tree->co[enda][0]);
+ SWAP(float, tree->co[a][1], tree->co[enda][1]);
+ SWAP(float, tree->co[a][2], tree->co[enda][2]);
+ }
+ else
+ a++;
+ }
+
+ *split= enda;
+}
+
+static void occ_build_8_split(OcclusionTree *tree, int begin, int end, int *offset, int *count)
+{
+ /* split faces into eight groups */
+ int b, splitx, splity[2], splitz[4];
+
+ occ_build_split(tree, begin, end, &splitx);
+
+ /* force split if none found, to deal with degenerate geometry */
+ if(splitx == begin || splitx == end)
+ splitx= (begin+end)/2;
+
+ occ_build_split(tree, begin, splitx, &splity[0]);
+ occ_build_split(tree, splitx, end, &splity[1]);
+
+ occ_build_split(tree, begin, splity[0], &splitz[0]);
+ occ_build_split(tree, splity[0], splitx, &splitz[1]);
+ occ_build_split(tree, splitx, splity[1], &splitz[2]);
+ occ_build_split(tree, splity[1], end, &splitz[3]);
+
+ offset[0]= begin;
+ offset[1]= splitz[0];
+ offset[2]= splity[0];
+ offset[3]= splitz[1];
+ offset[4]= splitx;
+ offset[5]= splitz[2];
+ offset[6]= splity[1];
+ offset[7]= splitz[3];
+
+ for(b=0; b<7; b++)
+ count[b]= offset[b+1] - offset[b];
+ count[7]= end - offset[7];
+}
+
+static void occ_build_recursive(OcclusionTree *tree, OccNode *node, int begin, int end, int depth);
+
+static void *exec_occ_build(void *data)
+{
+ OcclusionBuildThread *othread= (OcclusionBuildThread*)data;
+
+ occ_build_recursive(othread->tree, othread->node, othread->begin, othread->end, othread->depth);
+
+ return 0;
+}
+
+static void occ_build_recursive(OcclusionTree *tree, OccNode *node, int begin, int end, int depth)
+{
+ ListBase threads;
+ OcclusionBuildThread othreads[BLENDER_MAX_THREADS];
+ OccNode *child, tmpnode;
+ OccFace *face;
+ int a, b, totthread=0, offset[TOTCHILD], count[TOTCHILD];
+
+ /* keep track of maximum depth for stack */
+ if(depth > tree->maxdepth)
+ tree->maxdepth= depth;
+
+ /* add a new node */
+ node->occlusion= 1.0f;
+
+ /* leaf node with only children */
+ if(end - begin <= TOTCHILD) {
+ for(a=begin, b=0; a<end; a++, b++) {
+ face= &tree->face[a];
+ node->child[b].face= a;
+ node->childflag |= (1<<b);
+ }
+ }
+ else {
+ /* order faces */
+ occ_build_8_split(tree, begin, end, offset, count);
+
+ if(depth == 1 && tree->dothreadedbuild)
+ BLI_init_threads(&threads, exec_occ_build, tree->totbuildthread);
+
+ for(b=0; b<TOTCHILD; b++) {
+ if(count[b] == 0) {
+ node->child[b].node= NULL;
+ }
+ else if(count[b] == 1) {
+ face= &tree->face[offset[b]];
+ node->child[b].face= offset[b];
+ node->childflag |= (1<<b);
+ }
+ else {
+ if(tree->dothreadedbuild)
+ BLI_lock_thread(LOCK_CUSTOM1);
+
+ child= BLI_memarena_alloc(tree->arena, sizeof(OccNode));
+ node->child[b].node= child;
+
+ if(tree->dothreadedbuild)
+ BLI_unlock_thread(LOCK_CUSTOM1);
+
+ if(depth == 1 && tree->dothreadedbuild) {
+ othreads[totthread].tree= tree;
+ othreads[totthread].node= child;
+ othreads[totthread].begin= offset[b];
+ othreads[totthread].end= offset[b]+count[b];
+ othreads[totthread].depth= depth+1;
+ BLI_insert_thread(&threads, &othreads[totthread]);
+ totthread++;
+ }
+ else
+ occ_build_recursive(tree, child, offset[b], offset[b]+count[b], depth+1);
+ }
+ }
+
+ if(depth == 1 && tree->dothreadedbuild)
+ BLI_end_threads(&threads);
+ }
+
+ /* combine area, position and sh */
+ for(b=0; b<TOTCHILD; b++) {
+ if(node->childflag & (1<<b)) {
+ child= &tmpnode;
+ occ_node_from_face(tree->face+node->child[b].face, &tmpnode);
+ }
+ else {
+ child= node->child[b].node;
+ }
+
+ if(child) {
+ node->area += child->area;
+ sh_add(node->sh, node->sh, child->sh);
+ VECADDFAC(node->co, node->co, child->co, child->area);
+ }
+ }
+
+ if(node->area != 0.0f)
+ VecMulf(node->co, 1.0f/node->area);
+
+ /* compute maximum distance from center */
+ node->dco= 0.0f;
+ occ_build_dco(tree, node, node->co, &node->dco);
+}
+
+static void occ_build_sh_normalize(OccNode *node)
+{
+ /* normalize spherical harmonics to not include area, so
+ * we can clamp the dot product and then mutliply by area */
+ int b;
+
+ if(node->area != 0.0f)
+ sh_mul(node->sh, 1.0f/node->area);
+
+ for(b=0; b<TOTCHILD; b++) {
+ if(node->childflag & (1<<b));
+ else if(node->child[b].node)
+ occ_build_sh_normalize(node->child[b].node);
+ }
+}
+
+static OcclusionTree *occ_tree_build(Render *re)
+{
+ OcclusionTree *tree;
+ ObjectInstanceRen *obi;
+ ObjectRen *obr;
+ VlakRen *vlr= NULL;
+ int a, b, c, totface;
+
+ /* count */
+ totface= 0;
+ for(obi=re->instancetable.first; obi; obi=obi->next) {
+ obr= obi->obr;
+ for(a=0; a<obr->totvlak; a++) {
+ if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak;
+ else vlr++;
+
+ if(vlr->mat->mode & MA_TRACEBLE)
+ totface++;
+ }
+ }
+
+ if(totface == 0)
+ return NULL;
+
+ tree= MEM_callocN(sizeof(OcclusionTree), "OcclusionTree");
+ tree->totface= totface;
+
+ /* parameters */
+ tree->error= get_render_aosss_error(&re->r, re->wrld.ao_approx_error);
+ tree->distfac= (re->wrld.aomode & WO_AODIST)? re->wrld.aodistfac: 0.0f;
+
+ /* allocation */
+ tree->arena= BLI_memarena_new(0x8000 * sizeof(OccNode));
+ BLI_memarena_use_calloc(tree->arena);
+
+ if(re->wrld.aomode & WO_AOCACHE)
+ tree->cache= MEM_callocN(sizeof(OcclusionCache)*BLENDER_MAX_THREADS, "OcclusionCache");
+
+ tree->face= MEM_callocN(sizeof(OccFace)*totface, "OcclusionFace");
+ tree->co= MEM_callocN(sizeof(float)*3*totface, "OcclusionCo");
+ tree->occlusion= MEM_callocN(sizeof(float)*totface, "OcclusionOcclusion");
+
+ /* make array of face pointers */
+ for(b=0, c=0, obi=re->instancetable.first; obi; obi=obi->next, c++) {
+ obr= obi->obr;
+ for(a=0; a<obr->totvlak; a++) {
+ if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak;
+ else vlr++;
+
+ if(vlr->mat->mode & MA_TRACEBLE) {
+ tree->face[b].obi= c;
+ tree->face[b].facenr= a;
+ tree->occlusion[b]= 1.0f;
+ occ_face(&tree->face[b], tree->co[b], NULL, NULL);
+ b++;
+ }
+ }
+ }
+
+ /* threads */
+ tree->totbuildthread= (re->r.threads > 1 && totface > 10000)? 8: 1;
+ tree->dothreadedbuild= (tree->totbuildthread > 1);
+
+ /* recurse */
+ tree->root= BLI_memarena_alloc(tree->arena, sizeof(OccNode));
+ occ_build_recursive(tree, tree->root, 0, totface, 1);
+
+#if 0
+ if(tree->doindirect) {
+ occ_build_shade(re, tree);
+ occ_sum_occlusion(tree, tree->root);
+ }
+#endif
+
+ MEM_freeN(tree->co);
+ tree->co= NULL;
+
+ occ_build_sh_normalize(tree->root);
+
+ for(a=0; a<BLENDER_MAX_THREADS; a++)
+ tree->stack[a]= MEM_callocN(sizeof(OccNode)*TOTCHILD*(tree->maxdepth+1), "OccStack");
+
+ return tree;
+}
+
+static void occ_free_tree(OcclusionTree *tree)
+{
+ int a;
+
+ if(tree) {
+ if(tree->arena) BLI_memarena_free(tree->arena);
+ for(a=0; a<BLENDER_MAX_THREADS; a++)
+ if(tree->stack[a])
+ MEM_freeN(tree->stack[a]);
+ if(tree->occlusion) MEM_freeN(tree->occlusion);
+ if(tree->face) MEM_freeN(tree->face);
+ if(tree->cache) MEM_freeN(tree->cache);
+ MEM_freeN(tree);
+ }
+}
+
+/* ------------------------- Traversal --------------------------- */
+
+static float occ_solid_angle(OccNode *node, float *v, float d2, float invd2, float *receivenormal)
+{
+ float dotreceive, dotemit;
+ float ev[3];
+
+ ev[0]= -v[0]*invd2;
+ ev[1]= -v[1]*invd2;
+ ev[2]= -v[2]*invd2;
+ dotemit= sh_eval(node->sh, ev);
+ dotreceive= INPR(receivenormal, v)*invd2;
+
+ CLAMP(dotemit, 0.0f, 1.0f);
+ CLAMP(dotreceive, 0.0f, 1.0f);
+
+ return ((node->area*dotemit*dotreceive)/(d2 + node->area*INVPI))*INVPI;
+}
+
+static void VecAddDir(float *result, float *v1, float *v2, float fac)
+{
+ result[0]= v1[0] + fac*(v2[0] - v1[0]);
+ result[1]= v1[1] + fac*(v2[1] - v1[1]);
+ result[2]= v1[2] + fac*(v2[2] - v1[2]);
+}
+
+static int occ_visible_quad(float *p, float *n, float *v0, float *v1, float *v2, float *q0, float *q1, float *q2, float *q3)
+{
+ static const float epsilon = 1e-6f;
+ float c, sd[3];
+
+ c= INPR(n, p);
+
+ /* signed distances from the vertices to the plane. */
+ sd[0]= INPR(n, v0) - c;
+ sd[1]= INPR(n, v1) - c;
+ sd[2]= INPR(n, v2) - c;
+
+ if(fabs(sd[0]) < epsilon) sd[0] = 0.0f;
+ if(fabs(sd[1]) < epsilon) sd[1] = 0.0f;
+ if(fabs(sd[2]) < epsilon) sd[2] = 0.0f;
+
+ if(sd[0] > 0) {
+ if(sd[1] > 0) {
+ if(sd[2] > 0) {
+ // +++
+ VECCOPY(q0, v0);
+ VECCOPY(q1, v1);
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ else if(sd[2] < 0) {
+ // ++-
+ VECCOPY(q0, v0);
+ VECCOPY(q1, v1);
+ VecAddDir(q2, v1, v2, (sd[1]/(sd[1]-sd[2])));
+ VecAddDir(q3, v0, v2, (sd[0]/(sd[0]-sd[2])));
+ }
+ else {
+ // ++0
+ VECCOPY(q0, v0);
+ VECCOPY(q1, v1);
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ }
+ else if(sd[1] < 0) {
+ if(sd[2] > 0) {
+ // +-+
+ VECCOPY(q0, v0);
+ VecAddDir(q1, v0, v1, (sd[0]/(sd[0]-sd[1])));
+ VecAddDir(q2, v1, v2, (sd[1]/(sd[1]-sd[2])));
+ VECCOPY(q3, v2);
+ }
+ else if(sd[2] < 0) {
+ // +--
+ VECCOPY(q0, v0);
+ VecAddDir(q1, v0, v1, (sd[0]/(sd[0]-sd[1])));
+ VecAddDir(q2, v0, v2, (sd[0]/(sd[0]-sd[2])));
+ VECCOPY(q3, q2);
+ }
+ else {
+ // +-0
+ VECCOPY(q0, v0);
+ VecAddDir(q1, v0, v1, (sd[0]/(sd[0]-sd[1])));
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ }
+ else {
+ if(sd[2] > 0) {
+ // +0+
+ VECCOPY(q0, v0);
+ VECCOPY(q1, v1);
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ else if(sd[2] < 0) {
+ // +0-
+ VECCOPY(q0, v0);
+ VECCOPY(q1, v1);
+ VecAddDir(q2, v0, v2, (sd[0]/(sd[0]-sd[2])));
+ VECCOPY(q3, q2);
+ }
+ else {
+ // +00
+ VECCOPY(q0, v0);
+ VECCOPY(q1, v1);
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ }
+ }
+ else if(sd[0] < 0) {
+ if(sd[1] > 0) {
+ if(sd[2] > 0) {
+ // -++
+ VecAddDir(q0, v0, v1, (sd[0]/(sd[0]-sd[1])));
+ VECCOPY(q1, v1);
+ VECCOPY(q2, v2);
+ VecAddDir(q3, v0, v2, (sd[0]/(sd[0]-sd[2])));
+ }
+ else if(sd[2] < 0) {
+ // -+-
+ VecAddDir(q0, v0, v1, (sd[0]/(sd[0]-sd[1])));
+ VECCOPY(q1, v1);
+ VecAddDir(q2, v1, v2, (sd[1]/(sd[1]-sd[2])));
+ VECCOPY(q3, q2);
+ }
+ else {
+ // -+0
+ VecAddDir(q0, v0, v1, (sd[0]/(sd[0]-sd[1])));
+ VECCOPY(q1, v1);
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ }
+ else if(sd[1] < 0) {
+ if(sd[2] > 0) {
+ // --+
+ VecAddDir(q0, v0, v2, (sd[0]/(sd[0]-sd[2])));
+ VecAddDir(q1, v1, v2, (sd[1]/(sd[1]-sd[2])));
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ else if(sd[2] < 0) {
+ // ---
+ return 0;
+ }
+ else {
+ // --0
+ return 0;
+ }
+ }
+ else {
+ if(sd[2] > 0) {
+ // -0+
+ VecAddDir(q0, v0, v2, (sd[0]/(sd[0]-sd[2])));
+ VECCOPY(q1, v1);
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ else if(sd[2] < 0) {
+ // -0-
+ return 0;
+ }
+ else {
+ // -00
+ return 0;
+ }
+ }
+ }
+ else {
+ if(sd[1] > 0) {
+ if(sd[2] > 0) {
+ // 0++
+ VECCOPY(q0, v0);
+ VECCOPY(q1, v1);
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ else if(sd[2] < 0) {
+ // 0+-
+ VECCOPY(q0, v0);
+ VECCOPY(q1, v1);
+ VecAddDir(q2, v1, v2, (sd[1]/(sd[1]-sd[2])));
+ VECCOPY(q3, q2);
+ }
+ else {
+ // 0+0
+ VECCOPY(q0, v0);
+ VECCOPY(q1, v1);
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ }
+ else if(sd[1] < 0) {
+ if(sd[2] > 0) {
+ // 0-+
+ VECCOPY(q0, v0);
+ VecAddDir(q1, v1, v2, (sd[1]/(sd[1]-sd[2])));
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ else if(sd[2] < 0) {
+ // 0--
+ return 0;
+ }
+ else {
+ // 0-0
+ return 0;
+ }
+ }
+ else {
+ if(sd[2] > 0) {
+ // 00+
+ VECCOPY(q0, v0);
+ VECCOPY(q1, v1);
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ else if(sd[2] < 0) {
+ // 00-
+ return 0;
+ }
+ else {
+ // 000
+ return 0;
+ }
+ }
+ }
+
+ return 1;
+}
+
+/* altivec optimization, this works, but is unused */
+
+#if 0
+#include <Accelerate/Accelerate.h>
+
+typedef union {
+ vFloat v;
+ float f[4];
+} vFloatResult;
+
+static vFloat vec_splat_float(float val)
+{
+ return (vFloat){val, val, val, val};
+}
+
+static float occ_quad_form_factor(float *p, float *n, float *q0, float *q1, float *q2, float *q3)
+{
+ vFloat vcos, rlen, vrx, vry, vrz, vsrx, vsry, vsrz, gx, gy, gz, vangle;
+ vUInt8 rotate = (vUInt8){4,5,6,7,8,9,10,11,12,13,14,15,0,1,2,3};
+ vFloatResult vresult;
+ float result;
+
+ /* compute r* */
+ vrx = (vFloat){q0[0], q1[0], q2[0], q3[0]} - vec_splat_float(p[0]);
+ vry = (vFloat){q0[1], q1[1], q2[1], q3[1]} - vec_splat_float(p[1]);
+ vrz = (vFloat){q0[2], q1[2], q2[2], q3[2]} - vec_splat_float(p[2]);
+
+ /* normalize r* */
+ rlen = vec_rsqrte(vrx*vrx + vry*vry + vrz*vrz + vec_splat_float(1e-16f));
+ vrx = vrx*rlen;
+ vry = vry*rlen;
+ vrz = vrz*rlen;
+
+ /* rotate r* for cross and dot */
+ vsrx= vec_perm(vrx, vrx, rotate);
+ vsry= vec_perm(vry, vry, rotate);
+ vsrz= vec_perm(vrz, vrz, rotate);
+
+ /* cross product */
+ gx = vsry*vrz - vsrz*vry;
+ gy = vsrz*vrx - vsrx*vrz;
+ gz = vsrx*vry - vsry*vrx;
+
+ /* normalize */
+ rlen = vec_rsqrte(gx*gx + gy*gy + gz*gz + vec_splat_float(1e-16f));
+ gx = gx*rlen;
+ gy = gy*rlen;
+ gz = gz*rlen;
+
+ /* angle */
+ vcos = vrx*vsrx + vry*vsry + vrz*vsrz;
+ vcos= vec_max(vec_min(vcos, vec_splat_float(1.0f)), vec_splat_float(-1.0f));
+ vangle= vacosf(vcos);
+
+ /* dot */
+ vresult.v = (vec_splat_float(n[0])*gx +
+ vec_splat_float(n[1])*gy +
+ vec_splat_float(n[2])*gz)*vangle;
+
+ result= (vresult.f[0] + vresult.f[1] + vresult.f[2] + vresult.f[3])*(0.5f/(float)M_PI);
+ result= MAX2(result, 0.0f);
+
+ return result;
+}
+
+#endif
+
+/* SSE optimization, acos code doesn't work */
+
+#if 0
+
+#include <xmmintrin.h>
+
+static __m128 sse_approx_acos(__m128 x)
+{
+ /* needs a better approximation than taylor expansion of acos, since that
+ * gives big erros for near 1.0 values, sqrt(2*x)*acos(1-x) should work
+ * better, see http://www.tom.womack.net/projects/sse-fast-arctrig.html */
+
+ return _mm_set_ps1(1.0f);
+}
+
+static float occ_quad_form_factor(float *p, float *n, float *q0, float *q1, float *q2, float *q3)
+{
+ float r0[3], r1[3], r2[3], r3[3], g0[3], g1[3], g2[3], g3[3];
+ float a1, a2, a3, a4, dot1, dot2, dot3, dot4, result;
+ float fresult[4] __attribute__((aligned(16)));
+ __m128 qx, qy, qz, rx, ry, rz, rlen, srx, sry, srz, gx, gy, gz, glen, rcos, angle, aresult;
+
+ /* compute r */
+ qx = _mm_set_ps(q3[0], q2[0], q1[0], q0[0]);
+ qy = _mm_set_ps(q3[1], q2[1], q1[1], q0[1]);
+ qz = _mm_set_ps(q3[2], q2[2], q1[2], q0[2]);
+
+ rx = qx - _mm_set_ps1(p[0]);
+ ry = qy - _mm_set_ps1(p[1]);
+ rz = qz - _mm_set_ps1(p[2]);
+
+ /* normalize r */
+ rlen = _mm_rsqrt_ps(rx*rx + ry*ry + rz*rz + _mm_set_ps1(1e-16f));
+ rx = rx*rlen;
+ ry = ry*rlen;
+ rz = rz*rlen;
+
+ /* cross product */
+ srx = _mm_shuffle_ps(rx, rx, _MM_SHUFFLE(0,3,2,1));
+ sry = _mm_shuffle_ps(ry, ry, _MM_SHUFFLE(0,3,2,1));
+ srz = _mm_shuffle_ps(rz, rz, _MM_SHUFFLE(0,3,2,1));
+
+ gx = sry*rz - srz*ry;
+ gy = srz*rx - srx*rz;
+ gz = srx*ry - sry*rx;
+
+ /* normalize g */
+ glen = _mm_rsqrt_ps(gx*gx + gy*gy + gz*gz + _mm_set_ps1(1e-16f));
+ gx = gx*glen;
+ gy = gy*glen;
+ gz = gz*glen;
+
+ /* compute angle */
+ rcos = rx*srx + ry*sry + rz*srz;
+ rcos= _mm_max_ps(_mm_min_ps(rcos, _mm_set_ps1(1.0f)), _mm_set_ps1(-1.0f));
+
+ angle = sse_approx_cos(rcos);
+ aresult = (_mm_set_ps1(n[0])*gx + _mm_set_ps1(n[1])*gy + _mm_set_ps1(n[2])*gz)*angle;
+
+ /* sum together */
+ result= (fresult[0] + fresult[1] + fresult[2] + fresult[3])*(0.5f/(float)M_PI);
+ result= MAX2(result, 0.0f);
+
+ return result;
+}
+
+#endif
+
+static float saacosf(float fac)
+{
+ if(fac<= -1.0f) return (float)M_PI;
+ else if(fac>=1.0f) return 0.0f;
+ else return acos(fac); /* acosf(fac) */
+}
+
+static void normalizef(float *n)
+{
+ float d;
+
+ d= INPR(n, n);
+
+ if(d > 1.0e-35F) {
+ d= 1.0f/sqrt(d); /* sqrtf(d) */
+
+ n[0] *= d;
+ n[1] *= d;
+ n[2] *= d;
+ }
+}
+
+static float occ_quad_form_factor(float *p, float *n, float *q0, float *q1, float *q2, float *q3)
+{
+ float r0[3], r1[3], r2[3], r3[3], g0[3], g1[3], g2[3], g3[3];
+ float a1, a2, a3, a4, dot1, dot2, dot3, dot4, result;
+
+ VECSUB(r0, q0, p);
+ VECSUB(r1, q1, p);
+ VECSUB(r2, q2, p);
+ VECSUB(r3, q3, p);
+
+ normalizef(r0);
+ normalizef(r1);
+ normalizef(r2);
+ normalizef(r3);
+
+ Crossf(g0, r1, r0); normalizef(g0);
+ Crossf(g1, r2, r1); normalizef(g1);
+ Crossf(g2, r3, r2); normalizef(g2);
+ Crossf(g3, r0, r3); normalizef(g3);
+
+ a1= saacosf(INPR(r0, r1));
+ a2= saacosf(INPR(r1, r2));
+ a3= saacosf(INPR(r2, r3));
+ a4= saacosf(INPR(r3, r0));
+
+ dot1= INPR(n, g0);
+ dot2= INPR(n, g1);
+ dot3= INPR(n, g2);
+ dot4= INPR(n, g3);
+
+ result= (a1*dot1 + a2*dot2 + a3*dot3 + a4*dot4)*0.5f/(float)M_PI;
+ result= MAX2(result, 0.0f);
+
+ return result;
+}
+
+static float occ_form_factor(OccFace *face, float *p, float *n)
+{
+ ObjectInstanceRen *obi;
+ VlakRen *vlr;
+ float v1[3], v2[3], v3[3], v4[3], q0[3], q1[3], q2[3], q3[3], contrib= 0.0f;
+
+ obi= &R.objectinstance[face->obi];
+ vlr= RE_findOrAddVlak(obi->obr, face->facenr);
+
+ VECCOPY(v1, vlr->v1->co);
+ VECCOPY(v2, vlr->v2->co);
+ VECCOPY(v3, vlr->v3->co);
+
+ if(obi->flag & R_TRANSFORMED) {
+ Mat4MulVecfl(obi->mat, v1);
+ Mat4MulVecfl(obi->mat, v2);
+ Mat4MulVecfl(obi->mat, v3);
+ }
+
+ if(occ_visible_quad(p, n, v1, v2, v3, q0, q1, q2, q3))
+ contrib += occ_quad_form_factor(p, n, q0, q1, q2, q3);
+
+ if(vlr->v4) {
+ VECCOPY(v4, vlr->v4->co);
+ if(obi->flag & R_TRANSFORMED)
+ Mat4MulVecfl(obi->mat, v4);
+
+ if(occ_visible_quad(p, n, v1, v3, v4, q0, q1, q2, q3))
+ contrib += occ_quad_form_factor(p, n, q0, q1, q2, q3);
+ }
+
+ return contrib;
+}
+
+static void occ_lookup(OcclusionTree *tree, int thread, OccFace *exclude, float *pp, float *pn, float *occ, float *bentn)
+{
+ OccNode *node, **stack;
+ OccFace *face;
+ float resultocc, v[3], p[3], n[3], co[3], invd2;
+ float distfac, fac, error, d2, weight, emitarea;
+ int b, totstack;
+
+ /* init variables */
+ VECCOPY(p, pp);
+ VECCOPY(n, pn);
+ VECADDFAC(p, p, n, 1e-4f);
+
+ if(bentn)
+ VECCOPY(bentn, n);
+
+ error= tree->error;
+ distfac= tree->distfac;
+
+ resultocc= 0.0f;
+
+ /* init stack */
+ stack= tree->stack[thread];
+ stack[0]= tree->root;
+ totstack= 1;
+
+ while(totstack) {
+ /* pop point off the stack */
+ node= stack[--totstack];
+
+ VECSUB(v, node->co, p);
+ d2= INPR(v, v) + 1e-16f;
+ emitarea= MAX2(node->area, node->dco);
+
+ if(d2*error > emitarea) {
+ if(distfac != 0.0f) {
+ fac= 1.0f/(1.0f + distfac*d2);
+ if(fac < 0.01f)
+ continue;
+ }
+ else
+ fac= 1.0f;
+
+ /* accumulate occlusion from spherical harmonics */
+ invd2 = 1.0f/sqrt(d2);
+ weight= occ_solid_angle(node, v, d2, invd2, n);
+ weight *= node->occlusion;
+
+ if(bentn) {
+ bentn[0] -= weight*invd2*v[0];
+ bentn[1] -= weight*invd2*v[1];
+ bentn[2] -= weight*invd2*v[2];
+ }
+
+ resultocc += weight*fac;
+ }
+ else {
+ /* traverse into children */
+ for(b=0; b<TOTCHILD; b++) {
+ if(node->childflag & (1<<b)) {
+ face= tree->face+node->child[b].face;
+
+ /* accumulate occlusion with face form factor */
+ if(!exclude || !(face->obi == exclude->obi && face->facenr == exclude->facenr)) {
+ if(bentn || distfac != 0.0f) {
+ occ_face(face, co, NULL, NULL);
+ VECSUB(v, co, p);
+ d2= INPR(v, v) + 1e-16f;
+
+ fac= (distfac == 0.0f)? 1.0f: 1.0f/(1.0f + distfac*d2);
+ if(fac < 0.01f)
+ continue;
+ }
+ else
+ fac= 1.0f;
+
+ weight= occ_form_factor(face, p, n);
+ weight *= tree->occlusion[node->child[b].face];
+
+ if(bentn) {
+ invd2= 1.0f/sqrt(d2);
+ bentn[0] -= weight*invd2*v[0];
+ bentn[1] -= weight*invd2*v[1];
+ bentn[2] -= weight*invd2*v[2];
+ }
+
+ resultocc += weight*fac;
+ }
+ }
+ else if(node->child[b].node) {
+ /* push child on the stack */
+ stack[totstack++]= node->child[b].node;
+ }
+ }
+ }
+ }
+
+ if(occ) *occ= resultocc;
+ if(bentn) Normalize(bentn);
+}
+
+static void occ_compute_passes(Render *re, OcclusionTree *tree, int totpass)
+{
+ float *occ, co[3], n[3];
+ int pass, i;
+
+ occ= MEM_callocN(sizeof(float)*tree->totface, "OcclusionPassOcc");
+
+ for(pass=0; pass<totpass; pass++) {
+ for(i=0; i<tree->totface; i++) {
+ occ_face(&tree->face[i], co, n, NULL);
+ VecMulf(n, -1.0f);
+ VECADDFAC(co, co, n, 1e-8f);
+
+ occ_lookup(tree, 0, &tree->face[i], co, n, &occ[i], NULL);
+ if(re->test_break())
+ break;
+ }
+
+ if(re->test_break())
+ break;
+
+ for(i=0; i<tree->totface; i++) {
+ tree->occlusion[i] -= occ[i]; //MAX2(1.0f-occ[i], 0.0f);
+ if(tree->occlusion[i] < 0.0f)
+ tree->occlusion[i]= 0.0f;
+ }
+
+ occ_sum_occlusion(tree, tree->root);
+ }
+
+ MEM_freeN(occ);
+}
+
+static void sample_occ_tree(Render *re, OcclusionTree *tree, OccFace *exclude, float *co, float *n, int thread, int onlyshadow, float *skycol)
+{
+ float nn[3], bn[3], fac, occ, occlusion, correction;
+ int aocolor;
+
+ aocolor= re->wrld.aocolor;
+ if(onlyshadow)
+ aocolor= WO_AOPLAIN;
+
+ VECCOPY(nn, n);
+ VecMulf(nn, -1.0f);
+
+ occ_lookup(tree, thread, exclude, co, nn, &occ, (aocolor)? bn: NULL);
+
+ correction= re->wrld.ao_approx_correction;
+
+ occlusion= (1.0f-correction)*(1.0f-occ);
+ CLAMP(occlusion, 0.0f, 1.0f);
+ if(correction != 0.0f)
+ occlusion += correction*exp(-occ);
+
+ if(aocolor) {
+ /* sky shading using bent normal */
+ if(ELEM(aocolor, WO_AOSKYCOL, WO_AOSKYTEX)) {
+ fac= 0.5*(1.0f+bn[0]*re->grvec[0]+ bn[1]*re->grvec[1]+ bn[2]*re->grvec[2]);
+ skycol[0]= (1.0f-fac)*re->wrld.horr + fac*re->wrld.zenr;
+ skycol[1]= (1.0f-fac)*re->wrld.horg + fac*re->wrld.zeng;
+ skycol[2]= (1.0f-fac)*re->wrld.horb + fac*re->wrld.zenb;
+ }
+#if 0
+ else { /* WO_AOSKYTEX */
+ float dxyview[3];
+ bn[0]= -bn[0];
+ bn[1]= -bn[1];
+ bn[2]= -bn[2];
+ dxyview[0]= 1.0f;
+ dxyview[1]= 1.0f;
+ dxyview[2]= 0.0f;
+ shadeSkyView(skycol, co, bn, dxyview);
+ }
+#endif
+
+ VecMulf(skycol, occlusion);
+ }
+ else {
+ skycol[0]= occlusion;
+ skycol[1]= occlusion;
+ skycol[2]= occlusion;
+ }
+}
+
+/* ---------------------------- Caching ------------------------------- */
+
+static OcclusionCacheSample *find_occ_sample(OcclusionCache *cache, int x, int y)
+{
+ x -= cache->x;
+ y -= cache->y;
+
+ x /= cache->step;
+ y /= cache->step;
+ x *= cache->step;
+ y *= cache->step;
+
+ if(x < 0 || x >= cache->w || y < 0 || y >= cache->h)
+ return NULL;
+ else
+ return &cache->sample[y*cache->w + x];
+}
+
+static int sample_occ_cache(OcclusionTree *tree, float *co, float *n, int x, int y, int thread, float *col)
+{
+ OcclusionCache *cache;
+ OcclusionCacheSample *samples[4], *sample;
+ float wn[4], wz[4], wb[4], tx, ty, w, totw, mino, maxo;
+ float d[3], dist2;
+ int i, x1, y1, x2, y2;
+
+ if(!tree->cache)
+ return 0;
+
+ /* first try to find a sample in the same pixel */
+ cache= &tree->cache[thread];
+
+ if(cache->sample && cache->step) {
+ sample= &cache->sample[(y-cache->y)*cache->w + (x-cache->x)];
+ if(sample->filled) {
+ VECSUB(d, sample->co, co);
+ dist2= INPR(d, d);
+ if(dist2 < 0.5f*sample->dist2 && INPR(sample->n, n) > 0.98f) {
+ VECCOPY(col, sample->col);
+ return 1;
+ }
+ }
+ }
+ else
+ return 0;
+
+ /* try to interpolate between 4 neighbouring pixels */
+ samples[0]= find_occ_sample(cache, x, y);
+ samples[1]= find_occ_sample(cache, x+cache->step, y);
+ samples[2]= find_occ_sample(cache, x, y+cache->step);
+ samples[3]= find_occ_sample(cache, x+cache->step, y+cache->step);
+
+ for(i=0; i<4; i++)
+ if(!samples[i] || !samples[i]->filled)
+ return 0;
+
+ /* require intensities not being too different */
+ mino= MIN4(samples[0]->intensity, samples[1]->intensity, samples[2]->intensity, samples[3]->intensity);
+ maxo= MAX4(samples[0]->intensity, samples[1]->intensity, samples[2]->intensity, samples[3]->intensity);
+
+ if(maxo - mino > 0.05f)
+ return 0;
+
+ /* compute weighted interpolation between samples */
+ col[0]= col[1]= col[2]= 0.0f;
+ totw= 0.0f;
+
+ x1= samples[0]->x;
+ y1= samples[0]->y;
+ x2= samples[3]->x;
+ y2= samples[3]->y;
+
+ tx= (float)(x2 - x)/(float)(x2 - x1);
+ ty= (float)(y2 - y)/(float)(y2 - y1);
+
+ wb[3]= (1.0f-tx)*(1.0f-ty);
+ wb[2]= (tx)*(1.0f-ty);
+ wb[1]= (1.0f-tx)*(ty);
+ wb[0]= tx*ty;
+
+ for(i=0; i<4; i++) {
+ VECSUB(d, samples[i]->co, co);
+ dist2= INPR(d, d);
+
+ wz[i]= 1.0f; //(samples[i]->dist2/(1e-4f + dist2));
+ wn[i]= pow(INPR(samples[i]->n, n), 32.0f);
+
+ w= wb[i]*wn[i]*wz[i];
+
+ totw += w;
+ col[0] += w*samples[i]->col[0];
+ col[1] += w*samples[i]->col[1];
+ col[2] += w*samples[i]->col[2];
+ }
+
+ if(totw >= 0.9f) {
+ totw= 1.0f/totw;
+ col[0] *= totw;
+ col[1] *= totw;
+ col[2] *= totw;
+ return 1;
+ }
+
+ return 0;
+}
+
+static void sample_occ_surface(ShadeInput *shi)
+{
+ StrandRen *strand= shi->strand;
+ StrandSurface *mesh= strand->buffer->surface;
+ int *face, *index = RE_strandren_get_face(shi->obr, strand, 0);
+ float w[4], *co1, *co2, *co3, *co4;
+
+ if(mesh && mesh->face && mesh->co && mesh->col && index) {
+ face= mesh->face[*index];
+
+ co1= mesh->co[face[0]];
+ co2= mesh->co[face[1]];
+ co3= mesh->co[face[2]];
+ co4= (face[3])? mesh->co[face[3]]: NULL;
+
+ InterpWeightsQ3Dfl(co1, co2, co3, co4, strand->vert->co, w);
+
+ shi->ao[0]= shi->ao[1]= shi->ao[2]= 0.0f;
+ VECADDFAC(shi->ao, shi->ao, mesh->col[face[0]], w[0]);
+ VECADDFAC(shi->ao, shi->ao, mesh->col[face[1]], w[1]);
+ VECADDFAC(shi->ao, shi->ao, mesh->col[face[2]], w[2]);
+ if(face[3])
+ VECADDFAC(shi->ao, shi->ao, mesh->col[face[3]], w[3]);
+ }
+ else {
+ shi->ao[0]= 1.0f;
+ shi->ao[1]= 1.0f;
+ shi->ao[2]= 1.0f;
+ }
+}
+
+/* ------------------------- External Functions --------------------------- */
+
+static void *exec_strandsurface_sample(void *data)
+{
+ OcclusionThread *othread= (OcclusionThread*)data;
+ Render *re= othread->re;
+ StrandSurface *mesh= othread->mesh;
+ float col[3], co[3], n[3], *co1, *co2, *co3, *co4;
+ int a, *face;
+
+ for(a=othread->begin; a<othread->end; a++) {
+ face= mesh->face[a];
+ co1= mesh->co[face[0]];
+ co2= mesh->co[face[1]];
+ co3= mesh->co[face[2]];
+
+ if(face[3]) {
+ co4= mesh->co[face[3]];
+
+ VecLerpf(co, co1, co3, 0.5f);
+ CalcNormFloat4(co1, co2, co3, co4, n);
+ }
+ else {
+ CalcCent3f(co, co1, co2, co3);
+ CalcNormFloat(co1, co2, co3, n);
+ }
+ VecMulf(n, -1.0f);
+
+ sample_occ_tree(re, re->occlusiontree, NULL, co, n, othread->thread, 0, col);
+ VECCOPY(othread->facecol[a], col);
+ }
+
+ return 0;
+}
+
+void make_occ_tree(Render *re)
+{
+ OcclusionThread othreads[BLENDER_MAX_THREADS];
+ StrandSurface *mesh;
+ ListBase threads;
+ float col[3], (*facecol)[3];
+ int a, totface, totthread, *face, *count;
+
+ /* ugly, needed for occ_face */
+ R= *re;
+
+ re->i.infostr= "Occlusion preprocessing";
+ re->stats_draw(&re->i);
+
+ re->occlusiontree= occ_tree_build(re);
+
+ if(re->occlusiontree) {
+ if(re->wrld.ao_approx_passes)
+ occ_compute_passes(re, re->occlusiontree, re->wrld.ao_approx_passes);
+
+ for(mesh=re->strandsurface.first; mesh; mesh=mesh->next) {
+ if(!mesh->face || !mesh->co || !mesh->col)
+ continue;
+
+ count= MEM_callocN(sizeof(int)*mesh->totvert, "OcclusionCount");
+ facecol= MEM_callocN(sizeof(float)*3*mesh->totface, "StrandSurfFaceCol");
+
+ totthread= (mesh->totface > 10000)? re->r.threads: 1;
+ totface= mesh->totface/totthread;
+ for(a=0; a<totthread; a++) {
+ othreads[a].re= re;
+ othreads[a].facecol= facecol;
+ othreads[a].thread= a;
+ othreads[a].mesh= mesh;
+ othreads[a].begin= a*totface;
+ othreads[a].end= (a == totthread-1)? mesh->totface: (a+1)*totface;
+ }
+
+ if(totthread == 1) {
+ exec_strandsurface_sample(&othreads[0]);
+ }
+ else {
+ BLI_init_threads(&threads, exec_strandsurface_sample, totthread);
+
+ for(a=0; a<totthread; a++)
+ BLI_insert_thread(&threads, &othreads[a]);
+
+ BLI_end_threads(&threads);
+ }
+
+ for(a=0; a<mesh->totface; a++) {
+ face= mesh->face[a];
+
+ VECCOPY(col, facecol[a]);
+ VECADD(mesh->col[face[0]], mesh->col[face[0]], col);
+ count[face[0]]++;
+ VECADD(mesh->col[face[1]], mesh->col[face[1]], col);
+ count[face[1]]++;
+ VECADD(mesh->col[face[2]], mesh->col[face[2]], col);
+ count[face[2]]++;
+
+ if(face[3]) {
+ VECADD(mesh->col[face[3]], mesh->col[face[3]], col);
+ count[face[3]]++;
+ }
+ }
+
+ for(a=0; a<mesh->totvert; a++)
+ if(count[a])
+ VecMulf(mesh->col[a], 1.0f/count[a]);
+
+ MEM_freeN(count);
+ MEM_freeN(facecol);
+ }
+ }
+}
+
+void free_occ(Render *re)
+{
+ if(re->occlusiontree) {
+ occ_free_tree(re->occlusiontree);
+ re->occlusiontree = NULL;
+ }
+}
+
+void sample_occ(Render *re, ShadeInput *shi)
+{
+ OcclusionTree *tree= re->occlusiontree;
+ OcclusionCache *cache;
+ OcclusionCacheSample *sample;
+ OccFace exclude;
+ int onlyshadow;
+
+ if(tree) {
+ if(shi->strand) {
+ sample_occ_surface(shi);
+ }
+ /* try to get result from the cache if possible */
+ else if(!sample_occ_cache(tree, shi->co, shi->vno, shi->xs, shi->ys, shi->thread, shi->ao)) {
+ /* no luck, let's sample the occlusion */
+ exclude.obi= shi->obi - re->objectinstance;
+ exclude.facenr= shi->vlr->index;
+ onlyshadow= (shi->mat->mode & MA_ONLYSHADOW);
+ sample_occ_tree(re, tree, &exclude, shi->co, shi->vno, shi->thread, onlyshadow, shi->ao);
+
+ /* fill result into sample, each time */
+ if(tree->cache) {
+ cache= &tree->cache[shi->thread];
+
+ if(cache->sample && cache->step) {
+ sample= &cache->sample[(shi->ys-cache->y)*cache->w + (shi->xs-cache->x)];
+ VECCOPY(sample->co, shi->co);
+ VECCOPY(sample->n, shi->vno);
+ VECCOPY(sample->col, shi->ao);
+ sample->intensity= MAX3(sample->col[0], sample->col[1], sample->col[2]);
+ sample->dist2= INPR(shi->dxco, shi->dxco) + INPR(shi->dyco, shi->dyco);
+ sample->filled= 1;
+ }
+ }
+ }
+ }
+ else {
+ shi->ao[0]= 1.0f;
+ shi->ao[1]= 1.0f;
+ shi->ao[2]= 1.0f;
+ }
+}
+
+void cache_occ_samples(Render *re, RenderPart *pa, ShadeSample *ssamp)
+{
+ OcclusionTree *tree= re->occlusiontree;
+ PixStr ps;
+ OcclusionCache *cache;
+ OcclusionCacheSample *sample;
+ OccFace exclude;
+ ShadeInput *shi;
+ intptr_t *rd=NULL;
+ int *ro=NULL, *rp=NULL, *rz=NULL, onlyshadow;
+ int x, y, step = CACHE_STEP;
+
+ if(!tree->cache)
+ return;
+
+ cache= &tree->cache[pa->thread];
+ cache->w= pa->rectx;
+ cache->h= pa->recty;
+ cache->x= pa->disprect.xmin;
+ cache->y= pa->disprect.ymin;
+ cache->step= step;
+ cache->sample= MEM_callocN(sizeof(OcclusionCacheSample)*cache->w*cache->h, "OcclusionCacheSample");
+ sample= cache->sample;
+
+ if(re->osa) {
+ rd= pa->rectdaps;
+ }
+ else {
+ /* fake pixel struct for non-osa */
+ ps.next= NULL;
+ ps.mask= 0xFFFF;
+
+ ro= pa->recto;
+ rp= pa->rectp;
+ rz= pa->rectz;
+ }
+
+ /* compute a sample at every step pixels */
+ for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++) {
+ for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, sample++, rd++, ro++, rp++, rz++) {
+ if(!(((x - pa->disprect.xmin + step) % step) == 0 || x == pa->disprect.xmax-1))
+ continue;
+ if(!(((y - pa->disprect.ymin + step) % step) == 0 || y == pa->disprect.ymax-1))
+ continue;
+
+ if(re->osa) {
+ if(!*rd) continue;
+
+ shade_samples_fill_with_ps(ssamp, (PixStr *)(*rd), x, y);
+ }
+ else {
+ if(!*rp) continue;
+
+ ps.obi= *ro;
+ ps.facenr= *rp;
+ ps.z= *rz;
+ shade_samples_fill_with_ps(ssamp, &ps, x, y);
+ }
+
+ shi= ssamp->shi;
+ if(shi->vlr) {
+ onlyshadow= (shi->mat->mode & MA_ONLYSHADOW);
+ exclude.obi= shi->obi - re->objectinstance;
+ exclude.facenr= shi->vlr->index;
+ sample_occ_tree(re, tree, &exclude, shi->co, shi->vno, shi->thread, onlyshadow, shi->ao);
+
+ VECCOPY(sample->co, shi->co);
+ VECCOPY(sample->n, shi->vno);
+ VECCOPY(sample->col, shi->ao);
+ sample->intensity= MAX3(sample->col[0], sample->col[1], sample->col[2]);
+ sample->dist2= INPR(shi->dxco, shi->dxco) + INPR(shi->dyco, shi->dyco);
+ sample->x= shi->xs;
+ sample->y= shi->ys;
+ sample->filled= 1;
+ }
+
+ if(re->test_break())
+ break;
+ }
+ }
+}
+
+void free_occ_samples(Render *re, RenderPart *pa)
+{
+ OcclusionTree *tree= re->occlusiontree;
+ OcclusionCache *cache;
+
+ if(tree->cache) {
+ cache= &tree->cache[pa->thread];
+
+ if(cache->sample)
+ MEM_freeN(cache->sample);
+
+ cache->w= 0;
+ cache->h= 0;
+ cache->step= 0;
+ }
+}
+
diff --git a/source/blender/render/intern/source/pipeline.c b/source/blender/render/intern/source/pipeline.c
index 5315552310a..2d7d954b70d 100644
--- a/source/blender/render/intern/source/pipeline.c
+++ b/source/blender/render/intern/source/pipeline.c
@@ -38,6 +38,7 @@
#include "DNA_scene_types.h"
#include "DNA_userdef_types.h"
+#include "BKE_utildefines.h"
#include "BKE_global.h"
#include "BKE_image.h"
#include "BKE_main.h"
@@ -76,6 +77,7 @@
#include "envmap.h"
#include "initrender.h"
#include "shadbuf.h"
+#include "pixelblending.h"
#include "zbuf.h"
@@ -114,7 +116,7 @@ static struct ListBase RenderList= {NULL, NULL};
Render R;
/* commandline thread override */
-static int commandline_threads= 0;
+static int commandline_threads= -1;
/* ********* alloc and free ******** */
@@ -135,30 +137,27 @@ static void print_error(char *str) {printf("ERROR: %s\n", str);}
static void stats_background(RenderStats *rs)
{
- extern unsigned long mem_in_use;
+ uintptr_t mem_in_use= MEM_get_memory_in_use();
float megs_used_memory= mem_in_use/(1024.0*1024.0);
char str[400], *spos= str;
- if(rs->convertdone) {
-
- spos+= sprintf(spos, "Fra:%d Mem:%.2fM ", G.scene->r.cfra, megs_used_memory);
-
- if(rs->curfield)
- spos+= sprintf(spos, "Field %d ", rs->curfield);
- if(rs->curblur)
- spos+= sprintf(spos, "Blur %d ", rs->curblur);
-
- if(rs->infostr) {
- spos+= sprintf(spos, "| %s", rs->infostr);
- }
- else {
- if(rs->tothalo)
- spos+= sprintf(spos, "Sce: %s Ve:%d Fa:%d Ha:%d La:%d", G.scene->id.name+2, rs->totvert, rs->totface, rs->tothalo, rs->totlamp);
- else
- spos+= sprintf(spos, "Sce: %s Ve:%d Fa:%d La:%d", G.scene->id.name+2, rs->totvert, rs->totface, rs->totlamp);
- }
- printf(str); printf("\n");
- }
+ spos+= sprintf(spos, "Fra:%d Mem:%.2fM ", G.scene->r.cfra, megs_used_memory);
+
+ if(rs->curfield)
+ spos+= sprintf(spos, "Field %d ", rs->curfield);
+ if(rs->curblur)
+ spos+= sprintf(spos, "Blur %d ", rs->curblur);
+
+ if(rs->infostr) {
+ spos+= sprintf(spos, "| %s", rs->infostr);
+ }
+ else {
+ if(rs->tothalo)
+ spos+= sprintf(spos, "Sce: %s Ve:%d Fa:%d Ha:%d La:%d", G.scene->id.name+2, rs->totvert, rs->totface, rs->tothalo, rs->totlamp);
+ else
+ spos+= sprintf(spos, "Sce: %s Ve:%d Fa:%d La:%d", G.scene->id.name+2, rs->totvert, rs->totface, rs->totlamp);
+ }
+ printf(str); printf("\n");
}
void RE_FreeRenderResult(RenderResult *res)
@@ -193,6 +192,22 @@ void RE_FreeRenderResult(RenderResult *res)
MEM_freeN(res);
}
+/* version that's compatible with fullsample buffers */
+static void free_render_result(ListBase *lb, RenderResult *rr)
+{
+ RenderResult *rrnext;
+
+ for(; rr; rr= rrnext) {
+ rrnext= rr->next;
+
+ if(lb && lb->first)
+ BLI_remlink(lb, rr);
+
+ RE_FreeRenderResult(rr);
+ }
+}
+
+
/* all layers except the active one get temporally pushed away */
static void push_render_result(Render *re)
{
@@ -329,6 +344,10 @@ static char *get_pass_name(int passtype, int channel)
if(channel==-1) return "IndexOB";
return "IndexOB.X";
}
+ if(passtype == SCE_PASS_MIST) {
+ if(channel==-1) return "Mist";
+ return "Mist.Z";
+ }
return "Unknown";
}
@@ -377,23 +396,25 @@ static int passtype_from_name(char *str)
if(strcmp(str, "IndexOB")==0)
return SCE_PASS_INDEXOB;
+ if(strcmp(str, "Mist")==0)
+ return SCE_PASS_MIST;
+
return 0;
}
-
-
-static void render_unique_exr_name(Render *re, char *str)
+static void render_unique_exr_name(Render *re, char *str, int sample)
{
char di[FILE_MAX], name[FILE_MAXFILE], fi[FILE_MAXFILE];
BLI_strncpy(di, G.sce, FILE_MAX);
BLI_splitdirstring(di, fi);
- sprintf(name, "%s_%s.exr", fi, re->scene->id.name+2);
- if(G.background)
- BLI_make_file_string("/", str, "/tmp/", name);
+
+ if(sample==0)
+ sprintf(name, "%s_%s.exr", fi, re->scene->id.name+2);
else
- BLI_make_file_string("/", str, U.tempdir, name);
-
+ sprintf(name, "%s_%s%d.exr", fi, re->scene->id.name+2, sample);
+
+ BLI_make_file_string("/", str, btempdir, name);
}
static void render_layer_add_pass(RenderResult *rr, RenderLayer *rl, int channels, int passtype)
@@ -412,17 +433,22 @@ static void render_layer_add_pass(RenderResult *rr, RenderLayer *rl, int channel
IMB_exr_add_channel(rr->exrhandle, rl->name, get_pass_name(passtype, a), 0, 0, NULL);
}
else {
+ float *rect;
+ int x;
+
+ rpass->rect= MEM_mapallocN(sizeof(float)*rectsize, typestr);
+
if(passtype==SCE_PASS_VECTOR) {
- float *rect;
- int x;
-
/* initialize to max speed */
- rect= rpass->rect= MEM_mapallocN(sizeof(float)*rectsize, typestr);
+ rect= rpass->rect;
for(x= rectsize-1; x>=0; x--)
rect[x]= PASS_VECTOR_MAX;
}
- else
- rpass->rect= MEM_mapallocN(sizeof(float)*rectsize, typestr);
+ else if(passtype==SCE_PASS_Z) {
+ rect= rpass->rect;
+ for(x= rectsize-1; x>=0; x--)
+ rect[x]= 10e10;
+ }
}
}
@@ -496,6 +522,7 @@ static RenderResult *new_render_result(Render *re, rcti *partrct, int crop, int
strcpy(rl->name, srl->name);
rl->lay= srl->lay;
+ rl->lay_zmask= srl->lay_zmask;
rl->layflag= srl->layflag;
rl->passflag= srl->passflag;
rl->pass_xor= srl->pass_xor;
@@ -525,22 +552,20 @@ static RenderResult *new_render_result(Render *re, rcti *partrct, int crop, int
render_layer_add_pass(rr, rl, 3, SCE_PASS_DIFFUSE);
if(srl->passflag & SCE_PASS_SPEC)
render_layer_add_pass(rr, rl, 3, SCE_PASS_SPEC);
- if(re->r.mode & R_SHADOW)
- if(srl->passflag & SCE_PASS_SHADOW)
- render_layer_add_pass(rr, rl, 3, SCE_PASS_SHADOW);
- if(re->r.mode & R_RAYTRACE) {
- if(srl->passflag & SCE_PASS_AO)
- render_layer_add_pass(rr, rl, 3, SCE_PASS_AO);
- if(srl->passflag & SCE_PASS_REFLECT)
- render_layer_add_pass(rr, rl, 3, SCE_PASS_REFLECT);
- if(srl->passflag & SCE_PASS_REFRACT)
- render_layer_add_pass(rr, rl, 3, SCE_PASS_REFRACT);
- }
- if(re->r.mode & R_RADIO)
- if(srl->passflag & SCE_PASS_RADIO)
- render_layer_add_pass(rr, rl, 3, SCE_PASS_RADIO);
+ if(srl->passflag & SCE_PASS_AO)
+ render_layer_add_pass(rr, rl, 3, SCE_PASS_AO);
+ if(srl->passflag & SCE_PASS_SHADOW)
+ render_layer_add_pass(rr, rl, 3, SCE_PASS_SHADOW);
+ if(srl->passflag & SCE_PASS_REFLECT)
+ render_layer_add_pass(rr, rl, 3, SCE_PASS_REFLECT);
+ if(srl->passflag & SCE_PASS_REFRACT)
+ render_layer_add_pass(rr, rl, 3, SCE_PASS_REFRACT);
+ if(srl->passflag & SCE_PASS_RADIO)
+ render_layer_add_pass(rr, rl, 3, SCE_PASS_RADIO);
if(srl->passflag & SCE_PASS_INDEXOB)
render_layer_add_pass(rr, rl, 1, SCE_PASS_INDEXOB);
+ if(srl->passflag & SCE_PASS_MIST)
+ render_layer_add_pass(rr, rl, 1, SCE_PASS_MIST);
}
/* sss, previewrender and envmap don't do layers, so we make a default one */
@@ -575,14 +600,13 @@ static RenderResult *new_render_result(Render *re, rcti *partrct, int crop, int
static int render_scene_needs_vector(Render *re)
{
- if((re->r.scemode & R_DOCOMP) || re->r.imtype==R_MULTILAYER) {
- SceneRenderLayer *srl;
+ SceneRenderLayer *srl;
- for(srl= re->scene->r.layers.first; srl; srl= srl->next)
- if(!(srl->layflag & SCE_LAY_DISABLE))
- if(srl->passflag & SCE_PASS_VECTOR)
- return 1;
- }
+ for(srl= re->scene->r.layers.first; srl; srl= srl->next)
+ if(!(srl->layflag & SCE_LAY_DISABLE))
+ if(srl->passflag & SCE_PASS_VECTOR)
+ return 1;
+
return 0;
}
@@ -640,9 +664,8 @@ static void merge_render_result(RenderResult *rr, RenderResult *rrpart)
}
-static void save_render_result_tile(Render *re, RenderPart *pa)
+static void save_render_result_tile(RenderResult *rr, RenderResult *rrpart)
{
- RenderResult *rrpart= pa->result;
RenderLayer *rlp;
RenderPass *rpassp;
int offs, partx, party;
@@ -662,23 +685,23 @@ static void save_render_result_tile(Render *re, RenderPart *pa)
if(rlp->rectf) {
int a, xstride= 4;
for(a=0; a<xstride; a++)
- IMB_exr_set_channel(re->result->exrhandle, rlp->name, get_pass_name(SCE_PASS_COMBINED, a),
- xstride, xstride*pa->rectx, rlp->rectf+a + xstride*offs);
+ IMB_exr_set_channel(rr->exrhandle, rlp->name, get_pass_name(SCE_PASS_COMBINED, a),
+ xstride, xstride*rrpart->rectx, rlp->rectf+a + xstride*offs);
}
/* passes are allocated in sync */
for(rpassp= rlp->passes.first; rpassp; rpassp= rpassp->next) {
int a, xstride= rpassp->channels;
for(a=0; a<xstride; a++)
- IMB_exr_set_channel(re->result->exrhandle, rlp->name, get_pass_name(rpassp->passtype, a),
- xstride, xstride*pa->rectx, rpassp->rect+a + xstride*offs);
+ IMB_exr_set_channel(rr->exrhandle, rlp->name, get_pass_name(rpassp->passtype, a),
+ xstride, xstride*rrpart->rectx, rpassp->rect+a + xstride*offs);
}
}
party= rrpart->tilerect.ymin + rrpart->crop;
partx= rrpart->tilerect.xmin + rrpart->crop;
- IMB_exrtile_write_channels(re->result->exrhandle, partx, party);
+ IMB_exrtile_write_channels(rr->exrhandle, partx, party, 0);
BLI_unlock_thread(LOCK_IMAGE);
@@ -687,14 +710,17 @@ static void save_render_result_tile(Render *re, RenderPart *pa)
static void save_empty_result_tiles(Render *re)
{
RenderPart *pa;
+ RenderResult *rr;
- IMB_exrtile_clear_channels(re->result->exrhandle);
+ for(rr= re->result; rr; rr= rr->next) {
+ IMB_exrtile_clear_channels(rr->exrhandle);
- for(pa= re->parts.first; pa; pa= pa->next) {
- if(pa->ready==0) {
- int party= pa->disprect.ymin - re->disprect.ymin + pa->crop;
- int partx= pa->disprect.xmin - re->disprect.xmin + pa->crop;
- IMB_exrtile_write_channels(re->result->exrhandle, partx, party);
+ for(pa= re->parts.first; pa; pa= pa->next) {
+ if(pa->ready==0) {
+ int party= pa->disprect.ymin - re->disprect.ymin + pa->crop;
+ int partx= pa->disprect.xmin - re->disprect.xmin + pa->crop;
+ IMB_exrtile_write_channels(rr->exrhandle, partx, party, 0);
+ }
}
}
}
@@ -722,6 +748,8 @@ void RE_WriteRenderResult(RenderResult *rr, char *filename, int compress)
RenderLayer *rl;
RenderPass *rpass;
void *exrhandle= IMB_exr_get_handle();
+
+ BLI_make_existing_file(filename);
/* composite result */
if(rr->rectf) {
@@ -821,7 +849,7 @@ static void renderresult_add_names(RenderResult *rr)
/* only for temp buffer files, makes exact copy of render result */
-static void read_render_result(Render *re)
+static void read_render_result(Render *re, int sample)
{
RenderLayer *rl;
RenderPass *rpass;
@@ -832,14 +860,16 @@ static void read_render_result(Render *re)
RE_FreeRenderResult(re->result);
re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
- render_unique_exr_name(re, str);
+ render_unique_exr_name(re, str, sample);
if(IMB_exr_begin_read(exrhandle, str, &rectx, &recty)==0) {
IMB_exr_close(exrhandle);
printf("cannot read: %s\n", str);
return;
}
- if(rectx!=re->result->rectx || recty!=re->result->recty) {
+ printf("read exr tmp file: %s\n", str);
+
+ if(re->result == NULL || rectx!=re->result->rectx || recty!=re->result->recty) {
printf("error in reading render result\n");
}
else {
@@ -930,7 +960,6 @@ void RE_GetResultImage(Render *re, RenderResult *rr)
}
}
-#define FTOCHAR(val) val<=0.0f?0: (val>=1.0f?255: (char)(255.0f*val))
/* caller is responsible for allocating rect in correct size! */
void RE_ResultGet32(Render *re, unsigned int *rect)
{
@@ -962,6 +991,7 @@ RenderStats *RE_GetStats(Render *re)
return &re->i;
}
+/* Note, when rendering from a scene, ALWAYS use G.scene->id.name, else compositing wont work */
Render *RE_NewRender(const char *name)
{
Render *re;
@@ -1022,7 +1052,7 @@ void RE_FreeAllRender(void)
/* what doesn't change during entire render sequence */
/* disprect is optional, if NULL it assumes full window render */
-void RE_InitState(Render *re, RenderData *rd, int winx, int winy, rcti *disprect)
+void RE_InitState(Render *re, Render *source, RenderData *rd, int winx, int winy, rcti *disprect)
{
re->ok= TRUE; /* maybe flag */
@@ -1045,18 +1075,36 @@ void RE_InitState(Render *re, RenderData *rd, int winx, int winy, rcti *disprect
}
if(re->rectx < 2 || re->recty < 2 || (BKE_imtype_is_movie(rd->imtype) &&
-(re->rectx < 16 || re->recty < 16) )) {
+ (re->rectx < 16 || re->recty < 16) )) {
re->error("Image too small");
re->ok= 0;
}
else {
- /* check state variables, osa? */
- if(re->r.mode & (R_OSA)) {
- re->osa= re->r.osa;
- if(re->osa>16) re->osa= 16;
- }
- else re->osa= 0;
+#ifndef WITH_OPENEXR
+ /* can't do this without openexr support */
+ re->r.scemode &= ~R_EXR_TILE_FILE;
+#endif
+
+ if(!(re->r.scemode & R_EXR_TILE_FILE))
+ re->r.scemode &= ~R_FULL_SAMPLE; /* clear, so we can use this flag for test both */
+ /* fullsample wants uniform osa levels */
+ if(source && (re->r.scemode & R_FULL_SAMPLE)) {
+ /* but, if source has no full sample we disable it */
+ if((source->r.scemode & R_FULL_SAMPLE)==0)
+ re->r.scemode &= ~R_FULL_SAMPLE;
+ else
+ re->r.osa= re->osa= source->osa;
+ }
+ else {
+ /* check state variables, osa? */
+ if(re->r.mode & (R_OSA)) {
+ re->osa= re->r.osa;
+ if(re->osa>16) re->osa= 16;
+ }
+ else re->osa= 0;
+ }
+
/* always call, checks for gamma, gamma tables and jitter too */
make_sample_tables(re);
@@ -1069,11 +1117,11 @@ void RE_InitState(Render *re, RenderData *rd, int winx, int winy, rcti *disprect
/* we clip faces with a minimum of 2 pixel boundary outside of image border. see zbuf.c */
re->clipcrop= 1.0f + 2.0f/(float)(re->winx>re->winy?re->winy:re->winx);
- if(commandline_threads>0 && commandline_threads<=BLENDER_MAX_THREADS)
- re->r.threads= commandline_threads;
+ RE_init_threadcount(re);
}
}
+/* part of external api, not called for regular render pipeline */
void RE_SetDispRect (struct Render *re, rcti *disprect)
{
re->disprect= *disprect;
@@ -1174,13 +1222,36 @@ static int render_display_draw_enabled(Render *re)
return 1;
}
+/* allocate osa new results for samples */
+static RenderResult *new_full_sample_buffers(Render *re, ListBase *lb, rcti *partrct, int crop)
+{
+ int a;
+
+ if(re->osa==0)
+ return new_render_result(re, partrct, crop, RR_USEMEM);
+
+ for(a=0; a<re->osa; a++) {
+ RenderResult *rr= new_render_result(re, partrct, crop, RR_USEMEM);
+ BLI_addtail(lb, rr);
+ rr->sample_nr= a;
+ }
+
+ return lb->first;
+}
+
+
+/* the main thread call, renders an entire part */
static void *do_part_thread(void *pa_v)
{
RenderPart *pa= pa_v;
/* need to return nicely all parts on esc */
if(R.test_break()==0) {
- pa->result= new_render_result(&R, &pa->disprect, pa->crop, RR_USEMEM);
+
+ if(!R.sss_points && (R.r.scemode & R_FULL_SAMPLE))
+ pa->result= new_full_sample_buffers(&R, &pa->fullresult, &pa->disprect, pa->crop);
+ else
+ pa->result= new_render_result(&R, &pa->disprect, pa->crop, RR_USEMEM);
if(R.sss_points)
zbufshade_sss_tile(pa);
@@ -1190,8 +1261,13 @@ static void *do_part_thread(void *pa_v)
zbufshade_tile(pa);
/* merge too on break! */
- if(R.result->exrhandle)
- save_render_result_tile(&R, pa);
+ if(R.result->exrhandle) {
+ RenderResult *rr, *rrpart;
+
+ for(rr= R.result, rrpart= pa->result; rr && rrpart; rr= rr->next, rrpart= rrpart->next)
+ save_render_result_tile(rr, rrpart);
+
+ }
else if(render_display_draw_enabled(&R))
merge_render_result(R.result, pa->result);
}
@@ -1365,33 +1441,54 @@ static void print_part_stats(Render *re, RenderPart *pa)
re->i.infostr= NULL;
}
+/* make osa new results for samples */
+static RenderResult *new_full_sample_buffers_exr(Render *re)
+{
+ int a;
+
+ for(a=0; a<re->osa; a++) {
+ RenderResult *rr= new_render_result(re, &re->disprect, 0, 1);
+ BLI_addtail(&re->fullresult, rr);
+ rr->sample_nr= a;
+ }
+
+ return re->fullresult.first;
+}
+
static void threaded_tile_processor(Render *re)
{
ListBase threads;
RenderPart *pa, *nextpa;
- RenderResult *rr;
rctf viewplane= re->viewplane;
int rendering=1, counter= 1, drawtimer=0, hasdrawn, minx=0;
- /* first step; the entire render result, or prepare exr buffer saving */
+ /* first step; free the entire render result, make new, and/or prepare exr buffer saving */
RE_FreeRenderResult(re->result);
- rr= re->result= new_render_result(re, &re->disprect, 0, re->r.scemode & R_EXR_TILE_FILE);
- if(rr==NULL)
+ if(re->sss_points)
+ re->result= new_render_result(re, &re->disprect, 0, 0);
+ else if(re->r.scemode & R_FULL_SAMPLE)
+ re->result= new_full_sample_buffers_exr(re);
+ else
+ re->result= new_render_result(re, &re->disprect, 0, re->r.scemode & R_EXR_TILE_FILE);
+
+ if(re->result==NULL)
return;
+
/* warning; no return here without closing exr file */
-// if(re->re->test_break())
-// return;
initparts(re);
- if(rr->exrhandle) {
+ if(re->result->exrhandle) {
+ RenderResult *rr;
char str[FILE_MAX];
- render_unique_exr_name(re, str);
+ for(rr= re->result; rr; rr= rr->next) {
+ render_unique_exr_name(re, str, rr->sample_nr);
- printf("write exr tmp file, %dx%d, %s\n", rr->rectx, rr->recty, str);
- IMB_exrtile_begin_write(rr->exrhandle, str, rr->rectx, rr->recty, rr->rectx/re->xparts, rr->recty/re->yparts);
+ printf("write exr tmp file, %dx%d, %s\n", rr->rectx, rr->recty, str);
+ IMB_exrtile_begin_write(rr->exrhandle, str, 0, rr->rectx, rr->recty, re->partx, re->party);
+ }
}
BLI_init_threads(&threads, do_part_thread, re->r.threads);
@@ -1446,7 +1543,7 @@ static void threaded_tile_processor(Render *re)
re->display_draw(pa->result, NULL);
print_part_stats(re, pa);
- RE_FreeRenderResult(pa->result);
+ free_render_result(&pa->fullresult, pa->result);
pa->result= NULL;
re->i.partsdone++;
hasdrawn= 1;
@@ -1470,11 +1567,20 @@ static void threaded_tile_processor(Render *re)
}
- if(rr->exrhandle) {
+ if(re->result->exrhandle) {
+ RenderResult *rr;
+
save_empty_result_tiles(re);
- IMB_exr_close(rr->exrhandle);
- rr->exrhandle= NULL;
- read_render_result(re);
+
+ for(rr= re->result; rr; rr= rr->next) {
+ IMB_exr_close(rr->exrhandle);
+ rr->exrhandle= NULL;
+ }
+
+ free_render_result(&re->fullresult, re->result);
+ re->result= NULL;
+
+ read_render_result(re, 0);
}
/* unset threadsafety */
@@ -1492,14 +1598,16 @@ void RE_TileProcessor(Render *re, int firsttile, int threaded)
re->i.partsdone= firsttile;
- re->i.starttime= PIL_check_seconds_timer();
+ if(!re->sss_points)
+ re->i.starttime= PIL_check_seconds_timer();
if(threaded)
threaded_tile_processor(re);
else
render_tile_processor(re, firsttile);
- re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
+ if(!re->sss_points)
+ re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
re->stats_draw(&re->i);
}
@@ -1722,7 +1830,8 @@ static void load_backbuffer(Render *re)
char name[256];
strcpy(name, re->r.backbuf);
- BLI_convertstringcode(name, G.sce, re->r.cfra);
+ BLI_convertstringcode(name, G.sce);
+ BLI_convertstringframe(name, re->r.cfra);
if(re->backbuf) {
re->backbuf->id.us--;
@@ -1778,6 +1887,7 @@ static void do_render_fields_blur_3d(Render *re)
re->result->tilerect= re->disprect;
/* this copying sequence could become function? */
+ /* weak is: it chances disprect from border */
re->disprect.xmin= re->disprect.ymin= 0;
re->disprect.xmax= re->winx;
re->disprect.ymax= re->winy;
@@ -1807,14 +1917,18 @@ static void do_render_fields_blur_3d(Render *re)
static void render_scene(Render *re, Scene *sce, int cfra)
{
Render *resc= RE_NewRender(sce->id.name);
+ int winx= re->winx, winy= re->winy;
sce->r.cfra= cfra;
- /* initial setup */
- RE_InitState(resc, &sce->r, re->winx, re->winy, &re->disprect);
+ /* exception: scene uses own size (unfinished code) */
+ if(0) {
+ winx= (sce->r.size*sce->r.xsch)/100;
+ winy= (sce->r.size*sce->r.ysch)/100;
+ }
- /* this to enable this scene to create speed vectors */
- resc->r.scemode |= R_DOCOMP;
+ /* initial setup */
+ RE_InitState(resc, re, &sce->r, winx, winy, &re->disprect);
/* still unsure entity this... */
resc->scene= sce;
@@ -1830,10 +1944,15 @@ static void render_scene(Render *re, Scene *sce, int cfra)
do_render_fields_blur_3d(resc);
}
-static void ntree_render_scenes(Render *re)
+static void tag_scenes_for_render(Render *re)
{
bNode *node;
- int cfra= re->scene->r.cfra;
+ Scene *sce;
+
+ for(sce= G.main->scene.first; sce; sce= sce->id.next)
+ sce->id.flag &= ~LIB_DOIT;
+
+ re->scene->id.flag |= LIB_DOIT;
if(re->scene->nodetree==NULL) return;
@@ -1843,12 +1962,21 @@ static void ntree_render_scenes(Render *re)
if(node->id) {
if(node->id != (ID *)re->scene)
node->id->flag |= LIB_DOIT;
- else
- node->id->flag &= ~LIB_DOIT;
}
}
}
+}
+
+static void ntree_render_scenes(Render *re)
+{
+ bNode *node;
+ int cfra= re->scene->r.cfra;
+
+ if(re->scene->nodetree==NULL) return;
+
+ tag_scenes_for_render(re);
+
/* now foreach render-result node tagged we do a full render */
/* results are stored in a way compisitor will find it */
for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
@@ -1894,6 +2022,115 @@ static void render_composit_stats(char *str)
R.i.infostr= NULL;
}
+
+/* reads all buffers, calls optional composite, merges in first result->rectf */
+static void do_merge_fullsample(Render *re, bNodeTree *ntree)
+{
+ float *rectf, filt[3][3];
+ int sample;
+
+ /* filtmask needs it */
+ R= *re;
+
+ /* we accumulate in here */
+ rectf= MEM_mapallocN(re->rectx*re->recty*sizeof(float)*4, "fullsample rgba");
+
+ for(sample=0; sample<re->r.osa; sample++) {
+ RenderResult rres;
+ int x, y, mask;
+
+ /* set all involved renders on the samplebuffers (first was done by render itself) */
+ /* also function below assumes this */
+ if(sample) {
+ Render *re1;
+
+ tag_scenes_for_render(re);
+ for(re1= RenderList.first; re1; re1= re1->next) {
+ if(re1->scene->id.flag & LIB_DOIT)
+ if(re1->r.scemode & R_FULL_SAMPLE)
+ read_render_result(re1, sample);
+ }
+ }
+
+ /* composite */
+ if(ntree) {
+ ntreeCompositTagRender(re->scene);
+ ntreeCompositTagAnimated(ntree);
+
+ ntreeCompositExecTree(ntree, &re->r, G.background==0);
+ }
+
+ /* ensure we get either composited result or the active layer */
+ RE_GetResultImage(re, &rres);
+
+ /* accumulate with filter, and clip */
+ mask= (1<<sample);
+ mask_array(mask, filt);
+
+ for(y=0; y<re->recty; y++) {
+ float *rf= rectf + 4*y*re->rectx;
+ float *col= rres.rectf + 4*y*re->rectx;
+
+ for(x=0; x<re->rectx; x++, rf+=4, col+=4) {
+ if(col[0]<0.0f) col[0]=0.0f; else if(col[0] > 1.0f) col[0]= 1.0f;
+ if(col[1]<0.0f) col[1]=0.0f; else if(col[1] > 1.0f) col[1]= 1.0f;
+ if(col[2]<0.0f) col[2]=0.0f; else if(col[2] > 1.0f) col[2]= 1.0f;
+
+ add_filt_fmask_coord(filt, col, rf, re->rectx, re->recty, x, y);
+ }
+ }
+
+ /* show stuff */
+ if(sample!=re->osa-1) {
+ /* weak... the display callback wants an active renderlayer pointer... */
+ re->result->renlay= render_get_active_layer(re, re->result);
+ re->display_draw(re->result, NULL);
+ }
+
+ if(re->test_break())
+ break;
+ }
+
+ if(re->result->rectf)
+ MEM_freeN(re->result->rectf);
+ re->result->rectf= rectf;
+}
+
+void RE_MergeFullSample(Render *re, Scene *sce, bNodeTree *ntree)
+{
+ Scene *scene;
+ bNode *node;
+
+ /* first call RE_ReadRenderResult on every renderlayer scene. this creates Render structs */
+
+ /* tag scenes unread */
+ for(scene= G.main->scene.first; scene; scene= scene->id.next)
+ scene->id.flag |= LIB_DOIT;
+
+ for(node= ntree->nodes.first; node; node= node->next) {
+ if(node->type==CMP_NODE_R_LAYERS) {
+ Scene *nodescene= (Scene *)node->id;
+
+ if(nodescene==NULL) nodescene= sce;
+ if(nodescene->id.flag & LIB_DOIT) {
+ nodescene->r.mode |= R_OSA; /* render struct needs tables */
+ RE_ReadRenderResult(sce, nodescene);
+ nodescene->id.flag &= ~LIB_DOIT;
+ }
+ }
+ }
+
+ /* own render result should be read/allocated */
+ if(G.scene->id.flag & LIB_DOIT)
+ RE_ReadRenderResult(G.scene, G.scene);
+
+ /* and now we can draw (result is there) */
+ re->display_init(re->result);
+ re->display_clear(re->result);
+
+ do_merge_fullsample(re, ntree);
+}
+
/* returns fully composited render-result on given time step (in RenderData) */
static void do_render_composite_fields_blur_3d(Render *re)
{
@@ -1913,25 +2150,36 @@ static void do_render_composite_fields_blur_3d(Render *re)
if(re->r.scemode & R_SINGLE_LAYER)
pop_render_result(re);
- if(!re->test_break() && ntree) {
- ntreeCompositTagRender(re->scene);
- ntreeCompositTagAnimated(ntree);
+ if(!re->test_break()) {
- if(re->r.scemode & R_DOCOMP) {
- /* checks if there are render-result nodes that need scene */
- if((re->r.scemode & R_SINGLE_LAYER)==0)
- ntree_render_scenes(re);
-
- if(!re->test_break()) {
- ntree->stats_draw= render_composit_stats;
- ntree->test_break= re->test_break;
- /* in case it was never initialized */
- R.stats_draw= re->stats_draw;
+ if(ntree) {
+ ntreeCompositTagRender(re->scene);
+ ntreeCompositTagAnimated(ntree);
+ }
+
+ if(1 || !(re->r.scemode & R_COMP_RERENDER)) {
+ if(ntree && re->r.scemode & R_DOCOMP) {
+ /* checks if there are render-result nodes that need scene */
+ if((re->r.scemode & R_SINGLE_LAYER)==0)
+ ntree_render_scenes(re);
- ntreeCompositExecTree(ntree, &re->r, G.background==0);
- ntree->stats_draw= NULL;
- ntree->test_break= NULL;
+ if(!re->test_break()) {
+ ntree->stats_draw= render_composit_stats;
+ ntree->test_break= re->test_break;
+ /* in case it was never initialized */
+ R.stats_draw= re->stats_draw;
+
+ if(re->r.scemode & R_FULL_SAMPLE)
+ do_merge_fullsample(re, ntree);
+ else
+ ntreeCompositExecTree(ntree, &re->r, G.background==0);
+
+ ntree->stats_draw= NULL;
+ ntree->test_break= NULL;
+ }
}
+ else if(re->r.scemode & R_FULL_SAMPLE)
+ do_merge_fullsample(re, NULL);
}
}
@@ -2008,7 +2256,7 @@ static void renderresult_stampinfo()
RenderResult rres;
/* this is the basic trick to get the displayed float or char rect from render result */
RE_GetResultImage(RE_GetRender(G.scene->id.name), &rres);
- BKE_stamp_buf((unsigned char *)rres.rect32, rres.rectf, rres.rectx, rres.recty);
+ BKE_stamp_buf((unsigned char *)rres.rect32, rres.rectf, rres.rectx, rres.recty, 4);
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
@@ -2086,14 +2334,26 @@ static int is_rendering_allowed(Render *re)
if(re->r.scemode & R_EXR_TILE_FILE) {
char str[FILE_MAX];
- render_unique_exr_name(re, str);
+ render_unique_exr_name(re, str, 0);
if (BLI_is_writable(str)==0) {
re->error("Can not save render buffers, check the temp default path");
return 0;
}
+ /* no osa + fullsample won't work... */
+ if(re->osa==0)
+ re->r.scemode &= ~R_FULL_SAMPLE;
+
+ /* no fullsample and edge */
+ if((re->r.scemode & R_FULL_SAMPLE) && (re->r.mode & R_EDGE)) {
+ re->error("Full Sample doesn't support Edge Enhance");
+ return 0;
+ }
+
}
+ else
+ re->r.scemode &= ~R_FULL_SAMPLE; /* clear to be sure */
if(re->r.scemode & R_DOCOMP) {
if(re->scene->use_nodes) {
@@ -2152,7 +2412,7 @@ static int is_rendering_allowed(Render *re)
}
/* evaluating scene options for general Blender render */
-static int render_initialize_from_scene(Render *re, Scene *scene)
+static int render_initialize_from_scene(Render *re, Scene *scene, int anim)
{
int winx, winy;
rcti disprect;
@@ -2178,31 +2438,27 @@ static int render_initialize_from_scene(Render *re, Scene *scene)
disprect.ymax= winy;
}
- if(scene->r.scemode & R_EXR_TILE_FILE) {
- int partx= winx/scene->r.xparts, party= winy/scene->r.yparts;
-
- /* stupid exr tiles dont like different sizes */
- if(winx != partx*scene->r.xparts || winy != party*scene->r.yparts) {
- re->error("Sorry... exr tile saving only allowed with equally sized parts");
- return 0;
- }
- if((scene->r.mode & R_FIELDS) && (party & 1)) {
- re->error("Sorry... exr tile saving only allowed with equally sized parts");
- return 0;
- }
+ re->scene= scene;
+
+ /* not too nice, but it survives anim-border render */
+ if(anim) {
+ re->disprect= disprect;
+ return 1;
}
+ /* check all scenes involved */
+ tag_scenes_for_render(re);
+
if(scene->r.scemode & R_SINGLE_LAYER)
push_render_result(re);
- RE_InitState(re, &scene->r, winx, winy, &disprect);
+ RE_InitState(re, NULL, &scene->r, winx, winy, &disprect);
if(!re->ok) /* if an error was printed, abort */
return 0;
/* initstate makes new result, have to send changed tags around */
ntreeCompositTagRender(re->scene);
- re->scene= scene;
if(!is_rendering_allowed(re))
return 0;
@@ -2221,7 +2477,7 @@ void RE_BlenderFrame(Render *re, Scene *scene, int frame)
scene->r.cfra= frame;
- if(render_initialize_from_scene(re, scene)) {
+ if(render_initialize_from_scene(re, scene, 0)) {
do_render_all_options(re);
}
@@ -2301,13 +2557,15 @@ static void do_write_image_or_movie(Render *re, Scene *scene, bMovieHandle *mh)
}
/* saves images to disk */
-void RE_BlenderAnim(Render *re, Scene *scene, int sfra, int efra)
+void RE_BlenderAnim(Render *re, Scene *scene, int sfra, int efra, int tfra)
{
bMovieHandle *mh= BKE_get_movie_handle(scene->r.imtype);
+ unsigned int lay;
int cfrao= scene->r.cfra;
+ int nfra;
- /* do not call for each frame, it initializes & pops output window */
- if(!render_initialize_from_scene(re, scene))
+ /* do not fully call for each frame, it initializes & pops output window */
+ if(!render_initialize_from_scene(re, scene, 0))
return;
/* ugly global still... is to prevent renderwin events and signal subsurfs etc to make full resol */
@@ -2333,17 +2591,58 @@ void RE_BlenderAnim(Render *re, Scene *scene, int sfra, int efra)
}
}
} else {
- for(scene->r.cfra= sfra;
- scene->r.cfra<=efra; scene->r.cfra++) {
+ for(nfra= sfra, scene->r.cfra= sfra; scene->r.cfra<=efra; scene->r.cfra++) {
+ char name[FILE_MAX];
+
+ /* only border now, todo: camera lens. (ton) */
+ render_initialize_from_scene(re, scene, 1);
+
+ if(nfra!=scene->r.cfra) {
+ /*
+ * Skip this frame, but update for physics and particles system.
+ * From convertblender.c:
+ * in localview, lamps are using normal layers, objects only local bits.
+ */
+ if(scene->lay & 0xFF000000)
+ lay= scene->lay & 0xFF000000;
+ else
+ lay= scene->lay;
+
+ scene_update_for_newframe(scene, lay);
+ continue;
+ }
+ else
+ nfra+= tfra;
+
+ if (scene->r.mode & (R_NO_OVERWRITE | R_TOUCH) ) {
+ BKE_makepicstring(name, scene->r.pic, scene->r.cfra, scene->r.imtype);
+ }
+
+ if (scene->r.mode & R_NO_OVERWRITE && BLI_exist(name)) {
+ printf("skipping existing frame \"%s\"\n", name);
+ continue;
+ }
+ if (scene->r.mode & R_TOUCH && !BLI_exist(name)) {
+ BLI_make_existing_file(name); /* makes the dir if its not there */
+ BLI_touch(name);
+ }
+
re->r.cfra= scene->r.cfra; /* weak.... */
-
+
do_render_all_options(re);
-
+
if(re->test_break() == 0) {
do_write_image_or_movie(re, scene, mh);
}
- if(G.afbreek==1) break;
+ if(G.afbreek==1) {
+ /* remove touched file */
+ if (scene->r.mode & R_TOUCH && BLI_exist(name) && BLI_filepathsize(name) == 0) {
+ BLI_delete(name, 0, 0);
+ }
+
+ break;
+ }
}
}
@@ -2359,7 +2658,7 @@ void RE_BlenderAnim(Render *re, Scene *scene, int sfra, int efra)
/* note; repeated win/disprect calc... solve that nicer, also in compo */
-/* only temp file! */
+/* only the temp file! */
void RE_ReadRenderResult(Scene *scene, Scene *scenode)
{
Render *re;
@@ -2387,17 +2686,32 @@ void RE_ReadRenderResult(Scene *scene, Scene *scenode)
if(scenode)
scene= scenode;
- re= RE_NewRender(scene->id.name);
- RE_InitState(re, &scene->r, winx, winy, &disprect);
+ /* get render: it can be called from UI with draw callbacks */
+ re= RE_GetRender(scene->id.name);
+ if(re==NULL)
+ re= RE_NewRender(scene->id.name);
+ RE_InitState(re, NULL, &scene->r, winx, winy, &disprect);
re->scene= scene;
- read_render_result(re);
+ read_render_result(re, 0);
}
void RE_set_max_threads(int threads)
{
- if(threads>0 && threads<=BLENDER_MAX_THREADS)
+ if (threads==0) {
+ commandline_threads = BLI_system_thread_count();
+ } else if(threads>=1 && threads<=BLENDER_MAX_THREADS) {
commandline_threads= threads;
- else
+ } else {
printf("Error, threads has to be in range 1-%d\n", BLENDER_MAX_THREADS);
+ }
+}
+
+void RE_init_threadcount(Render *re)
+{
+ if(commandline_threads >= 1) { /* only set as an arg in background mode */
+ re->r.threads= MIN2(commandline_threads, BLENDER_MAX_THREADS);
+ } else if ((re->r.mode & R_FIXED_THREADS)==0 || commandline_threads == 0) { /* Automatic threads */
+ re->r.threads = BLI_system_thread_count();
+ }
}
diff --git a/source/blender/render/intern/source/pixelblending.c b/source/blender/render/intern/source/pixelblending.c
index 119cceaf3c2..0e453d461ab 100644
--- a/source/blender/render/intern/source/pixelblending.c
+++ b/source/blender/render/intern/source/pixelblending.c
@@ -31,6 +31,7 @@
*/
#include <math.h>
+#include <string.h>
/* global includes */
#include "BLI_arithb.h"
@@ -91,15 +92,6 @@ void addAlphaOverFloat(float *dest, float *source)
void addAlphaUnderFloat(float *dest, float *source)
{
float mul;
-
- if( (-RE_EMPTY_COLOR_FLOAT < dest[3])
- && (dest[3] < RE_EMPTY_COLOR_FLOAT) ) {
- dest[0] = source[0];
- dest[1] = source[1];
- dest[2] = source[2];
- dest[3] = source[3];
- return;
- }
mul= 1.0 - dest[3];
@@ -212,6 +204,121 @@ void add_filt_fmask(unsigned int mask, float *col, float *rowbuf, int row_w)
}
}
+
+void mask_array(unsigned int mask, float filt[][3])
+{
+ float **fmask1= R.samples->fmask1, **fmask2=R.samples->fmask2;
+ unsigned int maskand= (mask & 255);
+ unsigned int maskshift= (mask >>8);
+ int a, j;
+
+ for(j=2; j>=0; j--) {
+
+ a= j;
+
+ filt[2][2-j]= *(fmask1[a] +maskand) + *(fmask2[a] +maskshift);
+
+ a+=3;
+
+ filt[1][2-j]= *(fmask1[a] +maskand) + *(fmask2[a] +maskshift);
+
+ a+=3;
+
+ filt[0][2-j]= *(fmask1[a] +maskand) + *(fmask2[a] +maskshift);
+ }
+}
+
+
+/*
+
+index ordering, scanline based:
+
+ --- --- ---
+| 2,0 | 2,1 | 2,2 |
+ --- --- ---
+| 1,0 | 1,1 | 1,2 |
+ --- --- ---
+| 0,0 | 0,1 | 0,2 |
+ --- --- ---
+*/
+
+void add_filt_fmask_coord(float filt[][3], float *col, float *rowbuf, int row_w, int col_h, int x, int y)
+{
+ float *fpoin[3][3];
+ float val, r, g, b, al, lfilt[3][3];
+
+ r= col[0];
+ g= col[1];
+ b= col[2];
+ al= col[3];
+
+ memcpy(lfilt, filt, sizeof(lfilt));
+
+ fpoin[0][1]= rowbuf-4*row_w;
+ fpoin[1][1]= rowbuf;
+ fpoin[2][1]= rowbuf+4*row_w;
+
+ fpoin[0][0]= fpoin[0][1] - 4;
+ fpoin[1][0]= fpoin[1][1] - 4;
+ fpoin[2][0]= fpoin[2][1] - 4;
+
+ fpoin[0][2]= fpoin[0][1] + 4;
+ fpoin[1][2]= fpoin[1][1] + 4;
+ fpoin[2][2]= fpoin[2][1] + 4;
+
+ if(y==0) {
+ fpoin[0][0]= fpoin[1][0];
+ fpoin[0][1]= fpoin[1][1];
+ fpoin[0][2]= fpoin[1][2];
+ /* filter needs the opposite value yes! */
+ lfilt[0][0]= filt[2][0];
+ lfilt[0][1]= filt[2][1];
+ lfilt[0][2]= filt[2][2];
+ }
+ else if(y==col_h-1) {
+ fpoin[2][0]= fpoin[1][0];
+ fpoin[2][1]= fpoin[1][1];
+ fpoin[2][2]= fpoin[1][2];
+
+ lfilt[2][0]= filt[0][0];
+ lfilt[2][1]= filt[0][1];
+ lfilt[2][2]= filt[0][2];
+ }
+
+ if(x==0) {
+ fpoin[2][0]= fpoin[2][1];
+ fpoin[1][0]= fpoin[1][1];
+ fpoin[0][0]= fpoin[0][1];
+
+ lfilt[2][0]= filt[2][2];
+ lfilt[1][0]= filt[1][2];
+ lfilt[0][0]= filt[0][2];
+ }
+ else if(x==row_w-1) {
+ fpoin[2][2]= fpoin[2][1];
+ fpoin[1][2]= fpoin[1][1];
+ fpoin[0][2]= fpoin[0][1];
+
+ lfilt[2][2]= filt[2][0];
+ lfilt[1][2]= filt[1][0];
+ lfilt[0][2]= filt[0][0];
+ }
+
+
+ /* loop unroll */
+#define MASKFILT(i, j) val= lfilt[i][j]; if(val!=0.0f) {float *fp= fpoin[i][j]; fp[0]+= val*r; fp[1]+= val*g; fp[2]+= val*b; fp[3]+= val*al; }
+
+ MASKFILT(0, 0)
+ MASKFILT(0, 1)
+ MASKFILT(0, 2)
+ MASKFILT(1, 0)
+ MASKFILT(1, 1)
+ MASKFILT(1, 2)
+ MASKFILT(2, 0)
+ MASKFILT(2, 1)
+ MASKFILT(2, 2)
+}
+
void add_filt_fmask_pixsize(unsigned int mask, float *in, float *rowbuf, int row_w, int pixsize)
{
/* calc the value of mask */
diff --git a/source/blender/render/intern/source/pixelshading.c b/source/blender/render/intern/source/pixelshading.c
index cffed99c738..60723963af9 100644
--- a/source/blender/render/intern/source/pixelshading.c
+++ b/source/blender/render/intern/source/pixelshading.c
@@ -24,7 +24,9 @@
* ***** END GPL LICENSE BLOCK *****
*/
+#include <float.h>
#include <math.h>
+#include <string.h>
#include "BLI_arithb.h"
/* External modules: */
@@ -43,6 +45,7 @@
#include "BKE_image.h"
#include "BKE_global.h"
+#include "BKE_material.h"
#include "BKE_texture.h"
#include "BKE_utildefines.h"
@@ -55,6 +58,7 @@
#include "rendercore.h"
#include "shadbuf.h"
#include "pixelshading.h"
+#include "sunsky.h"
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* defined in pipeline.c, is hardcopy of active dynamic allocated Render */
@@ -130,9 +134,15 @@ static void render_lighting_halo(HaloRen *har, float *colf)
if(lar->mode & LA_TEXTURE) {
ShadeInput shi;
+
+ /* Warning, This is not that nice, and possibly a bit slow,
+ however some variables were not initialized properly in, unless using shade_input_initialize(...), we need to do a memset */
+ memset(&shi, 0, sizeof(ShadeInput));
+ /* end warning! - Campbell */
+
VECCOPY(shi.co, rco);
shi.osatex= 0;
- do_lamp_tex(lar, lv, &shi, lacol);
+ do_lamp_tex(lar, lv, &shi, lacol, LA_TEXTURE);
}
if(lar->type==LA_SPOT) {
@@ -175,7 +185,7 @@ static void render_lighting_halo(HaloRen *har, float *colf)
inp= vn[0]*lv[0] + vn[1]*lv[1] + vn[2]*lv[2];
if(inp>0.0) {
/* testshadowbuf==0.0 : 100% shadow */
- shadfac = testshadowbuf(lar->shb, rco, dco, dco, inp);
+ shadfac = testshadowbuf(&R, lar->shb, rco, dco, dco, inp, 0.0f);
if( shadfac>0.0 ) {
shadfac*= inp*soft*lar->energy;
ir -= shadfac;
@@ -212,7 +222,7 @@ static void render_lighting_halo(HaloRen *har, float *colf)
if(i> -0.41) { /* heuristic valua! */
shadfac= 1.0;
if(lar->shb) {
- shadfac = testshadowbuf(lar->shb, rco, dco, dco, inp);
+ shadfac = testshadowbuf(&R, lar->shb, rco, dco, dco, inp, 0.0f);
if(shadfac==0.0) continue;
i*= shadfac;
}
@@ -236,8 +246,36 @@ static void render_lighting_halo(HaloRen *har, float *colf)
}
+/**
+ * Converts a halo z-buffer value to distance from the camera's near plane
+ * @param z The z-buffer value to convert
+ * @return a distance from the camera's near plane in blender units
+ */
+static float haloZtoDist(int z)
+{
+ float zco = 0;
-void shadeHaloFloat(HaloRen *har, float *col, int zz,
+ if(z >= 0x7FFFFF)
+ return 10e10;
+ else {
+ zco = (float)z/(float)0x7FFFFF;
+ if(R.r.mode & R_ORTHO)
+ return (R.winmat[3][2] - zco*R.winmat[3][3])/(R.winmat[2][2]);
+ else
+ return (R.winmat[3][2])/(R.winmat[2][2] - R.winmat[2][3]*zco);
+ }
+}
+
+/**
+ * @param col (float[4]) Store the rgb color here (with alpha)
+ * The alpha is used to blend the color to the background
+ * color_new = (1-alpha)*color_background + color
+ * @param zz The current zbuffer value at the place of this pixel
+ * @param dist Distance of the pixel from the center of the halo squared. Given in pixels
+ * @param xn The x coordinate of the pixel relaticve to the center of the halo. given in pixels
+ * @param yn The y coordinate of the pixel relaticve to the center of the halo. given in pixels
+ */
+int shadeHaloFloat(HaloRen *har, float *col, int zz,
float dist, float xn, float yn, short flarec)
{
/* fill in col */
@@ -256,12 +294,40 @@ void shadeHaloFloat(HaloRen *har, float *col, int zz,
}
else alpha= har->alfa;
- if(alpha==0.0) {
- col[0] = 0.0;
- col[1] = 0.0;
- col[2] = 0.0;
- col[3] = 0.0;
- return;
+ if(alpha==0.0)
+ return 0;
+
+ /* soften the halo if it intersects geometry */
+ if(har->mat && har->mat->mode & MA_HALO_SOFT) {
+ float segment_length, halo_depth, distance_from_z, visible_depth, soften;
+
+ /* calculate halo depth */
+ segment_length= har->hasize*sasqrt(1.0f - dist/(har->rad*har->rad));
+ halo_depth= 2.0f*segment_length;
+
+ if(halo_depth < FLT_EPSILON)
+ return 0;
+
+ /* calculate how much of this depth is visible */
+ distance_from_z = haloZtoDist(zz) - haloZtoDist(har->zs);
+ visible_depth = halo_depth;
+ if(distance_from_z < segment_length) {
+ soften= (segment_length + distance_from_z)/halo_depth;
+
+ /* apply softening to alpha */
+ if(soften < 1.0f)
+ alpha *= soften;
+ if(alpha <= 0.0f)
+ return 0;
+ }
+ }
+ else {
+ /* not a soft halo. use the old softening code */
+ /* halo being intersected? */
+ if(har->zs> zz-har->zd) {
+ t= ((float)(zz-har->zs))/(float)har->zd;
+ alpha*= sqrt(sqrt(t));
+ }
}
radist= sqrt(dist);
@@ -359,21 +425,10 @@ void shadeHaloFloat(HaloRen *har, float *col, int zz,
if(ster<1.0) dist*= sqrt(ster);
}
}
-
- /* halo being intersected? */
- if(har->zs> zz-har->zd) {
- t= ((float)(zz-har->zs))/(float)har->zd;
- alpha*= sqrt(sqrt(t));
- }
/* disputable optimize... (ton) */
- if(dist<=0.00001) {
- col[0] = 0.0;
- col[1] = 0.0;
- col[2] = 0.0;
- col[3] = 0.0;
- return;
- }
+ if(dist<=0.00001)
+ return 0;
dist*= alpha;
ringf*= dist;
@@ -434,6 +489,8 @@ void shadeHaloFloat(HaloRen *har, float *col, int zz,
/* alpha requires clip, gives black dots */
if(col[3] > 1.0f)
col[3]= 1.0f;
+
+ return 1;
}
/* ------------------------------------------------------------------------- */
@@ -512,13 +569,48 @@ void shadeSkyView(float *colf, float *rco, float *view, float *dxyview)
}
}
+/* shade sky according to sun lamps, all parameters are like shadeSkyView except sunsky*/
+void shadeSunView(float *colf, float *view)
+{
+ GroupObject *go;
+ LampRen *lar;
+ float sview[3];
+ int do_init= 1;
+
+ for(go=R.lights.first; go; go= go->next) {
+ lar= go->lampren;
+ if(lar->type==LA_SUN && lar->sunsky && (lar->sunsky->effect_type & LA_SUN_EFFECT_SKY)){
+ float sun_collector[3];
+ float colorxyz[3];
+
+ if(do_init) {
+
+ VECCOPY(sview, view);
+ Normalize(sview);
+ MTC_Mat3MulVecfl(R.imat, sview);
+ if (sview[2] < 0.0)
+ sview[2] = 0.0;
+ Normalize(sview);
+ do_init= 0;
+ }
+
+ GetSkyXYZRadiancef(lar->sunsky, sview, colorxyz);
+ xyz_to_rgb(colorxyz[0], colorxyz[1], colorxyz[2], &sun_collector[0], &sun_collector[1], &sun_collector[2],
+ lar->sunsky->sky_colorspace);
+
+ ramp_blend(lar->sunsky->skyblendtype, colf, colf+1, colf+2, lar->sunsky->skyblendfac, sun_collector);
+ }
+ }
+}
+
+
/*
Stuff the sky color into the collector.
*/
void shadeSkyPixel(float *collector, float fx, float fy)
{
float view[3], dxyview[2];
-
+
/*
The rules for sky:
1. Draw an image, if a background image was provided. Stop
@@ -530,7 +622,6 @@ void shadeSkyPixel(float *collector, float fx, float fy)
/* 1. Do a backbuffer image: */
if(R.r.bufflag & 1) {
fillBackgroundImage(collector, fx, fy);
- return;
}
else if((R.wrld.skytype & (WO_SKYBLEND+WO_SKYTEX))==0) {
/* 2. solid color */
@@ -565,7 +656,20 @@ void shadeSkyPixel(float *collector, float fx, float fy)
shadeSkyView(collector, NULL, view, dxyview);
collector[3] = 0.0f;
}
+
+ calc_view_vector(view, fx, fy);
+ shadeSunView(collector, view);
}
+/* aerial perspective */
+void shadeAtmPixel(struct SunSky *sunsky, float *collector, float fx, float fy, float distance)
+{
+ float view[3];
+
+ calc_view_vector(view, fx, fy);
+ Normalize(view);
+ /*MTC_Mat3MulVecfl(R.imat, view);*/
+ AtmospherePixleShader(sunsky, view, distance, collector);
+}
/* eof */
diff --git a/source/blender/render/intern/source/rayshade.c b/source/blender/render/intern/source/rayshade.c
index 69e90a7537c..f822d41bb85 100644
--- a/source/blender/render/intern/source/rayshade.c
+++ b/source/blender/render/intern/source/rayshade.c
@@ -40,8 +40,9 @@
#include "BKE_utildefines.h"
#include "BLI_arithb.h"
-#include "BLI_rand.h"
+#include "BLI_blenlib.h"
#include "BLI_jitter.h"
+#include "BLI_rand.h"
#include "PIL_time.h"
@@ -77,15 +78,21 @@ static void vlr_face_coords(RayFace *face, float **v1, float **v2, float **v3, f
*v4 = (vlr->v4)? vlr->v4->co: NULL;
}
-static int vlr_check_intersect(Isect *is, RayFace *face)
+static int vlr_check_intersect(Isect *is, int ob, RayFace *face)
{
+ ObjectInstanceRen *obi= RAY_OBJECT_GET((Render*)is->userdata, ob);
VlakRen *vlr = (VlakRen*)face;
+ /* for baking selected to active non-traceable materials might still
+ * be in the raytree */
+ if(!(vlr->mat->mode & MA_TRACEBLE))
+ return 0;
+
/* I know... cpu cycle waste, might do smarter once */
if(is->mode==RE_RAY_MIRROR)
return !(vlr->mat->mode & MA_ONLYCAST);
else
- return (is->lay & vlr->lay);
+ return (is->lay & obi->lay);
}
static float *vlr_get_transform(void *userdata, int i)
@@ -110,7 +117,7 @@ void makeraytree(Render *re)
VlakRen *vlr= NULL;
float min[3], max[3], co1[3], co2[3], co3[3], co4[3];
double lasttime= PIL_check_seconds_timer();
- int v, totface = 0;
+ int v, totv = 0, totface = 0;
INIT_MINMAX(min, max);
@@ -124,7 +131,8 @@ void makeraytree(Render *re)
for(v=0;v<obr->totvlak;v++) {
if((v & 255)==0) vlr= obr->vlaknodes[v>>8].vlak;
else vlr++;
- if(vlr->mat->mode & MA_TRACEBLE) {
+ /* baking selected to active needs non-traceable too */
+ if((re->flag & R_BAKE_TRACE) || (vlr->mat->mode & MA_TRACEBLE)) {
if((vlr->mat->mode & MA_WIRE)==0) {
VECCOPY(co1, vlr->v1->co);
VECCOPY(co2, vlr->v2->co);
@@ -167,7 +175,7 @@ void makeraytree(Render *re)
if(re->excludeob && obr->ob == re->excludeob)
continue;
- for(v=0; v<obr->totvlak; v++) {
+ for(v=0; v<obr->totvlak; v++, totv++) {
if((v & 255)==0) {
double time= PIL_check_seconds_timer();
@@ -176,7 +184,7 @@ void makeraytree(Render *re)
break;
if(time-lasttime>1.0f) {
char str[32];
- sprintf(str, "Filling Octree: %d", v);
+ sprintf(str, "Filling Octree: %d", totv);
re->i.infostr= str;
re->stats_draw(&re->i);
re->i.infostr= NULL;
@@ -185,7 +193,7 @@ void makeraytree(Render *re)
}
else vlr++;
- if(vlr->mat->mode & MA_TRACEBLE)
+ if((re->flag & R_BAKE_TRACE) || (vlr->mat->mode & MA_TRACEBLE))
if((vlr->mat->mode & MA_WIRE)==0)
RE_ray_tree_add_face(re->raytree, RAY_OBJECT_SET(re, obi), vlr);
}
@@ -255,7 +263,12 @@ static void shade_ray(Isect *is, ShadeInput *shi, ShadeResult *shr)
shade_input_set_shade_texco(shi);
if(is->mode==RE_RAY_SHADOW_TRA)
- shade_color(shi, shr);
+ if(shi->mat->nodetree && shi->mat->use_nodes) {
+ ntreeShaderExecTree(shi->mat->nodetree, shi, shr);
+ shi->mat= vlr->mat; /* shi->mat is being set in nodetree */
+ }
+ else
+ shade_color(shi, shr);
else {
if(shi->mat->nodetree && shi->mat->use_nodes) {
ntreeShaderExecTree(shi->mat->nodetree, shi, shr);
@@ -376,7 +389,7 @@ static float shade_by_transmission(Isect *is, ShadeInput *shi, ShadeResult *shr)
static void ray_fadeout_endcolor(float *col, ShadeInput *origshi, ShadeInput *shi, ShadeResult *shr, Isect *isec, float *vec)
{
- /* un-intersected rays get either rendered material colour or sky colour */
+ /* un-intersected rays get either rendered material color or sky color */
if (origshi->mat->fadeto_mir == MA_RAYMIR_FADETOMAT) {
VECCOPY(col, shr->combined);
} else if (origshi->mat->fadeto_mir == MA_RAYMIR_FADETOSKY) {
@@ -384,12 +397,13 @@ static void ray_fadeout_endcolor(float *col, ShadeInput *origshi, ShadeInput *sh
Normalize(shi->view);
shadeSkyView(col, isec->start, shi->view, NULL);
+ shadeSunView(col, shi->view);
}
}
static void ray_fadeout(Isect *is, ShadeInput *shi, float *col, float *blendcol, float dist_mir)
{
- /* if fading out, linear blend against fade colour */
+ /* if fading out, linear blend against fade color */
float blendfac;
blendfac = 1.0 - VecLenf(shi->co, is->start)/dist_mir;
@@ -409,6 +423,11 @@ static void traceray(ShadeInput *origshi, ShadeResult *origshr, short depth, flo
float ref[3], maxsize=RE_ray_tree_max_size(R.raytree);
float dist_mir = origshi->mat->dist_mir;
+ /* Warning, This is not that nice, and possibly a bit slow for every ray,
+ however some variables were not initialized properly in, unless using shade_input_initialize(...), we need to do a memset */
+ memset(&shi, 0, sizeof(ShadeInput));
+ /* end warning! - Campbell */
+
VECCOPY(isec.start, start);
if (dist_mir > 0.0) {
isec.end[0]= start[0]+dist_mir*vec[0];
@@ -430,13 +449,13 @@ static void traceray(ShadeInput *origshi, ShadeResult *origshr, short depth, flo
shi.osatex= origshi->osatex;
shi.depth= 1; /* only used to indicate tracing */
shi.thread= origshi->thread;
- shi.sample= 0;
+ //shi.sample= 0; // memset above, so dont need this
shi.xs= origshi->xs;
shi.ys= origshi->ys;
shi.lay= origshi->lay;
shi.passflag= SCE_PASS_COMBINED; /* result of tracing needs no pass info */
shi.combinedflag= 0xFFFFFF; /* ray trace does all options */
- shi.do_preview= 0;
+ //shi.do_preview= 0; // memset above, so dont need this
shi.light_override= origshi->light_override;
shi.mat_override= origshi->mat_override;
@@ -531,8 +550,8 @@ static void traceray(ShadeInput *origshi, ShadeResult *origshr, short depth, flo
if (dist_mir > 0.0) {
float blendcol[3];
- /* max ray distance set, but found an intersection, so fade this colour
- * out towards the sky/material colour for a smooth transition */
+ /* max ray distance set, but found an intersection, so fade this color
+ * out towards the sky/material color for a smooth transition */
ray_fadeout_endcolor(blendcol, origshi, &shi, origshr, &isec, vec);
ray_fadeout(&isec, &shi, col, blendcol, dist_mir);
}
@@ -615,24 +634,27 @@ void init_jitter_plane(LampRen *lar)
/* at least 4, or max threads+1 tables */
if(BLENDER_MAX_THREADS < 4) x= 4;
else x= BLENDER_MAX_THREADS+1;
- fp= lar->jitter= MEM_mallocN(x*tot*2*sizeof(float), "lamp jitter tab");
-
- /* set per-lamp fixed seed */
- BLI_srandom(tot);
-
- /* fill table with random locations, area_size large */
- for(x=0; x<tot; x++, fp+=2) {
- fp[0]= (BLI_frand()-0.5)*lar->area_size;
- fp[1]= (BLI_frand()-0.5)*lar->area_sizey;
- }
+ fp= lar->jitter= MEM_callocN(x*tot*2*sizeof(float), "lamp jitter tab");
- while(iter--) {
- fp= lar->jitter;
- for(x=tot; x>0; x--, fp+=2) {
- DP_energy(lar->jitter, fp, tot, lar->area_size, lar->area_sizey);
+ /* if 1 sample, we leave table to be zero's */
+ if(tot>1) {
+
+ /* set per-lamp fixed seed */
+ BLI_srandom(tot);
+
+ /* fill table with random locations, area_size large */
+ for(x=0; x<tot; x++, fp+=2) {
+ fp[0]= (BLI_frand()-0.5)*lar->area_size;
+ fp[1]= (BLI_frand()-0.5)*lar->area_sizey;
}
- }
-
+
+ while(iter--) {
+ fp= lar->jitter;
+ for(x=tot; x>0; x--, fp+=2) {
+ DP_energy(lar->jitter, fp, tot, lar->area_size, lar->area_sizey);
+ }
+ }
+ }
/* create the dithered tables (could just check lamp type!) */
jitter_plane_offset(lar->jitter, lar->jitter+2*tot, tot, lar->area_size, lar->area_sizey, 0.5f, 0.0f);
jitter_plane_offset(lar->jitter, lar->jitter+4*tot, tot, lar->area_size, lar->area_sizey, 0.5f, 0.5f);
@@ -715,10 +737,10 @@ static void hammersley_create(double *out, int n)
}
}
-struct QMCSampler *QMC_initSampler(int type, int tot)
+static struct QMCSampler *QMC_initSampler(int type, int tot)
{
- QMCSampler *qsa = MEM_mallocN(sizeof(QMCSampler), "qmc sampler");
- qsa->samp2d = MEM_mallocN(2*sizeof(double)*tot, "qmc sample table");
+ QMCSampler *qsa = MEM_callocN(sizeof(QMCSampler), "qmc sampler");
+ qsa->samp2d = MEM_callocN(2*sizeof(double)*tot, "qmc sample table");
qsa->tot = tot;
qsa->type = type;
@@ -859,25 +881,55 @@ static void QMC_sampleHemiCosine(float *vec, QMCSampler *qsa, int thread, int nu
#endif
/* called from convertBlenderScene.c */
-/* samples don't change per pixel, so build the samples in advance for efficiency */
-void init_lamp_hammersley(LampRen *lar)
+void init_render_qmcsampler(Render *re)
{
- lar->qsa = QMC_initSampler(SAMP_TYPE_HAMMERSLEY, lar->ray_totsamp);
+ re->qmcsamplers= MEM_callocN(sizeof(ListBase)*BLENDER_MAX_THREADS, "QMCListBase");
}
-void init_render_hammersley(Render *re)
+static QMCSampler *get_thread_qmcsampler(Render *re, int thread, int type, int tot)
{
- re->qsa = QMC_initSampler(SAMP_TYPE_HAMMERSLEY, (re->wrld.aosamp * re->wrld.aosamp));
+ QMCSampler *qsa;
+
+ /* create qmc samplers as needed, since recursion makes it hard to
+ * predict how many are needed */
+
+ for(qsa=re->qmcsamplers[thread].first; qsa; qsa=qsa->next) {
+ if(qsa->type == type && qsa->tot == tot && !qsa->used) {
+ qsa->used= 1;
+ return qsa;
+ }
+ }
+
+ qsa= QMC_initSampler(type, tot);
+ qsa->used= 1;
+ BLI_addtail(&re->qmcsamplers[thread], qsa);
+
+ return qsa;
}
-void free_lamp_qmcsampler(LampRen *lar)
+static void release_thread_qmcsampler(Render *re, int thread, QMCSampler *qsa)
{
- QMC_freeSampler(lar->qsa);
+ qsa->used= 0;
}
void free_render_qmcsampler(Render *re)
{
- QMC_freeSampler(re->qsa);
+ QMCSampler *qsa, *next;
+ int a;
+
+ if(re->qmcsamplers) {
+ for(a=0; a<BLENDER_MAX_THREADS; a++) {
+ for(qsa=re->qmcsamplers[a].first; qsa; qsa=next) {
+ next= qsa->next;
+ QMC_freeSampler(qsa);
+ }
+
+ re->qmcsamplers[a].first= re->qmcsamplers[a].last= NULL;
+ }
+
+ MEM_freeN(re->qmcsamplers);
+ re->qmcsamplers= NULL;
+ }
}
static int adaptive_sample_variance(int samples, float *col, float *colsq, float thresh)
@@ -954,7 +1006,7 @@ static void trace_refract(float *col, ShadeInput *shi, ShadeResult *shr)
else samp_type = SAMP_TYPE_HAMMERSLEY;
/* all samples are generated per pixel */
- qsa = QMC_initSampler(samp_type, max_samples);
+ qsa = get_thread_qmcsampler(&R, shi->thread, samp_type, max_samples);
QMC_initPixel(qsa, shi->thread);
} else
max_samples = 1;
@@ -1012,7 +1064,8 @@ static void trace_refract(float *col, ShadeInput *shi, ShadeResult *shr)
col[2] /= (float)samples;
col[3] /= (float)samples;
- if (qsa) QMC_freeSampler(qsa);
+ if (qsa)
+ release_thread_qmcsampler(&R, shi->thread, qsa);
}
static void trace_reflect(float *col, ShadeInput *shi, ShadeResult *shr, float fresnelfac)
@@ -1039,7 +1092,7 @@ static void trace_reflect(float *col, ShadeInput *shi, ShadeResult *shr, float f
else samp_type = SAMP_TYPE_HAMMERSLEY;
/* all samples are generated per pixel */
- qsa = QMC_initSampler(samp_type, max_samples);
+ qsa = get_thread_qmcsampler(&R, shi->thread, samp_type, max_samples);
QMC_initPixel(qsa, shi->thread);
} else
max_samples = 1;
@@ -1117,13 +1170,13 @@ static void trace_reflect(float *col, ShadeInput *shi, ShadeResult *shr, float f
col[1] /= (float)samples;
col[2] /= (float)samples;
- if (qsa) QMC_freeSampler(qsa);
+ if (qsa)
+ release_thread_qmcsampler(&R, shi->thread, qsa);
}
/* extern call from render loop */
void ray_trace(ShadeInput *shi, ShadeResult *shr)
{
- VlakRen *vlr;
float i, f, f1, fr, fg, fb;
float mircol[4], tracol[4];
float diff[3];
@@ -1131,7 +1184,7 @@ void ray_trace(ShadeInput *shi, ShadeResult *shr)
do_tra= ((shi->mat->mode & (MA_RAYTRANSP)) && shr->alpha!=1.0f);
do_mir= ((shi->mat->mode & MA_RAYMIRROR) && shi->ray_mirror!=0.0f);
- vlr= shi->vlr;
+
/* raytrace mirror amd refract like to separate the spec color */
if(shi->combinedflag & SCE_PASS_SPEC)
@@ -1231,16 +1284,22 @@ static void ray_trace_shadow_tra(Isect *is, int depth, int traflag)
float d= 1.0f;
/* we got a face */
+ /* Warning, This is not that nice, and possibly a bit slow for every ray,
+ however some variables were not initialized properly in, unless using shade_input_initialize(...), we need to do a memset */
+ memset(&shi, 0, sizeof(ShadeInput));
+ /* end warning! - Campbell */
+
shi.depth= 1; /* only used to indicate tracing */
shi.mask= 1;
- shi.osatex= 0;
+
+ /*shi.osatex= 0;
shi.thread= shi.sample= 0;
shi.lay= 0;
shi.passflag= 0;
shi.combinedflag= 0;
shi.do_preview= 0;
shi.light_override= NULL;
- shi.mat_override= NULL;
+ shi.mat_override= NULL;*/
shade_ray(is, &shi, &shr);
if (traflag & RAY_TRA)
@@ -1300,6 +1359,12 @@ int ray_trace_shadow_rad(ShadeInput *ship, ShadeResult *shr)
if(RE_ray_tree_intersect(R.raytree, &isec)) {
float fac;
+
+ /* Warning, This is not that nice, and possibly a bit slow for every ray,
+ however some variables were not initialized properly in, unless using shade_input_initialize(...), we need to do a memset */
+ memset(&shi, 0, sizeof(ShadeInput));
+ /* end warning! - Campbell */
+
shade_ray(&isec, &shi, &shr_t);
fac= isec.labda*isec.labda;
fac= 1.0f;
@@ -1416,14 +1481,15 @@ static float *sphere_sampler(int type, int resol, int thread, int xs, int ys)
int tot;
float *vec;
- if(resol>16) resol= 16;
-
tot= 2*resol*resol;
if (type & WO_AORNDSMP) {
- static float sphere[2*3*256];
+ float *sphere;
int a;
+ // always returns table
+ sphere= threadsafe_table_sphere(0, thread, xs, ys, tot);
+
/* total random sampling. NOT THREADSAFE! (should be removed, is not useful) */
vec= sphere;
for (a=0; a<tot; a++, vec+=3) {
@@ -1438,7 +1504,8 @@ static float *sphere_sampler(int type, int resol, int thread, int xs, int ys)
float ang, *vec1;
int a;
- sphere= threadsafe_table_sphere(1, thread, xs, ys, tot); // returns table if xs and ys were equal to last call
+ // returns table if xs and ys were equal to last call
+ sphere= threadsafe_table_sphere(1, thread, xs, ys, tot);
if(sphere==NULL) {
sphere= threadsafe_table_sphere(0, thread, xs, ys, tot);
@@ -1460,7 +1527,7 @@ static float *sphere_sampler(int type, int resol, int thread, int xs, int ys)
}
}
-void ray_ao_qmc(ShadeInput *shi, float *shadfac)
+static void ray_ao_qmc(ShadeInput *shi, float *shadfac)
{
Isect isec;
QMCSampler *qsa=NULL;
@@ -1471,7 +1538,6 @@ void ray_ao_qmc(ShadeInput *shi, float *shadfac)
float fac=0.0f, prev=0.0f;
float adapt_thresh = G.scene->world->ao_adapt_thresh;
float adapt_speed_fac = G.scene->world->ao_adapt_speed_fac;
- float bias = G.scene->world->aobias;
int samples=0;
int max_samples = R.wrld.aosamp*R.wrld.aosamp;
@@ -1485,7 +1551,6 @@ void ray_ao_qmc(ShadeInput *shi, float *shadfac)
isec.ob_last= 0;
isec.mode= (R.wrld.aomode & WO_AODIST)?RE_RAY_SHADOW_TRA:RE_RAY_SHADOW;
isec.lay= -1;
- VECCOPY(isec.start, shi->co);
shadfac[0]= shadfac[1]= shadfac[2]= 0.0f;
@@ -1500,13 +1565,10 @@ void ray_ao_qmc(ShadeInput *shi, float *shadfac)
dxyview[2]= 0.0f;
}
- /* bias prevents smoothed faces to appear flat */
if(shi->vlr->flag & R_SMOOTH) {
- bias= G.scene->world->aobias;
VECCOPY(nrm, shi->vn);
}
else {
- bias= 0.0f;
VECCOPY(nrm, shi->facenor);
}
@@ -1521,9 +1583,9 @@ void ray_ao_qmc(ShadeInput *shi, float *shadfac)
max_samples /= speedfac;
if (max_samples < 5) max_samples = 5;
- qsa = QMC_initSampler(SAMP_TYPE_HALTON, max_samples);
+ qsa = get_thread_qmcsampler(&R, shi->thread, SAMP_TYPE_HALTON, max_samples);
} else if (R.wrld.ao_samp_method==WO_AOSAMP_HAMMERSLEY)
- qsa = R.qsa;
+ qsa = get_thread_qmcsampler(&R, shi->thread, SAMP_TYPE_HAMMERSLEY, max_samples);
QMC_initPixel(qsa, shi->thread);
@@ -1538,6 +1600,7 @@ void ray_ao_qmc(ShadeInput *shi, float *shadfac)
Normalize(dir);
+ VECCOPY(isec.start, shi->co);
isec.end[0] = shi->co[0] - maxdist*dir[0];
isec.end[1] = shi->co[1] - maxdist*dir[1];
isec.end[2] = shi->co[2] - maxdist*dir[2];
@@ -1565,6 +1628,7 @@ void ray_ao_qmc(ShadeInput *shi, float *shadfac)
}
else { /* WO_AOSKYTEX */
shadeSkyView(skycol, isec.start, view, dxyview);
+ shadeSunView(skycol, shi->view);
shadfac[0]+= skycol[0];
shadfac[1]+= skycol[1];
shadfac[2]+= skycol[2];
@@ -1595,17 +1659,18 @@ void ray_ao_qmc(ShadeInput *shi, float *shadfac)
shadfac[0]= shadfac[1]= shadfac[2]= 1.0f - fac/(float)samples;
}
- if ((qsa) && (qsa->type == SAMP_TYPE_HALTON)) QMC_freeSampler(qsa);
+ if (qsa)
+ release_thread_qmcsampler(&R, shi->thread, qsa);
}
/* extern call from shade_lamp_loop, ambient occlusion calculus */
-void ray_ao_spheresamp(ShadeInput *shi, float *shadfac)
+static void ray_ao_spheresamp(ShadeInput *shi, float *shadfac)
{
Isect isec;
float *vec, *nrm, div, bias, sh=0.0f;
float maxdist = R.wrld.aodist;
float dxyview[3];
- int j= -1, tot, actual=0, skyadded=0, aocolor;
+ int j= -1, tot, actual=0, skyadded=0, aocolor, resol= R.wrld.aosamp;
isec.faceorig= (RayFace*)shi->vlr;
isec.oborig= RAY_OBJECT_SET(&R, shi->obi);
@@ -1632,14 +1697,16 @@ void ray_ao_spheresamp(ShadeInput *shi, float *shadfac)
if(shi->mat->mode & MA_ONLYSHADOW)
aocolor= WO_AOPLAIN;
- vec= sphere_sampler(R.wrld.aomode, R.wrld.aosamp, shi->thread, shi->xs, shi->ys);
+ if(resol>32) resol= 32;
+
+ vec= sphere_sampler(R.wrld.aomode, resol, shi->thread, shi->xs, shi->ys);
// warning: since we use full sphere now, and dotproduct is below, we do twice as much
- tot= 2*R.wrld.aosamp*R.wrld.aosamp;
+ tot= 2*resol*resol;
if(aocolor == WO_AOSKYTEX) {
- dxyview[0]= 1.0f/(float)R.wrld.aosamp;
- dxyview[1]= 1.0f/(float)R.wrld.aosamp;
+ dxyview[0]= 1.0f/(float)resol;
+ dxyview[1]= 1.0f/(float)resol;
dxyview[2]= 0.0f;
}
@@ -1686,6 +1753,7 @@ void ray_ao_spheresamp(ShadeInput *shi, float *shadfac)
}
else { /* WO_AOSKYTEX */
shadeSkyView(skycol, isec.start, view, dxyview);
+ shadeSunView(skycol, shi->view);
shadfac[0]+= skycol[0];
shadfac[1]+= skycol[1];
shadfac[2]+= skycol[2];
@@ -1724,21 +1792,62 @@ void ray_ao(ShadeInput *shi, float *shadfac)
ray_ao_spheresamp(shi, shadfac);
}
+static void ray_shadow_jittered_coords(ShadeInput *shi, int max, float jitco[RE_MAX_OSA][3], int *totjitco)
+{
+ /* magic numbers for reordering sample positions to give better
+ * results with adaptive sample, when it usually only takes 4 samples */
+ int order8[8] = {0, 1, 5, 6, 2, 3, 4, 7};
+ int order11[11] = {1, 3, 8, 10, 0, 2, 4, 5, 6, 7, 9};
+ int order16[16] = {1, 3, 9, 12, 0, 6, 7, 8, 13, 2, 4, 5, 10, 11, 14, 15};
+ int count = count_mask(shi->mask);
+
+ /* for better antialising shadow samples are distributed over the subpixel
+ * sample coordinates, this only works for raytracing depth 0 though */
+ if(!shi->strand && shi->depth == 0 && count > 1 && count <= max) {
+ float xs, ys, zs, view[3];
+ int samp, ordsamp, tot= 0;
+
+ for(samp=0; samp<R.osa; samp++) {
+ if(R.osa == 8) ordsamp = order8[samp];
+ else if(R.osa == 11) ordsamp = order11[samp];
+ else if(R.osa == 16) ordsamp = order16[samp];
+ else ordsamp = samp;
+
+ if(shi->mask & (1<<ordsamp)) {
+ /* zbuffer has this inverse corrected, ensures xs,ys are inside pixel */
+ xs= (float)shi->scanco[0] + R.jit[ordsamp][0] + 0.5f;
+ ys= (float)shi->scanco[1] + R.jit[ordsamp][1] + 0.5f;
+ zs= shi->scanco[2];
+
+ shade_input_calc_viewco(shi, xs, ys, zs, view, NULL, jitco[tot], NULL, NULL);
+ tot++;
+ }
+ }
+
+ *totjitco= tot;
+ }
+ else {
+ VECCOPY(jitco[0], shi->co);
+ *totjitco= 1;
+ }
+}
static void ray_shadow_qmc(ShadeInput *shi, LampRen *lar, float *lampco, float *shadfac, Isect *isec)
{
QMCSampler *qsa=NULL;
- QMCSampler *qsa_jit=NULL;
int samples=0;
- float samp3d[3], jit[3];
+ float samp3d[3];
float fac=0.0f, vec[3];
float colsq[4];
float adapt_thresh = lar->adapt_thresh;
- int max_samples = lar->ray_totsamp;
- float pos[3];
+ int min_adapt_samples=4, max_samples = lar->ray_totsamp;
+ float *co;
int do_soft=1, full_osa=0;
+ float jitco[RE_MAX_OSA][3];
+ int totjitco;
+
colsq[0] = colsq[1] = colsq[2] = 0.0;
if(isec->mode==RE_RAY_SHADOW_TRA) {
shadfac[0]= shadfac[1]= shadfac[2]= shadfac[3]= 0.0f;
@@ -1756,17 +1865,15 @@ static void ray_shadow_qmc(ShadeInput *shi, LampRen *lar, float *lampco, float *
else max_samples = (R.osa > 4)?R.osa:5;
}
+ ray_shadow_jittered_coords(shi, max_samples, jitco, &totjitco);
+
/* sampling init */
- if (lar->ray_samp_method==LA_SAMP_HALTON) {
- qsa = QMC_initSampler(SAMP_TYPE_HALTON, max_samples);
- qsa_jit = QMC_initSampler(SAMP_TYPE_HALTON, max_samples);
- } else if (lar->ray_samp_method==LA_SAMP_HAMMERSLEY) {
- qsa = lar->qsa;
- qsa_jit = QMC_initSampler(SAMP_TYPE_HAMMERSLEY, max_samples);
- }
+ if (lar->ray_samp_method==LA_SAMP_HALTON)
+ qsa = get_thread_qmcsampler(&R, shi->thread, SAMP_TYPE_HALTON, max_samples);
+ else if (lar->ray_samp_method==LA_SAMP_HAMMERSLEY)
+ qsa = get_thread_qmcsampler(&R, shi->thread, SAMP_TYPE_HAMMERSLEY, max_samples);
QMC_initPixel(qsa, shi->thread);
- QMC_initPixel(qsa_jit, shi->thread);
VECCOPY(vec, lampco);
@@ -1774,18 +1881,11 @@ static void ray_shadow_qmc(ShadeInput *shi, LampRen *lar, float *lampco, float *
while (samples < max_samples) {
isec->faceorig= (RayFace*)shi->vlr;
isec->oborig= RAY_OBJECT_SET(&R, shi->obi);
-
+
/* manually jitter the start shading co-ord per sample
* based on the pre-generated OSA texture sampling offsets,
* for anti-aliasing sharp shadow edges. */
- VECCOPY(pos, shi->co);
- if (shi->vlr && !full_osa) {
- QMC_sampleRect(jit, qsa_jit, shi->thread, samples, 1.0, 1.0);
-
- pos[0] += shi->dxco[0]*jit[0] + shi->dyco[0]*jit[1];
- pos[1] += shi->dxco[1]*jit[0] + shi->dyco[1]*jit[1];
- pos[2] += shi->dxco[2]*jit[0] + shi->dyco[2]*jit[1];
- }
+ co = jitco[samples % totjitco];
if (do_soft) {
/* sphere shadow source */
@@ -1793,9 +1893,9 @@ static void ray_shadow_qmc(ShadeInput *shi, LampRen *lar, float *lampco, float *
float ru[3], rv[3], v[3], s[3];
/* calc tangent plane vectors */
- v[0] = pos[0] - lampco[0];
- v[1] = pos[1] - lampco[1];
- v[2] = pos[2] - lampco[2];
+ v[0] = co[0] - lampco[0];
+ v[1] = co[1] - lampco[1];
+ v[2] = co[2] - lampco[2];
Normalize(v);
VecOrthoBasisf(v, ru, rv);
@@ -1822,8 +1922,21 @@ static void ray_shadow_qmc(ShadeInput *shi, LampRen *lar, float *lampco, float *
} else {
VECCOPY(isec->end, vec);
}
- VECCOPY(isec->start, pos);
-
+
+ if(shi->strand) {
+ /* bias away somewhat to avoid self intersection */
+ float jitbias= 0.5f*(VecLength(shi->dxco) + VecLength(shi->dyco));
+ float v[3];
+
+ VECSUB(v, co, isec->end);
+ Normalize(v);
+
+ co[0] -= jitbias*v[0];
+ co[1] -= jitbias*v[1];
+ co[2] -= jitbias*v[2];
+ }
+
+ VECCOPY(isec->start, co);
/* trace the ray */
if(isec->mode==RE_RAY_SHADOW_TRA) {
@@ -1850,7 +1963,7 @@ static void ray_shadow_qmc(ShadeInput *shi, LampRen *lar, float *lampco, float *
if ((lar->ray_samp_method == LA_SAMP_HALTON)) {
/* adaptive sampling - consider samples below threshold as in shadow (or vice versa) and exit early */
- if ((max_samples > 4) && (adapt_thresh > 0.0) && (samples > max_samples / 3)) {
+ if ((max_samples > min_adapt_samples) && (adapt_thresh > 0.0) && (samples > max_samples / 3)) {
if (isec->mode==RE_RAY_SHADOW_TRA) {
if ((shadfac[3] / samples > (1.0-adapt_thresh)) || (shadfac[3] / samples < adapt_thresh))
break;
@@ -1872,8 +1985,8 @@ static void ray_shadow_qmc(ShadeInput *shi, LampRen *lar, float *lampco, float *
} else
shadfac[3]= 1.0f-fac/samples;
- if (qsa_jit) QMC_freeSampler(qsa_jit);
- if ((qsa) && (qsa->type == SAMP_TYPE_HALTON)) QMC_freeSampler(qsa);
+ if (qsa)
+ release_thread_qmcsampler(&R, shi->thread, qsa);
}
static void ray_shadow_jitter(ShadeInput *shi, LampRen *lar, float *lampco, float *shadfac, Isect *isec)
@@ -1964,7 +2077,10 @@ void ray_shadow(ShadeInput *shi, LampRen *lar, float *shadfac)
if(shi->mat->mode & MA_SHADOW_TRA) isec.mode= RE_RAY_SHADOW_TRA;
else isec.mode= RE_RAY_SHADOW;
- if(lar->mode & LA_LAYER) isec.lay= lar->lay; else isec.lay= -1;
+ if(lar->mode & (LA_LAYER|LA_LAYER_SHADOW))
+ isec.lay= lar->lay;
+ else
+ isec.lay= -1;
/* only when not mir tracing, first hit optimm */
if(shi->depth==0) {
@@ -2025,7 +2141,7 @@ void ray_shadow(ShadeInput *shi, LampRen *lar, float *shadfac)
}
/* only when face points away from lamp, in direction of lamp, trace ray and find first exit point */
-void ray_translucent(ShadeInput *shi, LampRen *lar, float *distfac, float *co)
+static void ray_translucent(ShadeInput *shi, LampRen *lar, float *distfac, float *co)
{
Isect isec;
float lampco[3], maxsize;
diff --git a/source/blender/render/intern/source/raytrace.c b/source/blender/render/intern/source/raytrace.c
index 54e8e4cfab5..ec47df74d04 100644
--- a/source/blender/render/intern/source/raytrace.c
+++ b/source/blender/render/intern/source/raytrace.c
@@ -635,6 +635,8 @@ void RE_ray_tree_done(RayTree *tree)
/* ************ raytracer **************** */
+#define ISECT_EPSILON ((float)FLT_EPSILON)
+
/* only for self-intersecting test with current render face (where ray left) */
static int intersection2(RayFace *face, int ob, RayObjectTransformFunc transformfunc, RayCoordsFunc coordsfunc, void *userdata, float r0, float r1, float r2, float rx1, float ry1, float rz1)
{
@@ -692,13 +694,13 @@ static int intersection2(RayFace *face, int ob, RayObjectTransformFunc transform
if(divdet!=0.0f) {
u1= det1/divdet;
- if(u1<=0.0f) {
+ if(u1<ISECT_EPSILON) {
det= t00*(m1*r2-m2*r1);
det+= t01*(m2*r0-m0*r2);
det+= t02*(m0*r1-m1*r0);
v= det/divdet;
- if(v<=0.0f && (u1 + v) >= -1.0f) {
+ if(v<ISECT_EPSILON && (u1 + v) > -(1.0f+ISECT_EPSILON)) {
return 1;
}
}
@@ -714,13 +716,13 @@ static int intersection2(RayFace *face, int ob, RayObjectTransformFunc transform
if(divdet!=0.0f) {
u2= det1/divdet;
- if(u2<=0.0f) {
+ if(u2<ISECT_EPSILON) {
det= t20*(m1*r2-m2*r1);
det+= t21*(m2*r0-m0*r2);
det+= t22*(m0*r1-m1*r0);
v= det/divdet;
- if(v<=0.0f && (u2 + v) >= -1.0f) {
+ if(v<ISECT_EPSILON && (u2 + v) >= -(1.0f+ISECT_EPSILON)) {
return 2;
}
}
@@ -860,7 +862,7 @@ int RE_ray_face_intersection(Isect *is, RayObjectTransformFunc transformfunc, Ra
divdet= 1.0f/divdet;
u= det1*divdet;
- if(u<0.0f && u>-1.0f) {
+ if(u<ISECT_EPSILON && u>-(1.0f+ISECT_EPSILON)) {
float v, cros0, cros1, cros2;
cros0= m1*t02-m2*t01;
@@ -868,11 +870,11 @@ int RE_ray_face_intersection(Isect *is, RayObjectTransformFunc transformfunc, Ra
cros2= m0*t01-m1*t00;
v= divdet*(cros0*r0 + cros1*r1 + cros2*r2);
- if(v<0.0f && (u + v) > -1.0f) {
+ if(v<ISECT_EPSILON && (u + v) > -(1.0f+ISECT_EPSILON)) {
float labda;
labda= divdet*(cros0*t10 + cros1*t11 + cros2*t12);
- if(labda>0.0f && labda<1.0f) {
+ if(labda>-ISECT_EPSILON && labda<1.0f+ISECT_EPSILON) {
is->labda= labda;
is->u= u; is->v= v;
ok= 1;
@@ -893,18 +895,18 @@ int RE_ray_face_intersection(Isect *is, RayObjectTransformFunc transformfunc, Ra
divdet= 1.0f/divdet;
u = det1*divdet;
- if(u<0.0f && u>-1.0f) {
+ if(u<ISECT_EPSILON && u>-(1.0f+ISECT_EPSILON)) {
float v, cros0, cros1, cros2;
cros0= m1*t22-m2*t21;
cros1= m2*t20-m0*t22;
cros2= m0*t21-m1*t20;
v= divdet*(cros0*r0 + cros1*r1 + cros2*r2);
- if(v<0.0f && (u + v) > -1.0f) {
+ if(v<ISECT_EPSILON && (u + v) >-(1.0f+ISECT_EPSILON)) {
float labda;
labda= divdet*(cros0*t10 + cros1*t11 + cros2*t12);
- if(labda>0.0f && labda<1.0f) {
+ if(labda>-ISECT_EPSILON && labda<1.0f+ISECT_EPSILON) {
ok= 2;
is->labda= labda;
is->u= u; is->v= v;
@@ -983,7 +985,7 @@ static int testnode(Octree *oc, Isect *is, Node *no, OcVal ocval, RayCheckFunc c
if(!(is->faceorig == face && is->oborig == ob)) {
- if(checkfunc(is, face)) {
+ if(checkfunc(is, ob, face)) {
ov= no->ov+nr;
if( (ov->ocx & ocval.ocx) && (ov->ocy & ocval.ocy) && (ov->ocz & ocval.ocz) ) {
@@ -1023,7 +1025,7 @@ static int testnode(Octree *oc, Isect *is, Node *no, OcVal ocval, RayCheckFunc c
while(face) {
if(!(is->faceorig == face && is->oborig == ob)) {
- if(checkfunc(is, face)) {
+ if(checkfunc(is, ob, face)) {
ov= no->ov+nr;
if( (ov->ocx & ocval.ocx) && (ov->ocy & ocval.ocy) && (ov->ocz & ocval.ocz) ) {
//accepted++;
@@ -1031,8 +1033,11 @@ static int testnode(Octree *oc, Isect *is, Node *no, OcVal ocval, RayCheckFunc c
isect.ob= ob;
isect.face= face;
if(RE_ray_face_intersection(&isect, oc->transformfunc, oc->coordsfunc)) {
- if(isect.labda<is->labda) *is= isect;
- found= 1;
+ if(isect.labda<is->labda) {
+ *is= isect;
+ found= 1;
+ }
+
}
}
//else rejected++;
@@ -1205,7 +1210,7 @@ int RE_ray_tree_intersect_check(RayTree *tree, Isect *is, RayCheckFunc checkfunc
/* check with last intersected shadow face */
if(is->face_last!=NULL && !(is->face_last==is->faceorig && is->ob_last==is->oborig)) {
- if(checkfunc(is, is->face_last)) {
+ if(checkfunc(is, is->ob_last, is->face_last)) {
is->ob= is->ob_last;
is->face= is->face_last;
VECSUB(is->vec, is->end, is->start);
diff --git a/source/blender/render/intern/source/rendercore.c b/source/blender/render/intern/source/rendercore.c
index 0a9078b32f0..1eb42bca569 100644
--- a/source/blender/render/intern/source/rendercore.c
+++ b/source/blender/render/intern/source/rendercore.c
@@ -29,6 +29,7 @@
/* system includes */
#include <stdio.h>
#include <math.h>
+#include <float.h>
#include <string.h>
/* External modules: */
@@ -46,6 +47,7 @@
#include "DNA_lamp_types.h"
#include "DNA_material_types.h"
#include "DNA_meshdata_types.h"
+#include "DNA_group_types.h"
#include "BKE_global.h"
#include "BKE_image.h"
@@ -60,6 +62,7 @@
#include "renderpipeline.h"
#include "render_types.h"
#include "renderdatabase.h"
+#include "occlusion.h"
#include "pixelblending.h"
#include "pixelshading.h"
#include "shadbuf.h"
@@ -155,7 +158,7 @@ static int calchalo_z(HaloRen *har, int zz)
{
if(har->type & HA_ONLYSKY) {
- if(zz!=0x7FFFFFFF) zz= - 0x7FFFFF;
+ if(zz < 0x7FFFFFF0) zz= - 0x7FFFFF; /* edge render messes zvalues */
}
else {
zz= (zz>>8);
@@ -163,11 +166,14 @@ static int calchalo_z(HaloRen *har, int zz)
return zz;
}
-static void halo_pixelstruct(HaloRen *har, float *rb, float dist, float xn, float yn, PixStr *ps)
+
+
+static void halo_pixelstruct(HaloRen *har, RenderLayer **rlpp, int totsample, int od, float dist, float xn, float yn, PixStr *ps)
{
- float col[4], accol[4];
- int amount, amountm, zz, flarec;
+ float col[4], accol[4], fac;
+ int amount, amountm, zz, flarec, sample, fullsample, mask=0;
+ fullsample= (totsample > 1);
amount= 0;
accol[0]=accol[1]=accol[2]=accol[3]= 0.0f;
flarec= har->flarec;
@@ -177,50 +183,70 @@ static void halo_pixelstruct(HaloRen *har, float *rb, float dist, float xn, floa
amount+= amountm;
zz= calchalo_z(har, ps->z);
- if(zz> har->zs) {
- float fac;
-
- shadeHaloFloat(har, col, zz, dist, xn, yn, flarec);
- fac= ((float)amountm)/(float)R.osa;
- accol[0]+= fac*col[0];
- accol[1]+= fac*col[1];
- accol[2]+= fac*col[2];
- accol[3]+= fac*col[3];
- flarec= 0;
+ if((zz> har->zs) || (har->mat && (har->mat->mode & MA_HALO_SOFT))) {
+ if(shadeHaloFloat(har, col, zz, dist, xn, yn, flarec)) {
+ flarec= 0;
+
+ if(fullsample) {
+ for(sample=0; sample<totsample; sample++)
+ if(ps->mask & (1 << sample))
+ addalphaAddfacFloat(rlpp[sample]->rectf + od*4, col, har->add);
+ }
+ else {
+ fac= ((float)amountm)/(float)R.osa;
+ accol[0]+= fac*col[0];
+ accol[1]+= fac*col[1];
+ accol[2]+= fac*col[2];
+ accol[3]+= fac*col[3];
+ }
+ }
}
+ mask |= ps->mask;
ps= ps->next;
}
+
/* now do the sky sub-pixels */
amount= R.osa-amount;
if(amount) {
- float fac;
+ if(shadeHaloFloat(har, col, 0x7FFFFF, dist, xn, yn, flarec)) {
+ if(!fullsample) {
+ fac= ((float)amount)/(float)R.osa;
+ accol[0]+= fac*col[0];
+ accol[1]+= fac*col[1];
+ accol[2]+= fac*col[2];
+ accol[3]+= fac*col[3];
+ }
+ }
+ }
- shadeHaloFloat(har, col, 0x7FFFFF, dist, xn, yn, flarec);
- fac= ((float)amount)/(float)R.osa;
- accol[0]+= fac*col[0];
- accol[1]+= fac*col[1];
- accol[2]+= fac*col[2];
- accol[3]+= fac*col[3];
+ if(fullsample) {
+ for(sample=0; sample<totsample; sample++)
+ if(!(mask & (1 << sample)))
+ addalphaAddfacFloat(rlpp[sample]->rectf + od*4, col, har->add);
+ }
+ else {
+ col[0]= accol[0];
+ col[1]= accol[1];
+ col[2]= accol[2];
+ col[3]= accol[3];
+
+ for(sample=0; sample<totsample; sample++)
+ addalphaAddfacFloat(rlpp[sample]->rectf + od*4, col, har->add);
}
- col[0]= accol[0];
- col[1]= accol[1];
- col[2]= accol[2];
- col[3]= accol[3];
-
- addalphaAddfacFloat(rb, col, har->add);
-
}
-static void halo_tile(RenderPart *pa, float *pass, unsigned int lay)
+static void halo_tile(RenderPart *pa, RenderLayer *rl)
{
+ RenderLayer *rlpp[RE_MAX_OSA];
HaloRen *har;
rcti disprect= pa->disprect, testrect= pa->disprect;
- float dist, xsq, ysq, xn, yn, *rb;
+ float dist, xsq, ysq, xn, yn;
float col[4];
- long *rd= NULL;
- int a, *rz, zz, y;
+ intptr_t *rd= NULL;
+ int a, *rz, zz, y, sample, totsample, od;
short minx, maxx, miny, maxy, x;
+ unsigned int lay= rl->lay;
/* we don't render halos in the cropped area, gives errors in flare counter */
if(pa->crop) {
@@ -230,6 +256,8 @@ static void halo_tile(RenderPart *pa, float *pass, unsigned int lay)
testrect.ymax-= pa->crop;
}
+ totsample= get_sample_layers(pa, rl, rlpp);
+
for(a=0; a<R.tothalo; a++) {
har= R.sortedhalos[a];
@@ -254,8 +282,8 @@ static void halo_tile(RenderPart *pa, float *pass, unsigned int lay)
for(y=miny; y<maxy; y++) {
int rectofs= (y-disprect.ymin)*pa->rectx + (minx - disprect.xmin);
- rb= pass + 4*rectofs;
rz= pa->rectz + rectofs;
+ od= rectofs;
if(pa->rectdaps)
rd= pa->rectdaps + rectofs;
@@ -263,19 +291,21 @@ static void halo_tile(RenderPart *pa, float *pass, unsigned int lay)
yn= (y-har->ys)*R.ycor;
ysq= yn*yn;
- for(x=minx; x<maxx; x++, rb+=4, rz++) {
+ for(x=minx; x<maxx; x++, rz++, od++) {
xn= x- har->xs;
xsq= xn*xn;
dist= xsq+ysq;
if(dist<har->radsq) {
if(rd && *rd) {
- halo_pixelstruct(har, rb, dist, xn, yn, (PixStr *)*rd);
+ halo_pixelstruct(har, rlpp, totsample, od, dist, xn, yn, (PixStr *)*rd);
}
else {
zz= calchalo_z(har, *rz);
- if(zz> har->zs) {
- shadeHaloFloat(har, col, zz, dist, xn, yn, har->flarec);
- addalphaAddfacFloat(rb, col, har->add);
+ if((zz> har->zs) || (har->mat && (har->mat->mode & MA_HALO_SOFT))) {
+ if(shadeHaloFloat(har, col, zz, dist, xn, yn, har->flarec)) {
+ for(sample=0; sample<totsample; sample++)
+ addalphaAddfacFloat(rlpp[sample]->rectf + od*4, col, har->add);
+ }
}
}
}
@@ -290,22 +320,27 @@ static void halo_tile(RenderPart *pa, float *pass, unsigned int lay)
static void lamphalo_tile(RenderPart *pa, RenderLayer *rl)
{
+ RenderLayer *rlpp[RE_MAX_OSA];
ShadeInput shi;
- float *pass= rl->rectf;
- float fac;
- long *rd= pa->rectdaps;
- int x, y, *rz= pa->rectz;
+ float *pass;
+ float fac, col[4];
+ intptr_t *rd= pa->rectdaps;
+ int *rz= pa->rectz;
+ int x, y, sample, totsample, fullsample, od;
- shade_input_initialize(&shi, pa, rl, 0);
+ totsample= get_sample_layers(pa, rl, rlpp);
+ fullsample= (totsample > 1);
+
+ shade_input_initialize(&shi, pa, rl, 0); /* this zero's ShadeInput for us */
- for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++) {
- for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, rz++, pass+=4) {
+ for(od=0, y=pa->disprect.ymin; y<pa->disprect.ymax; y++) {
+ for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, rz++, od++) {
calc_view_vector(shi.view, x, y);
if(rd && *rd) {
PixStr *ps= (PixStr *)*rd;
- int samp, totsamp= 0;
+ int count, totsamp= 0, mask= 0;
while(ps) {
if(R.r.mode & R_ORTHO)
@@ -313,15 +348,64 @@ static void lamphalo_tile(RenderPart *pa, RenderLayer *rl)
else
calc_renderco_zbuf(shi.co, shi.view, ps->z);
- totsamp+= samp= count_mask(ps->mask);
- fac= ((float)samp)/(float)R.osa;
- renderspothalo(&shi, pass, fac);
+ totsamp+= count= count_mask(ps->mask);
+ mask |= ps->mask;
+
+ col[0]= col[1]= col[2]= col[3]= 0.0f;
+ renderspothalo(&shi, col, 1.0f);
+
+ if(fullsample) {
+ for(sample=0; sample<totsample; sample++) {
+ if(ps->mask & (1 << sample)) {
+ pass= rlpp[sample]->rectf + od*4;
+ pass[0]+= col[0];
+ pass[1]+= col[1];
+ pass[2]+= col[2];
+ pass[3]+= col[3];
+ if(pass[3]>1.0f) pass[3]= 1.0f;
+ }
+ }
+ }
+ else {
+ fac= ((float)count)/(float)R.osa;
+ pass= rl->rectf + od*4;
+ pass[0]+= fac*col[0];
+ pass[1]+= fac*col[1];
+ pass[2]+= fac*col[2];
+ pass[3]+= fac*col[3];
+ if(pass[3]>1.0f) pass[3]= 1.0f;
+ }
+
ps= ps->next;
}
+
if(totsamp<R.osa) {
- fac= ((float)R.osa-totsamp)/(float)R.osa;
shi.co[2]= 0.0f;
- renderspothalo(&shi, pass, fac);
+
+ col[0]= col[1]= col[2]= col[3]= 0.0f;
+ renderspothalo(&shi, col, 1.0f);
+
+ if(fullsample) {
+ for(sample=0; sample<totsample; sample++) {
+ if(!(mask & (1 << sample))) {
+ pass= rlpp[sample]->rectf + od*4;
+ pass[0]+= col[0];
+ pass[1]+= col[1];
+ pass[2]+= col[2];
+ pass[3]+= col[3];
+ if(pass[3]>1.0f) pass[3]= 1.0f;
+ }
+ }
+ }
+ else {
+ fac= ((float)R.osa-totsamp)/(float)R.osa;
+ pass= rl->rectf + od*4;
+ pass[0]+= fac*col[0];
+ pass[1]+= fac*col[1];
+ pass[2]+= fac*col[2];
+ pass[3]+= fac*col[3];
+ if(pass[3]>1.0f) pass[3]= 1.0f;
+ }
}
}
else {
@@ -330,7 +414,17 @@ static void lamphalo_tile(RenderPart *pa, RenderLayer *rl)
else
calc_renderco_zbuf(shi.co, shi.view, *rz);
- renderspothalo(&shi, pass, 1.0f);
+ col[0]= col[1]= col[2]= col[3]= 0.0f;
+ renderspothalo(&shi, col, 1.0f);
+
+ for(sample=0; sample<totsample; sample++) {
+ pass= rlpp[sample]->rectf + od*4;
+ pass[0]+= col[0];
+ pass[1]+= col[1];
+ pass[2]+= col[2];
+ pass[3]+= col[3];
+ if(pass[3]>1.0f) pass[3]= 1.0f;
+ }
}
if(rd) rd++;
@@ -347,12 +441,19 @@ static void lamphalo_tile(RenderPart *pa, RenderLayer *rl)
static void add_filt_passes(RenderLayer *rl, int curmask, int rectx, int offset, ShadeInput *shi, ShadeResult *shr)
{
RenderPass *rpass;
+
+ /* combined rgb */
+ add_filt_fmask(curmask, shr->combined, rl->rectf + 4*offset, rectx);
for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
float *fp, *col= NULL;
int pixsize= 3;
switch(rpass->passtype) {
+ case SCE_PASS_Z:
+ fp= rpass->rect + offset;
+ *fp= shr->z;
+ break;
case SCE_PASS_RGBA:
col= shr->col;
pixsize= 4;
@@ -399,6 +500,12 @@ static void add_filt_passes(RenderLayer *rl, int curmask, int rectx, int offset,
*fp= (float)shi->obr->ob->index;
}
break;
+ case SCE_PASS_MIST:
+ /* */
+ col= &shr->mist;
+ pixsize= 1;
+ break;
+
case SCE_PASS_VECTOR:
{
/* add minimum speed in pixel, no filter */
@@ -425,12 +532,20 @@ static void add_filt_passes(RenderLayer *rl, int curmask, int rectx, int offset,
static void add_passes(RenderLayer *rl, int offset, ShadeInput *shi, ShadeResult *shr)
{
RenderPass *rpass;
+ float *fp;
+
+ fp= rl->rectf + 4*offset;
+ QUATCOPY(fp, shr->combined);
for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
- float *fp, *col= NULL, uvcol[3];
+ float *col= NULL, uvcol[3];
int a, pixsize= 3;
switch(rpass->passtype) {
+ case SCE_PASS_Z:
+ fp= rpass->rect + offset;
+ *fp= shr->z;
+ break;
case SCE_PASS_RGBA:
col= shr->col;
pixsize= 4;
@@ -477,6 +592,10 @@ static void add_passes(RenderLayer *rl, int offset, ShadeInput *shi, ShadeResult
*fp= (float)shi->obr->ob->index;
}
break;
+ case SCE_PASS_MIST:
+ fp= rpass->rect + offset;
+ *fp= shr->mist;
+ break;
}
if(col) {
fp= rpass->rect + pixsize*offset;
@@ -486,26 +605,60 @@ static void add_passes(RenderLayer *rl, int offset, ShadeInput *shi, ShadeResult
}
}
+int get_sample_layers(RenderPart *pa, RenderLayer *rl, RenderLayer **rlpp)
+{
+
+ if(pa->fullresult.first) {
+ int sample, nr= BLI_findindex(&pa->result->layers, rl);
+
+ for(sample=0; sample<R.osa; sample++) {
+ RenderResult *rr= BLI_findlink(&pa->fullresult, sample);
+
+ rlpp[sample]= BLI_findlink(&rr->layers, nr);
+ }
+ return R.osa;
+ }
+ else {
+ rlpp[0]= rl;
+ return 1;
+ }
+}
+
+
/* only do sky, is default in the solid layer (shade_tile) btw */
-static void sky_tile(RenderPart *pa, float *pass)
+static void sky_tile(RenderPart *pa, RenderLayer *rl)
{
- float col[4];
- int x, y;
+ RenderLayer *rlpp[RE_MAX_OSA];
+ int x, y, od=0, totsample;
if(R.r.alphamode!=R_ADDSKY)
return;
+ totsample= get_sample_layers(pa, rl, rlpp);
+
for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++) {
- for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, pass+=4) {
- if(pass[3]<1.0f) {
- if(pass[3]==0.0f)
- shadeSkyPixel(pass, x, y);
- else {
- shadeSkyPixel(col, x, y);
- addAlphaOverFloat(col, pass);
- QUATCOPY(pass, col);
+ for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, od+=4) {
+ float col[4];
+ int sample, done= 0;
+
+ for(sample= 0; sample<totsample; sample++) {
+ float *pass= rlpp[sample]->rectf + od;
+
+ if(pass[3]<1.0f) {
+
+ if(done==0) {
+ shadeSkyPixel(col, x, y);
+ done= 1;
+ }
+
+ if(pass[3]==0.0f) {
+ QUATCOPY(pass, col);
+ }
+ else {
+ addAlphaUnderFloat(pass, col);
+ }
}
- }
+ }
}
if(y&1)
@@ -513,14 +666,99 @@ static void sky_tile(RenderPart *pa, float *pass)
}
}
+static void atm_tile(RenderPart *pa, RenderLayer *rl)
+{
+ RenderPass *zpass;
+ GroupObject *go;
+ LampRen *lar;
+ RenderLayer *rlpp[RE_MAX_OSA];
+ int totsample;
+ int x, y, od= 0;
+
+ totsample= get_sample_layers(pa, rl, rlpp);
+
+ /* check that z pass is enabled */
+ if(pa->rectz==NULL) return;
+ for(zpass= rl->passes.first; zpass; zpass= zpass->next)
+ if(zpass->passtype==SCE_PASS_Z)
+ break;
+
+ if(zpass==NULL) return;
+
+ /* check for at least one sun lamp that its atmosphere flag is is enabled */
+ for(go=R.lights.first; go; go= go->next) {
+ lar= go->lampren;
+ if(lar->type==LA_SUN && lar->sunsky && (lar->sunsky->effect_type & LA_SUN_EFFECT_AP))
+ break;
+ }
+ /* do nothign and return if there is no sun lamp */
+ if(go==NULL)
+ return;
+
+ /* for each x,y and each sample, and each sun lamp*/
+ for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++) {
+ for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, od++) {
+ int sample;
+
+ for(sample=0; sample<totsample; sample++) {
+ float *zrect= RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_Z) + od;
+ float *rgbrect = rlpp[sample]->rectf + 4*od;
+ float rgb[3];
+ int done= 0;
+
+ for(go=R.lights.first; go; go= go->next) {
+
+
+ lar= go->lampren;
+ if(lar->type==LA_SUN && lar->sunsky) {
+
+ /* if it's sky continue and don't apply atmosphere effect on it */
+ if(*zrect >= 9.9e10 || rgbrect[3]==0.0f) {
+ continue;
+ }
+
+ if((lar->sunsky->effect_type & LA_SUN_EFFECT_AP)) {
+ float tmp_rgb[3];
+
+ VECCOPY(tmp_rgb, rgbrect);
+ if(rgbrect[3]!=1.0f) { /* de-premul */
+ float div= 1.0f/rgbrect[3];
+ VECMUL(tmp_rgb, div);
+ }
+ shadeAtmPixel(lar->sunsky, tmp_rgb, x, y, *zrect);
+ if(rgbrect[3]!=1.0f) { /* premul */
+ VECMUL(tmp_rgb, rgbrect[3]);
+ }
+
+ if(done==0) {
+ VECCOPY(rgb, tmp_rgb);
+ done = 1;
+ }
+ else{
+ rgb[0] = 0.5f*rgb[0] + 0.5f*tmp_rgb[0];
+ rgb[1] = 0.5f*rgb[1] + 0.5f*tmp_rgb[1];
+ rgb[2] = 0.5f*rgb[2] + 0.5f*tmp_rgb[2];
+ }
+ }
+ }
+ }
+
+ /* if at least for one sun lamp aerial perspective was applied*/
+ if(done) {
+ VECCOPY(rgbrect, rgb);
+ }
+ }
+ }
+ }
+}
+
static void shadeDA_tile(RenderPart *pa, RenderLayer *rl)
{
RenderResult *rr= pa->result;
ShadeSample ssamp;
- float *fcol, *rf, *rectf= rl->rectf;
- long *rd, *rectdaps= pa->rectdaps;
+ intptr_t *rd, *rectdaps= pa->rectdaps;
int samp;
- int x, y, seed, crop=0, offs=0, od, addpassflag;
+ int x, y, seed, crop=0, offs=0, od;
if(R.test_break()) return;
@@ -533,12 +771,14 @@ static void shadeDA_tile(RenderPart *pa, RenderLayer *rl)
/* general shader info, passes */
shade_sample_initialize(&ssamp, pa, rl);
- addpassflag= rl->passflag & ~(SCE_PASS_Z|SCE_PASS_COMBINED);
-
+
+ /* occlusion caching */
+ if(R.occlusiontree)
+ cache_occ_samples(&R, pa, &ssamp);
+
/* filtered render, for now we assume only 1 filter size */
if(pa->crop) {
crop= 1;
- rectf+= 4*(pa->rectx + 1);
rectdaps+= pa->rectx + 1;
offs= pa->rectx + 1;
}
@@ -549,28 +789,35 @@ static void shadeDA_tile(RenderPart *pa, RenderLayer *rl)
rr->renlay= rl;
for(y=pa->disprect.ymin+crop; y<pa->disprect.ymax-crop; y++, rr->renrect.ymax++) {
- rf= rectf;
rd= rectdaps;
od= offs;
- for(x=pa->disprect.xmin+crop; x<pa->disprect.xmax-crop; x++, rd++, rf+=4, od++) {
+ for(x=pa->disprect.xmin+crop; x<pa->disprect.xmax-crop; x++, rd++, od++) {
BLI_thread_srandom(pa->thread, seed++);
if(*rd) {
if(shade_samples(&ssamp, (PixStr *)(*rd), x, y)) {
- for(samp=0; samp<ssamp.tot; samp++) {
-
- fcol= ssamp.shr[samp].combined;
- add_filt_fmask(ssamp.shi[samp].mask, fcol, rf, pa->rectx);
-
- if(addpassflag)
+
+ /* multisample buffers or filtered mask filling? */
+ if(pa->fullresult.first) {
+ int a;
+ for(samp=0; samp<ssamp.tot; samp++) {
+ int smask= ssamp.shi[samp].mask;
+ for(a=0; a<R.osa; a++) {
+ int mask= 1<<a;
+ if(smask & mask)
+ add_passes(ssamp.rlpp[a], od, &ssamp.shi[samp], &ssamp.shr[samp]);
+ }
+ }
+ }
+ else {
+ for(samp=0; samp<ssamp.tot; samp++)
add_filt_passes(rl, ssamp.shi[samp].mask, pa->rectx, od, &ssamp.shi[samp], &ssamp.shr[samp]);
}
}
}
}
- rectf+= 4*pa->rectx;
rectdaps+= pa->rectx;
offs+= pa->rectx;
@@ -582,6 +829,9 @@ static void shadeDA_tile(RenderPart *pa, RenderLayer *rl)
if(R.r.mode & R_SHADOW)
ISB_free(pa);
+
+ if(R.occlusiontree)
+ free_occ_samples(&R, pa);
}
/* ************* pixel struct ******** */
@@ -613,7 +863,7 @@ static void freeps(ListBase *lb)
lb->first= lb->last= NULL;
}
-static void addps(ListBase *lb, long *rd, int obi, int facenr, int z, unsigned short mask)
+static void addps(ListBase *lb, intptr_t *rd, int obi, int facenr, int z, int maskz, unsigned short mask)
{
PixStrMain *psm;
PixStr *ps, *last= NULL;
@@ -640,12 +890,13 @@ static void addps(ListBase *lb, long *rd, int obi, int facenr, int z, unsigned s
ps= psm->ps + psm->counter++;
if(last) last->next= ps;
- else *rd= (long)ps;
+ else *rd= (intptr_t)ps;
ps->next= NULL;
ps->obi= obi;
ps->facenr= facenr;
ps->z= z;
+ ps->maskz= maskz;
ps->mask = mask;
ps->shadfac= 0;
}
@@ -669,23 +920,29 @@ static void edge_enhance_add(RenderPart *pa, float *rectf, float *arect)
}
}
-
-static void convert_to_key_alpha(RenderPart *pa, float *rectf)
+static void convert_to_key_alpha(RenderPart *pa, RenderLayer *rl)
{
- int y;
-
- for(y= pa->rectx*pa->recty; y>0; y--, rectf+=4) {
- if(rectf[3] >= 1.0f);
- else if(rectf[3] > 0.0f) {
- rectf[0] /= rectf[3];
- rectf[1] /= rectf[3];
- rectf[2] /= rectf[3];
+ RenderLayer *rlpp[RE_MAX_OSA];
+ int y, sample, totsample;
+
+ totsample= get_sample_layers(pa, rl, rlpp);
+
+ for(sample= 0; sample<totsample; sample++) {
+ float *rectf= rlpp[sample]->rectf;
+
+ for(y= pa->rectx*pa->recty; y>0; y--, rectf+=4) {
+ if(rectf[3] >= 1.0f);
+ else if(rectf[3] > 0.0f) {
+ rectf[0] /= rectf[3];
+ rectf[1] /= rectf[3];
+ rectf[2] /= rectf[3];
+ }
}
}
}
/* adds only alpha values */
-void edge_enhance_tile(RenderPart *pa, float *rectf)
+void edge_enhance_tile(RenderPart *pa, float *rectf, int *rectz)
{
/* use zbuffer to define edges, add it to the image */
int y, x, col, *rz, *rz1, *rz2, *rz3;
@@ -693,13 +950,13 @@ void edge_enhance_tile(RenderPart *pa, float *rectf)
float *rf;
/* shift values in zbuffer 4 to the right (anti overflows), for filter we need multiplying with 12 max */
- rz= pa->rectz;
+ rz= rectz;
if(rz==NULL) return;
for(y=0; y<pa->recty; y++)
for(x=0; x<pa->rectx; x++, rz++) (*rz)>>= 4;
- rz1= pa->rectz;
+ rz1= rectz;
rz2= rz1+pa->rectx;
rz3= rz2+pa->rectx;
@@ -739,7 +996,7 @@ void edge_enhance_tile(RenderPart *pa, float *rectf)
}
/* shift back zbuf values, we might need it still */
- rz= pa->rectz;
+ rz= rectz;
for(y=0; y<pa->recty; y++)
for(x=0; x<pa->rectx; x++, rz++) (*rz)<<= 4;
@@ -748,20 +1005,24 @@ void edge_enhance_tile(RenderPart *pa, float *rectf)
static void reset_sky_speed(RenderPart *pa, RenderLayer *rl)
{
/* for all pixels with max speed, set to zero */
+ RenderLayer *rlpp[RE_MAX_OSA];
float *fp;
- int a;
-
- fp= RE_RenderLayerGetPass(rl, SCE_PASS_VECTOR);
- if(fp==NULL) return;
+ int a, sample, totsample;
- for(a= 4*pa->rectx*pa->recty - 1; a>=0; a--)
- if(fp[a] == PASS_VECTOR_MAX) fp[a]= 0.0f;
-}
+ totsample= get_sample_layers(pa, rl, rlpp);
+ for(sample= 0; sample<totsample; sample++) {
+ fp= RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_VECTOR);
+ if(fp==NULL) break;
+
+ for(a= 4*pa->rectx*pa->recty - 1; a>=0; a--)
+ if(fp[a] == PASS_VECTOR_MAX) fp[a]= 0.0f;
+ }
+}
static unsigned short *make_solid_mask(RenderPart *pa)
{
- long *rd= pa->rectdaps;
+ intptr_t *rd= pa->rectdaps;
unsigned short *solidmask, *sp;
int x;
@@ -826,25 +1087,25 @@ void make_pixelstructs(RenderPart *pa, ZSpan *zspan, int sample, void *data)
{
ZbufSolidData *sdata= (ZbufSolidData*)data;
ListBase *lb= sdata->psmlist;
- long *rd= pa->rectdaps;
+ intptr_t *rd= pa->rectdaps;
int *ro= zspan->recto;
int *rp= zspan->rectp;
int *rz= zspan->rectz;
+ int *rm= zspan->rectmask;
int x, y;
int mask= 1<<sample;
for(y=0; y<pa->recty; y++) {
- for(x=0; x<pa->rectx; x++, rd++, rp++, ro++) {
+ for(x=0; x<pa->rectx; x++, rd++, rp++, ro++, rz++, rm++) {
if(*rp) {
- addps(lb, rd, *ro, *rp, *(rz+x), mask);
+ addps(lb, rd, *ro, *rp, *rz, (zspan->rectmask)? *rm: 0, mask);
}
}
- rz+= pa->rectx;
}
if(sdata->rl->layflag & SCE_LAY_EDGE)
if(R.r.mode & R_EDGE)
- edge_enhance_tile(pa, sdata->edgerect);
+ edge_enhance_tile(pa, sdata->edgerect, zspan->rectz);
}
/* main call for shading Delta Accum, for OSA */
@@ -861,12 +1122,13 @@ void zbufshadeDA_tile(RenderPart *pa)
pa->recto= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "recto");
pa->rectp= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectp");
pa->rectz= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectz");
-
for(rl= rr->layers.first; rl; rl= rl->next) {
-
+ if((rl->layflag & SCE_LAY_ZMASK) && (rl->layflag & SCE_LAY_NEG_ZMASK))
+ pa->rectmask= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectmask");
+
/* initialize pixelstructs and edge buffer */
addpsmain(&psmlist);
- pa->rectdaps= MEM_callocN(sizeof(long)*pa->rectx*pa->recty+4, "zbufDArectd");
+ pa->rectdaps= MEM_callocN(sizeof(intptr_t)*pa->rectx*pa->recty+4, "zbufDArectd");
if(rl->layflag & SCE_LAY_EDGE)
if(R.r.mode & R_EDGE)
@@ -879,7 +1141,7 @@ void zbufshadeDA_tile(RenderPart *pa)
sdata.rl= rl;
sdata.psmlist= &psmlist;
sdata.edgerect= edgerect;
- zbuffer_solid(pa, rl->lay, rl->layflag, make_pixelstructs, &sdata);
+ zbuffer_solid(pa, rl, make_pixelstructs, &sdata);
if(R.test_break()) break;
}
@@ -895,108 +1157,74 @@ void zbufshadeDA_tile(RenderPart *pa)
/* halo before ztra, because ztra fills in zbuffer now */
if(R.flag & R_HALO)
if(rl->layflag & SCE_LAY_HALO)
- halo_tile(pa, rl->rectf, rl->lay);
+ halo_tile(pa, rl);
/* transp layer */
- if(R.flag & R_ZTRA) {
- if(rl->layflag & SCE_LAY_ZTRA) {
- unsigned short *ztramask, *solidmask= NULL; /* 16 bits, MAX_OSA */
-
- /* allocate, but not free here, for asynchronous display of this rect in main thread */
- rl->acolrect= MEM_callocN(4*sizeof(float)*pa->rectx*pa->recty, "alpha layer");
-
- /* swap for live updates, and it is used in zbuf.c!!! */
- SWAP(float *, rl->acolrect, rl->rectf);
- ztramask= zbuffer_transp_shade(pa, rl, rl->rectf);
- SWAP(float *, rl->acolrect, rl->rectf);
-
- /* zbuffer transp only returns ztramask if there's solid rendered */
- if(ztramask)
- solidmask= make_solid_mask(pa);
-
- if(ztramask && solidmask) {
- unsigned short *sps= solidmask, *spz= ztramask;
- unsigned short fullmask= (1<<R.osa)-1;
- float *fcol= rl->rectf; float *acol= rl->acolrect;
- int x;
+ if(R.flag & R_ZTRA || R.totstrand) {
+ if(rl->layflag & (SCE_LAY_ZTRA|SCE_LAY_STRAND)) {
+ if(pa->fullresult.first) {
+ zbuffer_transp_shade(pa, rl, rl->rectf, &psmlist);
+ }
+ else {
+ unsigned short *ztramask, *solidmask= NULL; /* 16 bits, MAX_OSA */
- for(x=pa->rectx*pa->recty; x>0; x--, acol+=4, fcol+=4, sps++, spz++) {
- if(*sps == fullmask)
- addAlphaOverFloat(fcol, acol);
- else
- addAlphaOverFloatMask(fcol, acol, *sps, *spz);
+ /* allocate, but not free here, for asynchronous display of this rect in main thread */
+ rl->acolrect= MEM_callocN(4*sizeof(float)*pa->rectx*pa->recty, "alpha layer");
+
+ /* swap for live updates, and it is used in zbuf.c!!! */
+ SWAP(float *, rl->acolrect, rl->rectf);
+ ztramask= zbuffer_transp_shade(pa, rl, rl->rectf, &psmlist);
+ SWAP(float *, rl->acolrect, rl->rectf);
+
+ /* zbuffer transp only returns ztramask if there's solid rendered */
+ if(ztramask)
+ solidmask= make_solid_mask(pa);
+
+ if(ztramask && solidmask) {
+ unsigned short *sps= solidmask, *spz= ztramask;
+ unsigned short fullmask= (1<<R.osa)-1;
+ float *fcol= rl->rectf; float *acol= rl->acolrect;
+ int x;
+
+ for(x=pa->rectx*pa->recty; x>0; x--, acol+=4, fcol+=4, sps++, spz++) {
+ if(*sps == fullmask)
+ addAlphaOverFloat(fcol, acol);
+ else
+ addAlphaOverFloatMask(fcol, acol, *sps, *spz);
+ }
}
- }
- else {
- float *fcol= rl->rectf; float *acol= rl->acolrect;
- int x;
- for(x=pa->rectx*pa->recty; x>0; x--, acol+=4, fcol+=4) {
- addAlphaOverFloat(fcol, acol);
+ else {
+ float *fcol= rl->rectf; float *acol= rl->acolrect;
+ int x;
+ for(x=pa->rectx*pa->recty; x>0; x--, acol+=4, fcol+=4) {
+ addAlphaOverFloat(fcol, acol);
+ }
}
- }
- if(solidmask) MEM_freeN(solidmask);
- if(ztramask) MEM_freeN(ztramask);
- }
- }
-
- /* strand rendering */
- if((rl->layflag & SCE_LAY_STRAND) && R.totstrand) {
- float *fcol, *scol;
- unsigned short *strandmask, *solidmask= NULL; /* 16 bits, MAX_OSA */
- int x;
-
- /* allocate, but not free here, for asynchronous display of this rect in main thread */
- rl->scolrect= MEM_callocN(4*sizeof(float)*pa->rectx*pa->recty, "strand layer");
-
- /* swap for live updates, and it is used in zbuf.c!!! */
- SWAP(float*, rl->scolrect, rl->rectf);
- strandmask= zbuffer_strands_shade(&R, pa, rl, rl->rectf);
- SWAP(float*, rl->scolrect, rl->rectf);
-
- /* zbuffer strands only returns strandmask if there's solid rendered */
- if(strandmask)
- solidmask= make_solid_mask(pa);
-
- if(strandmask && solidmask) {
- unsigned short *sps= solidmask, *spz= strandmask;
- unsigned short fullmask= (1<<R.osa)-1;
-
- fcol= rl->rectf; scol= rl->scolrect;
- for(x=pa->rectx*pa->recty; x>0; x--, scol+=4, fcol+=4, sps++, spz++) {
- if(*sps == fullmask)
- addAlphaOverFloat(fcol, scol);
- else
- addAlphaOverFloatMask(fcol, scol, *sps, *spz);
+ if(solidmask) MEM_freeN(solidmask);
+ if(ztramask) MEM_freeN(ztramask);
}
}
- else {
- fcol= rl->rectf; scol= rl->scolrect;
- for(x=pa->rectx*pa->recty; x>0; x--, scol+=4, fcol+=4)
- addAlphaOverFloat(fcol, scol);
- }
-
- if(solidmask) MEM_freeN(solidmask);
- if(strandmask) MEM_freeN(strandmask);
}
+ /* sun/sky */
+ if(rl->layflag & SCE_LAY_SKY)
+ atm_tile(pa, rl);
+
/* sky before edge */
if(rl->layflag & SCE_LAY_SKY)
- sky_tile(pa, rl->rectf);
+ sky_tile(pa, rl);
/* extra layers */
if(rl->layflag & SCE_LAY_EDGE)
if(R.r.mode & R_EDGE)
edge_enhance_add(pa, rl->rectf, edgerect);
- if(rl->passflag & SCE_PASS_Z)
- convert_zbuf_to_distbuf(pa, rl);
-
if(rl->passflag & SCE_PASS_VECTOR)
reset_sky_speed(pa, rl);
/* de-premul alpha */
if(R.r.alphamode & R_ALPHAKEY)
- convert_to_key_alpha(pa, rl->rectf);
+ convert_to_key_alpha(pa, rl);
/* free stuff within loop! */
MEM_freeN(pa->rectdaps); pa->rectdaps= NULL;
@@ -1004,6 +1232,11 @@ void zbufshadeDA_tile(RenderPart *pa)
if(edgerect) MEM_freeN(edgerect);
edgerect= NULL;
+
+ if(pa->rectmask) {
+ MEM_freeN(pa->rectmask);
+ pa->rectmask= NULL;
+ }
}
/* free all */
@@ -1028,7 +1261,6 @@ void zbufshade_tile(RenderPart *pa)
RenderLayer *rl;
PixStr ps;
float *edgerect= NULL;
- int addpassflag;
/* fake pixel struct, to comply to osa render */
ps.next= NULL;
@@ -1040,12 +1272,13 @@ void zbufshade_tile(RenderPart *pa)
pa->rectz= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectz");
for(rl= rr->layers.first; rl; rl= rl->next) {
-
+ if((rl->layflag & SCE_LAY_ZMASK) && (rl->layflag & SCE_LAY_NEG_ZMASK))
+ pa->rectmask= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectmask");
+
/* general shader info, passes */
shade_sample_initialize(&ssamp, pa, rl);
- addpassflag= rl->passflag & ~(SCE_PASS_Z|SCE_PASS_COMBINED);
- zbuffer_solid(pa, rl->lay, rl->layflag, NULL, NULL);
+ zbuffer_solid(pa, rl, NULL, NULL);
if(!R.test_break()) { /* NOTE: this if() is not consistant */
@@ -1053,7 +1286,7 @@ void zbufshade_tile(RenderPart *pa)
if(rl->layflag & SCE_LAY_EDGE) {
if(R.r.mode & R_EDGE) {
edgerect= MEM_callocN(sizeof(float)*pa->rectx*pa->recty, "rectedge");
- edge_enhance_tile(pa, edgerect);
+ edge_enhance_tile(pa, edgerect, pa->rectz);
}
}
@@ -1072,6 +1305,9 @@ void zbufshade_tile(RenderPart *pa)
/* irregular shadowb buffer creation */
if(R.r.mode & R_SHADOW)
ISB_create(pa, NULL);
+
+ if(R.occlusiontree)
+ cache_occ_samples(&R, pa, &ssamp);
for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++, rr->renrect.ymax++) {
for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, ro++, rz++, rp++, fcol+=4, offs++) {
@@ -1083,14 +1319,8 @@ void zbufshade_tile(RenderPart *pa)
ps.facenr= *rp;
ps.z= *rz;
if(shade_samples(&ssamp, &ps, x, y)) {
- QUATCOPY(fcol, ssamp.shr[0].combined);
-
- if(!(fcol[0] == fcol[0]))
- printvecf("fudgecol", fcol);
-
- /* passes */
- if(addpassflag)
- add_passes(rl, offs, ssamp.shi, ssamp.shr);
+ /* combined and passes */
+ add_passes(rl, offs, ssamp.shi, ssamp.shr);
}
}
}
@@ -1098,6 +1328,9 @@ void zbufshade_tile(RenderPart *pa)
if(R.test_break()) break;
}
+ if(R.occlusiontree)
+ free_occ_samples(&R, pa);
+
if(R.r.mode & R_SHADOW)
ISB_free(pa);
}
@@ -1114,10 +1347,10 @@ void zbufshade_tile(RenderPart *pa)
/* halo before ztra, because ztra fills in zbuffer now */
if(R.flag & R_HALO)
if(rl->layflag & SCE_LAY_HALO)
- halo_tile(pa, rl->rectf, rl->lay);
+ halo_tile(pa, rl);
- if(R.flag & R_ZTRA) {
- if(rl->layflag & SCE_LAY_ZTRA) {
+ if(R.flag & R_ZTRA || R.totstrand) {
+ if(rl->layflag & (SCE_LAY_ZTRA|SCE_LAY_STRAND)) {
float *fcol, *acol;
int x;
@@ -1126,7 +1359,7 @@ void zbufshade_tile(RenderPart *pa)
/* swap for live updates */
SWAP(float *, rl->acolrect, rl->rectf);
- zbuffer_transp_shade(pa, rl, rl->rectf);
+ zbuffer_transp_shade(pa, rl, rl->rectf, NULL);
SWAP(float *, rl->acolrect, rl->rectf);
fcol= rl->rectf; acol= rl->acolrect;
@@ -1135,28 +1368,14 @@ void zbufshade_tile(RenderPart *pa)
}
}
}
-
- /* strand rendering */
- if((rl->layflag & SCE_LAY_STRAND) && R.totstrand) {
- float *fcol, *scol;
- int x;
-
- /* allocate, but not free here, for asynchronous display of this rect in main thread */
- rl->scolrect= MEM_callocN(4*sizeof(float)*pa->rectx*pa->recty, "strand layer");
-
- /* swap for live updates */
- SWAP(float*, rl->scolrect, rl->rectf);
- zbuffer_strands_shade(&R, pa, rl, rl->rectf);
- SWAP(float*, rl->scolrect, rl->rectf);
-
- fcol= rl->rectf; scol= rl->scolrect;
- for(x=pa->rectx*pa->recty; x>0; x--, scol+=4, fcol+=4)
- addAlphaOverFloat(fcol, scol);
- }
+
+ /* sun/sky */
+ if(rl->layflag & SCE_LAY_SKY)
+ atm_tile(pa, rl);
/* sky before edge */
if(rl->layflag & SCE_LAY_SKY)
- sky_tile(pa, rl->rectf);
+ sky_tile(pa, rl);
if(!R.test_break()) {
if(rl->layflag & SCE_LAY_EDGE)
@@ -1164,18 +1383,20 @@ void zbufshade_tile(RenderPart *pa)
edge_enhance_add(pa, rl->rectf, edgerect);
}
- if(rl->passflag & SCE_PASS_Z)
- convert_zbuf_to_distbuf(pa, rl);
-
if(rl->passflag & SCE_PASS_VECTOR)
reset_sky_speed(pa, rl);
/* de-premul alpha */
if(R.r.alphamode & R_ALPHAKEY)
- convert_to_key_alpha(pa, rl->rectf);
+ convert_to_key_alpha(pa, rl);
if(edgerect) MEM_freeN(edgerect);
edgerect= NULL;
+
+ if(pa->rectmask) {
+ MEM_freeN(pa->rectmask);
+ pa->rectmask= NULL;
+ }
}
/* display active layer */
@@ -1207,9 +1428,9 @@ static void addps_sss(void *cb_handle, int obi, int facenr, int x, int y, int z)
return;
if(pa->rectall) {
- long *rs= pa->rectall + pa->rectx*y + x;
+ intptr_t *rs= pa->rectall + pa->rectx*y + x;
- addps(&handle->psmlist, rs, obi, facenr, z, 0);
+ addps(&handle->psmlist, rs, obi, facenr, z, 0, 0);
handle->totps++;
}
if(pa->rectz) {
@@ -1244,10 +1465,10 @@ static void shade_sample_sss(ShadeSample *ssamp, Material *mat, ObjectInstanceRe
{
ShadeInput *shi= ssamp->shi;
ShadeResult shr;
- float texfac, orthoarea, nor[3];
+ float texfac, orthoarea, nor[3], alpha, sx, sy;
/* cache for shadow */
- shi->samplenr++;
+ shi->samplenr= R.shadowsamplenr[shi->thread]++;
if(quad)
shade_input_set_triangle_i(shi, obi, vlr, 0, 2, 3);
@@ -1255,8 +1476,8 @@ static void shade_sample_sss(ShadeSample *ssamp, Material *mat, ObjectInstanceRe
shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 2);
/* center pixel */
- x += 0.5f;
- y += 0.5f;
+ sx = x + 0.5f;
+ sy = y + 0.5f;
/* we estimate the area here using shi->dxco and shi->dyco. we need to
enabled shi->osatex these are filled. we compute two areas, one with
@@ -1265,13 +1486,13 @@ static void shade_sample_sss(ShadeSample *ssamp, Material *mat, ObjectInstanceRe
shi->osatex= 1;
VECCOPY(nor, shi->facenor);
- calc_view_vector(shi->facenor, x, y);
+ calc_view_vector(shi->facenor, sx, sy);
Normalize(shi->facenor);
- shade_input_set_viewco(shi, x, y, z);
+ shade_input_set_viewco(shi, x, y, sx, sy, z);
orthoarea= VecLength(shi->dxco)*VecLength(shi->dyco);
VECCOPY(shi->facenor, nor);
- shade_input_set_viewco(shi, x, y, z);
+ shade_input_set_viewco(shi, x, y, sx, sy, z);
*area= VecLength(shi->dxco)*VecLength(shi->dyco);
*area= MIN2(*area, 2.0f*orthoarea);
@@ -1310,16 +1531,8 @@ static void shade_sample_sss(ShadeSample *ssamp, Material *mat, ObjectInstanceRe
/* texture blending */
texfac= shi->mat->sss_texfac;
- if(texfac == 0.0f) {
- if(shr.col[0]!=0.0f) color[0] /= shr.col[0];
- if(shr.col[1]!=0.0f) color[1] /= shr.col[1];
- if(shr.col[2]!=0.0f) color[2] /= shr.col[2];
- }
- else if(texfac != 1.0f) {
- if(shr.col[0]!=0.0f) color[0] *= pow(shr.col[0], texfac)/shr.col[0];
- if(shr.col[1]!=0.0f) color[1] *= pow(shr.col[1], texfac)/shr.col[1];
- if(shr.col[2]!=0.0f) color[2] *= pow(shr.col[2], texfac)/shr.col[2];
- }
+ alpha= shr.combined[3];
+ *area *= alpha;
}
static void zbufshade_sss_free(RenderPart *pa)
@@ -1343,15 +1556,15 @@ void zbufshade_sss_tile(RenderPart *pa)
ShadeSample ssamp;
ZBufSSSHandle handle;
RenderResult *rr= pa->result;
- RenderLayer *rl= rr->layers.first;
+ RenderLayer *rl;
VlakRen *vlr;
Material *mat= re->sss_mat;
- float (*co)[3], (*color)[3], *area, *fcol= rl->rectf;
+ float (*co)[3], (*color)[3], *area, *fcol;
int x, y, seed, quad, totpoint, display = !(re->r.scemode & R_PREVIEWBUTS);
- int *ro, *rz, *rp, *rbo, *rbz, *rbp;
+ int *ro, *rz, *rp, *rbo, *rbz, *rbp, lay;
#if 0
PixStr *ps;
- long *rs;
+ intptr_t *rs;
int z;
#endif
@@ -1363,7 +1576,7 @@ void zbufshade_sss_tile(RenderPart *pa)
handle.psmlist.first= handle.psmlist.last= NULL;
addpsmain(&handle.psmlist);
- pa->rectall= MEM_callocN(sizeof(long)*pa->rectx*pa->recty+4, "rectall");
+ pa->rectall= MEM_callocN(sizeof(intptr_t)*pa->rectx*pa->recty+4, "rectall");
#else
pa->recto= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "recto");
pa->rectp= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectp");
@@ -1373,13 +1586,34 @@ void zbufshade_sss_tile(RenderPart *pa)
pa->rectbackz= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectbackz");
#endif
+ /* setup shade sample with correct passes */
+ memset(&ssamp, 0, sizeof(ssamp));
+ shade_sample_initialize(&ssamp, pa, rr->layers.first);
+ ssamp.tot= 1;
+
+ for(rl=rr->layers.first; rl; rl=rl->next) {
+ ssamp.shi[0].lay |= rl->lay;
+ ssamp.shi[0].layflag |= rl->layflag;
+ ssamp.shi[0].passflag |= rl->passflag;
+ ssamp.shi[0].combinedflag |= ~rl->pass_xor;
+ }
+
+ rl= rr->layers.first;
+ ssamp.shi[0].passflag |= SCE_PASS_RGBA|SCE_PASS_COMBINED;
+ ssamp.shi[0].combinedflag &= ~(SCE_PASS_SPEC);
+ ssamp.shi[0].mat_override= NULL;
+ ssamp.shi[0].light_override= NULL;
+ lay= ssamp.shi[0].lay;
+
/* create the pixelstrs to be used later */
- zbuffer_sss(pa, rl->lay, &handle, addps_sss);
+ zbuffer_sss(pa, lay, &handle, addps_sss);
if(handle.totps==0) {
zbufshade_sss_free(pa);
return;
}
+
+ fcol= rl->rectf;
co= MEM_mallocN(sizeof(float)*3*handle.totps, "SSSCo");
color= MEM_mallocN(sizeof(float)*3*handle.totps, "SSSColor");
@@ -1391,14 +1625,6 @@ void zbufshade_sss_tile(RenderPart *pa)
ISB_create(pa, NULL);
#endif
- /* setup shade sample with correct passes */
- memset(&ssamp, 0, sizeof(ssamp));
- shade_sample_initialize(&ssamp, pa, rl);
- ssamp.shi[0].passflag= SCE_PASS_DIFFUSE|SCE_PASS_AO|SCE_PASS_RADIO;
- ssamp.shi[0].passflag |= SCE_PASS_RGBA;
- ssamp.shi[0].combinedflag= ~(SCE_PASS_SPEC);
- ssamp.tot= 1;
-
if(display) {
/* initialize scanline updates for main thread */
rr->renrect.ymin= 0;
@@ -1563,8 +1789,8 @@ static void renderhalo_post(RenderResult *rr, float *rectf, HaloRen *har) /* pos
dist= xsq+ysq;
if(dist<har->radsq) {
- shadeHaloFloat(har, colf, 0x7FFFFF, dist, xn, yn, har->flarec);
- addalphaAddfacFloat(rtf, colf, har->add);
+ if(shadeHaloFloat(har, colf, 0x7FFFFF, dist, xn, yn, har->flarec))
+ addalphaAddfacFloat(rtf, colf, har->add);
}
rtf+=4;
}
@@ -1701,6 +1927,8 @@ void add_halo_flare(Render *re)
void RE_shade_external(Render *re, ShadeInput *shi, ShadeResult *shr)
{
static VlakRen vlr;
+ static ObjectRen obr;
+ static ObjectInstanceRen obi;
/* init */
if(re) {
@@ -1708,11 +1936,16 @@ void RE_shade_external(Render *re, ShadeInput *shi, ShadeResult *shr)
/* fake render face */
memset(&vlr, 0, sizeof(VlakRen));
- vlr.lay= -1;
+ memset(&obr, 0, sizeof(ObjectRen));
+ memset(&obi, 0, sizeof(ObjectInstanceRen));
+ obr.lay= -1;
+ obi.obr= &obr;
return;
}
shi->vlr= &vlr;
+ shi->obr= &obr;
+ shi->obi= &obi;
if(shi->mat->nodetree && shi->mat->use_nodes)
ntreeShaderExecTree(shi->mat->nodetree, shi, shr);
@@ -1727,7 +1960,6 @@ void RE_shade_external(Render *re, ShadeInput *shi, ShadeResult *shr)
/* ************************* bake ************************ */
-#define FTOCHAR(val) val<=0.0f?0: (val>=1.0f?255: (char)(255.0f*val))
typedef struct BakeShade {
ShadeSample ssamp;
@@ -1745,8 +1977,81 @@ typedef struct BakeShade {
unsigned int *rect;
float *rect_float;
+
+ int usemask;
+ char *rect_mask; /* bake pixel mask */
+
+ float dxco[3], dyco[3];
} BakeShade;
+/* bake uses a char mask to know what has been baked */
+#define BAKE_MASK_NULL 0
+#define BAKE_MASK_MARGIN 1
+#define BAKE_MASK_BAKED 2
+static void bake_mask_filter_extend( char *mask, int width, int height )
+{
+ char *row1, *row2, *row3;
+ int rowlen, x, y;
+ char *temprect;
+
+ rowlen= width;
+
+ /* make a copy, to prevent flooding */
+ temprect= MEM_dupallocN(mask);
+
+ for(y=1; y<=height; y++) {
+ /* setup rows */
+ row1= (char *)(temprect + (y-2)*rowlen);
+ row2= row1 + rowlen;
+ row3= row2 + rowlen;
+ if(y==1)
+ row1= row2;
+ else if(y==height)
+ row3= row2;
+
+ for(x=0; x<rowlen; x++) {
+ if (mask[((y-1)*rowlen)+x]==0) {
+ if (*row1 || *row2 || *row3 || *(row1+1) || *(row3+1) ) {
+ mask[((y-1)*rowlen)+x] = BAKE_MASK_MARGIN;
+ } else if((x!=rowlen-1) && (*(row1+2) || *(row2+2) || *(row3+2)) ) {
+ mask[((y-1)*rowlen)+x] = BAKE_MASK_MARGIN;
+ }
+ }
+
+ if(x!=0) {
+ row1++; row2++; row3++;
+ }
+ }
+ }
+ MEM_freeN(temprect);
+}
+
+static void bake_mask_clear( ImBuf *ibuf, char *mask, char val )
+{
+ int x,y;
+ if (ibuf->rect_float) {
+ for(x=0; x<ibuf->x; x++) {
+ for(y=0; y<ibuf->y; y++) {
+ if (mask[ibuf->x*y + x] == val) {
+ float *col= ibuf->rect_float + 4*(ibuf->x*y + x);
+ col[0] = col[1] = col[2] = col[3] = 0.0f;
+ }
+ }
+ }
+
+ } else {
+ /* char buffer */
+ for(x=0; x<ibuf->x; x++) {
+ for(y=0; y<ibuf->y; y++) {
+ if (mask[ibuf->x*y + x] == val) {
+ char *col= (char *)(ibuf->rect + ibuf->x*y + x);
+ col[0] = col[1] = col[2] = col[3] = 0;
+ }
+ }
+ }
+ }
+}
+
static void bake_set_shade_input(ObjectInstanceRen *obi, VlakRen *vlr, ShadeInput *shi, int quad, int isect, int x, int y, float u, float v)
{
if(isect) {
@@ -1768,23 +2073,28 @@ static void bake_set_shade_input(ObjectInstanceRen *obi, VlakRen *vlr, ShadeInpu
shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 2);
}
- /* set up view vector */
- VECCOPY(shi->view, shi->co);
- Normalize(shi->view);
-
/* cache for shadow */
- shi->samplenr++;
+ shi->samplenr= R.shadowsamplenr[shi->thread]++;
+
+ shi->mask= 0xFFFF; /* all samples */
shi->u= -u;
shi->v= -v;
shi->xs= x;
shi->ys= y;
+ shade_input_set_uv(shi);
shade_input_set_normals(shi);
/* no normal flip */
if(shi->flippednor)
shade_input_flip_normals(shi);
+
+ /* set up view vector to look right at the surface (note that the normal
+ * is negated in the renderer so it does not need to be done here) */
+ shi->view[0]= shi->vn[0];
+ shi->view[1]= shi->vn[1];
+ shi->view[2]= shi->vn[2];
}
static void bake_shade(void *handle, Object *ob, ShadeInput *shi, int quad, int x, int y, float u, float v, float *tvn, float *ttang)
@@ -1800,12 +2110,20 @@ static void bake_shade(void *handle, Object *ob, ShadeInput *shi, int quad, int
if(bs->type==RE_BAKE_AO) {
ambient_occlusion(shi);
- ambient_occlusion_to_diffuse(shi, shr.combined);
+
+ if(R.r.bake_flag & R_BAKE_NORMALIZE)
+ VECCOPY(shr.combined, shi->ao)
+ else
+ ambient_occlusion_to_diffuse(shi, shr.combined);
}
else {
+ if (bs->type==RE_BAKE_SHADOW) /* Why do shadows set the color anyhow?, ignore material color for baking */
+ shi->r = shi->g = shi->b = 1.0f;
+
shade_input_set_shade_texco(shi);
- shade_samples_do_AO(ssamp);
+ if(!ELEM3(bs->type, RE_BAKE_NORMALS, RE_BAKE_TEXTURE, RE_BAKE_SHADOW))
+ shade_samples_do_AO(ssamp);
if(shi->mat->nodetree && shi->mat->use_nodes) {
ntreeShaderExecTree(shi->mat->nodetree, shi, &shr);
@@ -1830,8 +2148,8 @@ static void bake_shade(void *handle, Object *ob, ShadeInput *shi, int quad, int
VECCOPY(mat[2], tvn);
}
else {
- VECCOPY(mat[0], shi->tang);
- Crossf(mat[1], shi->vn, shi->tang);
+ VECCOPY(mat[0], shi->nmaptang);
+ Crossf(mat[1], shi->vn, shi->nmaptang);
VECCOPY(mat[2], shi->vn);
}
@@ -1853,35 +2171,80 @@ static void bake_shade(void *handle, Object *ob, ShadeInput *shi, int quad, int
shr.combined[0]= shi->r;
shr.combined[1]= shi->g;
shr.combined[2]= shi->b;
+ shr.alpha = shi->alpha;
+ }
+ else if(bs->type==RE_BAKE_SHADOW) {
+ VECCOPY(shr.combined, shr.shad);
+ shr.alpha = shi->alpha;
}
}
- if(bs->rect) {
+ if(bs->rect_float) {
+ float *col= bs->rect_float + 4*(bs->rectx*y + x);
+ VECCOPY(col, shr.combined);
+ if (bs->type==RE_BAKE_ALL || bs->type==RE_BAKE_TEXTURE) {
+ col[3]= shr.alpha;
+ } else {
+ col[3]= 1.0;
+ }
+ }
+ else {
char *col= (char *)(bs->rect + bs->rectx*y + x);
col[0]= FTOCHAR(shr.combined[0]);
col[1]= FTOCHAR(shr.combined[1]);
col[2]= FTOCHAR(shr.combined[2]);
- col[3]= 255;
+
+
+ if (bs->type==RE_BAKE_ALL || bs->type==RE_BAKE_TEXTURE) {
+ col[3]= FTOCHAR(shr.alpha);
+ } else {
+ col[3]= 255;
+ }
}
- else {
+
+ if (bs->rect_mask) {
+ bs->rect_mask[bs->rectx*y + x] = BAKE_MASK_BAKED;
+ }
+}
+
+static void bake_displacement(void *handle, ShadeInput *shi, float dist, int x, int y)
+{
+ BakeShade *bs= handle;
+ float disp;
+
+ if(R.r.bake_flag & R_BAKE_NORMALIZE && R.r.bake_maxdist) {
+ disp = (dist+R.r.bake_maxdist) / (R.r.bake_maxdist*2); /* alter the range from [-bake_maxdist, bake_maxdist] to [0, 1]*/
+ } else {
+ disp = 0.5 + dist; /* alter the range from [-0.5,0.5] to [0,1]*/
+ }
+
+ if(bs->rect_float) {
float *col= bs->rect_float + 4*(bs->rectx*y + x);
- VECCOPY(col, shr.combined);
+ col[0] = col[1] = col[2] = disp;
col[3]= 1.0f;
+ } else {
+ char *col= (char *)(bs->rect + bs->rectx*y + x);
+ col[0]= FTOCHAR(disp);
+ col[1]= FTOCHAR(disp);
+ col[2]= FTOCHAR(disp);
+ col[3]= 255;
+ }
+ if (bs->rect_mask) {
+ bs->rect_mask[bs->rectx*y + x] = BAKE_MASK_BAKED;
}
}
-static int bake_check_intersect(Isect *is, RayFace *face)
+static int bake_check_intersect(Isect *is, int ob, RayFace *face)
{
- VlakRen *vlr = (VlakRen*)face;
BakeShade *bs = (BakeShade*)is->userdata;
/* no direction checking for now, doesn't always improve the result
* (INPR(shi->facenor, bs->dir) > 0.0f); */
- return (vlr->obr->ob != bs->actob);
+ return (R.objectinstance[ob].obr->ob != bs->actob);
}
-static int bake_intersect_tree(RayTree* raytree, Isect* isect, float *dir, float sign, float *hitco)
+static int bake_intersect_tree(RayTree* raytree, Isect* isect, float *start, float *dir, float sign, float *hitco, float *dist)
{
float maxdist;
int hit;
@@ -1890,7 +2253,9 @@ static int bake_intersect_tree(RayTree* raytree, Isect* isect, float *dir, float
if(R.r.bake_maxdist > 0.0f)
maxdist= R.r.bake_maxdist;
else
- maxdist= RE_ray_tree_max_size(R.raytree);
+ maxdist= RE_ray_tree_max_size(R.raytree) + R.r.bake_biasdist;
+
+ VECADDFAC(isect->start, start, dir, -R.r.bake_biasdist);
isect->end[0] = isect->start[0] + dir[0]*maxdist*sign;
isect->end[1] = isect->start[1] + dir[1]*maxdist*sign;
@@ -1901,11 +2266,62 @@ static int bake_intersect_tree(RayTree* raytree, Isect* isect, float *dir, float
hitco[0] = isect->start[0] + isect->labda*isect->vec[0];
hitco[1] = isect->start[1] + isect->labda*isect->vec[1];
hitco[2] = isect->start[2] + isect->labda*isect->vec[2];
+
+ *dist= VecLenf(start, hitco);
}
return hit;
}
+static void bake_set_vlr_dxyco(BakeShade *bs, float *uv1, float *uv2, float *uv3)
+{
+ VlakRen *vlr= bs->vlr;
+ float A, d1, d2, d3, *v1, *v2, *v3;
+
+ if(bs->quad) {
+ v1= vlr->v1->co;
+ v2= vlr->v3->co;
+ v3= vlr->v4->co;
+ }
+ else {
+ v1= vlr->v1->co;
+ v2= vlr->v2->co;
+ v3= vlr->v3->co;
+ }
+
+ /* formula derived from barycentric coordinates:
+ * (uvArea1*v1 + uvArea2*v2 + uvArea3*v3)/uvArea
+ * then taking u and v partial derivatives to get dxco and dyco */
+ A= (uv2[0] - uv1[0])*(uv3[1] - uv1[1]) - (uv3[0] - uv1[0])*(uv2[1] - uv1[1]);
+
+ if(fabs(A) > FLT_EPSILON) {
+ A= 0.5f/A;
+
+ d1= uv2[1] - uv3[1];
+ d2= uv3[1] - uv1[1];
+ d3= uv1[1] - uv2[1];
+ bs->dxco[0]= (v1[0]*d1 + v2[0]*d2 + v3[0]*d3)*A;
+ bs->dxco[1]= (v1[1]*d1 + v2[1]*d2 + v3[1]*d3)*A;
+ bs->dxco[2]= (v1[2]*d1 + v2[2]*d2 + v3[2]*d3)*A;
+
+ d1= uv3[0] - uv2[0];
+ d2= uv1[0] - uv3[0];
+ d3= uv2[0] - uv1[0];
+ bs->dyco[0]= (v1[0]*d1 + v2[0]*d2 + v3[0]*d3)*A;
+ bs->dyco[1]= (v1[1]*d1 + v2[1]*d2 + v3[1]*d3)*A;
+ bs->dyco[2]= (v1[2]*d1 + v2[2]*d2 + v3[2]*d3)*A;
+ }
+ else {
+ bs->dxco[0]= bs->dxco[1]= bs->dxco[2]= 0.0f;
+ bs->dyco[0]= bs->dyco[1]= bs->dyco[2]= 0.0f;
+ }
+
+ if(bs->obi->flag & R_TRANSFORMED) {
+ Mat3MulVecfl(bs->obi->nmat, bs->dxco);
+ Mat3MulVecfl(bs->obi->nmat, bs->dyco);
+ }
+}
+
static void do_bake_shade(void *handle, int x, int y, float u, float v)
{
BakeShade *bs= handle;
@@ -1943,52 +2359,64 @@ static void do_bake_shade(void *handle, int x, int y, float u, float v)
if(obi->flag & R_TRANSFORMED)
Mat4MulVecfl(obi->mat, shi->co);
+ VECCOPY(shi->dxco, bs->dxco);
+ VECCOPY(shi->dyco, bs->dyco);
+
quad= bs->quad;
bake_set_shade_input(obi, vlr, shi, quad, 0, x, y, u, v);
if(bs->type==RE_BAKE_NORMALS && R.r.bake_normal_space==R_BAKE_SPACE_TANGENT) {
shade_input_set_shade_texco(shi);
VECCOPY(tvn, shi->vn);
- VECCOPY(ttang, shi->tang);
+ VECCOPY(ttang, shi->nmaptang);
}
/* if we are doing selected to active baking, find point on other face */
if(bs->actob) {
Isect isec, minisec;
- float co[3], minco[3];
- int hit, sign;
+ float co[3], minco[3], dist, mindist=0.0f;
+ int hit, sign, dir=1;
/* intersect with ray going forward and backward*/
hit= 0;
memset(&minisec, 0, sizeof(minisec));
minco[0]= minco[1]= minco[2]= 0.0f;
-
+
VECCOPY(bs->dir, shi->vn);
-
+
for(sign=-1; sign<=1; sign+=2) {
memset(&isec, 0, sizeof(isec));
- VECCOPY(isec.start, shi->co);
isec.mode= RE_RAY_MIRROR;
isec.faceorig= (RayFace*)vlr;
isec.oborig= RAY_OBJECT_SET(&R, obi);
isec.userdata= bs;
-
- if(bake_intersect_tree(R.raytree, &isec, shi->vn, sign, co)) {
+
+ if(bake_intersect_tree(R.raytree, &isec, shi->co, shi->vn, sign, co, &dist)) {
if(!hit || VecLenf(shi->co, co) < VecLenf(shi->co, minco)) {
minisec= isec;
+ mindist= dist;
VECCOPY(minco, co);
hit= 1;
+ dir = sign;
}
}
}
+ if (bs->type==RE_BAKE_DISPLACEMENT) {
+ if(hit)
+ bake_displacement(handle, shi, (dir==-1)? mindist:-mindist, x, y);
+ else
+ bake_displacement(handle, shi, 0.0f, x, y);
+ return;
+ }
+
/* if hit, we shade from the new point, otherwise from point one starting face */
if(hit) {
vlr= (VlakRen*)minisec.face;
obi= RAY_OBJECT_GET(&R, minisec.ob);
quad= (minisec.isect == 2);
VECCOPY(shi->co, minco);
-
+
u= -minisec.u;
v= -minisec.v;
bake_set_shade_input(obi, vlr, shi, quad, 1, x, y, u, v);
@@ -2025,7 +2453,7 @@ static int get_next_bake_face(BakeShade *bs)
vlr= RE_findOrAddVlak(obr, v);
if((bs->actob && bs->actob == obr->ob) || (!bs->actob && (obr->ob->flag & SELECT))) {
- tface= RE_vlakren_get_tface(obr, vlr, obr->actmtface, NULL, 0);
+ tface= RE_vlakren_get_tface(obr, vlr, obr->bakemtface, NULL, 0);
if(tface && tface->tpage) {
Image *ima= tface->tpage;
@@ -2079,7 +2507,7 @@ static void shade_tface(BakeShade *bs)
VlakRen *vlr= bs->vlr;
ObjectInstanceRen *obi= bs->obi;
ObjectRen *obr= obi->obr;
- MTFace *tface= RE_vlakren_get_tface(obr, vlr, obr->actmtface, NULL, 0);
+ MTFace *tface= RE_vlakren_get_tface(obr, vlr, obr->bakemtface, NULL, 0);
Image *ima= tface->tpage;
float vec[4][2];
int a, i1, i2, i3;
@@ -2099,6 +2527,19 @@ static void shade_tface(BakeShade *bs)
bs->rect_float= bs->ibuf->rect_float;
bs->quad= 0;
+ if (bs->usemask) {
+ if (bs->ibuf->userdata==NULL) {
+ BLI_lock_thread(LOCK_CUSTOM1);
+ if (bs->ibuf->userdata==NULL) { /* since the thread was locked, its possible another thread alloced the value */
+ bs->ibuf->userdata = (void *)MEM_callocN(sizeof(char)*bs->rectx*bs->recty, "BakeMask");
+ bs->rect_mask= (char *)bs->ibuf->userdata;
+ }
+ BLI_unlock_thread(LOCK_CUSTOM1);
+ } else {
+ bs->rect_mask= (char *)bs->ibuf->userdata;
+ }
+ }
+
/* get pixel level vertex coordinates */
for(a=0; a<4; a++) {
vec[a][0]= tface->uv[a][0]*(float)bs->rectx - 0.5f;
@@ -2108,10 +2549,12 @@ static void shade_tface(BakeShade *bs)
/* UV indices have to be corrected for possible quad->tria splits */
i1= 0; i2= 1; i3= 2;
vlr_set_uv_indices(vlr, &i1, &i2, &i3);
+ bake_set_vlr_dxyco(bs, vec[i1], vec[i2], vec[i3]);
zspan_scanconvert(bs->zspan, bs, vec[i1], vec[i2], vec[i3], do_bake_shade);
if(vlr->v4) {
bs->quad= 1;
+ bake_set_vlr_dxyco(bs, vec[0], vec[2], vec[3]);
zspan_scanconvert(bs->zspan, bs, vec[0], vec[2], vec[3], do_bake_shade);
}
}
@@ -2140,8 +2583,8 @@ int RE_bake_shade_all_selected(Render *re, int type, Object *actob)
BakeShade handles[BLENDER_MAX_THREADS];
ListBase threads;
Image *ima;
- int a, vdone=0;
-
+ int a, vdone=0, usemask=0;
+
/* initialize render global */
R= *re;
R.bakebuf= NULL;
@@ -2149,9 +2592,17 @@ int RE_bake_shade_all_selected(Render *re, int type, Object *actob)
/* initialize static vars */
get_next_bake_face(NULL);
+ /* do we need a mask? */
+ if (re->r.bake_filter && (re->r.bake_flag & R_BAKE_CLEAR)==0)
+ usemask = 1;
+
/* baker uses this flag to detect if image was initialized */
- for(ima= G.main->image.first; ima; ima= ima->id.next)
+ for(ima= G.main->image.first; ima; ima= ima->id.next) {
+ ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
ima->id.flag |= LIB_DOIT;
+ if (ibuf)
+ ibuf->userdata = NULL; /* use for masking if needed */
+ }
BLI_init_threads(&threads, do_bake_thread, re->r.threads);
@@ -2161,7 +2612,12 @@ int RE_bake_shade_all_selected(Render *re, int type, Object *actob)
memset(&handles[a], 0, sizeof(BakeShade));
handles[a].ssamp.shi[0].lay= re->scene->lay;
- handles[a].ssamp.shi[0].passflag= SCE_PASS_COMBINED;
+
+ if (type==RE_BAKE_SHADOW) {
+ handles[a].ssamp.shi[0].passflag= SCE_PASS_SHADOW;
+ } else {
+ handles[a].ssamp.shi[0].passflag= SCE_PASS_COMBINED;
+ }
handles[a].ssamp.shi[0].combinedflag= ~(SCE_PASS_SPEC);
handles[a].ssamp.shi[0].thread= a;
handles[a].ssamp.tot= 1;
@@ -2170,6 +2626,8 @@ int RE_bake_shade_all_selected(Render *re, int type, Object *actob)
handles[a].actob= actob;
handles[a].zspan= MEM_callocN(sizeof(ZSpan), "zspan for bake");
+ handles[a].usemask = usemask;
+
BLI_insert_thread(&threads, &handles[a]);
}
@@ -2184,23 +2642,52 @@ int RE_bake_shade_all_selected(Render *re, int type, Object *actob)
break;
}
- /* filter images */
+ /* filter and refresh images */
for(ima= G.main->image.first; ima; ima= ima->id.next) {
if((ima->id.flag & LIB_DOIT)==0) {
ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
- for(a=0; a<re->r.bake_filter; a++)
- IMB_filter_extend(ibuf);
+ if (re->r.bake_filter) {
+ if (usemask) {
+ /* extend the mask +2 pixels from the image,
+ * this is so colors dont blend in from outside */
+ char *temprect;
+
+ for(a=0; a<re->r.bake_filter; a++)
+ bake_mask_filter_extend((char *)ibuf->userdata, ibuf->x, ibuf->y);
+
+ temprect = MEM_dupallocN(ibuf->userdata);
+
+ /* expand twice to clear this many pixels, so they blend back in */
+ bake_mask_filter_extend(temprect, ibuf->x, ibuf->y);
+ bake_mask_filter_extend(temprect, ibuf->x, ibuf->y);
+
+ /* clear all pixels in the margin*/
+ bake_mask_clear(ibuf, temprect, BAKE_MASK_MARGIN);
+ MEM_freeN(temprect);
+ }
+
+ for(a=0; a<re->r.bake_filter; a++) {
+ /*the mask, ibuf->userdata - can be null, in this case only zero alpha is used */
+ IMB_filter_extend(ibuf, (char *)ibuf->userdata);
+ }
+
+ if (ibuf->userdata) {
+ MEM_freeN(ibuf->userdata);
+ ibuf->userdata= NULL;
+ }
+ }
ibuf->userflags |= IB_BITMAPDIRTY;
+ if (ibuf->rect_float) IMB_rect_from_float(ibuf);
}
}
/* calculate return value */
- for(a=0; a<re->r.threads; a++) {
+ for(a=0; a<re->r.threads; a++) {
vdone+= handles[a].vdone;
zbuf_free_span(handles[a].zspan);
MEM_freeN(handles[a].zspan);
- }
+ }
BLI_end_threads(&threads);
return vdone;
diff --git a/source/blender/render/intern/source/renderdatabase.c b/source/blender/render/intern/source/renderdatabase.c
index 79c87252fc2..d44b49cc706 100644
--- a/source/blender/render/intern/source/renderdatabase.c
+++ b/source/blender/render/intern/source/renderdatabase.c
@@ -104,7 +104,10 @@
#define RE_MCOL_ELEMS 4
#define RE_UV_ELEMS 2
#define RE_SURFNOR_ELEMS 3
+#define RE_RADFACE_ELEMS 1
#define RE_SIMPLIFY_ELEMS 2
+#define RE_FACE_ELEMS 1
+#define RE_NMAP_TANGENT_ELEMS 12
float *RE_vertren_get_sticky(ObjectRen *obr, VertRen *ver, int verify)
{
@@ -362,12 +365,43 @@ float *RE_vlakren_get_surfnor(ObjectRen *obr, VlakRen *vlak, int verify)
return surfnor + (vlak->index & 255)*RE_SURFNOR_ELEMS;
}
+float *RE_vlakren_get_nmap_tangent(ObjectRen *obr, VlakRen *vlak, int verify)
+{
+ float *tangent;
+ int nr= vlak->index>>8;
+
+ tangent= obr->vlaknodes[nr].tangent;
+ if(tangent==NULL) {
+ if(verify)
+ tangent= obr->vlaknodes[nr].tangent= MEM_callocN(256*RE_NMAP_TANGENT_ELEMS*sizeof(float), "tangent table");
+ else
+ return NULL;
+ }
+ return tangent + (vlak->index & 255)*RE_NMAP_TANGENT_ELEMS;
+}
+
+RadFace **RE_vlakren_get_radface(ObjectRen *obr, VlakRen *vlak, int verify)
+{
+ RadFace **radface;
+ int nr= vlak->index>>8;
+
+ radface= obr->vlaknodes[nr].radface;
+ if(radface==NULL) {
+ if(verify)
+ radface= obr->vlaknodes[nr].radface= MEM_callocN(256*RE_RADFACE_ELEMS*sizeof(void*), "radface table");
+ else
+ return NULL;
+ }
+ return radface + (vlak->index & 255)*RE_RADFACE_ELEMS;
+}
+
VlakRen *RE_vlakren_copy(ObjectRen *obr, VlakRen *vlr)
{
VlakRen *vlr1 = RE_findOrAddVlak(obr, obr->totvlak++);
MTFace *mtface, *mtface1;
MCol *mcol, *mcol1;
- float *surfnor, *surfnor1;
+ float *surfnor, *surfnor1, *tangent, *tangent1;
+ RadFace **radface, **radface1;
int i, index = vlr1->index;
char *name;
@@ -390,24 +424,31 @@ VlakRen *RE_vlakren_copy(ObjectRen *obr, VlakRen *vlr)
VECCOPY(surfnor1, surfnor);
}
+ tangent= RE_vlakren_get_nmap_tangent(obr, vlr, 0);
+ if(tangent) {
+ tangent1= RE_vlakren_get_nmap_tangent(obr, vlr1, 1);
+ memcpy(tangent1, tangent, sizeof(float)*RE_NMAP_TANGENT_ELEMS);
+ }
+
+ radface= RE_vlakren_get_radface(obr, vlr, 0);
+ if(radface) {
+ radface1= RE_vlakren_get_radface(obr, vlr1, 1);
+ *radface1= *radface;
+ }
+
return vlr1;
}
int RE_vlakren_get_normal(Render *re, ObjectInstanceRen *obi, VlakRen *vlr, float *nor)
{
- float xn, yn, zn, v1[3];
- float (*imat)[3]= obi->imat;
+ float v1[3], (*nmat)[3]= obi->nmat;
int flipped= 0;
if(obi->flag & R_TRANSFORMED) {
- xn= vlr->n[0];
- yn= vlr->n[1];
- zn= vlr->n[2];
+ VECCOPY(nor, vlr->n);
- /* transpose! */
- nor[0]= imat[0][0]*xn+imat[0][1]*yn+imat[0][2]*zn;
- nor[1]= imat[1][0]*xn+imat[1][1]*yn+imat[1][2]*zn;
- nor[2]= imat[2][0]*xn+imat[2][1]*yn+imat[2][2]*zn;
+ Mat3MulVecfl(nmat, nor);
+ Normalize(nor);
}
else
VECCOPY(nor, vlr->n);
@@ -442,16 +483,16 @@ void RE_set_customdata_names(ObjectRen *obr, CustomData *data)
DerivedMesh which stores the layers is freed */
CustomDataLayer *layer;
- int numlayers, i, mtfn, mcn;
+ int numtf = 0, numcol = 0, i, mtfn, mcn;
if (CustomData_has_layer(data, CD_MTFACE)) {
- numlayers= CustomData_number_of_layers(data, CD_MTFACE);
- obr->mtface= MEM_callocN(sizeof(*obr->mtface)*numlayers, "mtfacenames");
+ numtf= CustomData_number_of_layers(data, CD_MTFACE);
+ obr->mtface= MEM_callocN(sizeof(*obr->mtface)*numtf, "mtfacenames");
}
if (CustomData_has_layer(data, CD_MCOL)) {
- numlayers= CustomData_number_of_layers(data, CD_MCOL);
- obr->mcol= MEM_callocN(sizeof(*obr->mcol)*numlayers, "mcolnames");
+ numcol= CustomData_number_of_layers(data, CD_MCOL);
+ obr->mcol= MEM_callocN(sizeof(*obr->mcol)*numcol, "mcolnames");
}
for (i=0, mtfn=0, mcn=0; i < data->totlayer; i++) {
@@ -459,11 +500,12 @@ void RE_set_customdata_names(ObjectRen *obr, CustomData *data)
if (layer->type == CD_MTFACE) {
strcpy(obr->mtface[mtfn++], layer->name);
- obr->actmtface= layer->active_rnd;
+ obr->actmtface= CLAMPIS(layer->active_rnd, 0, numtf);
+ obr->bakemtface= layer->active;
}
else if (layer->type == CD_MCOL) {
strcpy(obr->mcol[mcn++], layer->name);
- obr->actmcol= layer->active_rnd;
+ obr->actmcol= CLAMPIS(layer->active_rnd, 0, numcol);
}
}
}
@@ -516,7 +558,7 @@ float *RE_strandren_get_surfnor(ObjectRen *obr, StrandRen *strand, int verify)
surfnor= obr->strandnodes[nr].surfnor;
if(surfnor==NULL) {
if(verify)
- surfnor= obr->strandnodes[nr].surfnor= MEM_callocN(256*RE_SURFNOR_ELEMS*sizeof(float), "surfnor table");
+ surfnor= obr->strandnodes[nr].surfnor= MEM_callocN(256*RE_SURFNOR_ELEMS*sizeof(float), "surfnor strand table");
else
return NULL;
}
@@ -536,7 +578,7 @@ float *RE_strandren_get_uv(ObjectRen *obr, StrandRen *strand, int n, char **name
float *uv= node->uv;
int size= (n+1)*256;
- node->uv= MEM_callocN(size*sizeof(float)*RE_UV_ELEMS, "Strand uv");
+ node->uv= MEM_callocN(size*sizeof(float)*RE_UV_ELEMS, "strand uv table");
if(uv) {
size= node->totuv*256;
@@ -570,7 +612,7 @@ MCol *RE_strandren_get_mcol(ObjectRen *obr, StrandRen *strand, int n, char **nam
MCol *mcol= node->mcol;
int size= (n+1)*256;
- node->mcol= MEM_callocN(size*sizeof(MCol)*RE_MCOL_ELEMS, "Strand mcol");
+ node->mcol= MEM_callocN(size*sizeof(MCol)*RE_MCOL_ELEMS, "strand mcol table");
if(mcol) {
size= node->totmcol*256;
@@ -599,13 +641,28 @@ float *RE_strandren_get_simplify(struct ObjectRen *obr, struct StrandRen *strand
simplify= obr->strandnodes[nr].simplify;
if(simplify==NULL) {
if(verify)
- simplify= obr->strandnodes[nr].simplify= MEM_callocN(256*RE_SIMPLIFY_ELEMS*sizeof(float), "simplify table");
+ simplify= obr->strandnodes[nr].simplify= MEM_callocN(256*RE_SIMPLIFY_ELEMS*sizeof(float), "simplify strand table");
else
return NULL;
}
return simplify + (strand->index & 255)*RE_SIMPLIFY_ELEMS;
}
+int *RE_strandren_get_face(ObjectRen *obr, StrandRen *strand, int verify)
+{
+ int *face;
+ int nr= strand->index>>8;
+
+ face= obr->strandnodes[nr].face;
+ if(face==NULL) {
+ if(verify)
+ face= obr->strandnodes[nr].face= MEM_callocN(256*RE_FACE_ELEMS*sizeof(int), "face strand table");
+ else
+ return NULL;
+ }
+ return face + (strand->index & 255)*RE_FACE_ELEMS;
+}
+
/* winspeed is exception, it is stored per instance */
float *RE_strandren_get_winspeed(ObjectInstanceRen *obi, StrandRen *strand, int verify)
{
@@ -616,7 +673,7 @@ float *RE_strandren_get_winspeed(ObjectInstanceRen *obi, StrandRen *strand, int
if(winspeed==NULL) {
if(verify) {
totvector= obi->obr->totvert + obi->obr->totstrand;
- winspeed= obi->vectors= MEM_callocN(totvector*RE_WINSPEED_ELEMS*sizeof(float), "winspeed table");
+ winspeed= obi->vectors= MEM_callocN(totvector*RE_WINSPEED_ELEMS*sizeof(float), "winspeed strand table");
}
else
return NULL;
@@ -671,14 +728,14 @@ StrandBuffer *RE_addStrandBuffer(ObjectRen *obr, int totvert)
strandbuf->totvert= totvert;
strandbuf->obr= obr;
- BLI_addtail(&obr->strandbufs, strandbuf);
+ obr->strandbuf= strandbuf;
return strandbuf;
}
/* ------------------------------------------------------------------------ */
-ObjectRen *RE_addRenderObject(Render *re, Object *ob, Object *par, int index, int psysindex)
+ObjectRen *RE_addRenderObject(Render *re, Object *ob, Object *par, int index, int psysindex, int lay)
{
ObjectRen *obr= MEM_callocN(sizeof(ObjectRen), "object render struct");
@@ -687,11 +744,7 @@ ObjectRen *RE_addRenderObject(Render *re, Object *ob, Object *par, int index, in
obr->par= par;
obr->index= index;
obr->psysindex= psysindex;
-
- if(!re->objecthash)
- re->objecthash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
- if(!BLI_ghash_lookup(re->objecthash, ob))
- BLI_ghash_insert(re->objecthash, ob, obr);
+ obr->lay= lay;
return obr;
}
@@ -737,6 +790,10 @@ void free_renderdata_vlaknodes(VlakTableNode *vlaknodes)
MEM_freeN(vlaknodes[a].mcol);
if(vlaknodes[a].surfnor)
MEM_freeN(vlaknodes[a].surfnor);
+ if(vlaknodes[a].tangent)
+ MEM_freeN(vlaknodes[a].tangent);
+ if(vlaknodes[a].radface)
+ MEM_freeN(vlaknodes[a].radface);
}
MEM_freeN(vlaknodes);
@@ -761,6 +818,8 @@ void free_renderdata_strandnodes(StrandTableNode *strandnodes)
MEM_freeN(strandnodes[a].surfnor);
if(strandnodes[a].simplify)
MEM_freeN(strandnodes[a].simplify);
+ if(strandnodes[a].face)
+ MEM_freeN(strandnodes[a].face);
}
MEM_freeN(strandnodes);
@@ -802,9 +861,12 @@ void free_renderdata_tables(Render *re)
obr->strandnodeslen= 0;
}
- for(strandbuf=obr->strandbufs.first; strandbuf; strandbuf=strandbuf->next)
+ strandbuf= obr->strandbuf;
+ if(strandbuf) {
if(strandbuf->vert) MEM_freeN(strandbuf->vert);
- BLI_freelistN(&obr->strandbufs);
+ if(strandbuf->bound) MEM_freeN(strandbuf->bound);
+ MEM_freeN(strandbuf);
+ }
if(obr->mtface)
MEM_freeN(obr->mtface);
@@ -822,27 +884,15 @@ void free_renderdata_tables(Render *re)
re->totinstance= 0;
re->instancetable.first= re->instancetable.last= NULL;
}
- else {
- BLI_freelistN(&re->instancetable);
-
- if(re->objecthash) {
- BLI_ghash_free(re->objecthash, NULL, NULL);
- re->objecthash= NULL;
- }
- }
if(re->sortedhalos) {
MEM_freeN(re->sortedhalos);
re->sortedhalos= NULL;
}
- if(re->strandbuckets) {
- free_buckets(re->strandbuckets);
- re->strandbuckets= NULL;
- }
-
BLI_freelistN(&re->customdata_names);
BLI_freelistN(&re->objecttable);
+ BLI_freelistN(&re->instancetable);
}
/* ------------------------------------------------------------------------ */
@@ -1257,13 +1307,11 @@ void project_renderdata(Render *re, void (*projectfunc)(float *, float mat[][4],
}
}
-
- project_strands(re, projectfunc, do_pano, do_buckets);
}
/* ------------------------------------------------------------------------- */
-void RE_addRenderInstance(Render *re, ObjectRen *obr, Object *ob, Object *par, int index, int psysindex, float mat[][4])
+ObjectInstanceRen *RE_addRenderInstance(Render *re, ObjectRen *obr, Object *ob, Object *par, int index, int psysindex, float mat[][4], int lay)
{
ObjectInstanceRen *obi;
float mat3[3][3];
@@ -1274,15 +1322,19 @@ void RE_addRenderInstance(Render *re, ObjectRen *obr, Object *ob, Object *par, i
obi->par= par;
obi->index= index;
obi->psysindex= psysindex;
+ obi->lay= lay;
if(mat) {
Mat4CpyMat4(obi->mat, mat);
Mat3CpyMat4(mat3, mat);
- Mat3Inv(obi->imat, mat3);
+ Mat3Inv(obi->nmat, mat3);
+ Mat3Transp(obi->nmat);
obi->flag |= R_DUPLI_TRANSFORMED;
}
BLI_addtail(&re->instancetable, obi);
+
+ return obi;
}
void RE_makeRenderInstances(Render *re)
@@ -1301,15 +1353,6 @@ void RE_makeRenderInstances(Render *re)
for(oldobi=re->instancetable.first; oldobi; oldobi=oldobi->next) {
*obi= *oldobi;
- if(!obi->obr) {
- /* dupli objects are created after object instances, so they were
- * stored in a object -> objectren hash, we do lookup of the actual
- * pointer here */
- if(re->objecthash && (obi->obr=BLI_ghash_lookup(re->objecthash, obi->ob)))
- while(obi->obr && obi->obr->psysindex != obi->psysindex)
- obi->obr= obi->obr->next;
- }
-
if(obi->obr) {
obi->prev= obi->next= NULL;
BLI_addtail(&newlist, obi);
@@ -1319,11 +1362,44 @@ void RE_makeRenderInstances(Render *re)
re->totinstance--;
}
- if(re->objecthash) {
- BLI_ghash_free(re->objecthash, NULL, NULL);
- re->objecthash= NULL;
- }
BLI_freelistN(&re->instancetable);
re->instancetable= newlist;
}
+int clip_render_object(float boundbox[][3], float *bounds, float winmat[][4])
+{
+ float mat[4][4], vec[4];
+ int a, fl, flag= -1;
+
+ Mat4CpyMat4(mat, winmat);
+
+ for(a=0; a<8; a++) {
+ vec[0]= (a & 1)? boundbox[0][0]: boundbox[1][0];
+ vec[1]= (a & 2)? boundbox[0][1]: boundbox[1][1];
+ vec[2]= (a & 4)? boundbox[0][2]: boundbox[1][2];
+ vec[3]= 1.0;
+ Mat4MulVec4fl(mat, vec);
+
+ fl= 0;
+ if(bounds) {
+ if(vec[0] > bounds[1]*vec[3]) fl |= 1;
+ if(vec[0]< bounds[0]*vec[3]) fl |= 2;
+ if(vec[1] > bounds[3]*vec[3]) fl |= 4;
+ if(vec[1]< bounds[2]*vec[3]) fl |= 8;
+ }
+ else {
+ if(vec[0] < -vec[3]) fl |= 1;
+ if(vec[0] > vec[3]) fl |= 2;
+ if(vec[1] < -vec[3]) fl |= 4;
+ if(vec[1] > vec[3]) fl |= 8;
+ }
+ if(vec[2] < -vec[3]) fl |= 16;
+ if(vec[2] > vec[3]) fl |= 32;
+
+ flag &= fl;
+ if(flag==0) return 0;
+ }
+
+ return flag;
+}
+
diff --git a/source/blender/render/intern/source/shadbuf.c b/source/blender/render/intern/source/shadbuf.c
index 8e37606cdf9..c53a2b68c9c 100644
--- a/source/blender/render/intern/source/shadbuf.c
+++ b/source/blender/render/intern/source/shadbuf.c
@@ -34,6 +34,7 @@
#include "DNA_material_types.h"
#include "BKE_global.h"
+#include "BKE_scene.h"
#include "BKE_utildefines.h"
#include "BLI_arithb.h"
@@ -54,7 +55,7 @@
/* XXX, could be better implemented... this is for endian issues
*/
-#if defined(__sgi) || defined(__sparc) || defined(__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
+#if defined(__sgi) || defined(__sparc) || defined(__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__hppa__) || defined (__BIG_ENDIAN__)
#define RCOMP 3
#define GCOMP 2
#define BCOMP 1
@@ -140,10 +141,11 @@ static float *give_jitter_tab(int samp)
}
-static void make_jitter_weight_tab(ShadBuf *shb, short filtertype)
+static void make_jitter_weight_tab(Render *re, ShadBuf *shb, short filtertype)
{
float *jit, totw= 0.0f;
- int a, tot=shb->samp*shb->samp;
+ int samp= get_render_shadow_samples(&re->r, shb->samp);
+ int a, tot=samp*samp;
shb->weight= MEM_mallocN(sizeof(float)*tot, "weight tab lamp");
@@ -169,7 +171,7 @@ static void compress_shadowbuf(ShadBuf *shb, int *rectz, int square)
{
ShadSampleBuf *shsample;
float dist;
- unsigned long *ztile;
+ uintptr_t *ztile;
int *rz, *rz1, verg, verg1, size= shb->size;
int a, x, y, minx, miny, byt1, byt2;
char *rc, *rcline, *ctile, *zt;
@@ -177,10 +179,10 @@ static void compress_shadowbuf(ShadBuf *shb, int *rectz, int square)
shsample= MEM_mallocN( sizeof(ShadSampleBuf), "shad sample buf");
BLI_addtail(&shb->buffers, shsample);
- shsample->zbuf= MEM_mallocN( sizeof(unsigned long)*(size*size)/256, "initshadbuf2");
+ shsample->zbuf= MEM_mallocN( sizeof(uintptr_t)*(size*size)/256, "initshadbuf2");
shsample->cbuf= MEM_callocN( (size*size)/256, "initshadbuf3");
- ztile= (unsigned long *)shsample->zbuf;
+ ztile= (uintptr_t *)shsample->zbuf;
ctile= shsample->cbuf;
/* help buffer */
@@ -235,7 +237,7 @@ static void compress_shadowbuf(ShadBuf *shb, int *rectz, int square)
}
if(byt1 && byt2) { /* only store byte */
*ctile= 1;
- *ztile= (unsigned long)MEM_mallocN(256+4, "tile1");
+ *ztile= (uintptr_t)MEM_mallocN(256+4, "tile1");
rz= (int *)*ztile;
*rz= *rz1;
@@ -245,7 +247,7 @@ static void compress_shadowbuf(ShadBuf *shb, int *rectz, int square)
}
else if(byt1) { /* only store short */
*ctile= 2;
- *ztile= (unsigned long)MEM_mallocN(2*256+4,"Tile2");
+ *ztile= (uintptr_t)MEM_mallocN(2*256+4,"Tile2");
rz= (int *)*ztile;
*rz= *rz1;
@@ -258,7 +260,7 @@ static void compress_shadowbuf(ShadBuf *shb, int *rectz, int square)
}
else { /* store triple */
*ctile= 3;
- *ztile= (unsigned long)MEM_mallocN(3*256,"Tile3");
+ *ztile= (uintptr_t)MEM_mallocN(3*256,"Tile3");
zt= (char *)*ztile;
rc= rcline;
@@ -288,15 +290,19 @@ static void shadowbuf_autoclip(Render *re, LampRen *lar)
Material *ma= NULL;
float minz, maxz, vec[3], viewmat[4][4], obviewmat[4][4];
unsigned int lay = -1;
- int i, a, ok= 1;
+ int i, a, maxtotvert, ok= 1;
char *clipflag;
minz= 1.0e30f; maxz= -1.0e30f;
Mat4CpyMat4(viewmat, lar->shb->viewmat);
- if(lar->mode & LA_LAYER) lay= lar->lay;
+ if(lar->mode & (LA_LAYER|LA_LAYER_SHADOW)) lay= lar->lay;
- clipflag= MEM_callocN(sizeof(char)*re->totvert, "autoclipflag");
+ maxtotvert= 0;
+ for(obr=re->objecttable.first; obr; obr=obr->next)
+ maxtotvert= MAX2(obr->totvert, maxtotvert);
+
+ clipflag= MEM_callocN(sizeof(char)*maxtotvert, "autoclipflag");
/* set clip in vertices when face visible */
for(i=0, obi=re->instancetable.first; obi; i++, obi=obi->next) {
@@ -321,7 +327,7 @@ static void shadowbuf_autoclip(Render *re, LampRen *lar)
if((ma->mode & MA_SHADBUF)==0) ok= 0;
}
- if(ok && (vlr->lay & lay)) {
+ if(ok && (obi->lay & lay)) {
clipflag[vlr->v1->index]= 1;
clipflag[vlr->v2->index]= 1;
clipflag[vlr->v3->index]= 1;
@@ -402,8 +408,8 @@ void makeshadowbuf(Render *re, LampRen *lar)
if(ELEM(lar->buftype, LA_SHADBUF_REGULAR, LA_SHADBUF_HALFWAY)) {
/* jitter, weights - not threadsafe! */
BLI_lock_thread(LOCK_CUSTOM1);
- shb->jit= give_jitter_tab(shb->samp);
- make_jitter_weight_tab(shb, lar->filtertype);
+ shb->jit= give_jitter_tab(get_render_shadow_samples(&re->r, shb->samp));
+ make_jitter_weight_tab(re, shb, lar->filtertype);
BLI_unlock_thread(LOCK_CUSTOM1);
shb->totbuf= lar->buffers;
@@ -536,7 +542,7 @@ void freeshadowbuf(LampRen *lar)
v= (shb->size*shb->size)/256;
for(shsample= shb->buffers.first; shsample; shsample= shsample->next) {
- long *ztile= shsample->zbuf;
+ intptr_t *ztile= shsample->zbuf;
char *ctile= shsample->cbuf;
for(b=0; b<v; b++, ztile++, ctile++)
@@ -630,7 +636,7 @@ static float readshadowbuf(ShadBuf *shb, ShadSampleBuf *shsample, int bias, int
else {
/* got warning on this for 64 bits.... */
/* but it's working code! in this case rz is not a pointer but zvalue (ton) */
- zsamp= (int) rz;
+ zsamp= GET_INT_FROM_POINTER(rz);
}
/* tricky stuff here; we use ints which can overflow easily with bias values */
@@ -648,11 +654,11 @@ static float readshadowbuf(ShadBuf *shb, ShadSampleBuf *shsample, int bias, int
/* the externally called shadow testing (reading) function */
/* return 1.0: no shadow at all */
-float testshadowbuf(ShadBuf *shb, float *rco, float *dxco, float *dyco, float inp)
+float testshadowbuf(Render *re, ShadBuf *shb, float *rco, float *dxco, float *dyco, float inp, float mat_bias)
{
ShadSampleBuf *shsample;
float fac, co[4], dx[3], dy[3], shadfac=0.0f;
- float xs1,ys1, siz, *jit, *weight, xres, yres;
+ float xs1,ys1, siz, *jit, *weight, xres, yres, biasf;
int xs, ys, zs, bias, *rz;
short a, num;
@@ -686,13 +692,16 @@ float testshadowbuf(ShadBuf *shb, float *rco, float *dxco, float *dyco, float in
zs= ((float)0x7FFFFFFF)*fac;
/* take num*num samples, increase area with fac */
- num= shb->samp*shb->samp;
+ num= get_render_shadow_samples(&re->r, shb->samp);
+ num= num*num;
fac= shb->soft;
+ if(mat_bias!=0.0f) biasf= shb->bias*mat_bias;
+ else biasf= shb->bias;
/* with inp==1.0, bias is half the size. correction value was 1.1, giving errors
on cube edges, with one side being almost frontal lighted (ton) */
- bias= (1.5f-inp*inp)*shb->bias;
-
+ bias= (1.5f-inp*inp)*biasf;
+
if(num==1) {
for(shsample= shb->buffers.first; shsample; shsample= shsample->next)
shadfac += readshadowbuf(shb, shsample, bias, (int)xs1, (int)ys1, zs);
@@ -807,7 +816,7 @@ static float readshadowbuf_halo(ShadBuf *shb, ShadSampleBuf *shsample, int xs, i
else {
/* same as before */
/* still working code! (ton) */
- zsamp= (int) rz;
+ zsamp= GET_INT_FROM_POINTER(rz);
}
/* NO schadow when sampled at 'eternal' distance */
@@ -1511,7 +1520,7 @@ static void isb_bsp_fillfaces(Render *re, LampRen *lar, ISBBranch *root)
minmaxf[2]= (2.0f*root->box.ymin - size-2.0f)/size;
minmaxf[3]= (2.0f*root->box.ymax - size+2.0f)/size;
- if(lar->mode & LA_LAYER) lay= lar->lay;
+ if(lar->mode & (LA_LAYER|LA_LAYER_SHADOW)) lay= lar->lay;
/* (ab)use zspan, since we use zbuffer clipping code */
zbuf_alloc_span(&zspan, size, size, re->clipcrop);
@@ -1552,7 +1561,7 @@ static void isb_bsp_fillfaces(Render *re, LampRen *lar, ISBBranch *root)
zspanstrand.shad_alpha= zspan.shad_alpha= ma->shad_alpha;
}
- if(ok && (vlr->lay & lay)) {
+ if(ok && (obi->lay & lay)) {
float hoco[4][4];
int c1, c2, c3, c4=0;
int d1, d2, d3, d4=0;
@@ -1743,7 +1752,7 @@ static void isb_make_buffer(RenderPart *pa, LampRen *lar)
ISBSample *samp, *samplebuf[16]; /* should be RE_MAX_OSA */
ISBBranch root;
MemArena *memarena;
- long *rd;
+ intptr_t *rd;
int *recto, *rectp, x, y, sindex, sample, bsp_err=0;
/* storage for shadow, per thread */
diff --git a/source/blender/render/intern/source/shadeinput.c b/source/blender/render/intern/source/shadeinput.c
index f937218cdb6..476330152ec 100644
--- a/source/blender/render/intern/source/shadeinput.c
+++ b/source/blender/render/intern/source/shadeinput.c
@@ -31,6 +31,7 @@
#include "MTC_matrixops.h"
#include "BLI_arithb.h"
+#include "BLI_blenlib.h"
#include "DNA_curve_types.h"
#include "DNA_group_types.h"
@@ -129,7 +130,7 @@ void shade_material_loop(ShadeInput *shi, ShadeResult *shr)
}
/* disable adding of sky for raytransp */
if(shi->mat->mode & MA_RAYTRANSP)
- if(shi->layflag & SCE_LAY_SKY)
+ if((shi->layflag & SCE_LAY_SKY) && (R.r.alphamode==R_ADDSKY))
shr->alpha= 1.0f;
}
}
@@ -161,11 +162,16 @@ void shade_input_do_shade(ShadeInput *shi, ShadeResult *shr)
}
/* MIST */
- if((R.wrld.mode & WO_MIST) && (shi->mat->mode & MA_NOMIST)==0 ) {
+ if((shi->passflag & SCE_PASS_MIST) || ((R.wrld.mode & WO_MIST) && (shi->mat->mode & MA_NOMIST)==0)) {
if(R.r.mode & R_ORTHO)
- alpha= mistfactor(-shi->co[2], shi->co);
+ shr->mist= mistfactor(-shi->co[2], shi->co);
else
- alpha= mistfactor(VecLength(shi->co), shi->co);
+ shr->mist= mistfactor(VecLength(shi->co), shi->co);
+ }
+ else shr->mist= 0.0f;
+
+ if((R.wrld.mode & WO_MIST) && (shi->mat->mode & MA_NOMIST)==0 ) {
+ alpha= shr->mist;
}
else alpha= 1.0f;
@@ -180,6 +186,8 @@ void shade_input_do_shade(ShadeInput *shi, ShadeResult *shr)
}
else shr->combined[3]= 1.0f;
+ /* add z */
+ shr->z= -shi->co[2];
}
/* **************************************************************************** */
@@ -209,19 +217,6 @@ void vlr_set_uv_indices(VlakRen *vlr, int *i1, int *i2, int *i3)
}
}
-static void normal_transform(float imat[][3], float *nor)
-{
- float xn, yn, zn;
-
- xn= nor[0];
- yn= nor[1];
- zn= nor[2];
-
- nor[0]= imat[0][0]*xn+imat[0][1]*yn+imat[0][2]*zn;
- nor[1]= imat[1][0]*xn+imat[1][1]*yn+imat[1][2]*zn;
- nor[2]= imat[2][0]*xn+imat[2][1]*yn+imat[2][2]*zn;
-}
-
/* copy data from face to ShadeInput, general case */
/* indices 0 1 2 3 only */
void shade_input_set_triangle_i(ShadeInput *shi, ObjectInstanceRen *obi, VlakRen *vlr, short i1, short i2, short i3)
@@ -231,7 +226,7 @@ void shade_input_set_triangle_i(ShadeInput *shi, ObjectInstanceRen *obi, VlakRen
shi->vlr= vlr;
shi->obi= obi;
shi->obr= obi->obr;
-
+
shi->v1= vpp[i1];
shi->v2= vpp[i2];
shi->v3= vpp[i3];
@@ -261,9 +256,9 @@ void shade_input_set_triangle_i(ShadeInput *shi, ObjectInstanceRen *obi, VlakRen
VECCOPY(shi->n3, shi->v3->n);
if(obi->flag & R_TRANSFORMED) {
- normal_transform(obi->imat, shi->n1);
- normal_transform(obi->imat, shi->n2);
- normal_transform(obi->imat, shi->n3);
+ Mat3MulVecfl(obi->nmat, shi->n1);
+ Mat3MulVecfl(obi->nmat, shi->n2);
+ Mat3MulVecfl(obi->nmat, shi->n3);
}
if(!(vlr->flag & (R_NOPUNOFLIP|R_TANGENT))) {
@@ -348,10 +343,19 @@ void shade_input_set_strand(ShadeInput *shi, StrandRen *strand, StrandPoint *spo
VECCOPY(shi->orignor, shi->facenor);
/* shade_input_set_normals equivalent */
- if(shi->mat->mode & MA_TANGENT_STR)
+ if(shi->mat->mode & MA_TANGENT_STR) {
VECCOPY(shi->vn, spoint->tan)
- else
- VECCOPY(shi->vn, spoint->nor)
+ }
+ else {
+ float cross[3];
+
+ Crossf(cross, spoint->co, spoint->tan);
+ Crossf(shi->vn, cross, spoint->tan);
+ Normalize(shi->vn);
+
+ if(INPR(shi->vn, shi->view) < 0.0f)
+ VecMulf(shi->vn, -1.0f);
+ }
VECCOPY(shi->vno, shi->vn);
}
@@ -374,6 +378,7 @@ void shade_input_set_strand_texco(ShadeInput *shi, StrandRen *strand, StrandVert
if(mode & (MA_TANGENT_V|MA_NORMAP_TANG)) {
VECCOPY(shi->tang, spoint->tan);
+ VECCOPY(shi->nmaptang, spoint->tan);
}
if(mode & MA_STR_SURFDIFF) {
@@ -388,7 +393,7 @@ void shade_input_set_strand_texco(ShadeInput *shi, StrandRen *strand, StrandVert
shi->surfdist= 0.0f;
for(sv=strand->vert; sv!=svert; sv++)
shi->surfdist+=VecLenf(sv->co, (sv+1)->co);
- shi->surfdist += 0.5f*(spoint->strandco+1.0f)*VecLenf(sv->co, (sv+1)->co);
+ shi->surfdist += spoint->t*VecLenf(sv->co, (sv+1)->co);
}
}
@@ -422,7 +427,7 @@ void shade_input_set_strand_texco(ShadeInput *shi, StrandRen *strand, StrandVert
}
if(texco & TEXCO_STRAND) {
- shi->strand= spoint->strandco;
+ shi->strandco= spoint->strandco;
if(shi->osatex) {
shi->dxstrand= spoint->dtstrandco;
@@ -438,6 +443,8 @@ void shade_input_set_strand_texco(ShadeInput *shi, StrandRen *strand, StrandVert
shi->totuv= 0;
shi->totcol= 0;
+ shi->actuv= obr->actmtface;
+ shi->actcol= obr->actmcol;
if(mode & (MA_VERTEXCOL|MA_VERTEXCOLP)) {
for (i=0; (mcol=RE_strandren_get_mcol(obr, strand, i, &name, 0)); i++) {
@@ -447,15 +454,15 @@ void shade_input_set_strand_texco(ShadeInput *shi, StrandRen *strand, StrandVert
shi->totcol++;
scol->name= name;
- scol->col[0]= cp[0]/255.0f;
- scol->col[1]= cp[1]/255.0f;
- scol->col[2]= cp[2]/255.0f;
+ scol->col[0]= cp[3]/255.0f;
+ scol->col[1]= cp[2]/255.0f;
+ scol->col[2]= cp[1]/255.0f;
}
if(shi->totcol) {
- shi->vcol[0]= shi->col[0].col[0];
- shi->vcol[1]= shi->col[0].col[1];
- shi->vcol[2]= shi->col[0].col[2];
+ shi->vcol[0]= shi->col[shi->actcol].col[0];
+ shi->vcol[1]= shi->col[shi->actcol].col[1];
+ shi->vcol[2]= shi->col[shi->actcol].col[2];
}
else {
shi->vcol[0]= 0.0f;
@@ -488,7 +495,7 @@ void shade_input_set_strand_texco(ShadeInput *shi, StrandRen *strand, StrandVert
suv->dyuv[1]= 0.0f;
}
- if((mode & MA_FACETEXTURE) && i==0) {
+ if((mode & MA_FACETEXTURE) && i==obr->actmtface) {
if((mode & (MA_VERTEXCOL|MA_VERTEXCOLP))==0) {
shi->vcol[0]= 1.0f;
shi->vcol[1]= 1.0f;
@@ -537,6 +544,7 @@ void shade_input_set_strand_texco(ShadeInput *shi, StrandRen *strand, StrandVert
if((mode & MA_TANGENT_V)==0) {
/* just prevent surprises */
shi->tang[0]= shi->tang[1]= shi->tang[2]= 0.0f;
+ shi->nmaptang[0]= shi->nmaptang[1]= shi->nmaptang[2]= 0.0f;
}
}
}
@@ -565,31 +573,25 @@ void shade_input_set_strand_texco(ShadeInput *shi, StrandRen *strand, StrandVert
}
}
-/* scanline pixel coordinates */
-/* requires set_triangle */
-void shade_input_set_viewco(ShadeInput *shi, float x, float y, float z)
+/* from scanline pixel coordinates to 3d coordinates, requires set_triangle */
+void shade_input_calc_viewco(ShadeInput *shi, float x, float y, float z, float *view, float *dxyview, float *co, float *dxco, float *dyco)
{
- float fac;
-
- /* currently in use for dithering (soft shadow), node preview, irregular shad */
- shi->xs= (int)(x);
- shi->ys= (int)(y);
+ /* returns not normalized, so is in viewplane coords */
+ calc_view_vector(view, x, y);
- calc_view_vector(shi->view, x, y); /* returns not normalized, so is in viewplane coords */
-
- /* wire cannot use normal for calculating shi->co */
if(shi->mat->mode & MA_WIRE) {
-
+ /* wire cannot use normal for calculating shi->co, so
+ * we reconstruct the coordinate less accurate */
if(R.r.mode & R_ORTHO)
- calc_renderco_ortho(shi->co, x, y, z);
+ calc_renderco_ortho(co, x, y, z);
else
- calc_renderco_zbuf(shi->co, shi->view, z);
+ calc_renderco_zbuf(co, view, z);
}
else {
- float dface, v1[3];
+ /* for non-wire, intersect with the triangle to get the exact coord */
+ float fac, dface, v1[3];
VECCOPY(v1, shi->v1->co);
-
if(shi->obi->flag & R_TRANSFORMED)
Mat4MulVecfl(shi->obi->mat, v1);
@@ -601,72 +603,98 @@ void shade_input_set_viewco(ShadeInput *shi, float x, float y, float z)
float fx= 2.0f/(R.winx*R.winmat[0][0]);
float fy= 2.0f/(R.winy*R.winmat[1][1]);
- shi->co[0]= (x - 0.5f*R.winx)*fx - R.winmat[3][0]/R.winmat[0][0];
- shi->co[1]= (y - 0.5f*R.winy)*fy - R.winmat[3][1]/R.winmat[1][1];
+ co[0]= (x - 0.5f*R.winx)*fx - R.winmat[3][0]/R.winmat[0][0];
+ co[1]= (y - 0.5f*R.winy)*fy - R.winmat[3][1]/R.winmat[1][1];
/* using a*x + b*y + c*z = d equation, (a b c) is normal */
if(shi->facenor[2]!=0.0f)
- shi->co[2]= (dface - shi->facenor[0]*shi->co[0] - shi->facenor[1]*shi->co[1])/shi->facenor[2];
+ co[2]= (dface - shi->facenor[0]*co[0] - shi->facenor[1]*co[1])/shi->facenor[2];
else
- shi->co[2]= 0.0f;
+ co[2]= 0.0f;
- if(shi->osatex || (R.r.mode & R_SHADOW) ) {
- shi->dxco[0]= fx;
- shi->dxco[1]= 0.0f;
+ if(dxco && dyco) {
+ dxco[0]= fx;
+ dxco[1]= 0.0f;
if(shi->facenor[2]!=0.0f)
- shi->dxco[2]= (shi->facenor[0]*fx)/shi->facenor[2];
+ dxco[2]= (shi->facenor[0]*fx)/shi->facenor[2];
else
- shi->dxco[2]= 0.0f;
+ dxco[2]= 0.0f;
- shi->dyco[0]= 0.0f;
- shi->dyco[1]= fy;
+ dyco[0]= 0.0f;
+ dyco[1]= fy;
if(shi->facenor[2]!=0.0f)
- shi->dyco[2]= (shi->facenor[1]*fy)/shi->facenor[2];
+ dyco[2]= (shi->facenor[1]*fy)/shi->facenor[2];
else
- shi->dyco[2]= 0.0f;
+ dyco[2]= 0.0f;
- if( (shi->mat->texco & TEXCO_REFL) ) {
- if(shi->co[2]!=0.0f) fac= 1.0f/shi->co[2]; else fac= 0.0f;
- shi->dxview= -R.viewdx*fac;
- shi->dyview= -R.viewdy*fac;
+ if(dxyview) {
+ if(co[2]!=0.0f) fac= 1.0f/co[2]; else fac= 0.0f;
+ dxyview[0]= -R.viewdx*fac;
+ dxyview[1]= -R.viewdy*fac;
}
}
}
else {
float div;
- div= shi->facenor[0]*shi->view[0] + shi->facenor[1]*shi->view[1] + shi->facenor[2]*shi->view[2];
+ div= shi->facenor[0]*view[0] + shi->facenor[1]*view[1] + shi->facenor[2]*view[2];
if (div!=0.0f) fac= dface/div;
else fac= 0.0f;
- shi->co[0]= fac*shi->view[0];
- shi->co[1]= fac*shi->view[1];
- shi->co[2]= fac*shi->view[2];
+ co[0]= fac*view[0];
+ co[1]= fac*view[1];
+ co[2]= fac*view[2];
/* pixel dx/dy for render coord */
- if(shi->osatex || (R.r.mode & R_SHADOW) ) {
+ if(dxco && dyco) {
float u= dface/(div - R.viewdx*shi->facenor[0]);
float v= dface/(div - R.viewdy*shi->facenor[1]);
- shi->dxco[0]= shi->co[0]- (shi->view[0]-R.viewdx)*u;
- shi->dxco[1]= shi->co[1]- (shi->view[1])*u;
- shi->dxco[2]= shi->co[2]- (shi->view[2])*u;
+ dxco[0]= co[0]- (view[0]-R.viewdx)*u;
+ dxco[1]= co[1]- (view[1])*u;
+ dxco[2]= co[2]- (view[2])*u;
- shi->dyco[0]= shi->co[0]- (shi->view[0])*v;
- shi->dyco[1]= shi->co[1]- (shi->view[1]-R.viewdy)*v;
- shi->dyco[2]= shi->co[2]- (shi->view[2])*v;
+ dyco[0]= co[0]- (view[0])*v;
+ dyco[1]= co[1]- (view[1]-R.viewdy)*v;
+ dyco[2]= co[2]- (view[2])*v;
- if( (shi->mat->texco & TEXCO_REFL) ) {
+ if(dxyview) {
if(fac!=0.0f) fac= 1.0f/fac;
- shi->dxview= -R.viewdx*fac;
- shi->dyview= -R.viewdy*fac;
+ dxyview[0]= -R.viewdx*fac;
+ dxyview[1]= -R.viewdy*fac;
}
}
}
}
/* cannot normalize earlier, code above needs it at viewplane level */
- Normalize(shi->view);
+ Normalize(view);
+}
+
+/* from scanline pixel coordinates to 3d coordinates, requires set_triangle */
+void shade_input_set_viewco(ShadeInput *shi, float x, float y, float xs, float ys, float z)
+{
+ float *dxyview= NULL, *dxco= NULL, *dyco= NULL;
+
+ /* currently in use for dithering (soft shadow), node preview, irregular shad */
+ shi->xs= (int)xs;
+ shi->ys= (int)ys;
+
+ /* original scanline coordinate without jitter */
+ shi->scanco[0]= x;
+ shi->scanco[1]= y;
+ shi->scanco[2]= z;
+
+ /* check if we need derivatives */
+ if(shi->osatex || (R.r.mode & R_SHADOW)) {
+ dxco= shi->dxco;
+ dyco= shi->dyco;
+
+ if((shi->mat->texco & TEXCO_REFL))
+ dxyview= &shi->dxview;
+ }
+
+ shade_input_calc_viewco(shi, xs, ys, z, shi->view, dxyview, shi->co, dxco, dyco);
}
/* calculate U and V, for scanline (silly render face u and v are in range -1 to 0) */
@@ -798,7 +826,7 @@ void shade_input_set_shade_texco(ShadeInput *shi)
int mode= shi->mode; /* or-ed result for all nodes */
short texco= shi->mat->texco;
- /* calculate dxno and tangents */
+ /* calculate dxno */
if(shi->vlr->flag & R_SMOOTH) {
if(shi->osatex && (texco & (TEXCO_NORM|TEXCO_REFL)) ) {
@@ -814,47 +842,68 @@ void shade_input_set_shade_texco(ShadeInput *shi)
shi->dyno[2]= dl*n3[2]-shi->dy_u*n1[2]-shi->dy_v*n2[2];
}
-
- /* qdn: normalmap tangent space */
- if (mode & (MA_TANGENT_V|MA_NORMAP_TANG) || R.flag & R_NEED_TANGENT) {
- float *s1, *s2, *s3;
+ }
+
+ /* calc tangents */
+ if (mode & (MA_TANGENT_V|MA_NORMAP_TANG) || R.flag & R_NEED_TANGENT) {
+ float *tangent, *s1, *s2, *s3;
+ float tl, tu, tv;
+
+ if(shi->vlr->flag & R_SMOOTH) {
+ tl= l;
+ tu= u;
+ tv= v;
+ }
+ else {
+ /* qdn: flat faces have tangents too,
+ could pick either one, using average here */
+ tl= 1.0f/3.0f;
+ tu= -1.0f/3.0f;
+ tv= -1.0f/3.0f;
+ }
+
+ shi->tang[0]= shi->tang[1]= shi->tang[2]= 0.0f;
+ shi->nmaptang[0]= shi->nmaptang[1]= shi->nmaptang[2]= 0.0f;
+
+ if(mode & MA_TANGENT_V) {
+ s1 = RE_vertren_get_tangent(obr, v1, 0);
+ s2 = RE_vertren_get_tangent(obr, v2, 0);
+ s3 = RE_vertren_get_tangent(obr, v3, 0);
- s1= RE_vertren_get_tangent(obr, v1, 0);
- s2= RE_vertren_get_tangent(obr, v2, 0);
- s3= RE_vertren_get_tangent(obr, v3, 0);
if(s1 && s2 && s3) {
- shi->tang[0]= (l*s3[0] - u*s1[0] - v*s2[0]);
- shi->tang[1]= (l*s3[1] - u*s1[1] - v*s2[1]);
- shi->tang[2]= (l*s3[2] - u*s1[2] - v*s2[2]);
+ shi->tang[0]= (tl*s3[0] - tu*s1[0] - tv*s2[0]);
+ shi->tang[1]= (tl*s3[1] - tu*s1[1] - tv*s2[1]);
+ shi->tang[2]= (tl*s3[2] - tu*s1[2] - tv*s2[2]);
if(obi->flag & R_TRANSFORMED)
- normal_transform(obi->imat, shi->tang);
+ Mat3MulVecfl(obi->nmat, shi->tang);
- /* qdn: normalize just in case */
Normalize(shi->tang);
+ VECCOPY(shi->nmaptang, shi->tang);
}
- else shi->tang[0]= shi->tang[1]= shi->tang[2]= 0.0f;
}
- }
- else {
- /* qdn: normalmap tangent space */
- if (mode & (MA_TANGENT_V|MA_NORMAP_TANG) || R.flag & R_NEED_TANGENT) {
- /* qdn: flat faces have tangents too,
- could pick either one, using average here */
- float *s1 = RE_vertren_get_tangent(obr, v1, 0);
- float *s2 = RE_vertren_get_tangent(obr, v2, 0);
- float *s3 = RE_vertren_get_tangent(obr, v3, 0);
- if (s1 && s2 && s3) {
- shi->tang[0] = (s1[0] + s2[0] + s3[0]);
- shi->tang[1] = (s1[1] + s2[1] + s3[1]);
- shi->tang[2] = (s1[2] + s2[2] + s3[2]);
+
+ if(mode & MA_NORMAP_TANG || R.flag & R_NEED_TANGENT) {
+ tangent= RE_vlakren_get_nmap_tangent(obr, shi->vlr, 0);
+
+ if(tangent) {
+ int j1= shi->i1, j2= shi->i2, j3= shi->i3;
+
+ vlr_set_uv_indices(shi->vlr, &j1, &j2, &j3);
+
+ s1= &tangent[j1*3];
+ s2= &tangent[j2*3];
+ s3= &tangent[j3*3];
+
+ shi->nmaptang[0]= (tl*s3[0] - tu*s1[0] - tv*s2[0]);
+ shi->nmaptang[1]= (tl*s3[1] - tu*s1[1] - tv*s2[1]);
+ shi->nmaptang[2]= (tl*s3[2] - tu*s1[2] - tv*s2[2]);
if(obi->flag & R_TRANSFORMED)
- normal_transform(obi->imat, shi->tang);
+ Mat3MulVecfl(obi->nmat, shi->nmaptang);
- Normalize(shi->tang);
+ Normalize(shi->nmaptang);
}
- else shi->tang[0]= shi->tang[1]= shi->tang[2]= 0.0f;
}
}
@@ -864,7 +913,7 @@ void shade_input_set_shade_texco(ShadeInput *shi)
if(surfnor) {
VECCOPY(shi->surfnor, surfnor)
if(obi->flag & R_TRANSFORMED)
- normal_transform(obi->imat, shi->surfnor);
+ Mat3MulVecfl(obi->nmat, shi->surfnor);
}
else
VECCOPY(shi->surfnor, shi->vn)
@@ -919,6 +968,8 @@ void shade_input_set_shade_texco(ShadeInput *shi)
shi->dylo[2]= dl*o3[2]-shi->dy_u*o1[2]-shi->dy_v*o2[2];
}
}
+
+ VECCOPY(shi->duplilo, obi->dupliorco);
}
if(texco & TEXCO_GLOB) {
@@ -933,7 +984,7 @@ void shade_input_set_shade_texco(ShadeInput *shi)
}
if(texco & TEXCO_STRAND) {
- shi->strand= (l*v3->accum - u*v1->accum - v*v2->accum);
+ shi->strandco= (l*v3->accum - u*v1->accum - v*v2->accum);
if(shi->osatex) {
dl= shi->dx_u+shi->dx_v;
shi->dxstrand= dl*v3->accum-shi->dx_u*v1->accum-shi->dx_v*v2->accum;
@@ -975,9 +1026,9 @@ void shade_input_set_shade_texco(ShadeInput *shi)
}
if(shi->totcol) {
- shi->vcol[0]= shi->col[0].col[0];
- shi->vcol[1]= shi->col[0].col[1];
- shi->vcol[2]= shi->col[0].col[2];
+ shi->vcol[0]= shi->col[shi->actcol].col[0];
+ shi->vcol[1]= shi->col[shi->actcol].col[1];
+ shi->vcol[2]= shi->col[shi->actcol].col[2];
shi->vcol[3]= 1.0f;
}
else {
@@ -1033,6 +1084,10 @@ void shade_input_set_shade_texco(ShadeInput *shi)
}
}
+ shi->dupliuv[0]= -1.0f + 2.0f*obi->dupliuv[0];
+ shi->dupliuv[1]= -1.0f + 2.0f*obi->dupliuv[1];
+ shi->dupliuv[2]= 0.0f;
+
if(shi->totuv == 0) {
ShadeInputUV *suv= &shi->uv[0];
@@ -1097,6 +1152,7 @@ void shade_input_set_shade_texco(ShadeInput *shi)
if((mode & MA_TANGENT_V)==0) {
/* just prevent surprises */
shi->tang[0]= shi->tang[1]= shi->tang[2]= 0.0f;
+ shi->nmaptang[0]= shi->nmaptang[1]= shi->nmaptang[2]= 0.0f;
}
}
}
@@ -1181,7 +1237,9 @@ void shade_input_set_shade_texco(ShadeInput *shi)
}
}
}
- }
+ } /* else {
+ Note! For raytracing winco is not set, important because thus means all shader input's need to have their variables set to zero else in-initialized values are used
+ */
}
/* ****************** ShadeSample ************************************** */
@@ -1201,8 +1259,9 @@ void shade_input_initialize(ShadeInput *shi, RenderPart *pa, RenderLayer *rl, in
shi->combinedflag= ~rl->pass_xor;
shi->mat_override= rl->mat_override;
shi->light_override= rl->light_override;
-
+// shi->rl= rl;
/* note shi.depth==0 means first hit, not raytracing */
+
}
/* initialize per part, not per pixel! */
@@ -1217,7 +1276,7 @@ void shade_sample_initialize(ShadeSample *ssamp, RenderPart *pa, RenderLayer *rl
memset(&ssamp->shr[a], 0, sizeof(ShadeResult));
}
- ssamp->samplenr= 0; /* counter, detect shadow-reuse for shaders */
+ get_sample_layers(pa, rl, ssamp->rlpp);
}
/* Do AO or (future) GI */
@@ -1228,19 +1287,22 @@ void shade_samples_do_AO(ShadeSample *ssamp)
if(!(R.r.mode & R_SHADOW))
return;
- if(!(R.r.mode & R_RAYTRACE))
+ if(!(R.r.mode & R_RAYTRACE) && !(R.wrld.ao_gather_method == WO_AOGATHER_APPROX))
return;
- if(R.wrld.mode & WO_AMB_OCC)
- if(ssamp->shi[0].passflag & (SCE_PASS_COMBINED|SCE_PASS_AO))
+ if(R.wrld.mode & WO_AMB_OCC) {
+ shi= &ssamp->shi[0];
+
+ if(((shi->passflag & SCE_PASS_COMBINED) && (shi->combinedflag & SCE_PASS_AO))
+ || (shi->passflag & SCE_PASS_AO))
for(sample=0, shi= ssamp->shi; sample<ssamp->tot; shi++, sample++)
if(!(shi->mode & MA_SHLESS))
ambient_occlusion(shi); /* stores in shi->ao[] */
-
+ }
}
-static void shade_samples_fill_with_ps(ShadeSample *ssamp, PixStr *ps, int x, int y)
+void shade_samples_fill_with_ps(ShadeSample *ssamp, PixStr *ps, int x, int y)
{
ShadeInput *shi;
float xs, ys;
@@ -1259,15 +1321,17 @@ static void shade_samples_fill_with_ps(ShadeSample *ssamp, PixStr *ps, int x, in
for(samp=0; samp<R.osa; samp++) {
if(curmask & (1<<samp)) {
- xs= (float)x + R.jit[samp][0] + 0.5f; /* zbuffer has this inverse corrected, ensures xs,ys are inside pixel */
+ /* zbuffer has this inverse corrected, ensures xs,ys are inside pixel */
+ xs= (float)x + R.jit[samp][0] + 0.5f;
ys= (float)y + R.jit[samp][1] + 0.5f;
if(shi_cp)
shade_input_copy_triangle(shi, shi-1);
shi->mask= (1<<samp);
- shi->samplenr= ssamp->samplenr++;
- shade_input_set_viewco(shi, xs, ys, (float)ps->z);
+// shi->rl= ssamp->rlpp[samp];
+ shi->samplenr= R.shadowsamplenr[shi->thread]++; /* this counter is not being reset per pixel */
+ shade_input_set_viewco(shi, x, y, xs, ys, (float)ps->z);
shade_input_set_uv(shi);
shade_input_set_normals(shi);
@@ -1286,9 +1350,10 @@ static void shade_samples_fill_with_ps(ShadeSample *ssamp, PixStr *ps, int x, in
xs= (float)x + 0.5f;
ys= (float)y + 0.5f;
}
+
shi->mask= curmask;
- shi->samplenr= ssamp->samplenr++;
- shade_input_set_viewco(shi, xs, ys, (float)ps->z);
+ shi->samplenr= R.shadowsamplenr[shi->thread]++;
+ shade_input_set_viewco(shi, x, y, xs, ys, (float)ps->z);
shade_input_set_uv(shi);
shade_input_set_normals(shi);
shi++;
diff --git a/source/blender/render/intern/source/shadeoutput.c b/source/blender/render/intern/source/shadeoutput.c
index a08046da0da..4c627056c1d 100644
--- a/source/blender/render/intern/source/shadeoutput.c
+++ b/source/blender/render/intern/source/shadeoutput.c
@@ -43,6 +43,7 @@
#include "DNA_material_types.h"
/* local include */
+#include "occlusion.h"
#include "renderpipeline.h"
#include "render_types.h"
#include "pixelblending.h"
@@ -354,7 +355,7 @@ void renderspothalo(ShadeInput *shi, float *col, float alpha)
if(lar->type==LA_SPOT && (lar->mode & LA_HALO) && lar->haint>0) {
if(lar->mode & LA_LAYER)
- if(shi->vlr && (lar->lay & shi->vlr->lay)==0)
+ if(shi->vlr && (lar->lay & shi->obi->lay)==0)
continue;
if((lar->lay & shi->lay)==0)
continue;
@@ -428,10 +429,6 @@ static float area_lamp_energy(float (*area)[3], float *co, float *vn)
double cross[4][3]; /* cross products of this */
double rad[4]; /* angles between vecs */
- /* extra test for dot */
- if ( INPR(co, vn) <= 0.0f)
- return 0.0f;
-
VECSUB(vec[0], co, area[0]);
VECSUB(vec[1], co, area[1]);
VECSUB(vec[2], co, area[2]);
@@ -480,8 +477,12 @@ static float area_lamp_energy_multisample(LampRen *lar, float *co, float *vn)
float *jitlamp= lar->jitter, vec[3];
float area[4][3], intens= 0.0f;
int a= lar->ray_totsamp;
-
-
+
+ /* test if co is behind lamp */
+ VECSUB(vec, co, lar->co);
+ if(INPR(vec, lar->vec) < 0.0f)
+ return 0.0f;
+
while(a--) {
vec[0]= jitlamp[0];
vec[1]= jitlamp[1];
@@ -1006,8 +1007,9 @@ static void do_specular_ramp(ShadeInput *shi, float is, float t, float *spec)
/* pure AO, check for raytrace and world should have been done */
void ambient_occlusion(ShadeInput *shi)
{
-
- if((R.r.mode & R_RAYTRACE) && shi->mat->amb!=0.0f)
+ if((R.wrld.ao_gather_method == WO_AOGATHER_APPROX) && shi->mat->amb!=0.0f)
+ sample_occ(&R, shi);
+ else if((R.r.mode & R_RAYTRACE) && shi->mat->amb!=0.0f)
ray_ao(shi, shi->ao);
else
shi->ao[0]= shi->ao[1]= shi->ao[2]= 1.0f;
@@ -1017,25 +1019,28 @@ void ambient_occlusion(ShadeInput *shi)
/* wrld mode was checked for */
void ambient_occlusion_to_diffuse(ShadeInput *shi, float *diff)
{
-
- if((R.r.mode & R_RAYTRACE) && shi->mat->amb!=0.0f) {
- float f= R.wrld.aoenergy*shi->mat->amb;
-
- if (R.wrld.aomix==WO_AOADDSUB) {
- diff[0] = 2.0f*shi->ao[0]-1.0f;
- diff[1] = 2.0f*shi->ao[1]-1.0f;
- diff[2] = 2.0f*shi->ao[2]-1.0f;
- }
- else if (R.wrld.aomix==WO_AOSUB) {
- diff[0] = shi->ao[0]-1.0f;
- diff[1] = shi->ao[1]-1.0f;
- diff[2] = shi->ao[2]-1.0f;
- }
- else {
- VECCOPY(diff, shi->ao);
+ if((R.r.mode & R_RAYTRACE) || R.wrld.ao_gather_method == WO_AOGATHER_APPROX) {
+ if(shi->mat->amb!=0.0f) {
+ float f= R.wrld.aoenergy*shi->mat->amb;
+
+ if (R.wrld.aomix==WO_AOADDSUB) {
+ diff[0] = 2.0f*shi->ao[0]-1.0f;
+ diff[1] = 2.0f*shi->ao[1]-1.0f;
+ diff[2] = 2.0f*shi->ao[2]-1.0f;
+ }
+ else if (R.wrld.aomix==WO_AOSUB) {
+ diff[0] = shi->ao[0]-1.0f;
+ diff[1] = shi->ao[1]-1.0f;
+ diff[2] = shi->ao[2]-1.0f;
+ }
+ else {
+ VECCOPY(diff, shi->ao);
+ }
+
+ VECMUL(diff, f);
}
-
- VECMUL(diff, f);
+ else
+ diff[0]= diff[1]= diff[2]= 0.0f;
}
else
diff[0]= diff[1]= diff[2]= 0.0f;
@@ -1054,7 +1059,7 @@ void lamp_get_shadow(LampRen *lar, ShadeInput *shi, float inp, float *shadfac, i
if(lar->buftype==LA_SHADBUF_IRREGULAR)
shadfac[3]= ISB_getshadow(shi, lar->shb);
else
- shadfac[3] = testshadowbuf(lar->shb, shi->co, shi->dxco, shi->dyco, inp);
+ shadfac[3] = testshadowbuf(&R, lar->shb, shi->co, shi->dxco, shi->dyco, inp, shi->mat->lbias);
}
else if(lar->mode & LA_SHAD_RAY) {
ray_shadow(shi, lar, shadfac);
@@ -1174,15 +1179,18 @@ static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int
{
Material *ma= shi->mat;
VlakRen *vlr= shi->vlr;
- float lv[3], lampdist, lacol[3], shadfac[4];
+ float lv[3], lampdist, lacol[3], shadfac[4], lashdw[3];
float i, is, i_noshad, inp, *vn, *view, vnor[3], phongcorr=1.0f;
float visifac;
vn= shi->vn;
view= shi->view;
- if (lar->energy == 0.0) return;
+ if (lar->energy == 0.0) return;
+ /* only shadow lamps shouldn't affect shadow-less materials at all */
+ if ((lar->mode & LA_ONLYSHADOW) && (!(ma->mode & MA_SHADOW) || !(R.r.mode & R_SHADOW)))
+ return;
/* optimisation, don't render fully black lamps */
if (!(lar->mode & LA_TEXTURE) && (lar->r + lar->g + lar->b == 0.0f))
return;
@@ -1211,7 +1219,12 @@ static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int
lacol[1]= lar->g;
lacol[2]= lar->b;
- if(lar->mode & LA_TEXTURE) do_lamp_tex(lar, lv, shi, lacol);
+ lashdw[0]= lar->shdwr;
+ lashdw[1]= lar->shdwg;
+ lashdw[2]= lar->shdwb;
+
+ if(lar->mode & LA_TEXTURE) do_lamp_tex(lar, lv, shi, lacol, LA_TEXTURE);
+ if(lar->mode & LA_SHAD_TEX) do_lamp_tex(lar, lv, shi, lashdw, LA_SHAD_TEX);
/* tangent case; calculate fake face normal, aligned with lampvector */
/* note, vnor==vn is used as tangent trigger for buffer shadow */
@@ -1223,6 +1236,7 @@ static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int
Crossf(nstrand, vn, cross);
blend= INPR(nstrand, shi->surfnor);
+ blend= 1.0f - blend;
CLAMP(blend, 0.0f, 1.0f);
VecLerpf(vnor, nstrand, shi->surfnor, blend);
@@ -1231,6 +1245,7 @@ static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int
else {
Crossf(cross, lv, vn);
Crossf(vnor, cross, vn);
+ Normalize(vnor);
}
if(ma->strand_surfnor > 0.0f) {
@@ -1248,6 +1263,7 @@ static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int
float cross[3];
Crossf(cross, lv, shi->tang);
Crossf(vnor, cross, shi->tang);
+ Normalize(vnor);
vnor[0]= -vnor[0];vnor[1]= -vnor[1];vnor[2]= -vnor[2];
vn= vnor;
}
@@ -1297,7 +1313,10 @@ static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int
else is= inp; // Lambert
}
- /* i is diffuse */
+ /* 'is' is diffuse */
+ if((ma->shade_flag & MA_CUBIC) && is>0.0f && is<1.0f)
+ is= 3.0*is*is - 2.0*is*is*is; // nicer termination of shades
+
i= is*phongcorr;
if(i>0.0f) {
@@ -1328,13 +1347,13 @@ static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int
if((lar->mode & LA_ONLYSHADOW) && i>0.0) {
shadfac[3]= i*lar->energy*(1.0f-shadfac[3]);
- shr->shad[0] -= shadfac[3]*shi->r;
- shr->shad[1] -= shadfac[3]*shi->g;
- shr->shad[2] -= shadfac[3]*shi->b;
+ shr->shad[0] -= shadfac[3]*shi->r*(1.0f-lashdw[0]);
+ shr->shad[1] -= shadfac[3]*shi->g*(1.0f-lashdw[1]);
+ shr->shad[2] -= shadfac[3]*shi->b*(1.0f-lashdw[2]);
- shr->spec[0] -= shadfac[3]*shi->specr;
- shr->spec[1] -= shadfac[3]*shi->specg;
- shr->spec[2] -= shadfac[3]*shi->specb;
+ shr->spec[0] -= shadfac[3]*shi->specr*(1.0f-lashdw[0]);
+ shr->spec[1] -= shadfac[3]*shi->specg*(1.0f-lashdw[1]);
+ shr->spec[2] -= shadfac[3]*shi->specb*(1.0f-lashdw[2]);
return;
}
@@ -1352,6 +1371,10 @@ static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int
else
add_to_diffuse(shr->shad, shi, is, i*lacol[0], i*lacol[1], i*lacol[2]);
}
+ /* add light for colored shadow */
+ if (i_noshad>i && !(lashdw[0]==0 && lashdw[1]==0 && lashdw[2]==0)) {
+ add_to_diffuse(shr->shad, shi, is, lashdw[0]*(i_noshad-i)*lacol[0], lashdw[1]*(i_noshad-i)*lacol[1], lashdw[2]*(i_noshad-i)*lacol[2]);
+ }
if(i_noshad>0.0f) {
if(passflag & (SCE_PASS_DIFFUSE|SCE_PASS_SHADOW)) {
if(ma->mode & MA_SHADOW_TRA)
@@ -1365,6 +1388,8 @@ static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int
}
/* specularity */
+ shadfac[3]*= phongcorr; /* note, shadfac not allowed to be stored nonlocal */
+
if(shadfac[3]>0.0f && shi->spec!=0.0f && !(lar->mode & LA_NO_SPEC) && !(lar->mode & LA_ONLYSHADOW)) {
if(!(passflag & (SCE_PASS_COMBINED|SCE_PASS_SPEC)));
@@ -1435,10 +1460,10 @@ static void shade_lamp_loop_only_shadow(ShadeInput *shi, ShadeResult *shr)
LampRen *lar;
GroupObject *go;
float inpr, lv[3];
- float *vn, *view, shadfac[4];
+ float *view, shadfac[4];
float ir, accum, visifac, lampdist;
- vn= shi->vn;
+
view= shi->view;
accum= ir= 0.0f;
@@ -1451,7 +1476,7 @@ static void shade_lamp_loop_only_shadow(ShadeInput *shi, ShadeResult *shr)
/* yafray: ignore shading by photonlights, not used in Blender */
if (lar->type==LA_YF_PHOTON) continue;
- if(lar->mode & LA_LAYER) if((lar->lay & shi->vlr->lay)==0) continue;
+ if(lar->mode & LA_LAYER) if((lar->lay & shi->obi->lay)==0) continue;
if((lar->lay & shi->lay)==0) continue;
if(lar->shb || (lar->mode & LA_SHAD_RAY)) {
@@ -1501,8 +1526,10 @@ static void shade_lamp_loop_only_shadow(ShadeInput *shi, ShadeResult *shr)
}
}
+/* let's map negative light as if it mirrors positive light, otherwise negative values disappear */
static void wrld_exposure_correct(float *diff)
{
+
diff[0]= R.wrld.linfac*(1.0f-exp( diff[0]*R.wrld.logfac) );
diff[1]= R.wrld.linfac*(1.0f-exp( diff[1]*R.wrld.logfac) );
diff[2]= R.wrld.linfac*(1.0f-exp( diff[2]*R.wrld.logfac) );
@@ -1511,7 +1538,6 @@ static void wrld_exposure_correct(float *diff)
void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr)
{
Material *ma= shi->mat;
- VlakRen *vlr= shi->vlr;
int passflag= shi->passflag;
memset(shr, 0, sizeof(ShadeResult));
@@ -1541,6 +1567,24 @@ void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr)
shr->col[1]= shi->g*shi->alpha;
shr->col[2]= shi->b*shi->alpha;
shr->col[3]= shi->alpha;
+
+ if((ma->sss_flag & MA_DIFF_SSS) && !sss_pass_done(&R, ma)) {
+ if(ma->sss_texfac == 0.0f) {
+ shi->r= shi->g= shi->b= shi->alpha= 1.0f;
+ shr->col[0]= shr->col[1]= shr->col[2]= shr->col[3]= 1.0f;
+ }
+ else {
+ shi->r= pow(shi->r, ma->sss_texfac);
+ shi->g= pow(shi->g, ma->sss_texfac);
+ shi->b= pow(shi->b, ma->sss_texfac);
+ shi->alpha= pow(shi->alpha, ma->sss_texfac);
+
+ shr->col[0]= pow(shr->col[0], ma->sss_texfac);
+ shr->col[1]= pow(shr->col[1], ma->sss_texfac);
+ shr->col[2]= pow(shr->col[2], ma->sss_texfac);
+ shr->col[3]= pow(shr->col[3], ma->sss_texfac);
+ }
+ }
}
if(ma->mode & MA_SHLESS) {
@@ -1565,7 +1609,8 @@ void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr)
/* AO pass */
if(R.wrld.mode & WO_AMB_OCC) {
- if(passflag & (SCE_PASS_COMBINED|SCE_PASS_AO)) {
+ if(((passflag & SCE_PASS_COMBINED) && (shi->combinedflag & SCE_PASS_AO))
+ || (passflag & SCE_PASS_AO)) {
/* AO was calculated for scanline already */
if(shi->depth)
ambient_occlusion(shi);
@@ -1588,7 +1633,7 @@ void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr)
if (lar->type==LA_YF_PHOTON) continue;
/* test for lamp layer */
- if(lar->mode & LA_LAYER) if((lar->lay & vlr->lay)==0) continue;
+ if(lar->mode & LA_LAYER) if((lar->lay & shi->obi->lay)==0) continue;
if((lar->lay & shi->lay)==0) continue;
/* accumulates in shr->diff and shr->spec and shr->shad (diffuse with shadow!) */
@@ -1606,20 +1651,26 @@ void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr)
if (shr->shad[2] < 0) shr->shad[2] = 0;
if(ma->sss_flag & MA_DIFF_SSS) {
- float sss[3], col[3], texfac= ma->sss_texfac;
+ float sss[3], col[3], invalpha, texfac= ma->sss_texfac;
/* this will return false in the preprocess stage */
if(sample_sss(&R, ma, shi->co, sss)) {
+ invalpha= (shr->col[3] > FLT_EPSILON)? 1.0f/shr->col[3]: 1.0f;
+
if(texfac==0.0f) {
VECCOPY(col, shr->col);
+ VecMulf(col, invalpha);
}
else if(texfac==1.0f) {
col[0]= col[1]= col[2]= 1.0f;
+ VecMulf(col, invalpha);
}
else {
- col[0]= pow(shr->col[0], 1.0f-texfac);
- col[1]= pow(shr->col[1], 1.0f-texfac);
- col[2]= pow(shr->col[2], 1.0f-texfac);
+ VECCOPY(col, shr->col);
+ VecMulf(col, invalpha);
+ col[0]= pow(col[0], 1.0f-texfac);
+ col[1]= pow(col[1], 1.0f-texfac);
+ col[2]= pow(col[2], 1.0f-texfac);
}
shr->diff[0]= sss[0]*col[0];
@@ -1627,9 +1678,9 @@ void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr)
shr->diff[2]= sss[2]*col[2];
if(shi->combinedflag & SCE_PASS_SHADOW) {
- shr->shad[0]= sss[0]*col[0];
- shr->shad[1]= sss[1]*col[1];
- shr->shad[2]= sss[2]*col[2];
+ shr->shad[0]= shr->diff[0];
+ shr->shad[1]= shr->diff[1];
+ shr->shad[2]= shr->diff[2];
}
}
}
@@ -1647,7 +1698,7 @@ void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr)
}
/* exposure correction */
- if(R.wrld.exp!=0.0f || R.wrld.range!=1.0f) {
+ if((R.wrld.exp!=0.0f || R.wrld.range!=1.0f) && !R.sss_points) {
wrld_exposure_correct(shr->combined); /* has no spec! */
wrld_exposure_correct(shr->spec);
}
@@ -1671,10 +1722,16 @@ void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr)
shr->alpha= shi->alpha;
/* from now stuff everything in shr->combined: ambient, AO, radio, ramps, exposure */
- if(!(ma->sss_flag & MA_DIFF_SSS) || !has_sss_tree(&R, ma)) {
- shr->combined[0]+= shi->ambr + shi->r*shi->amb*shi->rad[0];
- shr->combined[1]+= shi->ambg + shi->g*shi->amb*shi->rad[1];
- shr->combined[2]+= shi->ambb + shi->b*shi->amb*shi->rad[2];
+ if(!(ma->sss_flag & MA_DIFF_SSS) || !sss_pass_done(&R, ma)) {
+ shr->combined[0]+= shi->ambr;
+ shr->combined[1]+= shi->ambg;
+ shr->combined[2]+= shi->ambb;
+
+ if(shi->combinedflag & SCE_PASS_RADIO) {
+ shr->combined[0]+= shi->r*shi->amb*shi->rad[0];
+ shr->combined[1]+= shi->g*shi->amb*shi->rad[1];
+ shr->combined[2]+= shi->b*shi->amb*shi->rad[2];
+ }
/* add AO in combined? */
if(R.wrld.mode & WO_AMB_OCC) {
@@ -1713,7 +1770,21 @@ void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr)
if(shi->combinedflag & SCE_PASS_SPEC)
VECADD(shr->combined, shr->combined, shr->spec);
+ /* modulate by the object color */
+ if((ma->shade_flag & MA_OBCOLOR) && shi->obr->ob) {
+ if(!(ma->sss_flag & MA_DIFF_SSS) || !sss_pass_done(&R, ma)) {
+ float obcol[4];
+
+ QUATCOPY(obcol, shi->obr->ob->col);
+ CLAMP(obcol[3], 0.0f, 1.0f);
+
+ shr->combined[0] *= obcol[0];
+ shr->combined[1] *= obcol[1];
+ shr->combined[2] *= obcol[2];
+ shr->alpha *= obcol[3];
+ }
+ }
+
shr->combined[3]= shr->alpha;
}
-
diff --git a/source/blender/render/intern/source/sss.c b/source/blender/render/intern/source/sss.c
index 09a3b9ef66d..9bde6675798 100644
--- a/source/blender/render/intern/source/sss.c
+++ b/source/blender/render/intern/source/sss.c
@@ -59,6 +59,7 @@
#include "BKE_main.h"
#include "BKE_material.h"
#include "BKE_node.h"
+#include "BKE_scene.h"
#include "BKE_utildefines.h"
/* this module */
@@ -450,13 +451,13 @@ static void compute_radiance(ScatterTree *tree, float *co, float *rad)
VECCOPY(rdsum, result.rdsum);
VECADD(backrdsum, result.rdsum, result.backrdsum);
- if(rdsum[0] > 0.0f) rad[0]= tree->ss[0]->color*rad[0]/rdsum[0];
- if(rdsum[1] > 0.0f) rad[1]= tree->ss[1]->color*rad[1]/rdsum[1];
- if(rdsum[2] > 0.0f) rad[2]= tree->ss[2]->color*rad[2]/rdsum[2];
+ if(rdsum[0] > 1e-16f) rad[0]= tree->ss[0]->color*rad[0]/rdsum[0];
+ if(rdsum[1] > 1e-16f) rad[1]= tree->ss[1]->color*rad[1]/rdsum[1];
+ if(rdsum[2] > 1e-16f) rad[2]= tree->ss[2]->color*rad[2]/rdsum[2];
- if(backrdsum[0] > 0.0f) backrad[0]= tree->ss[0]->color*backrad[0]/backrdsum[0];
- if(backrdsum[1] > 0.0f) backrad[1]= tree->ss[1]->color*backrad[1]/backrdsum[1];
- if(backrdsum[2] > 0.0f) backrad[2]= tree->ss[2]->color*backrad[2]/backrdsum[2];
+ if(backrdsum[0] > 1e-16f) backrad[0]= tree->ss[0]->color*backrad[0]/backrdsum[0];
+ if(backrdsum[1] > 1e-16f) backrad[1]= tree->ss[1]->color*backrad[1]/backrdsum[1];
+ if(backrdsum[2] > 1e-16f) backrad[2]= tree->ss[2]->color*backrad[2]/backrdsum[2];
rad[0]= MAX2(rad[0], backrad[0]);
rad[1]= MAX2(rad[1], backrad[1]);
@@ -503,20 +504,20 @@ static void sum_leaf_radiance(ScatterTree *tree, ScatterNode *node)
}
}
- if(node->area > 0) {
+ if(node->area > 1e-16f) {
inv= 1.0/node->area;
node->rad[0] *= inv;
node->rad[1] *= inv;
node->rad[2] *= inv;
}
- if(node->backarea > 0) {
+ if(node->backarea > 1e-16f) {
inv= 1.0/node->backarea;
node->backrad[0] *= inv;
node->backrad[1] *= inv;
node->backrad[2] *= inv;
}
- if(totrad > 0.0f) {
+ if(totrad > 1e-16f) {
inv= 1.0/totrad;
node->co[0] *= inv;
node->co[1] *= inv;
@@ -577,20 +578,20 @@ static void sum_branch_radiance(ScatterTree *tree, ScatterNode *node)
node->backarea += subnode->backarea;
}
- if(node->area > 0) {
+ if(node->area > 1e-16f) {
inv= 1.0/node->area;
node->rad[0] *= inv;
node->rad[1] *= inv;
node->rad[2] *= inv;
}
- if(node->backarea > 0) {
+ if(node->backarea > 1e-16f) {
inv= 1.0/node->backarea;
node->backrad[0] *= inv;
node->backrad[1] *= inv;
node->backrad[2] *= inv;
}
- if(totrad > 0.0f) {
+ if(totrad > 1e-16f) {
inv= 1.0/totrad;
node->co[0] *= inv;
node->co[1] *= inv;
@@ -847,7 +848,7 @@ static void sss_create_tree_mat(Render *re, Material *mat)
{
SSSPoints *p;
RenderResult *rr;
- ListBase layers, points;
+ ListBase points;
float (*co)[3] = NULL, (*color)[3] = NULL, *area = NULL;
int totpoint = 0, osa, osaflag, partsdone;
@@ -860,13 +861,11 @@ static void sss_create_tree_mat(Render *re, Material *mat)
setting them back, maybe we need to create our own Render? */
/* do SSS preprocessing render */
- layers= re->r.layers;
+ rr= re->result;
osa= re->osa;
osaflag= re->r.mode & R_OSA;
partsdone= re->i.partsdone;
- rr= re->result;
- re->r.layers.first= re->r.layers.last= NULL;
re->osa= 0;
re->r.mode &= ~R_OSA;
re->sss_points= &points;
@@ -881,7 +880,6 @@ static void sss_create_tree_mat(Render *re, Material *mat)
re->i.partsdone= partsdone;
re->sss_mat= NULL;
re->sss_points= NULL;
- re->r.layers= layers;
re->osa= osa;
if (osaflag) re->r.mode |= R_OSA;
@@ -921,7 +919,8 @@ static void sss_create_tree_mat(Render *re, Material *mat)
float *col= mat->sss_col, *radius= mat->sss_radius;
float fw= mat->sss_front, bw= mat->sss_back;
float error = mat->sss_error;
-
+
+ error= get_render_aosss_error(&re->r, error);
if((re->r.scemode & R_PREVIEWBUTS) && error < 0.5f)
error= 0.5f;
@@ -985,7 +984,7 @@ void make_sss_tree(Render *re)
re->stats_draw(&re->i);
for(mat= G.main->mat.first; mat; mat= mat->id.next)
- if(mat->id.us && (mat->sss_flag & MA_DIFF_SSS))
+ if(mat->id.us && (mat->flag & MA_IS_USED) && (mat->sss_flag & MA_DIFF_SSS))
sss_create_tree_mat(re, mat);
}
@@ -1024,8 +1023,8 @@ int sample_sss(Render *re, Material *mat, float *co, float *color)
return 0;
}
-int has_sss_tree(struct Render *re, struct Material *mat)
+int sss_pass_done(struct Render *re, struct Material *mat)
{
- return (re->sss_hash && BLI_ghash_lookup(re->sss_hash, mat));
+ return ((re->flag & R_BAKING) || !(re->r.mode & R_SSS) || (re->sss_hash && BLI_ghash_lookup(re->sss_hash, mat)));
}
diff --git a/source/blender/render/intern/source/strand.c b/source/blender/render/intern/source/strand.c
index 4f0e9764a43..05e36160f0e 100644
--- a/source/blender/render/intern/source/strand.c
+++ b/source/blender/render/intern/source/strand.c
@@ -35,12 +35,14 @@
#include "DNA_key_types.h"
#include "DNA_material_types.h"
+#include "DNA_meshdata_types.h"
#include "BLI_arithb.h"
#include "BLI_blenlib.h"
#include "BLI_ghash.h"
#include "BLI_memarena.h"
+#include "BKE_DerivedMesh.h"
#include "BKE_key.h"
#include "BKE_utildefines.h"
@@ -55,248 +57,9 @@
#include "zbuf.h"
/* to be removed */
-void merge_transp_passes(RenderLayer *rl, ShadeResult *shr);
-void add_transp_passes(RenderLayer *rl, int offset, ShadeResult *shr, float alpha);
void hoco_to_zco(ZSpan *zspan, float *zco, float *hoco);
void zspan_scanconvert_strand(ZSpan *zspan, void *handle, float *v1, float *v2, float *v3, void (*func)(void *, int, int, float, float, float) );
-void zbufsinglewire(ZSpan *zspan, ObjectRen *obr, int zvlnr, float *ho1, float *ho2);
-int addtosamp_shr(ShadeResult *samp_shr, ShadeSample *ssamp, int addpassflag);
-void add_transp_speed(RenderLayer *rl, int offset, float *speed, float alpha, long *rdrect);
-void reset_sky_speedvectors(RenderPart *pa, RenderLayer *rl, float *rectf);
-
-/* *************** */
-
-#define BUCKETPRIMS_SIZE 256
-
-typedef struct BucketPrims {
- struct BucketPrims *next, *prev;
- void *prim[BUCKETPRIMS_SIZE];
- int totprim;
-} BucketPrims;
-
-typedef struct RenderBuckets {
- ListBase all;
- ListBase *inside;
- ListBase *overlap;
- int x, y;
- float insize[2];
- float zmulx, zmuly, zofsx, zofsy;
-} RenderBuckets;
-
-static void add_bucket_prim(ListBase *lb, void *prim)
-{
- BucketPrims *bpr= lb->last;
-
- if(!bpr || bpr->totprim == BUCKETPRIMS_SIZE) {
- bpr= MEM_callocN(sizeof(BucketPrims), "BucketPrims");
- BLI_addtail(lb, bpr);
- }
-
- bpr->prim[bpr->totprim++]= prim;
-}
-
-RenderBuckets *init_buckets(Render *re)
-{
- RenderBuckets *buckets;
- RenderPart *pa;
- float scalex, scaley, cropx, cropy;
- int x, y, tempparts= 0;
-
- buckets= MEM_callocN(sizeof(RenderBuckets), "RenderBuckets");
-
- if(!re->parts.first) {
- initparts(re);
- tempparts= 1;
- }
-
- pa= re->parts.first;
- if(!pa)
- return buckets;
-
- x= re->xparts+1;
- y= re->yparts+1;
- buckets->x= x;
- buckets->y= y;
-
- scalex= (2.0f - re->xparts*re->partx/(float)re->winx);
- scaley= (2.0f - re->yparts*re->party/(float)re->winy);
-
- cropx= pa->crop/(float)re->partx;
- cropy= pa->crop/(float)re->party;
-
- buckets->insize[0]= 1.0f - 2.0f*cropx;
- buckets->insize[1]= 1.0f - 2.0f*cropy;
-
- buckets->zmulx= re->xparts*scalex;
- buckets->zmuly= re->yparts*scaley;
- buckets->zofsx= scalex*(1.0f - cropx);
- buckets->zofsy= scaley*(1.0f - cropy);
-
- buckets->inside= MEM_callocN(sizeof(ListBase)*x*y, "BucketPrimsInside");
- buckets->overlap= MEM_callocN(sizeof(ListBase)*x*y, "BucketPrimsOverlap");
-
- if(tempparts)
- freeparts(re);
-
- return buckets;
-}
-
-void add_buckets_primitive(RenderBuckets *buckets, float *min, float *max, void *prim)
-{
- float end[3];
- int x, y, a;
-
- x= (int)min[0];
- y= (int)min[1];
-
- if(x >= 0 && x < buckets->x && y >= 0 && y < buckets->y) {
- a= y*buckets->x + x;
-
- end[0]= x + buckets->insize[0];
- end[1]= y + buckets->insize[1];
-
- if(max[0] <= end[0] && max[1] <= end[1]) {
- add_bucket_prim(&buckets->inside[a], prim);
- return;
- }
- else {
- end[0]= x + 2;
- end[1]= y + 2;
-
- if(max[0] <= end[0] && max[1] <= end[1]) {
- add_bucket_prim(&buckets->overlap[a], prim);
- return;
- }
- }
- }
-
- add_bucket_prim(&buckets->all, prim);
-}
-
-void free_buckets(RenderBuckets *buckets)
-{
- int a, size;
-
- BLI_freelistN(&buckets->all);
-
- size= buckets->x*buckets->y;
- for(a=0; a<size; a++) {
- BLI_freelistN(&buckets->inside[a]);
- BLI_freelistN(&buckets->overlap[a]);
- }
-
- if(buckets->inside)
- MEM_freeN(buckets->inside);
- if(buckets->overlap)
- MEM_freeN(buckets->overlap);
-
- MEM_freeN(buckets);
-}
-
-void project_hoco_to_bucket(RenderBuckets *buckets, float *hoco, float *bucketco)
-{
- float div;
-
- div= 1.0f/hoco[3];
- bucketco[0]= buckets->zmulx*(0.5 + 0.5f*hoco[0]*div) + buckets->zofsx;
- bucketco[1]= buckets->zmuly*(0.5 + 0.5f*hoco[1]*div) + buckets->zofsy;
-}
-
-typedef struct RenderPrimitiveIterator {
- Render *re;
- RenderBuckets *buckets;
- ListBase *list[6];
- int listindex, totlist;
- BucketPrims *bpr;
- int bprindex;
-
- ObjectInstanceRen *obi;
- StrandRen *strand;
- int index, tot;
-} RenderPrimitiveIterator;
-
-RenderPrimitiveIterator *init_primitive_iterator(Render *re, RenderBuckets *buckets, RenderPart *pa)
-{
- RenderPrimitiveIterator *iter;
- int nr, x, y, width;
-
- iter= MEM_callocN(sizeof(RenderPrimitiveIterator), "RenderPrimitiveIterator");
- iter->re= re;
-
- if(buckets) {
- iter->buckets= buckets;
-
- nr= BLI_findindex(&re->parts, pa);
- width= buckets->x - 1;
- x= (nr % width) + 1;
- y= (nr / width) + 1;
-
- iter->list[iter->totlist++]= &buckets->all;
- iter->list[iter->totlist++]= &buckets->inside[y*buckets->x + x];
- iter->list[iter->totlist++]= &buckets->overlap[y*buckets->x + x];
- iter->list[iter->totlist++]= &buckets->overlap[y*buckets->x + (x-1)];
- iter->list[iter->totlist++]= &buckets->overlap[(y-1)*buckets->x + (x-1)];
- iter->list[iter->totlist++]= &buckets->overlap[(y-1)*buckets->x + x];
- }
- else {
- iter->index= 0;
- iter->obi= re->instancetable.first;
- if(iter->obi)
- iter->tot= iter->obi->obr->totstrand;
- }
-
- return iter;
-}
-
-void *next_primitive_iterator(RenderPrimitiveIterator *iter)
-{
- if(iter->buckets) {
- if(iter->bpr && iter->bprindex >= iter->bpr->totprim) {
- iter->bpr= iter->bpr->next;
- iter->bprindex= 0;
- }
-
- while(iter->bpr == NULL) {
- if(iter->listindex == iter->totlist)
- return NULL;
-
- iter->bpr= iter->list[iter->listindex++]->first;
- iter->bprindex= 0;
- }
-
- return iter->bpr->prim[iter->bprindex++];
- }
- else {
- if(!iter->obi)
- return NULL;
-
- if(iter->index >= iter->tot) {
- while((iter->obi=iter->obi->next) && !iter->obi->obr->totstrand)
- iter->obi= iter->obi->next;
-
- if(iter->obi)
- iter->tot= iter->obi->obr->totstrand;
- else
- return NULL;
- }
-
- if(iter->index < iter->tot) {
- if((iter->index & 255)==0)
- iter->strand= iter->obi->obr->strandnodes[iter->index>>8].strand;
- else
- iter->strand++;
-
- return iter->strand;
- }
- else
- return NULL;
- }
-}
-
-void free_primitive_iterator(RenderPrimitiveIterator *iter)
-{
- MEM_freeN(iter);
-}
+void zbufsinglewire(ZSpan *zspan, int obi, int zvlnr, float *ho1, float *ho2);
/* *************** */
@@ -388,9 +151,9 @@ void strand_eval_point(StrandSegment *sseg, StrandPoint *spoint)
Crossf(cross, spoint->co, spoint->tan);
w= spoint->co[2]*strandbuf->winmat[2][3] + strandbuf->winmat[3][3];
- dx= strandbuf->winx*cross[0]*strandbuf->winmat[0][0];
- dy= strandbuf->winy*cross[1]*strandbuf->winmat[1][1];
- w= sqrt(dx*dx + dy*dy)/w;
+ dx= strandbuf->winx*cross[0]*strandbuf->winmat[0][0]/w;
+ dy= strandbuf->winy*cross[1]*strandbuf->winmat[1][1]/w;
+ w= sqrt(dx*dx + dy*dy);
if(w > 0.0f) {
if(strandbuf->flag & R_STRAND_B_UNITS) {
@@ -420,42 +183,9 @@ void strand_eval_point(StrandSegment *sseg, StrandPoint *spoint)
/* *************** */
-typedef struct StrandPart {
- Render *re;
- ZSpan *zspan;
-
- RenderLayer *rl;
- ShadeResult *result;
- float *pass;
- int *rectz, *outrectz;
- unsigned short *mask;
- int rectx, recty;
- int addpassflag, addzbuf, sample;
-
- StrandSegment *segment;
- GHash *hash;
- StrandPoint point1, point2;
- ShadeSample ssamp1, ssamp2, ssamp;
- float t[3];
-} StrandPart;
-
-typedef struct StrandSortSegment {
- struct StrandSortSegment *next;
- int obi, strand, segment;
- float z;
-} StrandSortSegment;
-
-static int compare_strand_segment(const void *poin1, const void *poin2)
+static void interpolate_vec1(float *v1, float *v2, float t, float negt, float *v)
{
- const StrandSortSegment *seg1= (const StrandSortSegment*)poin1;
- const StrandSortSegment *seg2= (const StrandSortSegment*)poin2;
-
- if(seg1->z < seg2->z)
- return -1;
- else if(seg1->z == seg2->z)
- return 0;
- else
- return 1;
+ v[0]= negt*v1[0] + t*v2[0];
}
static void interpolate_vec3(float *v1, float *v2, float t, float negt, float *v)
@@ -473,7 +203,7 @@ static void interpolate_vec4(float *v1, float *v2, float t, float negt, float *v
v[3]= negt*v1[3] + t*v2[3];
}
-static void interpolate_shade_result(ShadeResult *shr1, ShadeResult *shr2, float t, ShadeResult *shr, int addpassflag)
+void interpolate_shade_result(ShadeResult *shr1, ShadeResult *shr2, float t, ShadeResult *shr, int addpassflag)
{
float negt= 1.0f - t;
@@ -484,6 +214,8 @@ static void interpolate_shade_result(ShadeResult *shr1, ShadeResult *shr2, float
}
/* optim... */
if(addpassflag & ~(SCE_PASS_VECTOR)) {
+ if(addpassflag & SCE_PASS_Z)
+ interpolate_vec1(&shr1->z, &shr2->z, t, negt, &shr->z);
if(addpassflag & SCE_PASS_RGBA)
interpolate_vec4(shr1->col, shr2->col, t, negt, shr->col);
if(addpassflag & SCE_PASS_NORMAL) {
@@ -504,142 +236,336 @@ static void interpolate_shade_result(ShadeResult *shr1, ShadeResult *shr2, float
interpolate_vec3(shr1->refr, shr2->refr, t, negt, shr->refr);
if(addpassflag & SCE_PASS_RADIO)
interpolate_vec3(shr1->rad, shr2->rad, t, negt, shr->rad);
+ if(addpassflag & SCE_PASS_MIST)
+ interpolate_vec1(&shr1->mist, &shr2->mist, t, negt, &shr->mist);
}
}
-static void add_strand_obindex(RenderLayer *rl, int offset, ObjectRen *obr)
+void strand_apply_shaderesult_alpha(ShadeResult *shr, float alpha)
{
- RenderPass *rpass;
-
- for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
- if(rpass->passtype == SCE_PASS_INDEXOB) {
- float *fp= rpass->rect + offset;
- *fp= (float)obr->ob->index;
- break;
- }
+ if(alpha < 1.0f) {
+ shr->combined[0] *= alpha;
+ shr->combined[1] *= alpha;
+ shr->combined[2] *= alpha;
+ shr->combined[3] *= alpha;
+
+ shr->col[0] *= alpha;
+ shr->col[1] *= alpha;
+ shr->col[2] *= alpha;
+ shr->col[3] *= alpha;
+
+ shr->alpha *= alpha;
}
}
-static void do_strand_point_project(float winmat[][4], ZSpan *zspan, float *co, float *hoco, float *zco)
+void strand_shade_point(Render *re, ShadeSample *ssamp, StrandSegment *sseg, StrandPoint *spoint)
{
- projectvert(co, winmat, hoco);
- hoco_to_zco(zspan, zco, hoco);
+ ShadeInput *shi= ssamp->shi;
+ ShadeResult *shr= ssamp->shr;
+ VlakRen vlr;
+
+ memset(&vlr, 0, sizeof(vlr));
+ vlr.flag= R_SMOOTH;
+ if(sseg->buffer->ma->mode & MA_TANGENT_STR)
+ vlr.flag |= R_TANGENT;
+
+ shi->vlr= &vlr;
+ shi->strand= sseg->strand;
+ shi->obi= sseg->obi;
+ shi->obr= sseg->obi->obr;
+
+ /* cache for shadow */
+ shi->samplenr= re->shadowsamplenr[shi->thread]++;
+
+ shade_input_set_strand(shi, sseg->strand, spoint);
+ shade_input_set_strand_texco(shi, sseg->strand, sseg->v[1], spoint);
+
+ /* init material vars */
+ // note, keep this synced with render_types.h
+ memcpy(&shi->r, &shi->mat->r, 23*sizeof(float));
+ shi->har= shi->mat->har;
+
+ /* shade */
+ shade_samples_do_AO(ssamp);
+ shade_input_do_shade(shi, shr);
+
+ /* apply simplification */
+ strand_apply_shaderesult_alpha(shr, spoint->alpha);
+
+ /* include lamphalos for strand, since halo layer was added already */
+ if(re->flag & R_LAMPHALO)
+ if(shi->layflag & SCE_LAY_HALO)
+ renderspothalo(shi, shr->combined, shr->combined[3]);
+
+ shi->strand= NULL;
}
-static void strand_project_point(float winmat[][4], float winx, float winy, StrandPoint *spoint)
-{
- float div;
+/* *************** */
- projectvert(spoint->co, winmat, spoint->hoco);
+struct StrandShadeCache {
+ GHash *resulthash;
+ GHash *refcounthash;
+ MemArena *memarena;
+};
- div= 1.0f/spoint->hoco[3];
- spoint->x= spoint->hoco[0]*div*winx*0.5f;
- spoint->y= spoint->hoco[1]*div*winy*0.5f;
+StrandShadeCache *strand_shade_cache_create()
+{
+ StrandShadeCache *cache;
+
+ cache= MEM_callocN(sizeof(StrandShadeCache), "StrandShadeCache");
+ cache->resulthash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
+ cache->refcounthash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
+ cache->memarena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
+
+ return cache;
}
-#include "BLI_rand.h"
-static void strand_shade_point(Render *re, ShadeSample *ssamp, StrandSegment *sseg, StrandPoint *spoint);
+void strand_shade_cache_free(StrandShadeCache *cache)
+{
+ BLI_ghash_free(cache->refcounthash, NULL, NULL);
+ BLI_ghash_free(cache->resulthash, NULL, (GHashValFreeFP)MEM_freeN);
+ BLI_memarena_free(cache->memarena);
+ MEM_freeN(cache);
+}
-static void strand_shade_get(StrandPart *spart, int lookup, ShadeSample *ssamp, StrandPoint *spoint, StrandVert *svert, StrandSegment *sseg)
+static void strand_shade_get(Render *re, StrandShadeCache *cache, ShadeSample *ssamp, StrandSegment *sseg, StrandVert *svert)
{
ShadeResult *hashshr;
+ StrandPoint p;
+ int *refcount;
- if(lookup) {
- hashshr= BLI_ghash_lookup(spart->hash, svert);
+ hashshr= BLI_ghash_lookup(cache->resulthash, svert);
+ refcount= BLI_ghash_lookup(cache->refcounthash, svert);
- if(!hashshr) {
- strand_shade_point(spart->re, ssamp, sseg, spoint);
+ if(!hashshr) {
+ /* not shaded yet, shade and insert into hash */
+ p.t= (sseg->v[1] == svert)? 0.0f: 1.0f;
+ strand_eval_point(sseg, &p);
+ strand_shade_point(re, ssamp, sseg, &p);
- hashshr= MEM_callocN(sizeof(ShadeResult), "HashShadeResult");
- *hashshr= ssamp->shr[0];
- BLI_ghash_insert(spart->hash, svert, hashshr);
- }
- else {
- ssamp->shr[0]= *hashshr;
- BLI_ghash_remove(spart->hash, svert, NULL, (GHashValFreeFP)MEM_freeN);
- }
+ hashshr= MEM_callocN(sizeof(ShadeResult), "HashShadeResult");
+ *hashshr= ssamp->shr[0];
+ BLI_ghash_insert(cache->resulthash, svert, hashshr);
}
else
- strand_shade_point(spart->re, ssamp, sseg, spoint);
+ /* already shaded, just copy previous result from hash */
+ ssamp->shr[0]= *hashshr;
+
+ /* lower reference count and remove if not needed anymore by any samples */
+ (*refcount)--;
+ if(*refcount == 0) {
+ BLI_ghash_remove(cache->resulthash, svert, NULL, (GHashValFreeFP)MEM_freeN);
+ BLI_ghash_remove(cache->refcounthash, svert, NULL, NULL);
+ }
}
-static void strand_shade_segment(StrandPart *spart)
+void strand_shade_segment(Render *re, StrandShadeCache *cache, StrandSegment *sseg, ShadeSample *ssamp, float t, float s, int addpassflag)
{
- StrandSegment *sseg= spart->segment;
- int first, last;
+ ShadeResult shr1, shr2;
- if(!sseg->shaded) {
- first= (sseg->v[1] == &sseg->strand->vert[0]);
- last= (sseg->v[2] == &sseg->strand->vert[sseg->strand->totvert-1]);
+ /* get shading for two endpoints and interpolate */
+ strand_shade_get(re, cache, ssamp, sseg, sseg->v[1]);
+ shr1= ssamp->shr[0];
+ strand_shade_get(re, cache, ssamp, sseg, sseg->v[2]);
+ shr2= ssamp->shr[0];
- strand_shade_get(spart, !first, &spart->ssamp1, &sseg->point1, sseg->v[1], sseg);
- strand_shade_get(spart, !last, &spart->ssamp2, &sseg->point2, sseg->v[2], sseg);
- sseg->shaded= 1;
+ interpolate_shade_result(&shr1, &shr2, t, ssamp->shr, addpassflag);
+
+ /* apply alpha along width */
+ if(sseg->buffer->widthfade != 0.0f) {
+ s = 1.0f - pow(fabs(s), sseg->buffer->widthfade);
+
+ strand_apply_shaderesult_alpha(ssamp->shr, s);
}
+}
-#if 0
- float c[3];
-
- c[0]= BLI_frand();
- c[1]= BLI_frand();
- c[2]= BLI_frand();
+void strand_shade_unref(StrandShadeCache *cache, StrandVert *svert)
+{
+ int *refcount;
- spart->ssamp1.shr[0].combined[0] *= c[0];
- spart->ssamp1.shr[0].combined[1] *= c[1];
- spart->ssamp1.shr[0].combined[2] *= c[2];
+ /* lower reference count and remove if not needed anymore by any samples */
+ refcount= BLI_ghash_lookup(cache->refcounthash, svert);
- spart->ssamp2.shr[0].combined[0] *= c[0];
- spart->ssamp2.shr[0].combined[1] *= c[1];
- spart->ssamp2.shr[0].combined[2] *= c[2];
-#endif
+ (*refcount)--;
+ if(*refcount == 0) {
+ BLI_ghash_remove(cache->resulthash, svert, NULL, (GHashValFreeFP)MEM_freeN);
+ BLI_ghash_remove(cache->refcounthash, svert, NULL, NULL);
+ }
}
-static void do_strand_blend(void *handle, int x, int y, float u, float v, float z)
+static void strand_shade_refcount(StrandShadeCache *cache, StrandVert *svert)
{
- StrandPart *spart= (StrandPart*)handle;
- StrandBuffer *buffer= spart->segment->buffer;
- ShadeResult *shr;
- float /**pass,*/ t;
- int offset, zverg;
+ int *refcount= BLI_ghash_lookup(cache->refcounthash, svert);
- /* check again solid z-buffer */
- offset = y*spart->rectx + x;
- zverg= (int)z;
+ if(!refcount) {
+ refcount= BLI_memarena_alloc(cache->memarena, sizeof(int));
+ *refcount= 1;
+ BLI_ghash_insert(cache->refcounthash, svert, refcount);
+ }
+ else
+ (*refcount)++;
+}
- if(zverg < spart->rectz[offset]) {
- /* fill in output z-buffer if needed */
- if(spart->addzbuf)
- if(zverg < spart->outrectz[offset])
- spart->outrectz[offset]= zverg;
+/* *************** */
- /* check alpha limit */
- shr= spart->result + offset*(spart->re->osa? spart->re->osa: 1);
- if(shr[spart->sample].combined[3]>0.999f)
- return;
+typedef struct StrandPart {
+ Render *re;
+ ZSpan *zspan;
- /* shade points if not shaded yet */
- strand_shade_segment(spart);
+ APixstrand *apixbuf;
+ int *totapixbuf;
+ int *rectz;
+ int *rectmask;
+ intptr_t *rectdaps;
+ int rectx, recty;
+ int sample;
- /* interpolate shading from two control points */
- t = u*spart->t[0] + v*spart->t[1] + (1.0f-u-v)*spart->t[2];
- interpolate_shade_result(spart->ssamp1.shr, spart->ssamp2.shr, t,
- spart->ssamp.shr, spart->addpassflag);
+ StrandSegment *segment;
+ float t[3], s[3];
- /* add in shaderesult array for part */
- spart->ssamp.shi[0].mask= (1<<spart->sample);
- addtosamp_shr(shr, &spart->ssamp, spart->addpassflag);
- spart->mask[offset] |= (1<<spart->sample);
+ StrandShadeCache *cache;
+} StrandPart;
-#if 0
- /* fill in pass for preview */
- if(spart->sample == 0) {
- pass= spart->pass + offset*4;
- QUATCOPY(pass, shr->combined);
+typedef struct StrandSortSegment {
+ struct StrandSortSegment *next;
+ int obi, strand, segment;
+ float z;
+} StrandSortSegment;
+
+static int compare_strand_segment(const void *poin1, const void *poin2)
+{
+ const StrandSortSegment *seg1= (const StrandSortSegment*)poin1;
+ const StrandSortSegment *seg2= (const StrandSortSegment*)poin2;
+
+ if(seg1->z < seg2->z)
+ return -1;
+ else if(seg1->z == seg2->z)
+ return 0;
+ else
+ return 1;
+}
+
+static void do_strand_point_project(float winmat[][4], ZSpan *zspan, float *co, float *hoco, float *zco)
+{
+ projectvert(co, winmat, hoco);
+ hoco_to_zco(zspan, zco, hoco);
+}
+
+static void strand_project_point(float winmat[][4], float winx, float winy, StrandPoint *spoint)
+{
+ float div;
+
+ projectvert(spoint->co, winmat, spoint->hoco);
+
+ div= 1.0f/spoint->hoco[3];
+ spoint->x= spoint->hoco[0]*div*winx*0.5f;
+ spoint->y= spoint->hoco[1]*div*winy*0.5f;
+}
+
+static APixstrand *addpsmainAstrand(ListBase *lb)
+{
+ APixstrMain *psm;
+
+ psm= MEM_mallocN(sizeof(APixstrMain), "addpsmainA");
+ BLI_addtail(lb, psm);
+ psm->ps= MEM_callocN(4096*sizeof(APixstrand),"pixstr");
+
+ return psm->ps;
+}
+
+static APixstrand *addpsAstrand(ZSpan *zspan)
+{
+ /* make new PS */
+ if(zspan->apstrandmcounter==0) {
+ zspan->curpstrand= addpsmainAstrand(zspan->apsmbase);
+ zspan->apstrandmcounter= 4095;
+ }
+ else {
+ zspan->curpstrand++;
+ zspan->apstrandmcounter--;
+ }
+ return zspan->curpstrand;
+}
+
+#define MAX_ZROW 2000
+
+static void do_strand_fillac(void *handle, int x, int y, float u, float v, float z)
+{
+ StrandPart *spart= (StrandPart*)handle;
+ StrandShadeCache *cache= spart->cache;
+ StrandSegment *sseg= spart->segment;
+ APixstrand *apn, *apnew;
+ float t, s;
+ int offset, mask, obi, strnr, seg, zverg, bufferz, maskz=0;
+
+ offset = y*spart->rectx + x;
+ obi= sseg->obi - spart->re->objectinstance;
+ strnr= sseg->strand->index + 1;
+ seg= sseg->v[1] - sseg->strand->vert;
+ mask= (1<<spart->sample);
+
+ /* check against solid z-buffer */
+ zverg= (int)z;
+
+ if(spart->rectdaps) {
+ /* find the z of the sample */
+ PixStr *ps;
+ intptr_t *rd= spart->rectdaps + offset;
+
+ bufferz= 0x7FFFFFFF;
+ if(spart->rectmask) maskz= 0x7FFFFFFF;
+
+ if(*rd) {
+ for(ps= (PixStr *)(*rd); ps; ps= ps->next) {
+ if(mask & ps->mask) {
+ bufferz= ps->z;
+ if(spart->rectmask)
+ maskz= ps->maskz;
+ break;
+ }
+ }
}
-#endif
+ }
+ else {
+ bufferz= spart->rectz[offset];
+ if(spart->rectmask)
+ maskz= spart->rectmask[offset];
+ }
+
+#define CHECK_ADD(n) \
+ if(apn->p[n]==strnr && apn->obi[n]==obi && apn->seg[n]==seg) \
+ { if(!(apn->mask[n] & mask)) { apn->mask[n] |= mask; apn->v[n] += t; apn->u[n] += s; } break; }
+#define CHECK_ASSIGN(n) \
+ if(apn->p[n]==0) \
+ {apn->obi[n]= obi; apn->p[n]= strnr; apn->z[n]= zverg; apn->mask[n]= mask; apn->v[n]= t; apn->u[n]= s; apn->seg[n]= seg; break; }
+
+ /* add to pixel list */
+ if(zverg < bufferz && (spart->totapixbuf[offset] < MAX_ZROW)) {
+ if(!spart->rectmask || zverg > maskz) {
+ t = u*spart->t[0] + v*spart->t[1] + (1.0f-u-v)*spart->t[2];
+ s = fabs(u*spart->s[0] + v*spart->s[1] + (1.0f-u-v)*spart->s[2]);
+
+ apn= spart->apixbuf + offset;
+ while(apn) {
+ CHECK_ADD(0);
+ CHECK_ADD(1);
+ CHECK_ADD(2);
+ CHECK_ADD(3);
+ CHECK_ASSIGN(0);
+ CHECK_ASSIGN(1);
+ CHECK_ASSIGN(2);
+ CHECK_ASSIGN(3);
+
+ apnew= addpsAstrand(spart->zspan);
+ SWAP(APixstrand, *apnew, *apn);
+ apn->next= apnew;
+ CHECK_ASSIGN(0);
+ }
- if(spart->addpassflag & SCE_PASS_INDEXOB)
- add_strand_obindex(spart->rl, offset, buffer->obr);
+ strand_shade_refcount(cache, sseg->v[1]);
+ strand_shade_refcount(cache, sseg->v[2]);
+ spart->totapixbuf[offset]++;
+ }
}
}
@@ -663,59 +589,6 @@ static int strand_test_clip(float winmat[][4], ZSpan *zspan, float *bounds, floa
return clipflag;
}
-static void strand_shade_point(Render *re, ShadeSample *ssamp, StrandSegment *sseg, StrandPoint *spoint)
-{
- ShadeInput *shi= ssamp->shi;
- ShadeResult *shr= ssamp->shr;
- VlakRen vlr;
-
- memset(&vlr, 0, sizeof(vlr));
- vlr.flag= R_SMOOTH;
- vlr.lay= sseg->strand->buffer->lay;
- vlr.obr= sseg->strand->buffer->obr;
- if(sseg->buffer->ma->mode & MA_TANGENT_STR)
- vlr.flag |= R_TANGENT;
-
- shi->vlr= &vlr;
- shi->obi= sseg->obi;
- shi->obr= sseg->obi->obr;
-
- /* cache for shadow */
- shi->samplenr++;
-
- shade_input_set_strand(shi, sseg->strand, spoint);
- shade_input_set_strand_texco(shi, sseg->strand, sseg->v[1], spoint);
-
- /* init material vars */
- // note, keep this synced with render_types.h
- memcpy(&shi->r, &shi->mat->r, 23*sizeof(float));
- shi->har= shi->mat->har;
-
- /* shade */
- shade_samples_do_AO(ssamp);
- shade_input_do_shade(shi, shr);
-
- /* apply simplification */
- if(spoint->alpha < 1.0f) {
- shr->combined[0] *= spoint->alpha;
- shr->combined[1] *= spoint->alpha;
- shr->combined[2] *= spoint->alpha;
- shr->combined[3] *= spoint->alpha;
-
- shr->col[0] *= spoint->alpha;
- shr->col[1] *= spoint->alpha;
- shr->col[2] *= spoint->alpha;
- shr->col[3] *= spoint->alpha;
-
- shr->alpha *= spoint->alpha;
- }
-
- /* include lamphalos for strand, since halo layer was added already */
- if(re->flag & R_LAMPHALO)
- if(shi->layflag & SCE_LAY_HALO)
- renderspothalo(shi, shr->combined, shr->combined[3]);
-}
-
static void do_scanconvert_strand(Render *re, StrandPart *spart, ZSpan *zspan, float t, float dt, float *co1, float *co2, float *co3, float *co4, int sample)
{
float jco1[3], jco2[3], jco3[3], jco4[3], jx, jy;
@@ -747,16 +620,22 @@ static void do_scanconvert_strand(Render *re, StrandPart *spart, ZSpan *zspan, f
spart->sample= sample;
spart->t[0]= t-dt;
+ spart->s[0]= -1.0f;
spart->t[1]= t-dt;
+ spart->s[1]= 1.0f;
spart->t[2]= t;
- zspan_scanconvert_strand(zspan, spart, jco1, jco2, jco3, do_strand_blend);
+ spart->s[2]= 1.0f;
+ zspan_scanconvert_strand(zspan, spart, jco1, jco2, jco3, do_strand_fillac);
spart->t[0]= t-dt;
+ spart->s[0]= -1.0f;
spart->t[1]= t;
+ spart->s[1]= 1.0f;
spart->t[2]= t;
- zspan_scanconvert_strand(zspan, spart, jco1, jco3, jco4, do_strand_blend);
+ spart->s[2]= -1.0f;
+ zspan_scanconvert_strand(zspan, spart, jco1, jco3, jco4, do_strand_fillac);
}
-static void strand_render(Render *re, float winmat[][4], StrandPart *spart, ZSpan *zspan, StrandPoint *p1, StrandPoint *p2)
+static void strand_render(Render *re, StrandSegment *sseg, float winmat[][4], StrandPart *spart, ZSpan *zspan, int totzspan, StrandPoint *p1, StrandPoint *p2)
{
if(spart) {
float t= p2->t;
@@ -771,18 +650,28 @@ static void strand_render(Render *re, float winmat[][4], StrandPart *spart, ZSpa
do_scanconvert_strand(re, spart, zspan, t, dt, p1->zco2, p1->zco1, p2->zco1, p2->zco2, 0);
}
else {
- float hoco1[4], hoco2[3];
-
- projectvert(p1->co, winmat, hoco1);
- projectvert(p2->co, winmat, hoco2);
-
- /* render both strand and single pixel wire to counter aliasing */
- zbufclip4(zspan, 0, 0, p1->hoco2, p1->hoco1, p2->hoco1, p2->hoco2, 0, 0, 0, 0);
- zbufsinglewire(zspan, 0, 0, hoco1, hoco2);
+ float hoco1[4], hoco2[4];
+ int a, obi, index;
+
+ obi= sseg->obi - re->objectinstance;
+ index= sseg->strand->index;
+
+ projectvert(p1->co, winmat, hoco1);
+ projectvert(p2->co, winmat, hoco2);
+
+ for(a=0; a<totzspan; a++) {
+#if 0
+ /* render both strand and single pixel wire to counter aliasing */
+ zbufclip4(re, &zspan[a], obi, index, p1->hoco2, p1->hoco1, p2->hoco1, p2->hoco2, p1->clip2, p1->clip1, p2->clip1, p2->clip2);
+#endif
+ /* only render a line for now, which makes the shadow map more
+ similiar across frames, and so reduces flicker */
+ zbufsinglewire(&zspan[a], obi, index, hoco1, hoco2);
+ }
}
}
-
-static int strand_segment_recursive(Render *re, float winmat[][4], StrandPart *spart, ZSpan *zspan, StrandSegment *sseg, StrandPoint *p1, StrandPoint *p2, int depth)
+
+static int strand_segment_recursive(Render *re, float winmat[][4], StrandPart *spart, ZSpan *zspan, int totzspan, StrandSegment *sseg, StrandPoint *p1, StrandPoint *p2, int depth)
{
StrandPoint p;
StrandBuffer *buffer= sseg->buffer;
@@ -815,19 +704,23 @@ static int strand_segment_recursive(Render *re, float winmat[][4], StrandPart *s
do_strand_point_project(winmat, zspan, p.co2, p.hoco2, p.zco2);
}
else {
+#if 0
projectvert(p.co1, winmat, p.hoco1);
projectvert(p.co2, winmat, p.hoco2);
+ p.clip1= testclip(p.hoco1);
+ p.clip2= testclip(p.hoco2);
+#endif
}
- if(!strand_segment_recursive(re, winmat, spart, zspan, sseg, p1, &p, depth+1))
- strand_render(re, winmat, spart, zspan, p1, &p);
- if(!strand_segment_recursive(re, winmat, spart, zspan, sseg, &p, p2, depth+1))
- strand_render(re, winmat, spart, zspan, &p, p2);
+ if(!strand_segment_recursive(re, winmat, spart, zspan, totzspan, sseg, p1, &p, depth+1))
+ strand_render(re, sseg, winmat, spart, zspan, totzspan, p1, &p);
+ if(!strand_segment_recursive(re, winmat, spart, zspan, totzspan, sseg, &p, p2, depth+1))
+ strand_render(re, sseg, winmat, spart, zspan, totzspan, &p, p2);
return 1;
}
-void render_strand_segment(Render *re, float winmat[][4], StrandPart *spart, ZSpan *zspan, StrandSegment *sseg)
+void render_strand_segment(Render *re, float winmat[][4], StrandPart *spart, ZSpan *zspan, int totzspan, StrandSegment *sseg)
{
StrandBuffer *buffer= sseg->buffer;
StrandPoint *p1= &sseg->point1;
@@ -848,149 +741,55 @@ void render_strand_segment(Render *re, float winmat[][4], StrandPart *spart, ZSp
do_strand_point_project(winmat, zspan, p2->co2, p2->hoco2, p2->zco2);
}
else {
+#if 0
projectvert(p1->co1, winmat, p1->hoco1);
projectvert(p1->co2, winmat, p1->hoco2);
projectvert(p2->co1, winmat, p2->hoco1);
projectvert(p2->co2, winmat, p2->hoco2);
+ p1->clip1= testclip(p1->hoco1);
+ p1->clip2= testclip(p1->hoco2);
+ p2->clip1= testclip(p2->hoco1);
+ p2->clip2= testclip(p2->hoco2);
+#endif
}
- if(!strand_segment_recursive(re, winmat, spart, zspan, sseg, p1, p2, 0))
- strand_render(re, winmat, spart, zspan, p1, p2);
-}
-
-static void zbuffer_strands_filter(Render *re, RenderPart *pa, RenderLayer *rl, StrandPart *spart, float *pass)
-{
- RenderResult *rr= pa->result;
- ShadeResult *shr, *shrrect= spart->result;
- float *passrect= pass;
- long *rdrect;
- int osa, x, y, a, crop= 0, offs=0, od;
-
- osa= (re->osa? re->osa: 1);
-
- /* filtered render, for now we assume only 1 filter size */
- if(pa->crop) {
- crop= 1;
- offs= pa->rectx + 1;
- passrect+= 4*offs;
- shrrect+= offs*osa;
- }
-
- rdrect= pa->rectdaps;
-
- /* zero alpha pixels get speed vector max again */
- if(spart->addpassflag & SCE_PASS_VECTOR)
- if(rl->layflag & SCE_LAY_SOLID)
- reset_sky_speedvectors(pa, rl, rl->scolrect);
-
- /* init scanline updates */
- rr->renrect.ymin= 0;
- rr->renrect.ymax= -pa->crop;
- rr->renlay= rl;
-
- /* filter the shade results */
- for(y=pa->disprect.ymin+crop; y<pa->disprect.ymax-crop; y++, rr->renrect.ymax++) {
- pass= passrect;
- shr= shrrect;
- od= offs;
-
- for(x=pa->disprect.xmin+crop; x<pa->disprect.xmax-crop; x++, shr+=osa, pass+=4, od++) {
- if(spart->mask[od] == 0) {
- if(spart->addpassflag & SCE_PASS_VECTOR)
- add_transp_speed(rl, od, NULL, 0.0f, rdrect);
- }
- else {
- if(re->osa == 0) {
- addAlphaUnderFloat(pass, shr->combined);
- }
- else {
- for(a=0; a<re->osa; a++)
- add_filt_fmask(1<<a, shr[a].combined, pass, rr->rectx);
- }
-
- if(spart->addpassflag) {
- /* merge all in one, and then add */
- merge_transp_passes(rl, shr);
- add_transp_passes(rl, od, shr, pass[3]);
-
- if(spart->addpassflag & SCE_PASS_VECTOR)
- add_transp_speed(rl, od, shr->winspeed, pass[3], rdrect);
- }
- }
- }
-
- shrrect+= pa->rectx*osa;
- passrect+= 4*pa->rectx;
- offs+= pa->rectx;
- }
-
- /* disable scanline updating */
- rr->renlay= NULL;
+ if(!strand_segment_recursive(re, winmat, spart, zspan, totzspan, sseg, p1, p2, 0))
+ strand_render(re, sseg, winmat, spart, zspan, totzspan, p1, p2);
}
/* render call to fill in strands */
-unsigned short *zbuffer_strands_shade(Render *re, RenderPart *pa, RenderLayer *rl, float *pass)
+int zbuffer_strands_abuf(Render *re, RenderPart *pa, RenderLayer *rl, APixstrand *apixbuf, ListBase *apsmbase, StrandShadeCache *cache)
{
- //struct RenderPrimitiveIterator *iter;
ObjectRen *obr;
ObjectInstanceRen *obi;
ZSpan zspan;
StrandRen *strand=0;
StrandVert *svert;
+ StrandBound *sbound;
StrandPart spart;
StrandSegment sseg;
StrandSortSegment *sortsegments = NULL, *sortseg, *firstseg;
MemArena *memarena;
float z[4], bounds[4], winmat[4][4];
- int a, b, i, resultsize, totsegment, clip[4];
+ int a, b, c, i, totsegment, clip[4];
if(re->test_break())
- return NULL;
+ return 0;
if(re->totstrand == 0)
- return NULL;
+ return 0;
/* setup StrandPart */
memset(&spart, 0, sizeof(spart));
spart.re= re;
- spart.rl= rl;
- spart.pass= pass;
spart.rectx= pa->rectx;
spart.recty= pa->recty;
+ spart.apixbuf= apixbuf;
+ spart.zspan= &zspan;
+ spart.rectdaps= pa->rectdaps;
spart.rectz= pa->rectz;
- spart.addpassflag= rl->passflag & ~(SCE_PASS_Z|SCE_PASS_COMBINED);
- spart.addzbuf= rl->passflag & SCE_PASS_Z;
-
- if(re->osa) resultsize= pa->rectx*pa->recty*re->osa;
- else resultsize= pa->rectx*pa->recty;
- spart.result= MEM_callocN(sizeof(ShadeResult)*resultsize, "StrandPartResult");
- spart.mask= MEM_callocN(pa->rectx*pa->recty*sizeof(short), "StrandPartMask");
-
- if(spart.addpassflag & SCE_PASS_VECTOR) {
- /* initialize speed vectors */
- for(a=0; a<resultsize; a++) {
- spart.result[a].winspeed[0]= PASS_VECTOR_MAX;
- spart.result[a].winspeed[1]= PASS_VECTOR_MAX;
- spart.result[a].winspeed[2]= PASS_VECTOR_MAX;
- spart.result[a].winspeed[3]= PASS_VECTOR_MAX;
- }
- }
-
- if(spart.addzbuf) {
- /* duplicate rectz so we can read from the old buffer, while
- * writing new z values */
- spart.rectz= MEM_dupallocN(pa->rectz);
- spart.outrectz= pa->rectz;
- }
-
- shade_sample_initialize(&spart.ssamp1, pa, rl);
- shade_sample_initialize(&spart.ssamp2, pa, rl);
- shade_sample_initialize(&spart.ssamp, pa, rl);
- spart.ssamp1.shi[0].sample= 0;
- spart.ssamp2.shi[0].sample= 1;
- spart.ssamp1.tot= 1;
- spart.ssamp2.tot= 1;
- spart.ssamp.tot= 1;
+ spart.rectmask= pa->rectmask;
+ spart.cache= cache;
zbuf_alloc_span(&zspan, pa->rectx, pa->recty, re->clipcrop);
@@ -1005,83 +804,83 @@ unsigned short *zbuffer_strands_shade(Render *re, RenderPart *pa, RenderLayer *r
zspan.zofsx -= 0.5f;
zspan.zofsy -= 0.5f;
+ zspan.apsmbase= apsmbase;
+
/* clipping setup */
bounds[0]= (2*pa->disprect.xmin - re->winx-1)/(float)re->winx;
bounds[1]= (2*pa->disprect.xmax - re->winx+1)/(float)re->winx;
bounds[2]= (2*pa->disprect.ymin - re->winy-1)/(float)re->winy;
bounds[3]= (2*pa->disprect.ymax - re->winy+1)/(float)re->winy;
- /* sort segments */
- //iter= init_primitive_iterator(re, re->strandbuckets, pa);
-
memarena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
firstseg= NULL;
sortseg= sortsegments;
totsegment= 0;
- //while((strand = next_primitive_iterator(iter))) {
+ /* for all object instances */
for(obi=re->instancetable.first, i=0; obi; obi=obi->next, i++) {
obr= obi->obr;
+ if(!obr->strandbuf || !(obr->strandbuf->lay & rl->lay))
+ continue;
+
+ /* compute matrix and try clipping whole object */
if(obi->flag & R_TRANSFORMED)
zbuf_make_winmat(re, obi->mat, winmat);
else
zbuf_make_winmat(re, NULL, winmat);
- for(a=0; a<obr->totstrand; a++) {
- if((a & 255)==0) strand= obr->strandnodes[a>>8].strand;
- else strand++;
+ if(clip_render_object(obi->obr->boundbox, bounds, winmat))
+ continue;
- if(re->test_break())
- break;
-
-#if 0
- if(strand->clip)
+ /* for each bounding box containing a number of strands */
+ sbound= obr->strandbuf->bound;
+ for(c=0; c<obr->strandbuf->totbound; c++, sbound++) {
+ if(clip_render_object(sbound->boundbox, bounds, winmat))
continue;
-#endif
-
- svert= strand->vert;
-
- /* keep clipping and z depth for 4 control points */
- clip[1]= strand_test_clip(winmat, &zspan, bounds, svert->co, &z[1]);
- clip[2]= strand_test_clip(winmat, &zspan, bounds, (svert+1)->co, &z[2]);
- clip[0]= clip[1]; z[0]= z[1];
- for(b=0; b<strand->totvert-1; b++, svert++) {
- /* compute 4th point clipping and z depth */
- if(b < strand->totvert-2) {
- clip[3]= strand_test_clip(winmat, &zspan, bounds, (svert+2)->co, &z[3]);
- }
- else {
- clip[3]= clip[2]; z[3]= z[2];
- }
-
- /* check clipping and add to sortsegments buffer */
- if(!(clip[0] & clip[1] & clip[2] & clip[3])) {
- sortseg= BLI_memarena_alloc(memarena, sizeof(StrandSortSegment));
- sortseg->obi= i;
- sortseg->strand= strand->index;
- sortseg->segment= b;
+ /* for each strand in this bounding box */
+ for(a=sbound->start; a<sbound->end; a++) {
+ strand= RE_findOrAddStrand(obr, a);
+ svert= strand->vert;
- sortseg->z= 0.5f*(z[1] + z[2]);
+ /* keep clipping and z depth for 4 control points */
+ clip[1]= strand_test_clip(winmat, &zspan, bounds, svert->co, &z[1]);
+ clip[2]= strand_test_clip(winmat, &zspan, bounds, (svert+1)->co, &z[2]);
+ clip[0]= clip[1]; z[0]= z[1];
- sortseg->next= firstseg;
- firstseg= sortseg;
- totsegment++;
+ for(b=0; b<strand->totvert-1; b++, svert++) {
+ /* compute 4th point clipping and z depth */
+ if(b < strand->totvert-2) {
+ clip[3]= strand_test_clip(winmat, &zspan, bounds, (svert+2)->co, &z[3]);
+ }
+ else {
+ clip[3]= clip[2]; z[3]= z[2];
+ }
+
+ /* check clipping and add to sortsegments buffer */
+ if(!(clip[0] & clip[1] & clip[2] & clip[3])) {
+ sortseg= BLI_memarena_alloc(memarena, sizeof(StrandSortSegment));
+ sortseg->obi= i;
+ sortseg->strand= strand->index;
+ sortseg->segment= b;
+
+ sortseg->z= 0.5f*(z[1] + z[2]);
+
+ sortseg->next= firstseg;
+ firstseg= sortseg;
+ totsegment++;
+ }
+
+ /* shift clipping and z depth */
+ clip[0]= clip[1]; z[0]= z[1];
+ clip[1]= clip[2]; z[1]= z[2];
+ clip[2]= clip[3]; z[2]= z[3];
}
-
- /* shift clipping and z depth */
- clip[0]= clip[1]; z[0]= z[1];
- clip[1]= clip[2]; z[1]= z[2];
- clip[2]= clip[3]; z[2]= z[3];
}
}
}
-#if 0
- free_primitive_iterator(iter);
-#endif
-
if(!re->test_break()) {
/* convert list to array and sort */
sortsegments= MEM_mallocN(sizeof(StrandSortSegment)*totsegment, "StrandSortSegment");
@@ -1092,7 +891,7 @@ unsigned short *zbuffer_strands_shade(Render *re, RenderPart *pa, RenderLayer *r
BLI_memarena_free(memarena);
- spart.hash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
+ spart.totapixbuf= MEM_callocN(sizeof(int)*pa->rectx*pa->recty, "totapixbuf");
if(!re->test_break()) {
/* render segments in sorted order */
@@ -1120,135 +919,94 @@ unsigned short *zbuffer_strands_shade(Render *re, RenderPart *pa, RenderLayer *r
spart.segment= &sseg;
- render_strand_segment(re, winmat, &spart, &zspan, &sseg);
+ render_strand_segment(re, winmat, &spart, &zspan, 1, &sseg);
}
}
- // TODO printf(">>> %d\n", BLI_ghash_size(spart.hash));
- BLI_ghash_free(spart.hash, NULL, (GHashValFreeFP)MEM_freeN);
-
- zbuffer_strands_filter(re, pa, rl, &spart, pass);
-
- /* free */
- MEM_freeN(spart.result);
-
- if(spart.addzbuf)
- MEM_freeN(spart.rectz);
-
if(sortsegments)
MEM_freeN(sortsegments);
+ MEM_freeN(spart.totapixbuf);
zbuf_free_span(&zspan);
- if(!(re->osa && (rl->layflag & SCE_LAY_SOLID))) {
- MEM_freeN(spart.mask);
- spart.mask= NULL;
- }
-
- return spart.mask;
+ return totsegment;
}
-void project_strands(Render *re, void (*projectfunc)(float *, float mat[][4], float *), int do_pano, int do_buckets)
-{
-#if 0
- ObjectRen *obr;
- StrandRen *strand = NULL;
- StrandVert *svert;
- float hoco[4], min[2], max[2], bucketco[2], vec[3];
- int a, b;
- /* float bmin[3], bmax[3], bpad[3], padding[2]; */
-
- if(re->strandbuckets) {
- free_buckets(re->strandbuckets);
- re->strandbuckets= NULL;
- }
-
- if(re->totstrand == 0)
- return;
-
- if(do_buckets)
- re->strandbuckets= init_buckets(re);
+/* *************** */
- /* calculate view coordinates (and zbuffer value) */
- for(obr=re->objecttable.first; obr; obr=obr->next) {
- for(a=0; a<obr->totstrand; a++) {
- if((a & 255)==0) strand= obr->strandnodes[a>>8].strand;
- else strand++;
+StrandSurface *cache_strand_surface(Render *re, ObjectRen *obr, DerivedMesh *dm, float mat[][4], int timeoffset)
+{
+ StrandSurface *mesh;
+ MFace *mface;
+ MVert *mvert;
+ float (*co)[3];
+ int a, totvert, totface;
+
+ totvert= dm->getNumVerts(dm);
+ totface= dm->getNumFaces(dm);
+
+ for(mesh=re->strandsurface.first; mesh; mesh=mesh->next)
+ if(mesh->obr.ob == obr->ob && mesh->obr.par == obr->par
+ && mesh->obr.index == obr->index && mesh->totvert==totvert && mesh->totface==totface)
+ break;
- strand->clip= ~0;
+ if(!mesh) {
+ mesh= MEM_callocN(sizeof(StrandSurface), "StrandSurface");
+ mesh->obr= *obr;
+ mesh->totvert= totvert;
+ mesh->totface= totface;
+ mesh->face= MEM_callocN(sizeof(int)*4*mesh->totface, "StrandSurfFaces");
+ mesh->col= MEM_callocN(sizeof(float)*3*mesh->totvert, "StrandSurfCol");
+ BLI_addtail(&re->strandsurface, mesh);
+ }
+
+ if(timeoffset == -1 && !mesh->prevco)
+ mesh->prevco= co= MEM_callocN(sizeof(float)*3*mesh->totvert, "StrandSurfCo");
+ else if(timeoffset == 0 && !mesh->co)
+ mesh->co= co= MEM_callocN(sizeof(float)*3*mesh->totvert, "StrandSurfCo");
+ else if(timeoffset == 1 && !mesh->nextco)
+ mesh->nextco= co= MEM_callocN(sizeof(float)*3*mesh->totvert, "StrandSurfCo");
+ else
+ return mesh;
-#if 0
- if(!(strand->buffer->flag & R_STRAND_BSPLINE)) {
- INIT_MINMAX(bmin, bmax);
- svert= strand->vert;
- for(b=0; b<strand->totvert; b++, svert++)
- DO_MINMAX(svert->co, bmin, bmax)
+ mvert= dm->getVertArray(dm);
+ for(a=0; a<mesh->totvert; a++, mvert++) {
+ VECCOPY(co[a], mvert->co);
+ Mat4MulVecfl(mat, co[a]);
+ }
- bpad[0]= (bmax[0]-bmin[0])*0.2f;
- bpad[1]= (bmax[1]-bmin[1])*0.2f;
- bpad[2]= (bmax[2]-bmin[2])*0.2f;
- }
- else
- bpad[0]= bpad[1]= bpad[2]= 0.0f;
-
- ma= strand->buffer->ma;
- width= MAX2(ma->strand_sta, ma->strand_end);
- if(strand->buffer->flag & R_STRAND_B_UNITS) {
- bpad[0] += 0.5f*width;
- bpad[1] += 0.5f*width;
- bpad[2] += 0.5f*width;
- }
-#endif
+ mface= dm->getFaceArray(dm);
+ for(a=0; a<mesh->totface; a++, mface++) {
+ mesh->face[a][0]= mface->v1;
+ mesh->face[a][1]= mface->v2;
+ mesh->face[a][2]= mface->v3;
+ mesh->face[a][3]= mface->v4;
+ }
- INIT_MINMAX2(min, max);
- svert= strand->vert;
- for(b=0; b<strand->totvert; b++, svert++) {
- //VECADD(vec, svert->co, bpad);
+ return mesh;
+}
- /* same as VertRen */
- if(do_pano) {
- vec[0]= re->panoco*svert->co[0] + re->panosi*svert->co[2];
- vec[1]= svert->co[1];
- vec[2]= -re->panosi*svert->co[0] + re->panoco*svert->co[2];
- }
- else
- VECCOPY(vec, svert->co)
+void free_strand_surface(Render *re)
+{
+ StrandSurface *mesh;
- /* Go from wcs to hcs ... */
- projectfunc(vec, re->winmat, hoco);
- /* ... and clip in that system. */
- strand->clip &= testclip(hoco);
+ for(mesh=re->strandsurface.first; mesh; mesh=mesh->next) {
+ if(mesh->co) MEM_freeN(mesh->co);
+ if(mesh->prevco) MEM_freeN(mesh->prevco);
+ if(mesh->nextco) MEM_freeN(mesh->nextco);
+ if(mesh->col) MEM_freeN(mesh->col);
+ if(mesh->face) MEM_freeN(mesh->face);
+ }
-#if 0
- if(do_buckets) {
- project_hoco_to_bucket(re->strandbuckets, hoco, bucketco);
- DO_MINMAX2(bucketco, min, max);
- }
-#endif
- }
+ BLI_freelistN(&re->strandsurface);
+}
-#if 0
- if(do_buckets) {
- if(strand->buffer->flag & R_STRAND_BSPLINE) {
- min[0] -= width;
- min[1] -= width;
- max[0] += width;
- max[1] += width;
- }
- else {
- /* catmull-rom stays within 1.2f bounds in object space,
- * is this still true after projection? */
- min[0] -= width + (max[0]-min[0])*0.2f;
- min[1] -= width + (max[1]-min[1])*0.2f;
- max[0] += width + (max[0]-min[0])*0.2f;
- max[1] += width + (max[1]-min[1])*0.2f;
- }
+void strand_minmax(StrandRen *strand, float *min, float *max)
+{
+ StrandVert *svert;
+ int a;
- add_buckets_primitive(re->strandbuckets, min, max, strand);
- }
-#endif
- }
- }
-#endif
+ for(a=0, svert=strand->vert; a<strand->totvert; a++, svert++)
+ DO_MINMAX(svert->co, min, max)
}
diff --git a/source/blender/render/intern/source/sunsky.c b/source/blender/render/intern/source/sunsky.c
new file mode 100644
index 00000000000..2b490e71142
--- /dev/null
+++ b/source/blender/render/intern/source/sunsky.c
@@ -0,0 +1,499 @@
+ /**
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+
+#include "sunsky.h"
+#include "math.h"
+#include "BLI_arithb.h"
+#include "BKE_global.h"
+
+/**
+ * These macros are defined for vector operations
+ * */
+
+/**
+ * compute v1 = v2 op v3
+ * v1, v2 and v3 are vectors contains 3 float
+ * */
+#define vec3opv(v1, v2, op, v3) \
+ v1[0] = (v2[0] op v3[0]); \
+ v1[1] = (v2[1] op v3[1]);\
+ v1[2] = (v2[2] op v3[2]);
+
+/**
+ * compute v1 = v2 op f1
+ * v1, v2 are vectors contains 3 float
+ * and f1 is a float
+ * */
+#define vec3opf(v1, v2, op, f1)\
+ v1[0] = (v2[0] op (f1));\
+ v1[1] = (v2[1] op (f1));\
+ v1[2] = (v2[2] op (f1));
+
+/**
+ * compute v1 = f1 op v2
+ * v1, v2 are vectors contains 3 float
+ * and f1 is a float
+ * */
+#define fopvec3(v1, f1, op, v2)\
+ v1[0] = ((f1) op v2[0]);\
+ v1[1] = ((f1) op v2[1]);\
+ v1[2] = ((f1) op v2[2]);
+
+/**
+ * ClipColor:
+ * clip a color to range [0,1];
+ * */
+void ClipColor(float c[3])
+{
+ if (c[0] > 1.0) c[0] = 1.0;
+ if (c[0] < 0.0) c[0] = 0.0;
+ if (c[1] > 1.0) c[1] = 1.0;
+ if (c[1] < 0.0) c[1] = 0.0;
+ if (c[2] > 1.0) c[2] = 1.0;
+ if (c[2] < 0.0) c[2] = 0.0;
+}
+
+/**
+ * AngleBetween:
+ * compute angle between to direction
+ * all angles are in radians
+ * */
+static float AngleBetween(float thetav, float phiv, float theta, float phi)
+{
+ float cospsi = sin(thetav) * sin(theta) * cos(phi - phiv) + cos(thetav) * cos(theta);
+
+ if (cospsi > 1.0)
+ return 0;
+ if (cospsi < -1.0)
+ return M_PI;
+
+ return acos(cospsi);
+}
+
+/**
+ * DirectionToThetaPhi:
+ * this function convert a direction to it's theta and phi value
+ * parameters:
+ * toSun: contains direction information
+ * theta, phi, are return values from this conversion
+ * */
+static void DirectionToThetaPhi(float *toSun, float *theta, float *phi)
+{
+ *theta = acos(toSun[2]);
+ if (fabs(*theta) < 1e-5)
+ *phi = 0;
+ else
+ *phi = atan2(toSun[1], toSun[0]);
+}
+
+/**
+ * PerezFunction:
+ * compute perez function value based on input paramters
+ * */
+float PerezFunction(struct SunSky *sunsky, const float *lam, float theta, float gamma, float lvz)
+{
+ float den, num;
+
+ den = ((1 + lam[0] * exp(lam[1])) *
+ (1 + lam[2] * exp(lam[3] * sunsky->theta) + lam[4] * cos(sunsky->theta) * cos(sunsky->theta)));
+
+ num = ((1 + lam[0] * exp(lam[1] / cos(theta))) *
+ (1 + lam[2] * exp(lam[3] * gamma) + lam[4] * cos(gamma) * cos(gamma)));
+
+ return(lvz * num / den);}
+
+/**
+ * InitSunSky:
+ * this function compute some sun,sky parameters according to input parameters and also initiate some other sun, sky parameters
+ * parameters:
+ * sunSky, is a structure that contains informtion about sun, sky and atmosphere, in this function, most of its values initiated
+ * turb, is atmosphere turbidity
+ * toSun, contains sun direction
+ * horizon_brighness, controls the brightness of the horizon colors
+ * spread, controls colors spreed at horizon
+ * sun_brightness, controls sun's brightness
+ * sun_size, controls sun's size
+ * back_scatter, controls back scatter light
+ * */
+void InitSunSky(struct SunSky *sunsky, float turb, float *toSun, float horizon_brightness,
+ float spread,float sun_brightness, float sun_size, float back_scatter,
+ float skyblendfac, short skyblendtype, float sky_exposure, float sky_colorspace)
+{
+
+ float theta2;
+ float theta3;
+ float T;
+ float T2;
+ float chi;
+
+ sunsky->turbidity = turb;
+
+ sunsky->horizon_brightness = horizon_brightness;
+ sunsky->spread = spread;
+ sunsky->sun_brightness = sun_brightness;
+ sunsky->sun_size = sun_size;
+ sunsky->backscattered_light = back_scatter;
+ sunsky->skyblendfac= skyblendfac;
+ sunsky->skyblendtype= skyblendtype;
+ sunsky->sky_exposure= -sky_exposure;
+ sunsky->sky_colorspace= sky_colorspace;
+
+ sunsky->toSun[0] = toSun[0];
+ sunsky->toSun[1] = toSun[1];
+ sunsky->toSun[2] = toSun[2];
+
+ DirectionToThetaPhi(sunsky->toSun, &sunsky->theta, &sunsky->phi);
+
+ sunsky->sunSolidAngle = 0.25 * M_PI * 1.39 * 1.39 / (150 * 150); // = 6.7443e-05
+
+ theta2 = sunsky->theta*sunsky->theta;
+ theta3 = theta2 * sunsky->theta;
+ T = turb;
+ T2 = turb*turb;
+
+ chi = (4.0 / 9.0 - T / 120.0) * (M_PI - 2 * sunsky->theta);
+ sunsky->zenith_Y = (4.0453 * T - 4.9710) * tan(chi) - .2155 * T + 2.4192;
+ sunsky->zenith_Y *= 1000; // conversion from kcd/m^2 to cd/m^2
+
+ if (sunsky->zenith_Y<=0)
+ sunsky->zenith_Y = 1e-6;
+
+ sunsky->zenith_x =
+ ( + 0.00165 * theta3 - 0.00374 * theta2 + 0.00208 * sunsky->theta + 0) * T2 +
+ ( -0.02902 * theta3 + 0.06377 * theta2 - 0.03202 * sunsky->theta + 0.00394) * T +
+ ( + 0.11693 * theta3 - 0.21196 * theta2 + 0.06052 * sunsky->theta + 0.25885);
+
+ sunsky->zenith_y =
+ ( + 0.00275 * theta3 - 0.00610 * theta2 + 0.00316 * sunsky->theta + 0) * T2 +
+ ( -0.04214 * theta3 + 0.08970 * theta2 - 0.04153 * sunsky->theta + 0.00515) * T +
+ ( + 0.15346 * theta3 - 0.26756 * theta2 + 0.06669 * sunsky->theta + 0.26688);
+
+
+ sunsky->perez_Y[0] = 0.17872 * T - 1.46303;
+ sunsky->perez_Y[1] = -0.35540 * T + 0.42749;
+ sunsky->perez_Y[2] = -0.02266 * T + 5.32505;
+ sunsky->perez_Y[3] = 0.12064 * T - 2.57705;
+ sunsky->perez_Y[4] = -0.06696 * T + 0.37027;
+
+ sunsky->perez_x[0] = -0.01925 * T - 0.25922;
+ sunsky->perez_x[1] = -0.06651 * T + 0.00081;
+ sunsky->perez_x[2] = -0.00041 * T + 0.21247;
+ sunsky->perez_x[3] = -0.06409 * T - 0.89887;
+ sunsky->perez_x[4] = -0.00325 * T + 0.04517;
+
+ sunsky->perez_y[0] = -0.01669 * T - 0.26078;
+ sunsky->perez_y[1] = -0.09495 * T + 0.00921;
+ sunsky->perez_y[2] = -0.00792 * T + 0.21023;
+ sunsky->perez_y[3] = -0.04405 * T - 1.65369;
+ sunsky->perez_y[4] = -0.01092 * T + 0.05291;
+
+ /* suggested by glome in
+ * http://projects.blender.org/tracker/?func=detail&atid=127&aid=8063&group_id=9*/
+ sunsky->perez_Y[0] *= sunsky->horizon_brightness;
+ sunsky->perez_x[0] *= sunsky->horizon_brightness;
+ sunsky->perez_y[0] *= sunsky->horizon_brightness;
+
+ sunsky->perez_Y[1] *= sunsky->spread;
+ sunsky->perez_x[1] *= sunsky->spread;
+ sunsky->perez_y[1] *= sunsky->spread;
+
+ sunsky->perez_Y[2] *= sunsky->sun_brightness;
+ sunsky->perez_x[2] *= sunsky->sun_brightness;
+ sunsky->perez_y[2] *= sunsky->sun_brightness;
+
+ sunsky->perez_Y[3] *= sunsky->sun_size;
+ sunsky->perez_x[3] *= sunsky->sun_size;
+ sunsky->perez_y[3] *= sunsky->sun_size;
+
+ sunsky->perez_Y[4] *= sunsky->backscattered_light;
+ sunsky->perez_x[4] *= sunsky->backscattered_light;
+ sunsky->perez_y[4] *= sunsky->backscattered_light;
+}
+
+/**
+ * GetSkyXYZRadiance:
+ * this function compute sky radiance according to a view parameters `theta' and `phi'and sunSky values
+ * parameters:
+ * sunSky, sontains sun and sky parameters
+ * theta, is sun's theta
+ * phi, is sun's phi
+ * color_out, is computed color that shows sky radiance in XYZ color format
+ * */
+void GetSkyXYZRadiance(struct SunSky* sunsky, float theta, float phi, float color_out[3])
+{
+ float gamma;
+ float x,y,Y,X,Z;
+ float hfade=1, nfade=1;
+
+
+ if (theta>(0.5*M_PI)) {
+ hfade = 1.0-(theta*M_1_PI-0.5)*2.0;
+ hfade = hfade*hfade*(3.0-2.0*hfade);
+ theta = 0.5*M_PI;
+ }
+
+ if (sunsky->theta>(0.5*M_PI)) {
+ if (theta<=0.5*M_PI) {
+ nfade = 1.0-(0.5-theta*M_1_PI)*2.0;
+ nfade *= 1.0-(sunsky->theta*M_1_PI-0.5)*2.0;
+ nfade = nfade*nfade*(3.0-2.0*nfade);
+ }
+ }
+
+ gamma = AngleBetween(theta, phi, sunsky->theta, sunsky->phi);
+
+ // Compute xyY values
+ x = PerezFunction(sunsky, sunsky->perez_x, theta, gamma, sunsky->zenith_x);
+ y = PerezFunction(sunsky, sunsky->perez_y, theta, gamma, sunsky->zenith_y);
+ Y = 6.666666667e-5 * nfade * hfade * PerezFunction(sunsky, sunsky->perez_Y, theta, gamma, sunsky->zenith_Y);
+
+ if(sunsky->sky_exposure!=0.0f)
+ Y = 1.0 - exp(Y*sunsky->sky_exposure);
+
+ X = (x / y) * Y;
+ Z = ((1 - x - y) / y) * Y;
+
+ color_out[0] = X;
+ color_out[1] = Y;
+ color_out[2] = Z;
+}
+
+/**
+ * GetSkyXYZRadiancef:
+ * this function compute sky radiance according to a view direction `varg' and sunSky values
+ * parameters:
+ * sunSky, sontains sun and sky parameters
+ * varg, shows direction
+ * color_out, is computed color that shows sky radiance in XYZ color format
+ * */
+void GetSkyXYZRadiancef(struct SunSky* sunsky, const float varg[3], float color_out[3])
+{
+ float theta, phi;
+ float v[3];
+
+ VecCopyf(v, (float*)varg);
+ Normalize(v);
+
+ if (v[2] < 0.001){
+ v[2] = 0.001;
+ Normalize(v);
+ }
+
+ DirectionToThetaPhi(v, &theta, &phi);
+ GetSkyXYZRadiance(sunsky, theta, phi, color_out);
+}
+
+/**
+ * ComputeAttenuatedSunlight:
+ * this function compute attenuated sun light based on sun's theta and atmosphere turbidity
+ * parameters:
+ * theta, is sun's theta
+ * turbidity: is atmosphere turbidity
+ * fTau: contains computed attenuated sun light
+ * */
+void ComputeAttenuatedSunlight(float theta, int turbidity, float fTau[3])
+{
+ float fBeta ;
+ float fTauR, fTauA;
+ float m ;
+ float fAlpha;
+
+ int i;
+ float fLambda[3];
+ fLambda[0] = 0.65f;
+ fLambda[1] = 0.57f;
+ fLambda[2] = 0.475f;
+
+ fAlpha = 1.3f;
+ fBeta = 0.04608365822050f * turbidity - 0.04586025928522f;
+
+ m = 1.0/(cos(theta) + 0.15f*pow(93.885f-theta/M_PI*180.0f,-1.253f));
+
+ for(i = 0; i < 3; i++)
+ {
+ // Rayleigh Scattering
+ fTauR = exp( -m * 0.008735f * pow(fLambda[i], (float)(-4.08f)));
+
+ // Aerosal (water + dust) attenuation
+ fTauA = exp(-m * fBeta * pow(fLambda[i], -fAlpha));
+
+ fTau[i] = fTauR * fTauA;
+ }
+}
+
+/**
+ * InitAtmosphere:
+ * this function intiate sunSky structure with user input parameters.
+ * parameters:
+ * sunSky, contains information about sun, and in this function some atmosphere parameters will initiated
+ * sun_intens, shows sun intensity value
+ * mief, Mie scattering factor this factor currently call with 1.0
+ * rayf, Rayleigh scattering factor, this factor currently call with 1.0
+ * inscattf, inscatter light factor that range from 0.0 to 1.0, 0.0 means no inscatter light and 1.0 means full inscatter light
+ * extincf, extinction light factor that range from 0.0 to 1.0, 0.0 means no extinction and 1.0 means full extinction
+ * disf, is distance factor, multiplyed to pixle's z value to compute each pixle's distance to camera,
+ * */
+void InitAtmosphere(struct SunSky *sunSky, float sun_intens, float mief, float rayf,
+ float inscattf, float extincf, float disf)
+{
+ const float pi = 3.14159265358f;
+ const float n = 1.003f; // refractive index
+ const float N = 2.545e25;
+ const float pn = 0.035f;
+ const float T = 2.0f;
+ float fTemp, fTemp2, fTemp3, fBeta, fBetaDash;
+ float c = (6.544*T - 6.51)*1e-17;
+ float K[3] = {0.685f, 0.679f, 0.670f};
+ float vBetaMieTemp[3];
+
+ float fLambda[3],fLambda2[3], fLambda4[3];
+ float vLambda2[3];
+ float vLambda4[3];
+
+ int i;
+
+ sunSky->atm_SunIntensity = sun_intens;
+ sunSky->atm_BetaMieMultiplier = mief;
+ sunSky->atm_BetaRayMultiplier = rayf;
+ sunSky->atm_InscatteringMultiplier = inscattf;
+ sunSky->atm_ExtinctionMultiplier = extincf;
+ sunSky->atm_DistanceMultiplier = disf;
+
+ sunSky->atm_HGg=0.8;
+
+ fLambda[0] = 1/650e-9f;
+ fLambda[1] = 1/570e-9f;
+ fLambda[2] = 1/475e-9f;
+ for (i=0; i < 3; i++)
+ {
+ fLambda2[i] = fLambda[i]*fLambda[i];
+ fLambda4[i] = fLambda2[i]*fLambda2[i];
+ }
+
+ vLambda2[0] = fLambda2[0];
+ vLambda2[1] = fLambda2[1];
+ vLambda2[2] = fLambda2[2];
+
+ vLambda4[0] = fLambda4[0];
+ vLambda4[1] = fLambda4[1];
+ vLambda4[2] = fLambda4[2];
+
+ // Rayleigh scattering constants.
+ fTemp = pi*pi*(n*n-1)*(n*n-1)*(6+3*pn)/(6-7*pn)/N;
+ fBeta = 8*fTemp*pi/3;
+
+ vec3opf(sunSky->atm_BetaRay, vLambda4, *, fBeta);
+ fBetaDash = fTemp/2;
+ vec3opf(sunSky->atm_BetaDashRay, vLambda4,*, fBetaDash);
+
+
+ // Mie scattering constants.
+ fTemp2 = 0.434*c*(2*pi)*(2*pi)*0.5f;
+ vec3opf(sunSky->atm_BetaDashMie, vLambda2, *, fTemp2);
+
+ fTemp3 = 0.434f*c*pi*(2*pi)*(2*pi);
+
+ vec3opv(vBetaMieTemp, K, *, fLambda);
+ vec3opf(sunSky->atm_BetaMie, vBetaMieTemp,*, fTemp3);
+
+}
+
+/**
+ * AtmospherePixleShader:
+ * this function apply atmosphere effect on a pixle color `rgb' at distance `s'
+ * parameters:
+ * sunSky, contains information about sun parameters and user values
+ * view, is camera view vector
+ * s, is distance
+ * rgb, contains rendered color value for a pixle
+ * */
+void AtmospherePixleShader( struct SunSky* sunSky, float view[3], float s, float rgb[3])
+{
+ float costheta;
+ float Phase_1;
+ float Phase_2;
+ float sunColor[3];
+
+ float E[3];
+ float E1[3];
+
+
+ float I[3];
+ float fTemp;
+ float vTemp1[3], vTemp2[3];
+
+ float sunDirection[3];
+
+ s *= sunSky->atm_DistanceMultiplier;
+
+ sunDirection[0] = sunSky->toSun[0];
+ sunDirection[1] = sunSky->toSun[1];
+ sunDirection[2] = sunSky->toSun[2];
+
+ costheta = Inpf(view, sunDirection); // cos(theta)
+ Phase_1 = 1 + (costheta * costheta); // Phase_1
+
+ vec3opf(sunSky->atm_BetaRay, sunSky->atm_BetaRay, *, sunSky->atm_BetaRayMultiplier);
+ vec3opf(sunSky->atm_BetaMie, sunSky->atm_BetaMie, *, sunSky->atm_BetaMieMultiplier);
+ vec3opv(sunSky->atm_BetaRM, sunSky->atm_BetaRay, +, sunSky->atm_BetaMie);
+
+ //e^(-(beta_1 + beta_2) * s) = E1
+ vec3opf(E1, sunSky->atm_BetaRM, *, -s/log(2));
+ E1[0] = exp(E1[0]);
+ E1[1] = exp(E1[1]);
+ E1[2] = exp(E1[2]);
+
+ VecCopyf(E, E1);
+
+ //Phase2(theta) = (1-g^2)/(1+g-2g*cos(theta))^(3/2)
+ fTemp = 1 + sunSky->atm_HGg - 2 * sunSky->atm_HGg * costheta;
+ fTemp = fTemp * sqrt(fTemp);
+ Phase_2 = (1 - sunSky->atm_HGg * sunSky->atm_HGg)/fTemp;
+
+ vec3opf(vTemp1, sunSky->atm_BetaDashRay, *, Phase_1);
+ vec3opf(vTemp2, sunSky->atm_BetaDashMie, *, Phase_2);
+
+ vec3opv(vTemp1, vTemp1, +, vTemp2);
+ fopvec3(vTemp2, 1.0, -, E1);
+ vec3opv(vTemp1, vTemp1, *, vTemp2);
+
+ fopvec3(vTemp2, 1.0, / , sunSky->atm_BetaRM);
+
+ vec3opv(I, vTemp1, *, vTemp2);
+
+ vec3opf(I, I, *, sunSky->atm_InscatteringMultiplier);
+ vec3opf(E, E, *, sunSky->atm_ExtinctionMultiplier);
+
+ //scale to color sun
+ ComputeAttenuatedSunlight(sunSky->theta, sunSky->turbidity, sunColor);
+ vec3opv(E, E, *, sunColor);
+
+ vec3opf(I, I, *, sunSky->atm_SunIntensity);
+
+ vec3opv(rgb, rgb, *, E);
+ vec3opv(rgb, rgb, +, I);
+}
+
+#undef vec3opv
+#undef vec3opf
+#undef fopvec3
+
+/* EOF */
diff --git a/source/blender/render/intern/source/texture.c b/source/blender/render/intern/source/texture.c
index b502fb2b421..7ce66ff6d12 100644
--- a/source/blender/render/intern/source/texture.c
+++ b/source/blender/render/intern/source/texture.c
@@ -53,6 +53,7 @@
#include "BKE_global.h"
#include "BKE_main.h"
+#include "BKE_material.h"
#include "BKE_library.h"
#include "BKE_image.h"
@@ -98,7 +99,7 @@ void init_render_texture(Render *re, Tex *tex)
}
else if(tex->type==TEX_ENVMAP) {
/* just in case */
- tex->imaflag= TEX_INTERPOL | TEX_MIPMAP;
+ tex->imaflag |= TEX_INTERPOL | TEX_MIPMAP;
tex->extend= TEX_CLIP;
if(tex->env) {
@@ -720,30 +721,59 @@ static int plugintex(Tex *tex, float *texvec, float *dxt, float *dyt, int osatex
{
PluginTex *pit;
int rgbnor=0;
+ float result[ 8 ];
texres->tin= 0.0;
pit= tex->plugin;
if(pit && pit->doit) {
if(texres->nor) {
- VECCOPY(pit->result+5, texres->nor);
+ if (pit->version < 6) {
+ VECCOPY(pit->result+5, texres->nor);
+ } else {
+ VECCOPY(result+5, texres->nor);
+ }
+ }
+ if (pit->version < 6) {
+ if(osatex) rgbnor= ((TexDoitold)pit->doit)(tex->stype,
+ pit->data, texvec, dxt, dyt);
+ else rgbnor= ((TexDoitold)pit->doit)(tex->stype,
+ pit->data, texvec, 0, 0);
+ } else {
+ if(osatex) rgbnor= ((TexDoit)pit->doit)(tex->stype,
+ pit->data, texvec, dxt, dyt, result);
+ else rgbnor= ((TexDoit)pit->doit)(tex->stype,
+ pit->data, texvec, 0, 0, result);
}
- if(osatex) rgbnor= ((TexDoit)pit->doit)(tex->stype, pit->data, texvec, dxt, dyt);
- else rgbnor= ((TexDoit)pit->doit)(tex->stype, pit->data, texvec, 0, 0);
- texres->tin= pit->result[0];
+ if (pit->version < 6) {
+ texres->tin = pit->result[0];
+ } else {
+ texres->tin = result[0];
+ }
if(rgbnor & TEX_NOR) {
if(texres->nor) {
- VECCOPY(texres->nor, pit->result+5);
+ if (pit->version < 6) {
+ VECCOPY(texres->nor, pit->result+5);
+ } else {
+ VECCOPY(texres->nor, result+5);
+ }
}
}
if(rgbnor & TEX_RGB) {
- texres->tr= pit->result[1];
- texres->tg= pit->result[2];
- texres->tb= pit->result[3];
- texres->ta= pit->result[4];
+ if (pit->version < 6) {
+ texres->tr = pit->result[1];
+ texres->tg = pit->result[2];
+ texres->tb = pit->result[3];
+ texres->ta = pit->result[4];
+ } else {
+ texres->tr = result[1];
+ texres->tg = result[2];
+ texres->tb = result[3];
+ texres->ta = result[4];
+ }
BRICONTRGB;
}
@@ -1202,6 +1232,8 @@ static int multitex(Tex *tex, float *texvec, float *dxt, float *dyt, int osatex,
return retval;
}
+/* Warning, if the texres's values are not declared zero, check the return value to be sure
+ * the color values are set before using the r/g/b values, otherwise you may use uninitialized values - Campbell */
int multitex_ext(Tex *tex, float *texvec, float *dxt, float *dyt, int osatex, TexResult *texres)
{
@@ -1255,7 +1287,7 @@ void texture_rgb_blend(float *in, float *tex, float *out, float fact, float facg
in[1]= (fact*tex[1] + facm*out[1]);
in[2]= (fact*tex[2] + facm*out[2]);
break;
-
+
case MTEX_MUL:
fact*= facg;
facm= 1.0-facg;
@@ -1343,9 +1375,28 @@ void texture_rgb_blend(float *in, float *tex, float *out, float fact, float facg
col= fact*tex[2];
if(col > out[2]) in[2]= col; else in[2]= out[2];
break;
+
+ case MTEX_BLEND_HUE:
+ fact*= facg;
+ VECCOPY(in, out);
+ ramp_blend(MA_RAMP_HUE, in, in+1, in+2, fact, tex);
+ break;
+ case MTEX_BLEND_SAT:
+ fact*= facg;
+ VECCOPY(in, out);
+ ramp_blend(MA_RAMP_SAT, in, in+1, in+2, fact, tex);
+ break;
+ case MTEX_BLEND_VAL:
+ fact*= facg;
+ VECCOPY(in, out);
+ ramp_blend(MA_RAMP_VAL, in, in+1, in+2, fact, tex);
+ break;
+ case MTEX_BLEND_COLOR:
+ fact*= facg;
+ VECCOPY(in, out);
+ ramp_blend(MA_RAMP_COLOR, in, in+1, in+2, fact, tex);
+ break;
}
-
-
}
float texture_value_blend(float tex, float out, float fact, float facg, int blendtype, int flip)
@@ -1427,7 +1478,14 @@ void do_material_tex(ShadeInput *shi)
/* which coords */
if(mtex->texco==TEXCO_ORCO) {
- co= shi->lo; dx= shi->dxlo; dy= shi->dylo;
+ if(mtex->texflag & MTEX_DUPLI_MAPTO) {
+ co= shi->duplilo; dx= dxt; dy= dyt;
+ dxt[0]= dxt[1]= dxt[2]= 0.0f;
+ dyt[0]= dyt[1]= dyt[2]= 0.0f;
+ }
+ else {
+ co= shi->lo; dx= shi->dxlo; dy= shi->dylo;
+ }
}
else if(mtex->texco==TEXCO_STICKY) {
co= shi->sticky; dx= shi->dxsticky; dy= shi->dysticky;
@@ -1439,6 +1497,9 @@ void do_material_tex(ShadeInput *shi)
dx= dxt;
dy= dyt;
VECCOPY(tempvec, shi->co);
+ if(mtex->texflag & MTEX_OB_DUPLI_ORIG)
+ if(shi->obi && shi->obi->duplitexmat)
+ MTC_Mat4MulVecfl(shi->obi->duplitexmat, tempvec);
MTC_Mat4MulVecfl(ob->imat, tempvec);
if(shi->osatex) {
VECCOPY(dxt, shi->dxco);
@@ -1466,28 +1527,35 @@ void do_material_tex(ShadeInput *shi)
co= shi->gl; dx= shi->dxco; dy= shi->dyco;
}
else if(mtex->texco==TEXCO_UV) {
- ShadeInputUV *suv= &shi->uv[shi->actuv];
- int i;
-
- if(mtex->uvname[0] != 0) {
- for(i = 0; i < shi->totuv; i++) {
- if(strcmp(shi->uv[i].name, mtex->uvname)==0) {
- suv= &shi->uv[i];
- break;
+ if(mtex->texflag & MTEX_DUPLI_MAPTO) {
+ co= shi->dupliuv; dx= dxt; dy= dyt;
+ dxt[0]= dxt[1]= dxt[2]= 0.0f;
+ dyt[0]= dyt[1]= dyt[2]= 0.0f;
+ }
+ else {
+ ShadeInputUV *suv= &shi->uv[shi->actuv];
+ int i;
+
+ if(mtex->uvname[0] != 0) {
+ for(i = 0; i < shi->totuv; i++) {
+ if(strcmp(shi->uv[i].name, mtex->uvname)==0) {
+ suv= &shi->uv[i];
+ break;
+ }
}
}
- }
- co= suv->uv;
- dx= suv->dxuv;
- dy= suv->dyuv;
+ co= suv->uv;
+ dx= suv->dxuv;
+ dy= suv->dyuv;
+ }
}
else if(mtex->texco==TEXCO_WINDOW) {
co= shi->winco; dx= shi->dxwin; dy= shi->dywin;
}
else if(mtex->texco==TEXCO_STRAND) {
co= tempvec; dx= dxt; dy= dyt;
- co[0]= shi->strand;
+ co[0]= shi->strandco;
co[1]= co[2]= 0.0f;
dx[0]= shi->dxstrand;
dx[1]= dx[2]= 0.0f;
@@ -1644,18 +1712,18 @@ void do_material_tex(ShadeInput *shi)
texres.nor[2]= texres.tb;
}
else {
- float co= 0.5*cos(texres.tin-0.5);
+ float co_nor= 0.5*cos(texres.tin-0.5);
float si= 0.5*sin(texres.tin-0.5);
float f1, f2;
f1= shi->vn[0];
f2= shi->vn[1];
- texres.nor[0]= f1*co+f2*si;
- texres.nor[1]= f2*co-f1*si;
+ texres.nor[0]= f1*co_nor+f2*si;
+ texres.nor[1]= f2*co_nor-f1*si;
f1= shi->vn[1];
f2= shi->vn[2];
- texres.nor[1]= f1*co+f2*si;
- texres.nor[2]= f2*co-f1*si;
+ texres.nor[1]= f1*co_nor+f2*si;
+ texres.nor[2]= f2*co_nor-f1*si;
}
}
// warping, local space
@@ -1743,11 +1811,11 @@ void do_material_tex(ShadeInput *shi)
if(mtex->normapspace == MTEX_NSPACE_TANGENT) {
/* qdn: tangent space */
float B[3], tv[3];
- Crossf(B, shi->vn, shi->tang); /* bitangent */
+ Crossf(B, shi->vn, shi->nmaptang); /* bitangent */
/* transform norvec from tangent space to object surface in camera space */
- tv[0] = texres.nor[0]*shi->tang[0] + texres.nor[1]*B[0] + texres.nor[2]*shi->vn[0];
- tv[1] = texres.nor[0]*shi->tang[1] + texres.nor[1]*B[1] + texres.nor[2]*shi->vn[1];
- tv[2] = texres.nor[0]*shi->tang[2] + texres.nor[1]*B[2] + texres.nor[2]*shi->vn[2];
+ tv[0] = texres.nor[0]*shi->nmaptang[0] + texres.nor[1]*B[0] + texres.nor[2]*shi->vn[0];
+ tv[1] = texres.nor[0]*shi->nmaptang[1] + texres.nor[1]*B[1] + texres.nor[2]*shi->vn[1];
+ tv[2] = texres.nor[0]*shi->nmaptang[2] + texres.nor[1]*B[2] + texres.nor[2]*shi->vn[2];
shi->vn[0]= facm*shi->vn[0] + fact*tv[0];
shi->vn[1]= facm*shi->vn[1] + fact*tv[1];
shi->vn[2]= facm*shi->vn[2] + fact*tv[2];
@@ -1762,8 +1830,8 @@ void do_material_tex(ShadeInput *shi)
Mat4Mul3Vecfl(R.viewmat, nor);
}
else if(mtex->normapspace == MTEX_NSPACE_OBJECT) {
- if(shi->vlr && shi->vlr->obr->ob)
- Mat4Mul3Vecfl(shi->vlr->obr->ob->obmat, nor);
+ if(shi->obr && shi->obr->ob)
+ Mat4Mul3Vecfl(shi->obr->ob->obmat, nor);
Mat4Mul3Vecfl(R.viewmat, nor);
}
@@ -1776,24 +1844,24 @@ void do_material_tex(ShadeInput *shi)
}
}
else {
+ float nor[3], dot;
+
if(shi->mat->mode & MA_TANGENT_V) {
shi->tang[0]+= Tnor*tex->norfac*texres.nor[0];
shi->tang[1]+= Tnor*tex->norfac*texres.nor[1];
shi->tang[2]+= Tnor*tex->norfac*texres.nor[2];
}
- else {
- float nor[3], dot;
- /* prevent bump to become negative normal */
- nor[0]= Tnor*tex->norfac*texres.nor[0];
- nor[1]= Tnor*tex->norfac*texres.nor[1];
- nor[2]= Tnor*tex->norfac*texres.nor[2];
-
- dot= 0.5f + 0.5f*INPR(nor, shi->vn);
-
- shi->vn[0]+= dot*nor[0];
- shi->vn[1]+= dot*nor[1];
- shi->vn[2]+= dot*nor[2];
- }
+
+ /* prevent bump to become negative normal */
+ nor[0]= Tnor*tex->norfac*texres.nor[0];
+ nor[1]= Tnor*tex->norfac*texres.nor[1];
+ nor[2]= Tnor*tex->norfac*texres.nor[2];
+
+ dot= 0.5f + 0.5f*INPR(nor, shi->vn);
+
+ shi->vn[0]+= dot*nor[0];
+ shi->vn[1]+= dot*nor[1];
+ shi->vn[2]+= dot*nor[2];
}
Normalize(shi->vn);
@@ -2233,7 +2301,7 @@ void do_sky_tex(float *rco, float *lo, float *dxyview, float *hor, float *zen, f
/* ------------------------------------------------------------------------- */
/* colf supposed to be initialized with la->r,g,b */
-void do_lamp_tex(LampRen *la, float *lavec, ShadeInput *shi, float *colf)
+void do_lamp_tex(LampRen *la, float *lavec, ShadeInput *shi, float *colf, int effect)
{
Object *ob;
MTex *mtex;
@@ -2372,7 +2440,7 @@ void do_lamp_tex(LampRen *la, float *lavec, ShadeInput *shi, float *colf)
}
/* mapping */
- if(mtex->mapto & LAMAP_COL) {
+ if(((mtex->mapto & LAMAP_COL) && (effect & LA_TEXTURE))||((mtex->mapto & LAMAP_SHAD) && (effect & LA_SHAD_TEX))) {
float col[3];
if(rgb==0) {
@@ -2450,21 +2518,31 @@ int externtex(MTex *mtex, float *vec, float *tin, float *tr, float *tg, float *t
void render_realtime_texture(ShadeInput *shi, Image *ima)
{
TexResult texr;
- static Tex tex1, tex2; // threadsafe
+ static Tex imatex[BLENDER_MAX_THREADS]; // threadsafe
static int firsttime= 1;
Tex *tex;
float texvec[3], dx[2], dy[2];
ShadeInputUV *suv= &shi->uv[shi->actuv];
+ int a;
+
+ if(R.r.scemode & R_NO_TEX) return;
if(firsttime) {
- firsttime= 0;
- default_tex(&tex1);
- default_tex(&tex2);
- tex1.type= TEX_IMAGE;
- tex2.type= TEX_IMAGE;
+ BLI_lock_thread(LOCK_IMAGE);
+ if(firsttime) {
+ for(a=0; a<BLENDER_MAX_THREADS; a++) {
+ memset(&imatex[a], 0, sizeof(Tex));
+ default_tex(&imatex[a]);
+ imatex[a].type= TEX_IMAGE;
+ }
+
+ firsttime= 0;
+ }
+ BLI_unlock_thread(LOCK_IMAGE);
}
- if(shi->ys & 1) tex= &tex1; else tex= &tex2; // threadsafe
+ tex= &imatex[shi->thread];
+ tex->iuser.ok= ima->ok;
texvec[0]= 0.5+0.5*suv->uv[0];
texvec[1]= 0.5+0.5*suv->uv[1];
@@ -2480,7 +2558,7 @@ void render_realtime_texture(ShadeInput *shi, Image *ima)
if(shi->osatex) imagewraposa(tex, ima, NULL, texvec, dx, dy, &texr);
else imagewrap(tex, ima, NULL, texvec, &texr);
-
+
shi->vcol[0]*= texr.tr;
shi->vcol[1]*= texr.tg;
shi->vcol[2]*= texr.tb;
diff --git a/source/blender/render/intern/source/zbuf.c b/source/blender/render/intern/source/zbuf.c
index 57d2bbb3489..509ac81c58b 100644
--- a/source/blender/render/intern/source/zbuf.c
+++ b/source/blender/render/intern/source/zbuf.c
@@ -196,7 +196,6 @@ static void zbuf_add_to_span(ZSpan *zspan, float *v1, float *v2)
/* Functions */
/*-----------------------------------------------------------*/
-
void fillrect(int *rect, int x, int y, int val)
{
int len, *drect;
@@ -307,8 +306,8 @@ static void zbuffillAc4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v2,
float x0,y0,z0;
float x1,y1,z1,x2,y2,z2,xx1;
float *span1, *span2;
- int *rz, x, y;
- int sn1, sn2, rectx, *rectzofs, my0, my2, mask;
+ int *rz, *rm, x, y;
+ int sn1, sn2, rectx, *rectzofs, *rectmaskofs, my0, my2, mask;
/* init */
zbuf_init_span(zspan);
@@ -353,6 +352,7 @@ static void zbuffillAc4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v2,
/* start-offset in rect */
rectx= zspan->rectx;
rectzofs= (int *)(zspan->arectz+rectx*(my2));
+ rectmaskofs= (int *)(zspan->rectmask+rectx*(my2));
apofs= (zspan->apixbuf+ rectx*(my2));
mask= zspan->mask;
@@ -377,35 +377,40 @@ static void zbuffillAc4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v2,
if(sn1<0) sn1= 0;
if(sn2>=sn1) {
+ int intzverg;
+
zverg= (double)sn1*zxd + zy0;
rz= rectzofs+sn1;
+ rm= rectmaskofs+sn1;
ap= apofs+sn1;
x= sn2-sn1;
zverg-= zspan->polygon_offset;
while(x>=0) {
- if( (int)zverg < *rz) {
-// int i= zvlnr & 3;
-
- apn= ap;
- while(apn) {
- if(apn->p[0]==0) {apn->obi[0]= obi; apn->p[0]= zvlnr; apn->z[0]= zverg; apn->mask[0]= mask; break; }
- if(apn->p[0]==zvlnr && apn->obi[0]==obi) {apn->mask[0]|= mask; break; }
- if(apn->p[1]==0) {apn->obi[1]= obi; apn->p[1]= zvlnr; apn->z[1]= zverg; apn->mask[1]= mask; break; }
- if(apn->p[1]==zvlnr && apn->obi[1]==obi) {apn->mask[1]|= mask; break; }
- if(apn->p[2]==0) {apn->obi[2]= obi; apn->p[2]= zvlnr; apn->z[2]= zverg; apn->mask[2]= mask; break; }
- if(apn->p[2]==zvlnr && apn->obi[2]==obi) {apn->mask[2]|= mask; break; }
- if(apn->p[3]==0) {apn->obi[3]= obi; apn->p[3]= zvlnr; apn->z[3]= zverg; apn->mask[3]= mask; break; }
- if(apn->p[3]==zvlnr && apn->obi[3]==obi) {apn->mask[3]|= mask; break; }
-// if(apn->p[i]==0) {apn->obi[i]= obi; apn->p[i]= zvlnr; apn->z[i]= zverg; apn->mask[i]= mask; break; }
-// if(apn->p[i]==zvlnr && apn->obi[i]==obi) {apn->mask[i]|= mask; break; }
- if(apn->next==NULL) apn->next= addpsA(zspan);
- apn= apn->next;
- }
+ intzverg= (int)CLAMPIS(zverg, INT_MIN, INT_MAX);
+
+ if( intzverg < *rz) {
+ if(!zspan->rectmask || intzverg > *rm) {
+
+ apn= ap;
+ while(apn) {
+ if(apn->p[0]==0) {apn->obi[0]= obi; apn->p[0]= zvlnr; apn->z[0]= intzverg; apn->mask[0]= mask; break; }
+ if(apn->p[0]==zvlnr && apn->obi[0]==obi) {apn->mask[0]|= mask; break; }
+ if(apn->p[1]==0) {apn->obi[1]= obi; apn->p[1]= zvlnr; apn->z[1]= intzverg; apn->mask[1]= mask; break; }
+ if(apn->p[1]==zvlnr && apn->obi[1]==obi) {apn->mask[1]|= mask; break; }
+ if(apn->p[2]==0) {apn->obi[2]= obi; apn->p[2]= zvlnr; apn->z[2]= intzverg; apn->mask[2]= mask; break; }
+ if(apn->p[2]==zvlnr && apn->obi[2]==obi) {apn->mask[2]|= mask; break; }
+ if(apn->p[3]==0) {apn->obi[3]= obi; apn->p[3]= zvlnr; apn->z[3]= intzverg; apn->mask[3]= mask; break; }
+ if(apn->p[3]==zvlnr && apn->obi[3]==obi) {apn->mask[3]|= mask; break; }
+ if(apn->next==NULL) apn->next= addpsA(zspan);
+ apn= apn->next;
+ }
+ }
}
zverg+= zxd;
rz++;
+ rm++;
ap++;
x--;
}
@@ -413,6 +418,7 @@ static void zbuffillAc4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v2,
zy0-=zyd;
rectzofs-= rectx;
+ rectmaskofs-= rectx;
apofs-= rectx;
}
}
@@ -422,7 +428,7 @@ static void zbuffillAc4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v2,
static void zbuflineAc(ZSpan *zspan, int obi, int zvlnr, float *vec1, float *vec2)
{
APixstr *ap, *apn;
- int *rectz;
+ int *rectz, *rectmask;
int start, end, x, y, oldx, oldy, ofs;
int dz, vergz, mask, maxtest=0;
float dx, dy;
@@ -459,37 +465,40 @@ static void zbuflineAc(ZSpan *zspan, int obi, int zvlnr, float *vec1, float *vec
if(vergz>0x50000000 && dz>0) maxtest= 1; // prevent overflow
rectz= (int *)(zspan->arectz+zspan->rectx*(oldy) +start);
+ rectmask= (int *)(zspan->rectmask+zspan->rectx*(oldy) +start);
ap= (zspan->apixbuf+ zspan->rectx*(oldy) +start);
if(dy<0) ofs= -zspan->rectx;
else ofs= zspan->rectx;
- for(x= start; x<=end; x++, rectz++, ap++) {
+ for(x= start; x<=end; x++, rectz++, rectmask++, ap++) {
y= floor(v1[1]);
if(y!=oldy) {
oldy= y;
rectz+= ofs;
+ rectmask+= ofs;
ap+= ofs;
}
if(x>=0 && y>=0 && y<zspan->recty) {
if(vergz<*rectz) {
-
- apn= ap;
- while(apn) { /* loop unrolled */
- if(apn->p[0]==0) {apn->obi[0]= obi; apn->p[0]= zvlnr; apn->z[0]= vergz; apn->mask[0]= mask; break; }
- if(apn->p[0]==zvlnr && apn->obi[0]==obi) {apn->mask[0]|= mask; break; }
- if(apn->p[1]==0) {apn->obi[1]= obi; apn->p[1]= zvlnr; apn->z[1]= vergz; apn->mask[1]= mask; break; }
- if(apn->p[1]==zvlnr && apn->obi[1]==obi) {apn->mask[1]|= mask; break; }
- if(apn->p[2]==0) {apn->obi[2]= obi; apn->p[2]= zvlnr; apn->z[2]= vergz; apn->mask[2]= mask; break; }
- if(apn->p[2]==zvlnr && apn->obi[2]==obi) {apn->mask[2]|= mask; break; }
- if(apn->p[3]==0) {apn->obi[3]= obi; apn->p[3]= zvlnr; apn->z[3]= vergz; apn->mask[3]= mask; break; }
- if(apn->p[3]==zvlnr && apn->obi[3]==obi) {apn->mask[3]|= mask; break; }
- if(apn->next==0) apn->next= addpsA(zspan);
- apn= apn->next;
- }
+ if(!zspan->rectmask || vergz>*rectmask) {
+ apn= ap;
+ while(apn) { /* loop unrolled */
+ if(apn->p[0]==0) {apn->obi[0]= obi; apn->p[0]= zvlnr; apn->z[0]= vergz; apn->mask[0]= mask; break; }
+ if(apn->p[0]==zvlnr && apn->obi[0]==obi) {apn->mask[0]|= mask; break; }
+ if(apn->p[1]==0) {apn->obi[1]= obi; apn->p[1]= zvlnr; apn->z[1]= vergz; apn->mask[1]= mask; break; }
+ if(apn->p[1]==zvlnr && apn->obi[1]==obi) {apn->mask[1]|= mask; break; }
+ if(apn->p[2]==0) {apn->obi[2]= obi; apn->p[2]= zvlnr; apn->z[2]= vergz; apn->mask[2]= mask; break; }
+ if(apn->p[2]==zvlnr && apn->obi[2]==obi) {apn->mask[2]|= mask; break; }
+ if(apn->p[3]==0) {apn->obi[3]= obi; apn->p[3]= zvlnr; apn->z[3]= vergz; apn->mask[3]= mask; break; }
+ if(apn->p[3]==zvlnr && apn->obi[3]==obi) {apn->mask[3]|= mask; break; }
+ if(apn->next==0) apn->next= addpsA(zspan);
+ apn= apn->next;
+ }
+ }
}
}
@@ -527,37 +536,40 @@ static void zbuflineAc(ZSpan *zspan, int obi, int zvlnr, float *vec1, float *vec
if(vergz>0x50000000 && dz>0) maxtest= 1; // prevent overflow
rectz= (int *)( zspan->arectz+ (start)*zspan->rectx+ oldx );
+ rectmask= (int *)( zspan->rectmask+ (start)*zspan->rectx+ oldx );
ap= (zspan->apixbuf+ zspan->rectx*(start) +oldx);
if(dx<0) ofs= -1;
else ofs= 1;
- for(y= start; y<=end; y++, rectz+=zspan->rectx, ap+=zspan->rectx) {
+ for(y= start; y<=end; y++, rectz+=zspan->rectx, rectmask+=zspan->rectx, ap+=zspan->rectx) {
x= floor(v1[0]);
if(x!=oldx) {
oldx= x;
rectz+= ofs;
+ rectmask+= ofs;
ap+= ofs;
}
if(x>=0 && y>=0 && x<zspan->rectx) {
if(vergz<*rectz) {
-
- apn= ap;
- while(apn) { /* loop unrolled */
- if(apn->p[0]==0) {apn->p[0]= zvlnr; apn->z[0]= vergz; apn->mask[0]= mask; break; }
- if(apn->p[0]==zvlnr) {apn->mask[0]|= mask; break; }
- if(apn->p[1]==0) {apn->p[1]= zvlnr; apn->z[1]= vergz; apn->mask[1]= mask; break; }
- if(apn->p[1]==zvlnr) {apn->mask[1]|= mask; break; }
- if(apn->p[2]==0) {apn->p[2]= zvlnr; apn->z[2]= vergz; apn->mask[2]= mask; break; }
- if(apn->p[2]==zvlnr) {apn->mask[2]|= mask; break; }
- if(apn->p[3]==0) {apn->p[3]= zvlnr; apn->z[3]= vergz; apn->mask[3]= mask; break; }
- if(apn->p[3]==zvlnr) {apn->mask[3]|= mask; break; }
- if(apn->next==0) apn->next= addpsA(zspan);
- apn= apn->next;
- }
-
+ if(!zspan->rectmask || vergz>*rectmask) {
+
+ apn= ap;
+ while(apn) { /* loop unrolled */
+ if(apn->p[0]==0) {apn->obi[0]= obi; apn->p[0]= zvlnr; apn->z[0]= vergz; apn->mask[0]= mask; break; }
+ if(apn->p[0]==zvlnr) {apn->mask[0]|= mask; break; }
+ if(apn->p[1]==0) {apn->obi[1]= obi; apn->p[1]= zvlnr; apn->z[1]= vergz; apn->mask[1]= mask; break; }
+ if(apn->p[1]==zvlnr) {apn->mask[1]|= mask; break; }
+ if(apn->p[2]==0) {apn->obi[2]= obi; apn->p[2]= zvlnr; apn->z[2]= vergz; apn->mask[2]= mask; break; }
+ if(apn->p[2]==zvlnr) {apn->mask[2]|= mask; break; }
+ if(apn->p[3]==0) {apn->obi[3]= obi; apn->p[3]= zvlnr; apn->z[3]= vergz; apn->mask[3]= mask; break; }
+ if(apn->p[3]==zvlnr) {apn->mask[3]|= mask; break; }
+ if(apn->next==0) apn->next= addpsA(zspan);
+ apn= apn->next;
+ }
+ }
}
}
@@ -572,7 +584,7 @@ static void zbuflineAc(ZSpan *zspan, int obi, int zvlnr, float *vec1, float *vec
static void zbufline(ZSpan *zspan, int obi, int zvlnr, float *vec1, float *vec2)
{
- int *rectz, *rectp, *recto;
+ int *rectz, *rectp, *recto, *rectmask;
int start, end, x, y, oldx, oldy, ofs;
int dz, vergz, maxtest= 0;
float dx, dy;
@@ -608,11 +620,12 @@ static void zbufline(ZSpan *zspan, int obi, int zvlnr, float *vec1, float *vec2)
rectz= zspan->rectz + oldy*zspan->rectx+ start;
rectp= zspan->rectp + oldy*zspan->rectx+ start;
recto= zspan->recto + oldy*zspan->rectx+ start;
+ rectmask= zspan->rectmask + oldy*zspan->rectx+ start;
if(dy<0) ofs= -zspan->rectx;
else ofs= zspan->rectx;
- for(x= start; x<=end; x++, rectz++, rectp++, recto++) {
+ for(x= start; x<=end; x++, rectz++, rectp++, recto++, rectmask++) {
y= floor(v1[1]);
if(y!=oldy) {
@@ -620,13 +633,16 @@ static void zbufline(ZSpan *zspan, int obi, int zvlnr, float *vec1, float *vec2)
rectz+= ofs;
rectp+= ofs;
recto+= ofs;
+ rectmask+= ofs;
}
if(x>=0 && y>=0 && y<zspan->recty) {
if(vergz<*rectz) {
- *recto= obi;
- *rectz= vergz;
- *rectp= zvlnr;
+ if(!zspan->rectmask || vergz>*rectmask) {
+ *recto= obi;
+ *rectz= vergz;
+ *rectp= zvlnr;
+ }
}
}
@@ -663,11 +679,12 @@ static void zbufline(ZSpan *zspan, int obi, int zvlnr, float *vec1, float *vec2)
rectz= zspan->rectz + start*zspan->rectx+ oldx;
rectp= zspan->rectp + start*zspan->rectx+ oldx;
recto= zspan->recto + start*zspan->rectx+ oldx;
+ rectmask= zspan->rectmask + start*zspan->rectx+ oldx;
if(dx<0) ofs= -1;
else ofs= 1;
- for(y= start; y<=end; y++, rectz+=zspan->rectx, rectp+=zspan->rectx, recto+=zspan->rectx) {
+ for(y= start; y<=end; y++, rectz+=zspan->rectx, rectp+=zspan->rectx, recto+=zspan->rectx, rectmask+=zspan->rectx) {
x= floor(v1[0]);
if(x!=oldx) {
@@ -675,13 +692,16 @@ static void zbufline(ZSpan *zspan, int obi, int zvlnr, float *vec1, float *vec2)
rectz+= ofs;
rectp+= ofs;
recto+= ofs;
+ rectmask+= ofs;
}
if(x>=0 && y>=0 && x<zspan->rectx) {
if(vergz<*rectz) {
- *rectz= vergz;
- *rectp= zvlnr;
- *recto= obi;
+ if(!zspan->rectmask || vergz>*rectmask) {
+ *rectz= vergz;
+ *rectp= zvlnr;
+ *recto= obi;
+ }
}
}
@@ -1022,6 +1042,7 @@ static void zbuffillGLinv4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v
float *span1, *span2;
int *rectoofs, *ro;
int *rectpofs, *rp;
+ int *rectmaskofs, *rm;
int *rz, x, y;
int sn1, sn2, rectx, *rectzofs, my0, my2;
@@ -1072,6 +1093,7 @@ static void zbuffillGLinv4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v
rectzofs= (zspan->rectz+rectx*my2);
rectpofs= (zspan->rectp+rectx*my2);
rectoofs= (zspan->recto+rectx*my2);
+ rectmaskofs= (zspan->rectmask+rectx*my2);
/* correct span */
sn1= (my0 + my2)/2;
@@ -1094,22 +1116,30 @@ static void zbuffillGLinv4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v
if(sn1<0) sn1= 0;
if(sn2>=sn1) {
+ int intzverg;
+
zverg= (double)sn1*zxd + zy0;
rz= rectzofs+sn1;
rp= rectpofs+sn1;
ro= rectoofs+sn1;
+ rm= rectmaskofs+sn1;
x= sn2-sn1;
while(x>=0) {
- if( (int)zverg > *rz || *rz==0x7FFFFFFF) {
- *ro= obi;
- *rz= (int)zverg;
- *rp= zvlnr;
+ intzverg= (int)CLAMPIS(zverg, INT_MIN, INT_MAX);
+
+ if( intzverg > *rz || *rz==0x7FFFFFFF) {
+ if(!zspan->rectmask || intzverg > *rm) {
+ *ro= obi;
+ *rz= intzverg;
+ *rp= zvlnr;
+ }
}
zverg+= zxd;
rz++;
rp++;
ro++;
+ rm++;
x--;
}
}
@@ -1118,6 +1148,7 @@ static void zbuffillGLinv4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v
rectzofs-= rectx;
rectpofs-= rectx;
rectoofs-= rectx;
+ rectmaskofs-= rectx;
}
}
@@ -1131,6 +1162,7 @@ static void zbuffillGL4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v2,
float *span1, *span2;
int *rectoofs, *ro;
int *rectpofs, *rp;
+ int *rectmaskofs, *rm;
int *rz, x, y;
int sn1, sn2, rectx, *rectzofs, my0, my2;
@@ -1181,6 +1213,7 @@ static void zbuffillGL4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v2,
rectzofs= (zspan->rectz+rectx*my2);
rectpofs= (zspan->rectp+rectx*my2);
rectoofs= (zspan->recto+rectx*my2);
+ rectmaskofs= (zspan->rectmask+rectx*my2);
/* correct span */
sn1= (my0 + my2)/2;
@@ -1203,22 +1236,30 @@ static void zbuffillGL4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v2,
if(sn1<0) sn1= 0;
if(sn2>=sn1) {
+ int intzverg;
+
zverg= (double)sn1*zxd + zy0;
rz= rectzofs+sn1;
rp= rectpofs+sn1;
ro= rectoofs+sn1;
+ rm= rectmaskofs+sn1;
x= sn2-sn1;
while(x>=0) {
- if( (int)zverg < *rz) {
- *rz= (int)zverg;
- *rp= zvlnr;
- *ro= obi;
+ intzverg= (int)CLAMPIS(zverg, INT_MIN, INT_MAX);
+
+ if(intzverg < *rz) {
+ if(!zspan->rectmask || intzverg > *rm) {
+ *rz= intzverg;
+ *rp= zvlnr;
+ *ro= obi;
+ }
}
zverg+= zxd;
rz++;
rp++;
ro++;
+ rm++;
x--;
}
}
@@ -1227,6 +1268,7 @@ static void zbuffillGL4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v2,
rectzofs-= rectx;
rectpofs-= rectx;
rectoofs-= rectx;
+ rectmaskofs-= rectx;
}
}
@@ -1326,7 +1368,8 @@ static void zbuffillGL_onlyZ(ZSpan *zspan, int obi, int zvlnr, float *v1, float
x= sn2-sn1;
while(x>=0) {
- int zvergi= (int)zverg;
+ int zvergi= (int)CLAMPIS(zverg, INT_MIN, INT_MAX);
+
/* option: maintain two depth values, closest and 2nd closest */
if(zvergi < *rz) {
if(rectzofs1) *rz1= *rz;
@@ -1922,10 +1965,82 @@ void zbufclip4(ZSpan *zspan, int obi, int zvlnr, float *f1, float *f2, float *f3
zspan->zbuffunc(zspan, obi, zvlnr, vez, vez+4, vez+8, vez+12);
}
+/* ************** ZMASK ******************************** */
+
+#define EXTEND_PIXEL(a) if(temprectp[a]) {z+= rectz[a]; tot++;}
+
+/* changes the zbuffer to be ready for z-masking: applies an extend-filter, and then clears */
+static void zmask_rect(int *rectz, int *rectp, int xs, int ys, int neg)
+{
+ int len=0, x, y;
+ int *temprectp;
+ int row1, row2, row3, *curp, *curz;
+
+ temprectp= MEM_dupallocN(rectp);
+
+ /* extend: if pixel is not filled in, we check surrounding pixels and average z value */
+
+ for(y=1; y<=ys; y++) {
+ /* setup row indices */
+ row1= (y-2)*xs;
+ row2= row1 + xs;
+ row3= row2 + xs;
+ if(y==1)
+ row1= row2;
+ else if(y==ys)
+ row3= row2;
+
+ curp= rectp + (y-1)*xs;
+ curz= rectz + (y-1)*xs;
+
+ for(x=0; x<xs; x++, curp++, curz++) {
+ if(curp[0]==0) {
+ int tot= 0;
+ float z= 0.0f;
+
+ EXTEND_PIXEL(row1);
+ EXTEND_PIXEL(row2);
+ EXTEND_PIXEL(row3);
+ EXTEND_PIXEL(row1 + 1);
+ EXTEND_PIXEL(row3 + 1);
+ if(x!=xs-1) {
+ EXTEND_PIXEL(row1 + 2);
+ EXTEND_PIXEL(row2 + 2);
+ EXTEND_PIXEL(row3 + 2);
+ }
+ if(tot) {
+ len++;
+ curz[0]= (int)(z/(float)tot);
+ curp[0]= -1; /* env */
+ }
+ }
+
+ if(x!=0) {
+ row1++; row2++; row3++;
+ }
+ }
+ }
+
+ MEM_freeN(temprectp);
+
+ if(neg); /* z values for negative are already correct */
+ else {
+ /* clear not filled z values */
+ for(len= xs*ys -1; len>=0; len--) {
+ if(rectp[len]==0) {
+ rectz[len] = -0x7FFFFFFF;
+ rectp[len]= -1; /* env code */
+ }
+ }
+ }
+}
+
+
+
/* ***************** ZBUFFER MAIN ROUTINES **************** */
-void zbuffer_solid(RenderPart *pa, unsigned int lay, short layflag, void(*fillfunc)(RenderPart*, ZSpan*, int, void*), void *data)
+void zbuffer_solid(RenderPart *pa, RenderLayer *rl, void(*fillfunc)(RenderPart*, ZSpan*, int, void*), void *data)
{
ZbufProjectCache cache[ZBUF_PROJECT_CACHE_SIZE];
ZSpan zspans[16], *zspan; /* 16 = RE_MAX_OSA */
@@ -1935,9 +2050,12 @@ void zbuffer_solid(RenderPart *pa, unsigned int lay, short layflag, void(*fillfu
ObjectInstanceRen *obi;
ObjectRen *obr;
float winmat[4][4], bounds[4], ho1[4], ho2[4], ho3[4], ho4[4]={0};
+ unsigned int lay= rl->lay, lay_zmask= rl->lay_zmask;
int i, v, zvlnr, zsample, samples, c1, c2, c3, c4=0;
- short nofill=0, env=0, wire=0, all_z= layflag & SCE_LAY_ALL_Z;
-
+ short nofill=0, env=0, wire=0, zmaskpass=0;
+ short all_z= (rl->layflag & SCE_LAY_ALL_Z) && !(rl->layflag & SCE_LAY_ZMASK);
+ short neg_zmask= (rl->layflag & SCE_LAY_ZMASK) && (rl->layflag & SCE_LAY_NEG_ZMASK);
+
samples= (R.osa? R.osa: 1);
samples= MIN2(4, samples-pa->sample);
@@ -1969,9 +2087,13 @@ void zbuffer_solid(RenderPart *pa, unsigned int lay, short layflag, void(*fillfu
/* the buffers */
if(zsample == samples-1) {
- zspan->rectz= pa->rectz;
zspan->rectp= pa->rectp;
zspan->recto= pa->recto;
+
+ if(neg_zmask)
+ zspan->rectz= pa->rectmask;
+ else
+ zspan->rectz= pa->rectz;
}
else {
zspan->recto= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "recto");
@@ -1982,104 +2104,153 @@ void zbuffer_solid(RenderPart *pa, unsigned int lay, short layflag, void(*fillfu
fillrect(zspan->rectz, pa->rectx, pa->recty, 0x7FFFFFFF);
fillrect(zspan->rectp, pa->rectx, pa->recty, 0);
fillrect(zspan->recto, pa->rectx, pa->recty, 0);
-
- /* filling methods */
- zspan->zbuffunc= zbuffillGL4;
- zspan->zbuflinefunc= zbufline;
}
- for(i=0, obi=R.instancetable.first; obi; i++, obi=obi->next) {
- obr= obi->obr;
+ /* in case zmask we fill Z for objects in lay_zmask first, then clear Z, and then do normal zbuffering */
+ if(rl->layflag & SCE_LAY_ZMASK)
+ zmaskpass= 1;
+
+ for(; zmaskpass >=0; zmaskpass--) {
+ ma= NULL;
- if(obi->flag & R_TRANSFORMED)
- zbuf_make_winmat(&R, obi->mat, winmat);
- else
- zbuf_make_winmat(&R, NULL, winmat);
+ /* filling methods */
+ for(zsample=0; zsample<samples; zsample++) {
+ zspan= &zspans[zsample];
- zbuf_project_cache_clear(cache, obr->totvert);
+ if(zmaskpass && neg_zmask)
+ zspan->zbuffunc= zbuffillGLinv4;
+ else
+ zspan->zbuffunc= zbuffillGL4;
+ zspan->zbuflinefunc= zbufline;
+ }
- for(v=0; v<obr->totvlak; v++) {
- if((v & 255)==0) vlr= obr->vlaknodes[v>>8].vlak;
- else vlr++;
+ /* regular zbuffering loop, does all sample buffers */
+ for(i=0, obi=R.instancetable.first; obi; i++, obi=obi->next) {
+ obr= obi->obr;
- /* three cases, visible for render, only z values and nothing */
- if(vlr->lay & lay) {
- if(vlr->mat!=ma) {
- ma= vlr->mat;
- nofill= ma->mode & (MA_ZTRA|MA_ONLYCAST);
- env= (ma->mode & MA_ENV);
- wire= (ma->mode & MA_WIRE);
-
- for(zsample=0; zsample<samples; zsample++) {
- if(ma->mode & MA_ZINV) zspans[zsample].zbuffunc= zbuffillGLinv4;
- else zspans[zsample].zbuffunc= zbuffillGL4;
- }
- }
- }
- else if(all_z) {
- env= 1;
- nofill= 0;
- ma= NULL;
- }
- else {
- nofill= 1;
- ma= NULL; /* otherwise nofill can hang */
+ /* continue happens in 2 different ways... zmaskpass only does lay_zmask stuff */
+ if(zmaskpass) {
+ if((obi->lay & lay_zmask)==0)
+ continue;
}
+ else if(!all_z && !(obi->lay & (lay|lay_zmask)))
+ continue;
+
+ if(obi->flag & R_TRANSFORMED)
+ zbuf_make_winmat(&R, obi->mat, winmat);
+ else
+ zbuf_make_winmat(&R, NULL, winmat);
- if(!(vlr->flag & R_HIDDEN) && nofill==0) {
- unsigned short partclip;
-
- v1= vlr->v1;
- v2= vlr->v2;
- v3= vlr->v3;
- v4= vlr->v4;
-
- c1= zbuf_part_project(cache, v1->index, winmat, bounds, v1->co, ho1);
- c2= zbuf_part_project(cache, v2->index, winmat, bounds, v2->co, ho2);
- c3= zbuf_part_project(cache, v3->index, winmat, bounds, v3->co, ho3);
-
- /* partclipping doesn't need viewplane clipping */
- partclip= c1 & c2 & c3;
- if(v4) {
- c4= zbuf_part_project(cache, v4->index, winmat, bounds, v4->co, ho4);
- partclip &= c4;
+ if(clip_render_object(obi->obr->boundbox, bounds, winmat))
+ continue;
+
+ zbuf_project_cache_clear(cache, obr->totvert);
+
+ for(v=0; v<obr->totvlak; v++) {
+ if((v & 255)==0) vlr= obr->vlaknodes[v>>8].vlak;
+ else vlr++;
+
+ /* the cases: visible for render, only z values, zmask, nothing */
+ if(obi->lay & lay) {
+ if(vlr->mat!=ma) {
+ ma= vlr->mat;
+ nofill= ma->mode & (MA_ZTRA|MA_ONLYCAST);
+ env= (ma->mode & MA_ENV);
+ wire= (ma->mode & MA_WIRE);
+
+ for(zsample=0; zsample<samples; zsample++) {
+ if(ma->mode & MA_ZINV || (zmaskpass && neg_zmask))
+ zspans[zsample].zbuffunc= zbuffillGLinv4;
+ else
+ zspans[zsample].zbuffunc= zbuffillGL4;
+ }
+ }
+ }
+ else if(all_z || (obi->lay & lay_zmask)) {
+ env= 1;
+ nofill= 0;
+ ma= NULL;
+ }
+ else {
+ nofill= 1;
+ ma= NULL; /* otherwise nofill can hang */
}
- if(partclip==0) {
+ if(!(vlr->flag & R_HIDDEN) && nofill==0) {
+ unsigned short partclip;
- if(env) zvlnr= -1;
- else zvlnr= v+1;
+ v1= vlr->v1;
+ v2= vlr->v2;
+ v3= vlr->v3;
+ v4= vlr->v4;
+
+ c1= zbuf_part_project(cache, v1->index, winmat, bounds, v1->co, ho1);
+ c2= zbuf_part_project(cache, v2->index, winmat, bounds, v2->co, ho2);
+ c3= zbuf_part_project(cache, v3->index, winmat, bounds, v3->co, ho3);
+
+ /* partclipping doesn't need viewplane clipping */
+ partclip= c1 & c2 & c3;
+ if(v4) {
+ c4= zbuf_part_project(cache, v4->index, winmat, bounds, v4->co, ho4);
+ partclip &= c4;
+ }
- c1= testclip(ho1);
- c2= testclip(ho2);
- c3= testclip(ho3);
- if(v4)
- c4= testclip(ho4);
+ if(partclip==0) {
+
+ if(env) zvlnr= -1;
+ else zvlnr= v+1;
- for(zsample=0; zsample<samples; zsample++) {
- zspan= &zspans[zsample];
+ c1= testclip(ho1);
+ c2= testclip(ho2);
+ c3= testclip(ho3);
+ if(v4)
+ c4= testclip(ho4);
- if(wire) {
- if(v4)
- zbufclipwire(zspan, i, zvlnr, vlr->ec, ho1, ho2, ho3, ho4, c1, c2, c3, c4);
- else
- zbufclipwire(zspan, i, zvlnr, vlr->ec, ho1, ho2, ho3, 0, c1, c2, c3, 0);
- }
- else {
- /* strands allow to be filled in as quad */
- if(v4 && (vlr->flag & R_STRAND)) {
- zbufclip4(zspan, i, zvlnr, ho1, ho2, ho3, ho4, c1, c2, c3, c4);
+ for(zsample=0; zsample<samples; zsample++) {
+ zspan= &zspans[zsample];
+
+ if(wire) {
+ if(v4)
+ zbufclipwire(zspan, i, zvlnr, vlr->ec, ho1, ho2, ho3, ho4, c1, c2, c3, c4);
+ else
+ zbufclipwire(zspan, i, zvlnr, vlr->ec, ho1, ho2, ho3, 0, c1, c2, c3, 0);
}
else {
- zbufclip(zspan, i, zvlnr, ho1, ho2, ho3, c1, c2, c3);
- if(v4)
- zbufclip(zspan, i, zvlnr+RE_QUAD_OFFS, ho1, ho3, ho4, c1, c3, c4);
+ /* strands allow to be filled in as quad */
+ if(v4 && (vlr->flag & R_STRAND)) {
+ zbufclip4(zspan, i, zvlnr, ho1, ho2, ho3, ho4, c1, c2, c3, c4);
+ }
+ else {
+ zbufclip(zspan, i, zvlnr, ho1, ho2, ho3, c1, c2, c3);
+ if(v4)
+ zbufclip(zspan, i, (env)? zvlnr: zvlnr+RE_QUAD_OFFS, ho1, ho3, ho4, c1, c3, c4);
+ }
}
}
}
}
}
}
+
+ /* clear all z to close value, so it works as mask for next passes (ztra+strand) */
+ if(zmaskpass) {
+ for(zsample=0; zsample<samples; zsample++) {
+ zspan= &zspans[zsample];
+
+ if(neg_zmask) {
+ zspan->rectmask= zspan->rectz;
+ if(zsample == samples-1)
+ zspan->rectz= pa->rectz;
+ else
+ zspan->rectz= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectz");
+ fillrect(zspan->rectz, pa->rectx, pa->recty, 0x7FFFFFFF);
+
+ zmask_rect(zspan->rectmask, zspan->rectp, pa->rectx, pa->recty, 1);
+ }
+ else
+ zmask_rect(zspan->rectz, zspan->rectp, pa->rectx, pa->recty, 0);
+ }
+ }
}
for(zsample=0; zsample<samples; zsample++) {
@@ -2092,6 +2263,8 @@ void zbuffer_solid(RenderPart *pa, unsigned int lay, short layflag, void(*fillfu
MEM_freeN(zspan->rectz);
MEM_freeN(zspan->rectp);
MEM_freeN(zspan->recto);
+ if(zspan->rectmask)
+ MEM_freeN(zspan->rectmask);
}
zbuf_free_span(zspan);
@@ -2115,7 +2288,7 @@ static int hashlist_projectvert(float *v1, float winmat[][4], float *hoco)
return 0;
}
- buck= &bucket[ (((long)v1)/16) & 255 ];
+ buck= &bucket[ (((intptr_t)v1)/16) & 255 ];
if(buck->vert==v1) {
QUATCOPY(hoco, buck->hoco);
return buck->clip;
@@ -2191,7 +2364,7 @@ void RE_zbufferall_radio(struct RadView *vw, RNode **rg_elem, int rg_totelem, Re
else { /* radio render */
ObjectRen *obr;
VlakRen *vlr=NULL;
- RadFace *rf;
+ RadFace **radface, *rf;
int totface=0;
/* note: radio render doesn't support duplis */
@@ -2201,8 +2374,8 @@ void RE_zbufferall_radio(struct RadView *vw, RNode **rg_elem, int rg_totelem, Re
for(a=0; a<obr->totvlak; a++) {
if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak; else vlr++;
- if(vlr->radface) {
- rf= vlr->radface;
+ if((radface=RE_vlakren_get_radface(obr, vlr, 0)) && *radface) {
+ rf= *radface;
if( (rf->flag & RAD_SHOOT)==0 ) { /* no shootelement */
if( rf->flag & RAD_TWOSIDED) zvlnr= totface;
@@ -2243,10 +2416,11 @@ void zbuffer_shadow(Render *re, float winmat[][4], LampRen *lar, int *rectz, int
StrandSegment sseg;
StrandRen *strand= NULL;
StrandVert *svert;
+ StrandBound *sbound;
float obwinmat[4][4], ho1[4], ho2[4], ho3[4], ho4[4];
- int a, b, i, c1, c2, c3, c4, ok=1, lay= -1;
+ int a, b, c, i, c1, c2, c3, c4, ok=1, lay= -1;
- if(lar->mode & LA_LAYER) lay= lar->lay;
+ if(lar->mode & (LA_LAYER|LA_LAYER_SHADOW)) lay= lar->lay;
/* 1.0f for clipping in clippyra()... bad stuff actually */
zbuf_alloc_span(&zspan, size, size, 1.0f);
@@ -2272,12 +2446,17 @@ void zbuffer_shadow(Render *re, float winmat[][4], LampRen *lar, int *rectz, int
if(obr->ob==re->excludeob)
continue;
+ else if(!(obi->lay & lay))
+ continue;
if(obi->flag & R_TRANSFORMED)
Mat4MulMat4(obwinmat, obi->mat, winmat);
else
Mat4CpyMat4(obwinmat, winmat);
+ if(clip_render_object(obi->obr->boundbox, NULL, obwinmat))
+ continue;
+
zbuf_project_cache_clear(cache, obr->totvert);
/* faces */
@@ -2293,7 +2472,7 @@ void zbuffer_shadow(Render *re, float winmat[][4], LampRen *lar, int *rectz, int
if((ma->mode & MA_SHADBUF)==0) ok= 0;
}
- if(ok && (vlr->lay & lay) && !(vlr->flag & R_HIDDEN)) {
+ if(ok && (obi->lay & lay) && !(vlr->flag & R_HIDDEN)) {
c1= zbuf_shadow_project(cache, vlr->v1->index, obwinmat, vlr->v1->co, ho1);
c2= zbuf_shadow_project(cache, vlr->v2->index, obwinmat, vlr->v2->co, ho2);
c3= zbuf_shadow_project(cache, vlr->v3->index, obwinmat, vlr->v3->co, ho3);
@@ -2321,45 +2500,54 @@ void zbuffer_shadow(Render *re, float winmat[][4], LampRen *lar, int *rectz, int
}
/* strands */
- for(a=0; a<obr->totstrand; a++) {
- if((a & 255)==0) strand= obr->strandnodes[a>>8].strand;
- else strand++;
-
- sseg.obi= obi;
- sseg.buffer= strand->buffer;
- sseg.sqadaptcos= sseg.buffer->adaptcos;
- sseg.sqadaptcos *= sseg.sqadaptcos;
- sseg.strand= strand;
- svert= strand->vert;
+ if(obr->strandbuf) {
+ /* for each bounding box containing a number of strands */
+ sbound= obr->strandbuf->bound;
+ for(c=0; c<obr->strandbuf->totbound; c++, sbound++) {
+ if(clip_render_object(sbound->boundbox, NULL, obwinmat))
+ continue;
+
+ /* for each strand in this bounding box */
+ for(a=sbound->start; a<sbound->end; a++) {
+ strand= RE_findOrAddStrand(obr, a);
+
+ sseg.obi= obi;
+ sseg.buffer= strand->buffer;
+ sseg.sqadaptcos= sseg.buffer->adaptcos;
+ sseg.sqadaptcos *= sseg.sqadaptcos;
+ sseg.strand= strand;
+ svert= strand->vert;
+
+ /* note, these conditions are copied in shadowbuf_autoclip() */
+ if(sseg.buffer->ma!= ma) {
+ ma= sseg.buffer->ma;
+ ok= 1;
+ if((ma->mode & MA_SHADBUF)==0) ok= 0;
+ }
- /* note, these conditions are copied in shadowbuf_autoclip() */
- if(sseg.buffer->ma!= ma) {
- ma= sseg.buffer->ma;
- ok= 1;
- if((ma->mode & MA_SHADBUF)==0) ok= 0;
- }
+ if(ok && (sseg.buffer->lay & lay)) {
+ zbuf_project_cache_clear(cache, strand->totvert);
- if(ok && (sseg.buffer->lay & lay)) {
- zbuf_project_cache_clear(cache, strand->totvert);
+ for(b=0; b<strand->totvert-1; b++, svert++) {
+ sseg.v[0]= (b > 0)? (svert-1): svert;
+ sseg.v[1]= svert;
+ sseg.v[2]= svert+1;
+ sseg.v[3]= (b < strand->totvert-2)? svert+2: svert+1;
- for(b=0; b<strand->totvert-1; b++, svert++) {
- sseg.v[0]= (b > 0)? (svert-1): svert;
- sseg.v[1]= svert;
- sseg.v[2]= svert+1;
- sseg.v[3]= (b < strand->totvert-2)? svert+2: svert+1;
+ c1= zbuf_shadow_project(cache, sseg.v[0]-strand->vert, obwinmat, sseg.v[0]->co, ho1);
+ c2= zbuf_shadow_project(cache, sseg.v[1]-strand->vert, obwinmat, sseg.v[1]->co, ho2);
+ c3= zbuf_shadow_project(cache, sseg.v[2]-strand->vert, obwinmat, sseg.v[2]->co, ho3);
+ c4= zbuf_shadow_project(cache, sseg.v[3]-strand->vert, obwinmat, sseg.v[3]->co, ho4);
- c1= zbuf_shadow_project(cache, sseg.v[0]-strand->vert, obwinmat, sseg.v[0]->co, ho1);
- c2= zbuf_shadow_project(cache, sseg.v[1]-strand->vert, obwinmat, sseg.v[1]->co, ho2);
- c3= zbuf_shadow_project(cache, sseg.v[2]-strand->vert, obwinmat, sseg.v[2]->co, ho3);
- c4= zbuf_shadow_project(cache, sseg.v[3]-strand->vert, obwinmat, sseg.v[3]->co, ho4);
+ if(!(c1 & c2 & c3 & c4))
+ render_strand_segment(re, winmat, NULL, &zspan, 1, &sseg);
+ }
+ }
- if(!(c1 & c2 & c3 & c4))
- render_strand_segment(NULL, winmat, NULL, &zspan, &sseg);
+ if((a & 255)==255 && re->test_break())
+ break;
}
}
-
- if((a & 255)==255 && re->test_break())
- break;
}
if(re->test_break())
@@ -2495,11 +2683,17 @@ void zbuffer_sss(RenderPart *pa, unsigned int lay, void *handle, void (*func)(vo
for(i=0, obi=R.instancetable.first; obi; i++, obi=obi->next) {
obr= obi->obr;
+ if(!(obi->lay & lay))
+ continue;
+
if(obi->flag & R_TRANSFORMED)
zbuf_make_winmat(&R, obi->mat, winmat);
else
zbuf_make_winmat(&R, NULL, winmat);
+ if(clip_render_object(obi->obr->boundbox, bounds, winmat))
+ continue;
+
zbuf_project_cache_clear(cache, obr->totvert);
for(v=0; v<obr->totvlak; v++) {
@@ -2508,7 +2702,7 @@ void zbuffer_sss(RenderPart *pa, unsigned int lay, void *handle, void (*func)(vo
if(material_in_material(vlr->mat, sss_ma)) {
/* three cases, visible for render, only z values and nothing */
- if(vlr->lay & lay) {
+ if(obi->lay & lay) {
if(vlr->mat!=ma) {
ma= vlr->mat;
nofill= ma->mode & MA_ONLYCAST;
@@ -2762,14 +2956,46 @@ void antialias_tagbuf(int xsize, int ysize, char *rectmove)
}
}
+/* in: two vectors, first vector points from origin back in time, 2nd vector points to future */
+/* we make this into 3 points, center point is (0,0) */
+/* and offset the center point just enough to make curve go through midpoint */
+
+static void quad_bezier_2d(float *result, float *v1, float *v2, float *ipodata)
+{
+ float p1[2], p2[2], p3[2];
+
+ p3[0]= -v2[0];
+ p3[1]= -v2[1];
+
+ p1[0]= v1[0];
+ p1[1]= v1[1];
+
+ /* official formula 2*p2 - .5*p1 - .5*p3 */
+ p2[0]= -0.5*p1[0] - 0.5*p3[0];
+ p2[1]= -0.5*p1[1] - 0.5*p3[1];
+
+ result[0]= ipodata[0]*p1[0] + ipodata[1]*p2[0] + ipodata[2]*p3[0];
+ result[1]= ipodata[0]*p1[1] + ipodata[1]*p2[1] + ipodata[2]*p3[1];
+}
+
+static void set_quad_bezier_ipo(float fac, float *data)
+{
+ float mfac= (1.0f-fac);
+
+ data[0]= mfac*mfac;
+ data[1]= 2.0f*mfac*fac;
+ data[2]= fac*fac;
+}
+
void RE_zbuf_accumulate_vecblur(NodeBlurData *nbd, int xsize, int ysize, float *newrect, float *imgrect, float *vecbufrect, float *zbufrect)
{
ZSpan zspan;
DrawBufPixel *rectdraw, *dr;
- static float jit[16][2];
+ static float jit[256][2];
float v1[3], v2[3], v3[3], v4[3], fx, fy;
- float *rectvz, *dvz, *dimg, *dvec1, *dvec2, *dz1, *dz2, *rectz, *minvecbufrect= NULL;
- float maxspeedsq= (float)nbd->maxspeed*nbd->maxspeed;
+ float *rectvz, *dvz, *dimg, *dvec1, *dvec2, *dz, *dz1, *dz2, *rectz;
+ float *minvecbufrect= NULL, *rectweight, *rw, *rectmax, *rm, *ro;
+ float maxspeedsq= (float)nbd->maxspeed*nbd->maxspeed, totfac;
int y, x, step, maxspeed=nbd->maxspeed, samples= nbd->samples;
int tsktsk= 0;
static int firsttime= 1;
@@ -2788,6 +3014,9 @@ void RE_zbuf_accumulate_vecblur(NodeBlurData *nbd, int xsize, int ysize, float *
rectmove= MEM_mapallocN(xsize*ysize, "rectmove");
rectdraw= MEM_mapallocN(sizeof(DrawBufPixel)*xsize*ysize, "rect draw");
zspan.rectp= (int *)rectdraw;
+
+ rectweight= MEM_mapallocN(sizeof(float)*xsize*ysize, "rect weight");
+ rectmax= MEM_mapallocN(sizeof(float)*xsize*ysize, "rect max");
/* debug... check if PASS_VECTOR_MAX still is in buffers */
dvec1= vecbufrect;
@@ -2830,29 +3059,21 @@ void RE_zbuf_accumulate_vecblur(NodeBlurData *nbd, int xsize, int ysize, float *
}
/* make vertex buffer with averaged speed and zvalues */
- rectvz= MEM_mapallocN(5*sizeof(float)*(xsize+1)*(ysize+1), "vertices");
+ rectvz= MEM_mapallocN(4*sizeof(float)*(xsize+1)*(ysize+1), "vertices");
dvz= rectvz;
for(y=0; y<=ysize; y++) {
- if(y==0) {
+ if(y==0)
dvec1= vecbufrect + 4*y*xsize;
- dz1= zbufrect + y*xsize;
- }
- else {
+ else
dvec1= vecbufrect + 4*(y-1)*xsize;
- dz1= zbufrect + (y-1)*xsize;
- }
- if(y==ysize) {
+ if(y==ysize)
dvec2= vecbufrect + 4*(y-1)*xsize;
- dz2= zbufrect + (y-1)*xsize;
- }
- else {
+ else
dvec2= vecbufrect + 4*y*xsize;
- dz2= zbufrect + y*xsize;
- }
- for(x=0; x<=xsize; x++, dz1++, dz2++) {
+ for(x=0; x<=xsize; x++) {
/* two vectors, so a step loop */
for(step=0; step<2; step++, dvec1+=2, dvec2+=2, dvz+=2) {
@@ -2910,30 +3131,21 @@ void RE_zbuf_accumulate_vecblur(NodeBlurData *nbd, int xsize, int ysize, float *
}
}
}
- /* the z coordinate */
- if(x!=0) {
- if(x!=xsize)
- dvz[0]= 0.25f*(dz1[-1] + dz2[-1] + dz1[0] + dz2[0]);
- else dvz[0]= 0.5f*(dz1[0] + dz2[0]);
- }
- else dvz[0]= 0.5f*(dz1[-1] + dz2[-1]);
-
- dvz++;
}
}
/* set border speeds to keep border speeds on border */
dz1= rectvz;
- dz2= rectvz+5*(ysize)*(xsize+1);
- for(x=0; x<=xsize; x++, dz1+=5, dz2+=5) {
+ dz2= rectvz+4*(ysize)*(xsize+1);
+ for(x=0; x<=xsize; x++, dz1+=4, dz2+=4) {
dz1[1]= 0.0f;
dz2[1]= 0.0f;
dz1[3]= 0.0f;
dz2[3]= 0.0f;
}
dz1= rectvz;
- dz2= rectvz+5*(xsize);
- for(y=0; y<=ysize; y++, dz1+=5*(xsize+1), dz2+=5*(xsize+1)) {
+ dz2= rectvz+4*(xsize);
+ for(y=0; y<=ysize; y++, dz1+=4*(xsize+1), dz2+=4*(xsize+1)) {
dz1[0]= 0.0f;
dz2[0]= 0.0f;
dz1[2]= 0.0f;
@@ -2944,7 +3156,7 @@ void RE_zbuf_accumulate_vecblur(NodeBlurData *nbd, int xsize, int ysize, float *
dm= rectmove;
dvec1= vecbufrect;
for(x=xsize*ysize; x>0; x--, dm++, dvec1+=4) {
- if(dvec1[0]!=0.0f || dvec1[1]!=0.0f || dvec1[2]!=0.0f || dvec1[3]!=0.0f)
+ if((dvec1[0]!=0.0f || dvec1[1]!=0.0f || dvec1[2]!=0.0f || dvec1[3]!=0.0f))
*dm= 255;
}
@@ -2953,17 +3165,20 @@ void RE_zbuf_accumulate_vecblur(NodeBlurData *nbd, int xsize, int ysize, float *
/* has to become static, the init-jit calls a random-seed, screwing up texture noise node */
if(firsttime) {
firsttime= 0;
- BLI_initjit(jit[0], 16);
+ BLI_initjit(jit[0], 256);
}
+ memset(newrect, 0, sizeof(float)*xsize*ysize*4);
+ totfac= 0.0f;
+
/* accumulate */
samples/= 2;
for(step= 1; step<=samples; step++) {
float speedfac= 0.5f*nbd->fac*(float)step/(float)(samples+1);
- float blendfac= 1.0f/(ABS(step)+1);
- int side, z= 4;
+ int side;
for(side=0; side<2; side++) {
+ float blendfac, ipodata[4];
/* clear zbuf, if we draw future we fill in not moving pixels */
if(0)
@@ -2981,58 +3196,111 @@ void RE_zbuf_accumulate_vecblur(NodeBlurData *nbd, int xsize, int ysize, float *
dimg= imgrect;
dm= rectmove;
+ dz= zbufrect;
dz1= rectvz;
- dz2= rectvz + 5*(xsize + 1);
+ dz2= rectvz + 4*(xsize + 1);
if(side) {
- dz1+= 2;
- dz2+= 2;
- z= 2;
+ if(nbd->curved==0) {
+ dz1+= 2;
+ dz2+= 2;
+ }
speedfac= -speedfac;
}
-
- for(fy= -0.5f+jit[step & 15][0], y=0; y<ysize; y++, fy+=1.0f) {
- for(fx= -0.5f+jit[step & 15][1], x=0; x<xsize; x++, fx+=1.0f, dimg+=4, dz1+=5, dz2+=5, dm++) {
+
+ set_quad_bezier_ipo(0.5f + 0.5f*speedfac, ipodata);
+
+ for(fy= -0.5f+jit[step & 255][0], y=0; y<ysize; y++, fy+=1.0f) {
+ for(fx= -0.5f+jit[step & 255][1], x=0; x<xsize; x++, fx+=1.0f, dimg+=4, dz1+=4, dz2+=4, dm++, dz++) {
if(*dm>1) {
+ float jfx = fx + 0.5f;
+ float jfy = fy + 0.5f;
DrawBufPixel col;
/* make vertices */
- v1[0]= speedfac*dz1[0]+fx; v1[1]= speedfac*dz1[1]+fy; v1[2]= dz1[z];
- v2[0]= speedfac*dz1[5]+fx+1.0f; v2[1]= speedfac*dz1[6]+fy; v2[2]= dz1[z+5];
- v3[0]= speedfac*dz2[5]+fx+1.0f; v3[1]= speedfac*dz2[6]+fy+1.0f; v3[2]= dz2[z+5];
- v4[0]= speedfac*dz2[0]+fx; v4[1]= speedfac*dz2[1]+fy+1.0f; v4[2]= dz2[z];
-
+ if(nbd->curved) { /* curved */
+ quad_bezier_2d(v1, dz1, dz1+2, ipodata);
+ v1[0]+= jfx; v1[1]+= jfy; v1[2]= *dz;
+
+ quad_bezier_2d(v2, dz1+4, dz1+4+2, ipodata);
+ v2[0]+= jfx+1.0f; v2[1]+= jfy; v2[2]= *dz;
+
+ quad_bezier_2d(v3, dz2+4, dz2+4+2, ipodata);
+ v3[0]+= jfx+1.0f; v3[1]+= jfy+1.0f; v3[2]= *dz;
+
+ quad_bezier_2d(v4, dz2, dz2+2, ipodata);
+ v4[0]+= jfx; v4[1]+= jfy+1.0f; v4[2]= *dz;
+ }
+ else {
+ v1[0]= speedfac*dz1[0]+jfx; v1[1]= speedfac*dz1[1]+jfy; v1[2]= *dz;
+ v2[0]= speedfac*dz1[4]+jfx+1.0f; v2[1]= speedfac*dz1[5]+jfy; v2[2]= *dz;
+ v3[0]= speedfac*dz2[4]+jfx+1.0f; v3[1]= speedfac*dz2[5]+jfy+1.0f; v3[2]= *dz;
+ v4[0]= speedfac*dz2[0]+jfx; v4[1]= speedfac*dz2[1]+jfy+1.0f; v4[2]= *dz;
+ }
if(*dm==255) col.alpha= 1.0f;
else if(*dm<2) col.alpha= 0.0f;
else col.alpha= ((float)*dm)/255.0f;
col.colpoin= dimg;
-
+
zbuf_fill_in_rgba(&zspan, &col, v1, v2, v3, v4);
}
}
- dz1+=5;
- dz2+=5;
+ dz1+=4;
+ dz2+=4;
}
-
+
+ /* blend with a falloff. this fixes the ugly effect you get with
+ * a fast moving object. then it looks like a solid object overlayed
+ * over a very transparent moving version of itself. in reality, the
+ * whole object should become transparent if it is moving fast, be
+ * we don't know what is behind it so we don't do that. this hack
+ * overestimates the contribution of foreground pixels but looks a
+ * bit better without a sudden cutoff. */
+ blendfac= ((samples - step)/(float)samples);
+ /* smoothstep to make it look a bit nicer as well */
+ blendfac= 3.0f*pow(blendfac, 2.0f) - 2.0f*pow(blendfac, 3.0f);
+
/* accum */
- for(dr= rectdraw, dz2=newrect, x= xsize*ysize-1; x>=0; x--, dr++, dz2+=4) {
+ rw= rectweight;
+ rm= rectmax;
+ for(dr= rectdraw, dz2=newrect, x= xsize*ysize-1; x>=0; x--, dr++, dz2+=4, rw++, rm++) {
if(dr->colpoin) {
float bfac= dr->alpha*blendfac;
- float mf= 1.0f - bfac;
- dz2[0]= mf*dz2[0] + bfac*dr->colpoin[0];
- dz2[1]= mf*dz2[1] + bfac*dr->colpoin[1];
- dz2[2]= mf*dz2[2] + bfac*dr->colpoin[2];
- dz2[3]= mf*dz2[3] + bfac*dr->colpoin[3];
+ dz2[0] += bfac*dr->colpoin[0];
+ dz2[1] += bfac*dr->colpoin[1];
+ dz2[2] += bfac*dr->colpoin[2];
+ dz2[3] += bfac*dr->colpoin[3];
+
+ *rw += bfac;
+ *rm= MAX2(*rm, bfac);
}
}
}
}
+ /* blend between original images and accumulated image */
+ rw= rectweight;
+ rm= rectmax;
+ ro= imgrect;
+ dm= rectmove;
+ for(dz2=newrect, x= xsize*ysize-1; x>=0; x--, dz2+=4, ro+=4, rw++, rm++, dm++) {
+ float mfac = *rm;
+ float fac = (*rw == 0.0f)? 0.0f: mfac/(*rw);
+ float nfac = 1.0f - mfac;
+
+ dz2[0]= fac*dz2[0] + nfac*ro[0];
+ dz2[1]= fac*dz2[1] + nfac*ro[1];
+ dz2[2]= fac*dz2[2] + nfac*ro[2];
+ dz2[3]= fac*dz2[3] + nfac*ro[3];
+ }
+
MEM_freeN(rectz);
MEM_freeN(rectmove);
MEM_freeN(rectdraw);
MEM_freeN(rectvz);
+ MEM_freeN(rectweight);
+ MEM_freeN(rectmax);
if(minvecbufrect) MEM_freeN(vecbufrect); /* rects were swapped! */
zbuf_free_span(&zspan);
}
@@ -3043,18 +3311,21 @@ void RE_zbuf_accumulate_vecblur(NodeBlurData *nbd, int xsize, int ysize, float *
* Copy results from the solid face z buffering to the transparent
* buffer.
*/
-static void copyto_abufz(RenderPart *pa, int *arectz, int sample)
+static void copyto_abufz(RenderPart *pa, int *arectz, int *rectmask, int sample)
{
PixStr *ps;
- int x, y, *rza;
- long *rd;
+ int x, y, *rza, *rma;
+ intptr_t *rd;
if(R.osa==0) {
- memcpy(arectz, pa->rectz, 4*pa->rectx*pa->recty);
+ memcpy(arectz, pa->rectz, sizeof(int)*pa->rectx*pa->recty);
+ if(rectmask && pa->rectmask)
+ memcpy(rectmask, pa->rectmask, sizeof(int)*pa->rectx*pa->recty);
return;
}
rza= arectz;
+ rma= rectmask;
rd= pa->rectdaps;
sample= (1<<sample);
@@ -3063,17 +3334,19 @@ static void copyto_abufz(RenderPart *pa, int *arectz, int sample)
for(x=0; x<pa->rectx; x++) {
*rza= 0x7FFFFFFF;
+ if(rectmask) *rma= 0x7FFFFFFF;
if(*rd) {
/* when there's a sky pixstruct, fill in sky-Z, otherwise solid Z */
for(ps= (PixStr *)(*rd); ps; ps= ps->next) {
if(sample & ps->mask) {
*rza= ps->z;
+ if(rectmask) *rma= ps->maskz;
break;
}
}
}
- rd++; rza++;
+ rd++; rza++, rma++;
}
}
}
@@ -3085,7 +3358,7 @@ static void copyto_abufz(RenderPart *pa, int *arectz, int sample)
* Do accumulation z buffering.
*/
-static int zbuffer_abuf(RenderPart *pa, APixstr *APixbuf, ListBase *apsmbase, unsigned int lay)
+static int zbuffer_abuf(RenderPart *pa, APixstr *APixbuf, ListBase *apsmbase, RenderLayer *rl, unsigned int lay)
{
ZbufProjectCache cache[ZBUF_PROJECT_CACHE_SIZE];
ZSpan zspans[16], *zspan; /* MAX_OSA */
@@ -3116,11 +3389,14 @@ static int zbuffer_abuf(RenderPart *pa, APixstr *APixbuf, ListBase *apsmbase, un
zspan->apixbuf= APixbuf;
zspan->apsmbase= apsmbase;
+ if((rl->layflag & SCE_LAY_ZMASK) && (rl->layflag & SCE_LAY_NEG_ZMASK))
+ zspan->rectmask= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "Arectmask");
+
/* filling methods */
zspan->zbuffunc= zbuffillAc4;
zspan->zbuflinefunc= zbuflineAc;
- copyto_abufz(pa, zspan->arectz, zsample); /* init zbuffer */
+ copyto_abufz(pa, zspan->arectz, zspan->rectmask, zsample); /* init zbuffer */
zspan->mask= 1<<zsample;
if(R.osa) {
@@ -3138,7 +3414,6 @@ static int zbuffer_abuf(RenderPart *pa, APixstr *APixbuf, ListBase *apsmbase, un
/* to center the sample position */
zspan->zofsx -= 0.5f;
zspan->zofsy -= 0.5f;
-
}
/* we use this to test if nothing was filled in */
@@ -3147,11 +3422,17 @@ static int zbuffer_abuf(RenderPart *pa, APixstr *APixbuf, ListBase *apsmbase, un
for(i=0, obi=R.instancetable.first; obi; i++, obi=obi->next) {
obr= obi->obr;
+ if(!(obi->lay & lay))
+ continue;
+
if(obi->flag & R_TRANSFORMED)
zbuf_make_winmat(&R, obi->mat, winmat);
else
zbuf_make_winmat(&R, NULL, winmat);
+ if(clip_render_object(obi->obr->boundbox, bounds, winmat))
+ continue;
+
zbuf_project_cache_clear(cache, obr->totvert);
for(v=0; v<obr->totvlak; v++) {
@@ -3165,7 +3446,7 @@ static int zbuffer_abuf(RenderPart *pa, APixstr *APixbuf, ListBase *apsmbase, un
}
if(dofill) {
- if(!(vlr->flag & R_HIDDEN) && (vlr->lay & lay)) {
+ if(!(vlr->flag & R_HIDDEN) && (obi->lay & lay)) {
unsigned short partclip;
v1= vlr->v1;
@@ -3243,6 +3524,8 @@ static int zbuffer_abuf(RenderPart *pa, APixstr *APixbuf, ListBase *apsmbase, un
for(zsample=0; zsample<samples; zsample++) {
zspan= &zspans[zsample];
MEM_freeN(zspan->arectz);
+ if(zspan->rectmask)
+ MEM_freeN(zspan->rectmask);
zbuf_free_span(zspan);
}
@@ -3253,7 +3536,7 @@ static int zbuffer_abuf(RenderPart *pa, APixstr *APixbuf, ListBase *apsmbase, un
/* speed pointer NULL = sky, we clear */
/* else if either alpha is full or no solid was filled in: copy speed */
/* else fill in minimum speed */
-void add_transp_speed(RenderLayer *rl, int offset, float *speed, float alpha, long *rdrect)
+void add_transp_speed(RenderLayer *rl, int offset, float *speed, float alpha, intptr_t *rdrect)
{
RenderPass *rpass;
@@ -3287,20 +3570,15 @@ void add_transp_speed(RenderLayer *rl, int offset, float *speed, float alpha, lo
}
}
-static void add_transp_obindex(RenderLayer *rl, int offset, int obi, int facenr)
+static void add_transp_obindex(RenderLayer *rl, int offset, Object *ob)
{
- ObjectRen *obr= R.objectinstance[obi].obr;
- VlakRen *vlr= RE_findOrAddVlak(obr, (facenr-1) & RE_QUAD_MASK);
-
- if(vlr && obr->ob) {
- RenderPass *rpass;
-
- for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
- if(rpass->passtype == SCE_PASS_INDEXOB) {
- float *fp= rpass->rect + offset;
- *fp= (float)obr->ob->index;
- break;
- }
+ RenderPass *rpass;
+
+ for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
+ if(rpass->passtype == SCE_PASS_INDEXOB) {
+ float *fp= rpass->rect + offset;
+ *fp= (float)ob->index;
+ break;
}
}
}
@@ -3315,7 +3593,7 @@ void merge_transp_passes(RenderLayer *rl, ShadeResult *shr)
for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
float *col= NULL;
- int pixsize= 0;
+ int pixsize= 3;
switch(rpass->passtype) {
case SCE_PASS_RGBA:
@@ -3346,6 +3624,14 @@ void merge_transp_passes(RenderLayer *rl, ShadeResult *shr)
case SCE_PASS_NORMAL:
col= shr->nor;
break;
+ case SCE_PASS_MIST:
+ col= &shr->mist;
+ pixsize= 1;
+ break;
+ case SCE_PASS_Z:
+ col= &shr->z;
+ pixsize= 1;
+ break;
case SCE_PASS_VECTOR:
{
@@ -3378,14 +3664,18 @@ void merge_transp_passes(RenderLayer *rl, ShadeResult *shr)
for(samp= 1; samp<R.osa; samp++, fp+=delta) {
col[0]+= fp[0];
- col[1]+= fp[1];
- col[2]+= fp[2];
- if(pixsize) col[3]+= fp[3];
+ if(pixsize>1) {
+ col[1]+= fp[1];
+ col[2]+= fp[2];
+ if(pixsize==4) col[3]+= fp[3];
+ }
}
col[0]*= weight;
- col[1]*= weight;
- col[2]*= weight;
- if(pixsize) col[3]*= weight;
+ if(pixsize>1) {
+ col[1]*= weight;
+ col[2]*= weight;
+ if(pixsize==4) col[3]*= weight;
+ }
}
}
@@ -3397,8 +3687,14 @@ void add_transp_passes(RenderLayer *rl, int offset, ShadeResult *shr, float alph
for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
float *fp, *col= NULL;
+ int pixsize= 3;
switch(rpass->passtype) {
+ case SCE_PASS_Z:
+ fp= rpass->rect + offset;
+ if(shr->z < *fp)
+ *fp= shr->z;
+ break;
case SCE_PASS_RGBA:
fp= rpass->rect + 4*offset;
addAlphaOverFloat(fp, shr->col);
@@ -3427,23 +3723,30 @@ void add_transp_passes(RenderLayer *rl, int offset, ShadeResult *shr, float alph
case SCE_PASS_NORMAL:
col= shr->nor;
break;
+ case SCE_PASS_MIST:
+ col= &shr->mist;
+ pixsize= 1;
+ break;
}
if(col) {
- fp= rpass->rect + 3*offset;
- fp[0]= alpha*col[0] + (1.0f-alpha)*fp[0];
- fp[1]= alpha*col[1] + (1.0f-alpha)*fp[1];
- fp[2]= alpha*col[2] + (1.0f-alpha)*fp[2];
+ fp= rpass->rect + pixsize*offset;
+ fp[0]= col[0] + (1.0f-alpha)*fp[0];
+ if(pixsize==3) {
+ fp[1]= col[1] + (1.0f-alpha)*fp[1];
+ fp[2]= col[2] + (1.0f-alpha)*fp[2];
+ }
}
}
}
-
typedef struct ZTranspRow {
int obi;
int z;
int p;
int mask;
+ int segment;
+ float u, v;
} ZTranspRow;
static int vergzvlak(const void *a1, const void *a2)
@@ -3455,6 +3758,56 @@ static int vergzvlak(const void *a1, const void *a2)
return 0;
}
+static void shade_strand_samples(StrandShadeCache *cache, ShadeSample *ssamp, int x, int y, ZTranspRow *row, int addpassflag)
+{
+ StrandSegment sseg;
+ StrandVert *svert;
+ ObjectInstanceRen *obi;
+ ObjectRen *obr;
+
+ obi= R.objectinstance + row->obi;
+ obr= obi->obr;
+
+ sseg.obi= obi;
+ sseg.strand= RE_findOrAddStrand(obr, row->p-1);
+ sseg.buffer= sseg.strand->buffer;
+
+ svert= sseg.strand->vert + row->segment;
+ sseg.v[0]= (row->segment > 0)? (svert-1): svert;
+ sseg.v[1]= svert;
+ sseg.v[2]= svert+1;
+ sseg.v[3]= (row->segment < sseg.strand->totvert-2)? svert+2: svert+1;
+
+ ssamp->tot= 1;
+ strand_shade_segment(&R, cache, &sseg, ssamp, row->v, row->u, addpassflag);
+ ssamp->shi[0].mask= row->mask;
+}
+
+static void unref_strand_samples(StrandShadeCache *cache, ZTranspRow *row, int totface)
+{
+ StrandVert *svert;
+ ObjectInstanceRen *obi;
+ ObjectRen *obr;
+ StrandRen *strand;
+
+ /* remove references to samples that are not being rendered, but we still
+ * need to remove them so that the reference count of strand vertex shade
+ * samples correctly drops to zero */
+ while(totface > 0) {
+ totface--;
+
+ if(row[totface].segment != -1) {
+ obi= R.objectinstance + row[totface].obi;
+ obr= obi->obr;
+ strand= RE_findOrAddStrand(obr, row[totface].p-1);
+ svert= strand->vert + row[totface].segment;
+
+ strand_shade_unref(cache, svert);
+ strand_shade_unref(cache, svert+1);
+ }
+ }
+}
+
static void shade_tra_samples_fill(ShadeSample *ssamp, int x, int y, int z, int obi, int facenr, int curmask)
{
ShadeInput *shi= ssamp->shi;
@@ -3481,8 +3834,8 @@ static void shade_tra_samples_fill(ShadeSample *ssamp, int x, int y, int z, int
shi++;
}
shi->mask= (1<<samp);
- shi->samplenr= ssamp->samplenr++;
- shade_input_set_viewco(shi, xs, ys, (float)z);
+ shi->samplenr= R.shadowsamplenr[shi->thread]++;
+ shade_input_set_viewco(shi, x, y, xs, ys, (float)z);
shade_input_set_uv(shi);
shade_input_set_normals(shi);
@@ -3501,8 +3854,8 @@ static void shade_tra_samples_fill(ShadeSample *ssamp, int x, int y, int z, int
ys= (float)y + 0.5f;
}
shi->mask= curmask;
- shi->samplenr= ssamp->samplenr++;
- shade_input_set_viewco(shi, xs, ys, (float)z);
+ shi->samplenr= R.shadowsamplenr[shi->thread]++;
+ shade_input_set_viewco(shi, x, y, xs, ys, (float)z);
shade_input_set_uv(shi);
shade_input_set_normals(shi);
}
@@ -3512,8 +3865,13 @@ static void shade_tra_samples_fill(ShadeSample *ssamp, int x, int y, int z, int
}
}
-static int shade_tra_samples(ShadeSample *ssamp, int x, int y, ZTranspRow *row)
+static int shade_tra_samples(ShadeSample *ssamp, StrandShadeCache *cache, int x, int y, ZTranspRow *row, int addpassflag)
{
+ if(row->segment != -1) {
+ shade_strand_samples(cache, ssamp, x, y, row, addpassflag);
+ return 1;
+ }
+
shade_tra_samples_fill(ssamp, x, y, row->z, row->obi, row->p, row->mask);
if(ssamp->tot) {
@@ -3548,7 +3906,7 @@ static void addvecmul(float *v1, float *v2, float fac)
v1[2]= v1[2]+fac*v2[2];
}
-int addtosamp_shr(ShadeResult *samp_shr, ShadeSample *ssamp, int addpassflag)
+static int addtosamp_shr(ShadeResult *samp_shr, ShadeSample *ssamp, int addpassflag)
{
int a, sample, osa = (R.osa? R.osa: 1), retval = osa;
@@ -3563,6 +3921,8 @@ int addtosamp_shr(ShadeResult *samp_shr, ShadeSample *ssamp, int addpassflag)
addAlphaUnderFloat(samp_shr->combined, shr->combined);
+ samp_shr->z= MIN2(samp_shr->z, shr->z);
+
if(addpassflag & SCE_PASS_VECTOR) {
QUATCOPY(samp_shr->winspeed, shr->winspeed);
}
@@ -3595,6 +3955,10 @@ int addtosamp_shr(ShadeResult *samp_shr, ShadeSample *ssamp, int addpassflag)
if(addpassflag & SCE_PASS_RADIO)
addvecmul(samp_shr->rad, shr->rad, fac);
+
+ if(addpassflag & SCE_PASS_MIST)
+ samp_shr->mist= samp_shr->mist+fac*shr->mist;
+
}
}
}
@@ -3604,7 +3968,7 @@ int addtosamp_shr(ShadeResult *samp_shr, ShadeSample *ssamp, int addpassflag)
return retval;
}
-void reset_sky_speedvectors(RenderPart *pa, RenderLayer *rl, float *rectf)
+static void reset_sky_speedvectors(RenderPart *pa, RenderLayer *rl, float *rectf)
{
/* speed vector exception... if solid render was done, sky pixels are set to zero already */
/* for all pixels with alpha zero, we re-initialize speed again then */
@@ -3627,23 +3991,27 @@ void reset_sky_speedvectors(RenderPart *pa, RenderLayer *rl, float *rectf)
#define MAX_ZROW 2000
-/* main render call to fill in pass the full transparent layer */
+/* main render call to do the z-transparent layer */
/* returns a mask, only if a) transp rendered and b) solid was rendered */
-unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pass)
+unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pass, ListBase *psmlist)
{
RenderResult *rr= pa->result;
ShadeSample ssamp;
APixstr *APixbuf; /* Zbuffer: linked list of face samples */
+ APixstrand *APixbufstrand = NULL;
APixstr *ap, *aprect, *apn;
+ APixstrand *apstrand, *aprectstrand, *apnstrand;
ListBase apsmbase={NULL, NULL};
ShadeResult samp_shr[16]; /* MAX_OSA */
ZTranspRow zrow[MAX_ZROW];
- float sampalpha, *passrect= pass;
- long *rdrect;
- int x, y, crop=0, a, totface;
- int addpassflag, offs= 0, od, addzbuf;
- unsigned short *ztramask= NULL;
-
+ StrandShadeCache *sscache= NULL;
+ RenderLayer *rlpp[RE_MAX_OSA];
+ float sampalpha, alpha, *passrect= pass;
+ intptr_t *rdrect;
+ int x, y, crop=0, a, b, totface, totfullsample, totsample, doztra;
+ int addpassflag, offs= 0, od, osa = (R.osa? R.osa: 1);
+ unsigned short *ztramask= NULL, filled;
+
/* looks nicer for calling code */
if(R.test_break())
return NULL;
@@ -3655,14 +4023,14 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
}
APixbuf= MEM_callocN(pa->rectx*pa->recty*sizeof(APixstr), "APixbuf");
+ if(R.totstrand && (rl->layflag & SCE_LAY_STRAND)) {
+ APixbufstrand= MEM_callocN(pa->rectx*pa->recty*sizeof(APixstrand), "APixbufstrand");
+ sscache= strand_shade_cache_create();
+ }
/* general shader info, passes */
shade_sample_initialize(&ssamp, pa, rl);
- addpassflag= rl->passflag & ~(SCE_PASS_Z|SCE_PASS_COMBINED);
- if((rl->layflag & SCE_LAY_STRAND) && R.totstrand)
- addzbuf= 1; /* strands layer needs the z-buffer */
- else
- addzbuf= rl->passflag & SCE_PASS_Z;
+ addpassflag= rl->passflag & ~(SCE_PASS_COMBINED);
if(R.osa)
sampalpha= 1.0f/(float)R.osa;
@@ -3670,28 +4038,42 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
sampalpha= 1.0f;
/* fill the Apixbuf */
- if(0 == zbuffer_abuf(pa, APixbuf, &apsmbase, rl->lay)) {
+ doztra= 0;
+ if(rl->layflag & SCE_LAY_ZTRA)
+ doztra+= zbuffer_abuf(pa, APixbuf, &apsmbase, rl, rl->lay);
+ if((rl->layflag & SCE_LAY_STRAND) && APixbufstrand)
+ doztra+= zbuffer_strands_abuf(&R, pa, rl, APixbufstrand, &apsmbase, sscache);
+
+ if(doztra == 0) {
/* nothing filled in */
MEM_freeN(APixbuf);
+ if(APixbufstrand)
+ MEM_freeN(APixbufstrand);
+ if(sscache)
+ strand_shade_cache_free(sscache);
freepsA(&apsmbase);
return NULL;
}
aprect= APixbuf;
+ aprectstrand= APixbufstrand;
rdrect= pa->rectdaps;
+
+ /* needed for correct zbuf/index pass */
+ totfullsample= get_sample_layers(pa, rl, rlpp);
/* irregular shadowb buffer creation */
if(R.r.mode & R_SHADOW)
ISB_create(pa, APixbuf);
/* masks, to have correct alpha combine */
- if(R.osa && (rl->layflag & SCE_LAY_SOLID))
+ if(R.osa && (rl->layflag & SCE_LAY_SOLID) && pa->fullresult.first==NULL)
ztramask= MEM_callocN(pa->rectx*pa->recty*sizeof(short), "ztramask");
/* zero alpha pixels get speed vector max again */
if(addpassflag & SCE_PASS_VECTOR)
if(rl->layflag & SCE_LAY_SOLID)
- reset_sky_speedvectors(pa, rl, rl->acolrect);
+ reset_sky_speedvectors(pa, rl, rl->acolrect?rl->acolrect:rl->rectf); /* if acolrect is set we use it */
/* filtered render, for now we assume only 1 filter size */
if(pa->crop) {
@@ -3699,6 +4081,7 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
offs= pa->rectx + 1;
passrect+= 4*offs;
aprect+= offs;
+ aprectstrand+= offs;
}
/* init scanline updates */
@@ -3710,14 +4093,15 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
for(y=pa->disprect.ymin+crop; y<pa->disprect.ymax-crop; y++, rr->renrect.ymax++) {
pass= passrect;
ap= aprect;
+ apstrand= aprectstrand;
od= offs;
if(R.test_break())
break;
- for(x=pa->disprect.xmin+crop; x<pa->disprect.xmax-crop; x++, ap++, pass+=4, od++) {
+ for(x=pa->disprect.xmin+crop; x<pa->disprect.xmax-crop; x++, ap++, apstrand++, pass+=4, od++) {
- if(ap->p[0]==0) {
+ if(ap->p[0]==0 && (!APixbufstrand || apstrand->p[0]==0)) {
if(addpassflag & SCE_PASS_VECTOR)
add_transp_speed(rl, od, NULL, 0.0f, rdrect);
}
@@ -3732,6 +4116,7 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
zrow[totface].z= apn->z[a];
zrow[totface].p= apn->p[a];
zrow[totface].mask= apn->mask[a];
+ zrow[totface].segment= -1;
totface++;
if(totface>=MAX_ZROW) totface= MAX_ZROW-1;
}
@@ -3739,7 +4124,35 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
}
apn= apn->next;
}
-
+
+ apnstrand= (APixbufstrand)? apstrand: NULL;
+ while(apnstrand) {
+ for(a=0; a<4; a++) {
+ if(apnstrand->p[a]) {
+ zrow[totface].obi= apnstrand->obi[a];
+ zrow[totface].z= apnstrand->z[a];
+ zrow[totface].p= apnstrand->p[a];
+ zrow[totface].mask= apnstrand->mask[a];
+ zrow[totface].segment= apnstrand->seg[a];
+
+ if(R.osa) {
+ totsample= 0;
+ for(b=0; b<R.osa; b++)
+ if(zrow[totface].mask & (1<<b))
+ totsample++;
+ }
+ else
+ totsample= 1;
+
+ zrow[totface].u= apnstrand->u[a]/totsample;
+ zrow[totface].v= apnstrand->v[a]/totsample;
+ totface++;
+ if(totface>=MAX_ZROW) totface= MAX_ZROW-1;
+ }
+ }
+ apnstrand= apnstrand->next;
+ }
+
if(totface==2) {
if(zrow[0].z < zrow[1].z) {
SWAP(ZTranspRow, zrow[0], zrow[1]);
@@ -3750,70 +4163,110 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
qsort(zrow, totface, sizeof(ZTranspRow), vergzvlak);
}
- /* zbuffer and index pass for transparent, no AA or filters */
- if(addzbuf)
- if(pa->rectz[od]>zrow[totface-1].z)
- pa->rectz[od]= zrow[totface-1].z;
-
- if(addpassflag & SCE_PASS_INDEXOB)
- add_transp_obindex(rl, od, zrow[totface-1].obi, zrow[totface-1].p);
-
+ /* front face does index pass for transparent, no AA or filters, but yes FSA */
+ if(addpassflag & SCE_PASS_INDEXOB) {
+ ObjectRen *obr= R.objectinstance[zrow[totface-1].obi].obr;
+ if(obr->ob) {
+ for(a= 0; a<totfullsample; a++)
+ add_transp_obindex(rlpp[a], od, obr->ob);
+ }
+ }
+ /* for each mask-sample we alpha-under colors. then in end it's added using filter */
+ memset(samp_shr, 0, sizeof(ShadeResult)*osa);
+ for(a=0; a<osa; a++) {
+ samp_shr[a].z= 10e10f;
+ if(addpassflag & SCE_PASS_VECTOR) {
+ samp_shr[a].winspeed[0]= PASS_VECTOR_MAX;
+ samp_shr[a].winspeed[1]= PASS_VECTOR_MAX;
+ samp_shr[a].winspeed[2]= PASS_VECTOR_MAX;
+ samp_shr[a].winspeed[3]= PASS_VECTOR_MAX;
+ }
+ }
+
if(R.osa==0) {
while(totface>0) {
totface--;
- if(shade_tra_samples(&ssamp, x, y, &zrow[totface])) {
- if(addpassflag)
- add_transp_passes(rl, od, ssamp.shr, (1.0f-pass[3])*ssamp.shr[0].combined[3]);
-
+ if(shade_tra_samples(&ssamp, sscache, x, y, &zrow[totface], addpassflag)) {
+ filled= addtosamp_shr(samp_shr, &ssamp, addpassflag);
addAlphaUnderFloat(pass, ssamp.shr[0].combined);
- if(pass[3]>=0.999) break;
+
+ if(filled == 0) {
+ if(sscache)
+ unref_strand_samples(sscache, zrow, totface);
+ break;
+ }
}
}
- if(addpassflag & SCE_PASS_VECTOR)
- add_transp_speed(rl, od, ssamp.shr[0].winspeed, pass[3], rdrect);
+
+ alpha= samp_shr->combined[3];
+ if(alpha!=0.0f) {
+ add_transp_passes(rl, od, samp_shr, alpha);
+ if(addpassflag & SCE_PASS_VECTOR)
+ add_transp_speed(rl, od, samp_shr->winspeed, alpha, rdrect);
+ }
}
else {
- short filled, *sp= (short *)(ztramask+od);
-
- /* for each mask-sample we alpha-under colors. then in end it's added using filter */
- memset(samp_shr, 0, sizeof(ShadeResult)*R.osa);
-
- /* nice this memset, but speed vectors are not initialized OK then. it is sufficient to only clear 1 (see merge_transp_passes) */
- if(addpassflag & SCE_PASS_VECTOR)
- samp_shr->winspeed[0]= samp_shr->winspeed[1]= samp_shr->winspeed[2]= samp_shr->winspeed[3]= PASS_VECTOR_MAX;
+ short *sp= (short *)(ztramask+od);
while(totface>0) {
totface--;
- if(shade_tra_samples(&ssamp, x, y, &zrow[totface])) {
+ if(shade_tra_samples(&ssamp, sscache, x, y, &zrow[totface], addpassflag)) {
filled= addtosamp_shr(samp_shr, &ssamp, addpassflag);
if(ztramask)
*sp |= zrow[totface].mask;
- if(filled==0)
+ if(filled==0) {
+ if(sscache)
+ unref_strand_samples(sscache, zrow, totface);
break;
+ }
}
}
- for(a=0; a<R.osa; a++) {
- add_filt_fmask(1<<a, samp_shr[a].combined, pass, rr->rectx);
+ /* multisample buffers or filtered mask filling? */
+ if(pa->fullresult.first) {
+ for(a=0; a<R.osa; a++) {
+ alpha= samp_shr[a].combined[3];
+ if(alpha!=0.0f) {
+ RenderLayer *rl= ssamp.rlpp[a];
+
+ addAlphaOverFloat(rl->rectf + 4*od, samp_shr[a].combined);
+
+ add_transp_passes(rl, od, &samp_shr[a], alpha);
+ if(addpassflag & SCE_PASS_VECTOR)
+ add_transp_speed(rl, od, samp_shr[a].winspeed, alpha, rdrect);
+ }
+ }
}
-
- if(addpassflag) {
- /* merge all in one, and then add */
- merge_transp_passes(rl, samp_shr);
- add_transp_passes(rl, od, samp_shr, pass[3]);
+ else {
+ alpha= 0.0f;
- if(addpassflag & SCE_PASS_VECTOR)
- add_transp_speed(rl, od, samp_shr[0].winspeed, pass[3], rdrect);
+ /* note; cannot use pass[3] for alpha due to filtermask */
+ for(a=0; a<R.osa; a++) {
+ add_filt_fmask(1<<a, samp_shr[a].combined, pass, rr->rectx);
+ alpha+= samp_shr[a].combined[3];
+ }
+
+ if(addpassflag) {
+ alpha*= sampalpha;
+
+ /* merge all in one, and then add */
+ merge_transp_passes(rl, samp_shr);
+ add_transp_passes(rl, od, samp_shr, alpha);
+
+ if(addpassflag & SCE_PASS_VECTOR)
+ add_transp_speed(rl, od, samp_shr[0].winspeed, alpha, rdrect);
+ }
}
}
}
}
aprect+= pa->rectx;
+ aprectstrand+= pa->rectx;
passrect+= 4*pa->rectx;
offs+= pa->rectx;
}
@@ -3822,6 +4275,10 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
rr->renlay= NULL;
MEM_freeN(APixbuf);
+ if(APixbufstrand)
+ MEM_freeN(APixbufstrand);
+ if(sscache)
+ strand_shade_cache_free(sscache);
freepsA(&apsmbase);
if(R.r.mode & R_SHADOW)
@@ -3830,45 +4287,6 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
return ztramask;
}
-/* *************** */
-
-/* uses part zbuffer values to convert into distances from camera in renderlayer */
-void convert_zbuf_to_distbuf(RenderPart *pa, RenderLayer *rl)
-{
- RenderPass *rpass;
- float *rectzf, zco;
- int a, *rectz, ortho= R.r.mode & R_ORTHO;
-
- if(pa->rectz==NULL) return;
- for(rpass= rl->passes.first; rpass; rpass= rpass->next)
- if(rpass->passtype==SCE_PASS_Z)
- break;
-
- if(rpass==NULL) {
- printf("called convert zbuf wrong...\n");
- return;
- }
-
- rectzf= rpass->rect;
- rectz= pa->rectz;
-
- for(a=pa->rectx*pa->recty; a>0; a--, rectz++, rectzf++) {
- if(*rectz>=0x7FFFFFF0)
- *rectzf= 10e10;
- else {
- /* inverse of zbuf calc: zbuf = MAXZ*hoco_z/hoco_w */
- /* or: (R.winmat[3][2] - zco*R.winmat[3][3])/(R.winmat[2][2] - R.winmat[2][3]*zco); */
- /* if ortho [2][3] is zero, else [3][3] is zero */
-
- zco= ((float)*rectz)/2147483647.0f;
- if(ortho)
- *rectzf= (R.winmat[3][2] - zco*R.winmat[3][3])/(R.winmat[2][2]);
- else
- *rectzf= (R.winmat[3][2])/(R.winmat[2][2] - R.winmat[2][3]*zco);
- }
- }
-}
-
/* end of zbuf.c */
diff --git a/source/blender/windowmanager/SConscript b/source/blender/windowmanager/SConscript
index e70a7207c11..cdc5edfeaa6 100644
--- a/source/blender/windowmanager/SConscript
+++ b/source/blender/windowmanager/SConscript
@@ -11,5 +11,5 @@ incs += ' ../nodes ../imbuf ../blenloader ../render/extern/include'
incs += ' ../ftfont ../radiosity/extern/include ../../kernel/gen_system'
incs += ' #/intern/guardedalloc #/intern/memutil #/intern/ghost #/intern/bmfont'
-incs += ' #/intern/elbeem'
+incs += ' #/intern/elbeem #/extern/glew/include'
env.BlenderLib ( 'bf_windowmanager', sources, Split(incs), [], libtype=['core','intern'], priority=[45, 45] )
diff --git a/source/blender/windowmanager/intern/Makefile b/source/blender/windowmanager/intern/Makefile
index 3eb4ef7a028..cbd0b3afa87 100644
--- a/source/blender/windowmanager/intern/Makefile
+++ b/source/blender/windowmanager/intern/Makefile
@@ -36,6 +36,7 @@ include nan_compile.mk
CFLAGS += $(LEVEL_1_C_WARNINGS)
# OpenGL and Python
+CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += $(OGL_CPPFLAGS)
CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION)
diff --git a/source/blender/windowmanager/intern/wm_init_exit.c b/source/blender/windowmanager/intern/wm_init_exit.c
index 67670383060..422a655f53a 100644
--- a/source/blender/windowmanager/intern/wm_init_exit.c
+++ b/source/blender/windowmanager/intern/wm_init_exit.c
@@ -240,8 +240,8 @@ void WM_exit(bContext *C)
MEM_freeN(C);
- if(totblock!=0) {
- printf("Error Totblock: %d\n",totblock);
+ if(MEM_get_memory_blocks_in_use()!=0) {
+ printf("Error Totblock: %d\n", MEM_get_memory_blocks_in_use());
MEM_printmemlist();
}
// delete_autosave();
diff --git a/source/blender/yafray/intern/export_File.cpp b/source/blender/yafray/intern/export_File.cpp
index 40992513c8e..ea700965826 100644
--- a/source/blender/yafray/intern/export_File.cpp
+++ b/source/blender/yafray/intern/export_File.cpp
@@ -1,6 +1,7 @@
#include "export_File.h"
#include <math.h>
+
#include <cstring>
using namespace std;
@@ -95,7 +96,7 @@ static void addDrive(string &path)
static string unixYafrayPath()
{
- static char *alternative[]=
+ static const char *alternative[]=
{
"/usr/local/bin/",
"/usr/bin/",
@@ -125,7 +126,7 @@ static void adjustPath(string &path)
// if relative, expand to full path
char cpath[MAXPATHLEN];
strcpy(cpath, path.c_str());
- BLI_convertstringcode(cpath, G.sce, 0);
+ BLI_convertstringcode(cpath, G.sce);
path = cpath;
#ifdef WIN32
// add drive char if not there
@@ -880,7 +881,7 @@ void yafrayFileRender_t::writeShader(const string &shader_name, Material* matr,
ostr << "\t\t<input value=\"" << shader_name << "_map" << m2 << "\" />\n";
// blendtype, would have been nice if the order would have been the same as for ramps...
- const string blendtype[9] = {"mix", "mul", "add", "sub", "divide", "darken", "difference", "lighten", "screen"};
+ const string blendtype[MTEX_NUM_BLENDTYPES] = {"mix", "mul", "add", "sub", "divide", "darken", "difference", "lighten", "screen", "hue", "sat", "val", "color"};
ostr << "\t\t<mode value=\"" << blendtype[(int)mtex->blendtype] << "\" />\n";
// texture color (for use with MUL and/or no_rgb etc..)
@@ -1189,7 +1190,7 @@ void yafrayFileRender_t::writeMaterialsAndModulators()
}
-void yafrayFileRender_t::writeObject(Object* obj, const vector<VlakRen*> &VLR_list, const float obmat[4][4])
+void yafrayFileRender_t::writeObject(Object* obj, ObjectRen *obr, const vector<VlakRen*> &VLR_list, const float obmat[4][4])
{
ostr.str("");
// transform first (not necessarily actual obj->obmat, can be duplivert see below)
@@ -1231,7 +1232,6 @@ void yafrayFileRender_t::writeObject(Object* obj, const vector<VlakRen*> &VLR_li
string matname(face0mat->id.name);
// use name in imgtex_shader list if 'TexFace' enabled for this material
if (face0mat->mode & MA_FACETEXTURE) {
- ObjectRen *obr = face0->obr;
MTFace* tface = RE_vlakren_get_tface(obr, face0, obr->actmtface, NULL, 0);
if (tface) {
Image* fimg = (Image*)tface->tpage;
@@ -1409,7 +1409,6 @@ void yafrayFileRender_t::writeObject(Object* obj, const vector<VlakRen*> &VLR_li
fci2!=VLR_list.end();++fci2)
{
VlakRen* vlr = *fci2;
- ObjectRen *obr = vlr->obr;
Material* fmat = vlr->mat;
bool EXPORT_VCOL = ((fmat->mode & (MA_VERTEXCOL|MA_VERTEXCOLP))!=0);
string fmatname(fmat->id.name);
@@ -1511,13 +1510,13 @@ void yafrayFileRender_t::writeAllObjects()
{
// first all objects except dupliverts (and main instance object for dups)
- for (map<Object*, vector<VlakRen*> >::const_iterator obi=all_objects.begin();
+ for (map<Object*, yafrayObjectRen >::const_iterator obi=all_objects.begin();
obi!=all_objects.end(); ++obi)
{
// skip main duplivert object if in dupliMtx_list, written later
Object* obj = obi->first;
if (dupliMtx_list.find(string(obj->id.name))!=dupliMtx_list.end()) continue;
- writeObject(obj, obi->second, obj->obmat);
+ writeObject(obj, obi->second.obr, obi->second.faces, obj->obmat);
}
// Now all duplivert objects (if any) as instances of main object
@@ -1537,7 +1536,7 @@ void yafrayFileRender_t::writeAllObjects()
// first object written as normal (but with transform of first duplivert)
Object* obj = dup_srcob[dupMtx->first];
- writeObject(obj, all_objects[obj], obmat);
+ writeObject(obj, all_objects[obj].obr, all_objects[obj].faces, obmat);
// all others instances of first
for (unsigned int curmtx=16;curmtx<dupMtx->second.size();curmtx+=16) { // number of 4x4 matrices
@@ -2018,7 +2017,7 @@ bool yafrayFileRender_t::executeYafray(const string &xmlpath)
{
ostr.str("");
if (re->r.mode & R_BORDER) {
- ostr << command_path << "yafray -c " << re->r.YF_numprocs
+ ostr << command_path << "yafray -c " << re->r.threads
<< " -r " << (2.f*re->r.border.xmin - 1.f)
<< ":" << (2.f*re->r.border.xmax - 1.f)
<< ":" << (2.f*re->r.border.ymin - 1.f)
@@ -2026,7 +2025,7 @@ bool yafrayFileRender_t::executeYafray(const string &xmlpath)
<< " \"" << xmlpath << "\"";
}
else
- ostr << command_path << "yafray -c " << re->r.YF_numprocs << " \"" << xmlpath << "\"";
+ ostr << command_path << "yafray -c " << re->r.threads << " \"" << xmlpath << "\"";
string command = ostr.str();
cout << "COMMAND: " << command << endl;
diff --git a/source/blender/yafray/intern/export_File.h b/source/blender/yafray/intern/export_File.h
index 5d2e0c53a21..0eb1bfec1ed 100644
--- a/source/blender/yafray/intern/export_File.h
+++ b/source/blender/yafray/intern/export_File.h
@@ -18,7 +18,7 @@ class yafrayFileRender_t : public yafrayRender_t
virtual void writeTextures();
virtual void writeShader(const std::string &shader_name, Material* matr, const std::string &facetexname="");
virtual void writeMaterialsAndModulators();
- virtual void writeObject(Object* obj, const std::vector<VlakRen*> &VLR_list, const float obmat[4][4]);
+ virtual void writeObject(Object* obj, ObjectRen *obr, const std::vector<VlakRen*> &VLR_list, const float obmat[4][4]);
virtual void writeAllObjects();
virtual void writeAreaLamp(LampRen* lamp, int num, float iview[4][4]);
virtual void writeLamps();
diff --git a/source/blender/yafray/intern/export_Plugin.cpp b/source/blender/yafray/intern/export_Plugin.cpp
index 16ae2d97f62..db9fb7ccc72 100644
--- a/source/blender/yafray/intern/export_Plugin.cpp
+++ b/source/blender/yafray/intern/export_Plugin.cpp
@@ -1,7 +1,9 @@
#include "export_Plugin.h"
#include <math.h>
+
#include <cstring>
+
using namespace std;
@@ -72,7 +74,7 @@ extern "C" { extern char bprogname[]; }
// add drive character if not in path string, using blender executable location as reference
static void addDrive(string &path)
{
- int sp = path.find_first_of(":");
+ size_t sp = path.find_first_of(":");
if (sp==-1) {
string blpath = bprogname;
sp = blpath.find_first_of(":");
@@ -96,9 +98,12 @@ static string YafrayPath()
string path=find_path();
return path;
#else
- static char *alternative[]=
+ static const char *alternative[]=
{
"/usr/local/lib/",
+#ifdef __x86_64__
+ "/usr/lib64/",
+#endif
"/usr/lib/",
NULL
};
@@ -119,9 +124,12 @@ static string YafrayPluginPath()
#ifdef WIN32
return find_path()+"\\plugins";
#else
- static char *alternative[]=
+ static const char *alternative[]=
{
"/usr/local/lib/yafray",
+#ifdef __x86_64__
+ "/usr/lib64/yafray",
+#endif
"/usr/lib/yafray",
NULL
};
@@ -163,7 +171,9 @@ bool yafrayPluginRender_t::initExport()
corehandle = PIL_dynlib_open((char *)(location + "\\yafraycore.dll").c_str());
if (corehandle==NULL)
{
- cerr << "Error loading yafray plugin: " << PIL_dynlib_get_error_as_string(corehandle) << endl;
+ char *err = PIL_dynlib_get_error_as_string(corehandle);
+ if (err) cerr << "Error loading yafray plugin: " << err << endl;
+ else cerr << "Error loading yafray plugin: Unknown." << endl;
return false;
}
location += "\\yafrayplugin.dll";
@@ -184,7 +194,7 @@ bool yafrayPluginRender_t::initExport()
cerr << "Error loading yafray plugin: " << PIL_dynlib_get_error_as_string(handle) << endl;
return false;
}
- yafrayGate = constructor(re->r.YF_numprocs, YafrayPluginPath());
+ yafrayGate = constructor(re->r.threads, YafrayPluginPath());
cout << "YafRay plugin loaded" << endl;
plugin_loaded = true;
@@ -244,7 +254,7 @@ bool yafrayPluginRender_t::writeRender()
params["bias"] = yafray::parameter_t(re->r.YF_raybias);
params["clamp_rgb"] = yafray::parameter_t((re->r.YF_clamprgb==0) ? "on" : "off");
// lynx request
- params["threads"] = yafray::parameter_t((int)re->r.YF_numprocs);
+ params["threads"] = yafray::parameter_t((int)re->r.threads);
blenderYafrayOutput_t output(re);
yafrayGate->render(params, output);
cout << "render finished" << endl;
@@ -270,7 +280,7 @@ static void adjustPath(string &path)
// if relative, expand to full path
char cpath[MAXPATHLEN];
strcpy(cpath, path.c_str());
- BLI_convertstringcode(cpath, G.sce, 0);
+ BLI_convertstringcode(cpath, G.sce);
path = cpath;
#ifdef WIN32
// add drive char if not there
@@ -774,7 +784,7 @@ void yafrayPluginRender_t::writeShader(const string &shader_name, Material* matr
mparams["input"] = yafray::parameter_t(shader_name + temp);
// blendtype, would have been nice if the order would have been the same as for ramps...
- const string blendtype[9] = {"mix", "mul", "add", "sub", "divide", "darken", "difference", "lighten", "screen"};
+ const string blendtype[MTEX_NUM_BLENDTYPES] = {"mix", "mul", "add", "sub", "divide", "darken", "difference", "lighten", "screen", "hue", "sat", "val", "color"};
mparams["mode"] = yafray::parameter_t(blendtype[(int)mtex->blendtype]);
// texture color (for use with MUL and/or no_rgb etc..)
@@ -1080,7 +1090,7 @@ void yafrayPluginRender_t::writeMaterialsAndModulators()
}
-void yafrayPluginRender_t::genUVcoords(vector<yafray::GFLOAT> &uvcoords, VlakRen *vlr, MTFace* uvc, bool comple)
+void yafrayPluginRender_t::genUVcoords(vector<yafray::GFLOAT> &uvcoords, ObjectRen *obr, VlakRen *vlr, MTFace* uvc, bool comple)
{
if (uvc)
{
@@ -1108,9 +1118,8 @@ void yafrayPluginRender_t::genUVcoords(vector<yafray::GFLOAT> &uvcoords, VlakRen
}
}
-void yafrayPluginRender_t::genVcol(vector<yafray::CFLOAT> &vcol, VlakRen *vlr, bool comple)
+void yafrayPluginRender_t::genVcol(vector<yafray::CFLOAT> &vcol, ObjectRen *obr, VlakRen *vlr, bool comple)
{
- ObjectRen *obr= vlr->obr;
MCol *mcol= RE_vlakren_get_mcol(obr, vlr, obr->actmcol, NULL, 0);
if (mcol)
@@ -1144,10 +1153,9 @@ void yafrayPluginRender_t::genVcol(vector<yafray::CFLOAT> &vcol, VlakRen *vlr, b
void yafrayPluginRender_t::genFace(vector<int> &faces,vector<string> &shaders,vector<int> &faceshader,
vector<yafray::GFLOAT> &uvcoords,vector<yafray::CFLOAT> &vcol,
- map<VertRen*, int> &vert_idx,VlakRen *vlr,
+ map<VertRen*, int> &vert_idx,ObjectRen *obr,VlakRen *vlr,
int has_orco,bool has_uv)
{
- ObjectRen *obr= vlr->obr;
Material* fmat = vlr->mat;
bool EXPORT_VCOL = ((fmat->mode & (MA_VERTEXCOL|MA_VERTEXCOLP))!=0);
string fmatname(fmat->id.name);
@@ -1186,16 +1194,15 @@ void yafrayPluginRender_t::genFace(vector<int> &faces,vector<string> &shaders,ve
faces.push_back(idx1); faces.push_back(idx2); faces.push_back(idx3);
- if(has_uv) genUVcoords(uvcoords, vlr, uvc);
- if (EXPORT_VCOL) genVcol(vcol, vlr);
+ if(has_uv) genUVcoords(uvcoords, obr, vlr, uvc);
+ if (EXPORT_VCOL) genVcol(vcol, obr, vlr);
}
void yafrayPluginRender_t::genCompleFace(vector<int> &faces,/*vector<string> &shaders,*/vector<int> &faceshader,
vector<yafray::GFLOAT> &uvcoords,vector<yafray::CFLOAT> &vcol,
- map<VertRen*, int> &vert_idx,VlakRen *vlr,
+ map<VertRen*, int> &vert_idx,ObjectRen *obr,VlakRen *vlr,
int has_orco,bool has_uv)
{
- ObjectRen *obr= vlr->obr;
Material* fmat = vlr->mat;
bool EXPORT_VCOL = ((fmat->mode & (MA_VERTEXCOL|MA_VERTEXCOLP))!=0);
@@ -1211,12 +1218,12 @@ void yafrayPluginRender_t::genCompleFace(vector<int> &faces,/*vector<string> &sh
faces.push_back(idx1); faces.push_back(idx2); faces.push_back(idx3);
- if (has_uv) genUVcoords(uvcoords, vlr, uvc, true);
- if (EXPORT_VCOL) genVcol(vcol, vlr, true);
+ if (has_uv) genUVcoords(uvcoords, obr, vlr, uvc, true);
+ if (EXPORT_VCOL) genVcol(vcol, obr, vlr, true);
}
void yafrayPluginRender_t::genVertices(vector<yafray::point3d_t> &verts, int &vidx,
- map<VertRen*, int> &vert_idx, VlakRen* vlr, int has_orco, Object* obj)
+ map<VertRen*, int> &vert_idx, ObjectRen *obr, VlakRen* vlr, int has_orco, Object* obj)
{
VertRen* ver;
float tvec[3]; // for back2world transform
@@ -1281,7 +1288,7 @@ void yafrayPluginRender_t::genVertices(vector<yafray::point3d_t> &verts, int &vi
}
}
-void yafrayPluginRender_t::writeObject(Object* obj, const vector<VlakRen*> &VLR_list, const float obmat[4][4])
+void yafrayPluginRender_t::writeObject(Object* obj, ObjectRen *obr, const vector<VlakRen*> &VLR_list, const float obmat[4][4])
{
float mtr[4*4];
mtr[0*4+0]=obmat[0][0]; mtr[0*4+1]=obmat[1][0]; mtr[0*4+2]=obmat[2][0]; mtr[0*4+3]=obmat[3][0];
@@ -1342,8 +1349,7 @@ void yafrayPluginRender_t::writeObject(Object* obj, const vector<VlakRen*> &VLR_
fci!=VLR_list.end();++fci)
{
VlakRen* vlr = *fci;
- ObjectRen *obr = vlr->obr;
- genVertices(verts, vidx, vert_idx, vlr, has_orco, obj);
+ genVertices(verts, vidx, vert_idx, obr, vlr, has_orco, obj);
if(RE_vlakren_get_tface(obr, vlr, obr->actmtface, NULL, 0)) has_uv=true;
}
// all faces using the index list created above
@@ -1355,9 +1361,9 @@ void yafrayPluginRender_t::writeObject(Object* obj, const vector<VlakRen*> &VLR_
fci2!=VLR_list.end();++fci2)
{
VlakRen* vlr = *fci2;
- genFace(faces, shaders, faceshader, uvcoords, vcol, vert_idx, vlr, has_orco, has_uv);
+ genFace(faces, shaders, faceshader, uvcoords, vcol, vert_idx, obr, vlr, has_orco, has_uv);
if (vlr->v4)
- genCompleFace(faces, faceshader, uvcoords, vcol, vert_idx, vlr, has_orco, has_uv);
+ genCompleFace(faces, faceshader, uvcoords, vcol, vert_idx, obr, vlr, has_orco, has_uv);
}
// using the ObjectRen database, contruct a new name if object has a parent.
@@ -1388,13 +1394,13 @@ void yafrayPluginRender_t::writeObject(Object* obj, const vector<VlakRen*> &VLR_
void yafrayPluginRender_t::writeAllObjects()
{
// first all objects except dupliverts (and main instance object for dups)
- for (map<Object*, vector<VlakRen*> >::const_iterator obi=all_objects.begin();
+ for (map<Object*, yafrayObjectRen >::const_iterator obi=all_objects.begin();
obi!=all_objects.end(); ++obi)
{
// skip main duplivert object if in dupliMtx_list, written later
Object* obj = obi->first;
if (dupliMtx_list.find(string(obj->id.name))!=dupliMtx_list.end()) continue;
- writeObject(obj, obi->second, obj->obmat);
+ writeObject(obj, obi->second.obr, obi->second.faces, obj->obmat);
}
// Now all duplivert objects (if any) as instances of main object
@@ -1412,7 +1418,7 @@ void yafrayPluginRender_t::writeAllObjects()
// first object written as normal (but with transform of first duplivert)
Object* obj = dup_srcob[dupMtx->first];
- writeObject(obj, all_objects[obj], obmat);
+ writeObject(obj, all_objects[obj].obr, all_objects[obj].faces, obmat);
// all others instances of first
for (unsigned int curmtx=16;curmtx<dupMtx->second.size();curmtx+=16)
diff --git a/source/blender/yafray/intern/export_Plugin.h b/source/blender/yafray/intern/export_Plugin.h
index 1ce4988a260..660271daf96 100644
--- a/source/blender/yafray/intern/export_Plugin.h
+++ b/source/blender/yafray/intern/export_Plugin.h
@@ -35,7 +35,7 @@ class yafrayPluginRender_t : public yafrayRender_t
virtual void writeTextures();
virtual void writeShader(const std::string &shader_name, Material* matr, const std::string &facetexname="");
virtual void writeMaterialsAndModulators();
- virtual void writeObject(Object* obj,
+ virtual void writeObject(Object* obj, ObjectRen *obr,
const std::vector<VlakRen*> &VLR_list, const float obmat[4][4]);
virtual void writeAllObjects();
virtual void writeAreaLamp(LampRen* lamp, int num, float iview[4][4]);
@@ -48,18 +48,18 @@ class yafrayPluginRender_t : public yafrayRender_t
virtual bool initExport();
virtual bool finishExport();
- void genUVcoords(std::vector<yafray::GFLOAT> &uvcoords,VlakRen *vlr,MTFace* uvc, bool comple=false);
- void genVcol(std::vector<yafray::CFLOAT> &vcol, VlakRen *vlr, bool comple=false);
+ void genUVcoords(std::vector<yafray::GFLOAT> &uvcoords,ObjectRen *obr,VlakRen *vlr,MTFace* uvc, bool comple=false);
+ void genVcol(std::vector<yafray::CFLOAT> &vcol, ObjectRen *obr, VlakRen *vlr, bool comple=false);
void genFace(std::vector<int> &faces,std::vector<std::string> &shaders,std::vector<int> &faceshader,
std::vector<yafray::GFLOAT> &uvcoords,std::vector<yafray::CFLOAT> &vcol,
- std::map<VertRen*, int> &vert_idx,VlakRen *vlr,
+ std::map<VertRen*, int> &vert_idx,ObjectRen *obr,VlakRen *vlr,
int has_orco,bool has_uv);
void genCompleFace(std::vector<int> &faces,/*std::vector<std::string> &shaders,*/std::vector<int> &faceshader,
std::vector<yafray::GFLOAT> &uvcoords,std::vector<yafray::CFLOAT> &vcol,
- std::map<VertRen*, int> &vert_idx,VlakRen *vlr,
+ std::map<VertRen*, int> &vert_idx,ObjectRen *obr, VlakRen *vlr,
int has_orco,bool has_uv);
void genVertices(std::vector<yafray::point3d_t> &verts, int &vidx,
- std::map<VertRen*, int> &vert_idx, VlakRen* vlr, int has_orco, Object* obj);
+ std::map<VertRen*, int> &vert_idx, ObjectRen *obr, VlakRen* vlr, int has_orco, Object* obj);
};
class blenderYafrayOutput_t : public yafray::colorOutput_t
diff --git a/source/blender/yafray/intern/yafray_Render.cpp b/source/blender/yafray/intern/yafray_Render.cpp
index 90229575235..01da4683d71 100644
--- a/source/blender/yafray/intern/yafray_Render.cpp
+++ b/source/blender/yafray/intern/yafray_Render.cpp
@@ -7,6 +7,7 @@
#include "yafray_Render.h"
#include <math.h>
+
#include <cstring>
using namespace std;
@@ -142,15 +143,15 @@ bool yafrayRender_t::getAllMatTexObs()
// Make list of faces per object, ignore <3 vert faces, duplicate vertex sorting done later.
// ignore null object pointers.
// Also make list of facetexture images (material 'TexFace').
- if (vlr->obr->ob) {
+ if (obr->ob) {
int nv = 0; // number of vertices
MTFace *tface;
if (vlr->v4) nv=4; else if (vlr->v3) nv=3;
if (nv) {
- ObjectRen *obr= vlr->obr;
renderobs[obr->ob->id.name] = obr->ob;
- all_objects[obr->ob].push_back(vlr);
+ all_objects[obr->ob].obr= obr;
+ all_objects[obr->ob].faces.push_back(vlr);
tface= RE_vlakren_get_tface(obr, vlr, obr->actmtface, NULL, 0);
if (tface && tface->tpage) {
@@ -185,7 +186,7 @@ bool yafrayRender_t::getAllMatTexObs()
// in all_objects with the name given in dupliMtx_list
if (!dupliMtx_list.empty()) {
- for (map<Object*, vector<VlakRen*> >::const_iterator obn=all_objects.begin();
+ for (map<Object*, yafrayObjectRen>::const_iterator obn=all_objects.begin();
obn!=all_objects.end();++obn)
{
Object* obj = obn->first;
diff --git a/source/blender/yafray/intern/yafray_Render.h b/source/blender/yafray/intern/yafray_Render.h
index 0debb0009fa..43d2c6c602a 100644
--- a/source/blender/yafray/intern/yafray_Render.h
+++ b/source/blender/yafray/intern/yafray_Render.h
@@ -52,6 +52,12 @@ extern void error (char *fmt, ...);
#include <vector>
#include <set>
+class yafrayObjectRen {
+ public:
+ std::vector<VlakRen*> faces;
+ ObjectRen *obr;
+};
+
class yafrayRender_t
{
public:
@@ -72,7 +78,7 @@ class yafrayRender_t
bool hasworld;
- std::map<Object*, std::vector<VlakRen*> > all_objects;
+ std::map<Object*, yafrayObjectRen> all_objects;
std::map<std::string, Material*> used_materials;
std::map<std::string, MTex*> used_textures;
std::map<std::string, std::vector<float> > dupliMtx_list;
@@ -86,7 +92,7 @@ class yafrayRender_t
virtual void writeTextures()=0;
virtual void writeShader(const std::string &shader_name, Material* matr, const std::string &facetexname)=0;
virtual void writeMaterialsAndModulators()=0;
- virtual void writeObject(Object* obj, const std::vector<VlakRen*> &VLR_list, const float obmat[4][4])=0;
+ virtual void writeObject(Object* obj, ObjectRen *obr, const std::vector<VlakRen*> &VLR_list, const float obmat[4][4])=0;
virtual void writeAllObjects()=0;
virtual void writeLamps()=0;
virtual void writeCamera()=0;
diff --git a/source/creator/CMakeLists.txt b/source/creator/CMakeLists.txt
index 874e905c75b..5cf39adab29 100644
--- a/source/creator/CMakeLists.txt
+++ b/source/creator/CMakeLists.txt
@@ -37,18 +37,27 @@ INCLUDE_DIRECTORIES(../../intern/guardedalloc
../blender/render/extern/include
../blender/python
../blender/makesdna
+ ../blender/gpu
../blender/windowmanager
../kernel/gen_messaging
../kernel/gen_system
+ ../../extern/glew/include
)
+
+
IF(WITH_QUICKTIME)
ADD_DEFINITIONS(-DWITH_QUICKTIME)
ENDIF(WITH_QUICKTIME)
-IF(YESIAMSTUPID)
- ADD_DEFINITIONS(-DYESIAMSTUPID)
-ENDIF(YESIAMSTUPID)
+IF(WITH_OPENEXR)
+ ADD_DEFINITIONS(-DWITH_OPENEXR)
+ENDIF(WITH_OPENEXR)
+
+IF(LINUX)
+ ADD_DEFINITIONS(-DWITH_BINRELOC)
+ INCLUDE_DIRECTORIES(${BINRELOC_INC})
+endif(LINUX)
MESSAGE(STATUS "Configuring blender")
@@ -125,16 +134,17 @@ IF(WIN32)
ADD_CUSTOM_COMMAND(TARGET blender
POST_BUILD
MAIN_DEPENDENCY blender
- COMMAND if not exist \"$\(TargetDir\)\\.blender\" mkdir \"$\(TargetDir\)\\.blender\"
- COMMAND if not exist \"$\(TargetDir\)\\.blender\\locale\" mkdir \"$\(TargetDir\)\\.blender\\locale\"
- COMMAND if not exist \"$\(TargetDir\)\\.blender\\scripts\" mkdir \"$\(TargetDir\)\\.blender\\scripts\"
- COMMAND if not exist \"$\(TargetDir\)\\plugins\" mkdir \"$\(TargetDir\)\\plugins\"
- COMMAND copy /Y \"${WIN_SOURCE_DIR}\\bin\\.blender\\.Blanguages\" \"$\(TargetDir\)\\.blender\\\"
- COMMAND copy /Y \"${WIN_SOURCE_DIR}\\bin\\.blender\\.bfont.ttf\" \"$\(TargetDir\)\\.blender\\\"
- COMMAND xcopy /E /Y \"${WIN_SOURCE_DIR}\\bin\\.blender\\locale\\*.*\" \"$\(TargetDir\)\\.blender\\locale\"
- COMMAND xcopy /E /Y \"${WIN_SOURCE_DIR}\\release\\scripts\\*.*\" \"$\(TargetDir\)\\.blender\\scripts\"
- COMMAND xcopy /E /Y \"${WIN_SOURCE_DIR}\\release\\plugins\\*.*\" \"$\(TargetDir\)\\plugins\"
- COMMAND copy /Y \"${WIN_SOURCE_DIR}\\release\\text\\*.*\" \"$\(TargetDir\)\"
+ COMMAND if not exist \"${TARGETDIR}\\.blender\" mkdir \"${TARGETDIR}\\.blender\"
+ COMMAND if not exist \"${TARGETDIR}\\.blender\\locale\" mkdir \"${TARGETDIR}\\.blender\\locale\"
+ COMMAND if not exist \"${TARGETDIR}\\.blender\\scripts\" mkdir \"${TARGETDIR}\\.blender\\scripts\"
+ COMMAND if not exist \"${TARGETDIR}\\plugins\" mkdir \"${TARGETDIR}\\plugins\"
+ COMMAND copy /Y \"${WIN_SOURCE_DIR}\\bin\\.blender\\.Blanguages\" \"${TARGETDIR}\\.blender\\\"
+ COMMAND copy /Y \"${WIN_SOURCE_DIR}\\bin\\.blender\\.bfont.ttf\" \"${TARGETDIR}\\.blender\\\"
+ COMMAND xcopy /E /Y \"${WIN_SOURCE_DIR}\\bin\\.blender\\locale\\*.*\" \"${TARGETDIR}\\.blender\\locale\"
+ COMMAND xcopy /E /Y \"${WIN_SOURCE_DIR}\\release\\scripts\\*.*\" \"${TARGETDIR}\\.blender\\scripts\"
+ COMMAND xcopy /E /Y \"${WIN_SOURCE_DIR}\\release\\plugins\\*.*\" \"${TARGETDIR}\\plugins\"
+ COMMAND copy /Y \"${WIN_SOURCE_DIR}\\release\\text\\*.*\" \"${TARGETDIR}\"
+ COMMAND copy /Y \"${WIN_SOURCE_DIR}\\release\\windows\\extra\\python25.zip\" \"${TARGETDIR}\\\"
)
FILE(TO_NATIVE_PATH "${LIBDIR}" WIN_LIBDIR)
@@ -142,22 +152,20 @@ IF(WIN32)
ADD_CUSTOM_COMMAND(TARGET blender
POST_BUILD
MAIN_DEPENDENCY blender
- COMMAND copy /Y \"${WIN_LIBDIR}\\gettext\\lib\\gnu_gettext.dll\" \"$\(TargetDir\)\\\"
- COMMAND copy /Y \"${WIN_LIBDIR}\\png\\lib\\libpng.dll\" \"$\(TargetDir\)\\\"
- COMMAND copy /Y \"${WIN_LIBDIR}\\sdl\\lib\\SDL.dll\" \"$\(TargetDir\)\\\"
- COMMAND copy /Y \"${WIN_LIBDIR}\\zlib\\lib\\zlib.dll\" \"$\(TargetDir\)\\\"
- COMMAND copy /Y \"${WIN_LIBDIR}\\tiff\\lib\\libtiff.dll\" \"$\(TargetDir\)\\\"
- COMMAND if $\(ConfigurationName\)==Debug copy /Y \"${WIN_LIBDIR}\\python\\lib\\python25_D.dll\" \"$\(TargetDir\)\\\"
- COMMAND if $\(ConfigurationName\)==Debug copy /Y \"${WIN_LIBDIR}\\CRTL\\lib\\msvcrtd.dll\" \"$\(TargetDir\)\\\"
- COMMAND if NOT $\(ConfigurationName\)==Debug copy /Y \"${WIN_LIBDIR}\\python\\lib\\python25.dll\" \"$\(TargetDir\)\\\"
- COMMAND copy /Y \"${WIN_LIBDIR}\\pthreads\\lib\\pthreadVC2.dll\" \"$\(TargetDir\)\\\"
+ COMMAND copy /Y \"${WIN_LIBDIR}\\gettext\\lib\\gnu_gettext.dll\" \"${TARGETDIR}\\\"
+ COMMAND copy /Y \"${WIN_LIBDIR}\\png\\lib\\libpng.dll\" \"${TARGETDIR}\\\"
+ COMMAND copy /Y \"${WIN_LIBDIR}\\sdl\\lib\\SDL.dll\" \"${TARGETDIR}\\\"
+ COMMAND copy /Y \"${WIN_LIBDIR}\\zlib\\lib\\zlib.dll\" \"${TARGETDIR}\\\"
+ COMMAND copy /Y \"${WIN_LIBDIR}\\tiff\\lib\\libtiff.dll\" \"${TARGETDIR}\\\"
+ COMMAND copy /Y \"${WIN_LIBDIR}\\python\\lib\\python25.dll\" \"${TARGETDIR}\\\"
+ COMMAND copy /Y \"${WIN_LIBDIR}\\pthreads\\lib\\pthreadVC2.dll\" \"${TARGETDIR}\\\"
)
IF(WITH_INTERNATIONAL)
ADD_CUSTOM_COMMAND(TARGET blender
POST_BUILD
MAIN_DEPENDENCY blender
- COMMAND copy /Y \"${WIN_LIBDIR}\\iconv\\lib\\iconv.dll\" \"$\(TargetDir\)\\\"
+ COMMAND copy /Y \"${WIN_LIBDIR}\\iconv\\lib\\iconv.dll\" \"${TARGETDIR}\\\"
)
ENDIF(WITH_INTERNATIONAL)
@@ -165,20 +173,16 @@ IF(WIN32)
ADD_CUSTOM_COMMAND(TARGET blender
POST_BUILD
MAIN_DEPENDENCY blender
- COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\avcodec-51.dll\" \"$\(TargetDir\)\\\"
- COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\avformat-51.dll\" \"$\(TargetDir\)\\\"
- COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\avutil-49.dll\" \"$\(TargetDir\)\\\"
- COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\libdts.dll\" \"$\(TargetDir\)\\\"
- COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\libfaac.dll\" \"$\(TargetDir\)\\\"
- COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\libfaad.dll\" \"$\(TargetDir\)\\\"
- COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\libgsm.dll\" \"$\(TargetDir\)\\\"
- COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\libmp3lame-0.dll\" \"$\(TargetDir\)\\\"
- COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\libogg-0.dll\" \"$\(TargetDir\)\\\"
- COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\libvorbis-0.dll\" \"$\(TargetDir\)\\\"
- COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\libvorbisenc-2.dll\" \"$\(TargetDir\)\\\"
- COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\libx264-54.dll\" \"$\(TargetDir\)\\\"
- COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\postproc-51.dll\" \"$\(TargetDir\)\\\"
- COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\xvidcore.dll\" \"$\(TargetDir\)\\\"
+ COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\avcodec-51.dll\" \"${TARGETDIR}\\\"
+ COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\avformat-52.dll\" \"${TARGETDIR}\\\"
+ COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\avdevice-52.dll\" \"${TARGETDIR}\\\"
+ COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\avutil-49.dll\" \"${TARGETDIR}\\\"
+ COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\libfaac-0.dll\" \"${TARGETDIR}\\\"
+ COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\libfaad-0.dll\" \"${TARGETDIR}\\\"
+ COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\libmp3lame-0.dll\" \"${TARGETDIR}\\\"
+ COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\libx264-59.dll\" \"${TARGETDIR}\\\"
+ COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\swscale-0.dll\" \"${TARGETDIR}\\\"
+ COMMAND copy /Y \"${WIN_LIBDIR}\\ffmpeg\\lib\\xvidcore.dll\" \"${TARGETDIR}\\\"
)
ENDIF(WITH_FFMPEG)
ENDIF(WIN32)
@@ -187,7 +191,15 @@ ADD_DEPENDENCIES(blender makesdna)
FILE(READ ${CMAKE_BINARY_DIR}/cmake_blender_libs.txt BLENDER_LINK_LIBS)
-SET(BLENDER_LINK_LIBS bf_nodes ${BLENDER_LINK_LIBS} bf_windowmanager bf_editors blender_render blender_radiosity blender_IK bf_elbeem)
+SET(BLENDER_LINK_LIBS bf_nodes ${BLENDER_LINK_LIBS} bf_windowmanager bf_editors blender_render blender_radiosity)
+
+IF(WITH_ELBEEM)
+ SET(BLENDER_LINK_LIBS ${BLENDER_LINK_LIBS} bf_elbeem)
+ENDIF(WITH_ELBEEM)
+
+IF(CMAKE_SYSTEM_NAME MATCHES "Linux")
+ SET(BLENDER_LINK_LIBS ${BLENDER_LINK_LIBS} extern_binreloc)
+ENDIF(CMAKE_SYSTEM_NAME MATCHES "Linux")
IF(UNIX)
# Sort libraries
@@ -205,6 +217,7 @@ IF(UNIX)
bf_python
bf_blenkernel
bf_nodes
+ bf_gpu
bf_blenloader
bf_blenpluginapi
bf_imbuf
@@ -212,13 +225,14 @@ IF(UNIX)
bf_avi
bf_cineon
bf_openexr
+ bf_dds
bf_readblenfile
blender_bop
bf_kernel
bf_decimation
bf_elbeem
bf_yafray
- blender_IK
+ bf_IK
bf_memutil
bf_guardedalloc
blender_CTR
@@ -254,6 +268,9 @@ IF(UNIX)
bf_moto
bf_python
bf_quicktime
+ extern_binreloc
+ extern_glew
+ bf_videotex
)
FOREACH(SORTLIB ${BLENDER_SORTED_LIBS})
diff --git a/source/creator/Makefile b/source/creator/Makefile
index df07aab6786..ea301ad80a9 100644
--- a/source/creator/Makefile
+++ b/source/creator/Makefile
@@ -39,6 +39,7 @@ CFLAGS += $(LEVEL_1_C_WARNINGS)
CPPFLAGS += -I../blender/render/extern/include
CPPFLAGS += -I../blender/radiosity/extern/include
+
# two needed for the kernel
CPPFLAGS += -I../blender/imbuf
CPPFLAGS += -I../blender/makesdna
@@ -48,17 +49,19 @@ CPPFLAGS += -I../blender/renderconverter
CPPFLAGS += -I../blender/blenkernel
CPPFLAGS += -I../blender/python
CPPFLAGS += -I../blender/blenloader
+CPPFLAGS += -I../blender/gpu
CPPFLAGS += -I../blender/windowmanager
CPPFLAGS += -I../kernel/gen_system
CPPFLAGS += -I../kernel/gen_messaging
CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include
+CPPFLAGS += -I$(NAN_GLEW)/include
ifeq ($(WITH_QUICKTIME), true)
CPPFLAGS += -I$(NAN_QUICKTIME)/include -DWITH_QUICKTIME
endif
-ifeq ($(NAN_YESIAMSTUPID), true)
- CPPFLAGS += -DYESIAMSTUPID
+ifeq ($(WITH_BINRELOC), true)
+ CPPFLAGS += -I$(NANBLENDERHOME)/extern/binreloc/include -DWITH_BINRELOC
endif
CPPFLAGS += -I$(OPENGL_HEADERS)
diff --git a/source/creator/SConscript b/source/creator/SConscript
index a39937d7721..6c36a8f5b41 100644
--- a/source/creator/SConscript
+++ b/source/creator/SConscript
@@ -6,13 +6,28 @@ sources = 'creator.c'
incs = '#/intern/guardedalloc ../blender/blenlib ../blender/blenkernel'
incs += ' ../blender/editors/include ../blender/blenloader ../blender/imbuf'
incs += ' ../blender/renderconverter ../blender/render/extern/include ../blender/windowmanager'
-incs += ' ../blender/python ../blender/makesdna ../kernel/gen_messaging'
-incs += ' ../kernel/gen_system'
+incs += ' ../blender/makesdna ../kernel/gen_messaging'
+incs += ' ../kernel/gen_system #/extern/glew/include ../blender/gpu'
incs += ' ' + env['BF_OPENGL_INC']
defs = []
-if env['WITH_BF_QUICKTIME']==1:
- incs += ' ' + env['BF_QUICKTIME_INC']
- defs.append('WITH_QUICKTIME')
+if env['WITH_BF_QUICKTIME']:
+ incs += ' ' + env['BF_QUICKTIME_INC']
+ defs.append('WITH_QUICKTIME')
+
+if env['WITH_BF_BINRELOC']:
+ incs += ' ../../extern/binreloc/include'
+ defs.append('WITH_BINRELOC')
+
+if env['WITH_BF_OPENEXR']:
+ defs.append('WITH_OPENEXR')
+
+if not env['WITH_BF_SDL']:
+ defs.append('DISABLE_SDL')
+
+if env['WITH_BF_PYTHON']:
+ incs += ' ../blender/python'
+else:
+ defs.append('DISABLE_PYTHON')
env.BlenderLib ( libname = 'bf_creator', sources = Split(sources), includes = Split(incs), defines = defs, libtype='core', priority = 0 )
diff --git a/source/creator/creator.c b/source/creator/creator.c
index baf5f736214..63e0fc87da0 100644
--- a/source/creator/creator.c
+++ b/source/creator/creator.c
@@ -56,7 +56,9 @@
#include "IMB_imbuf.h" // for quicktime_init
+#ifndef DISABLE_PYTHON
#include "BPY_extern.h"
+#endif
#include "RE_pipeline.h"
@@ -67,6 +69,9 @@
#include "WM_api.h"
+#include "GPU_draw.h"
+#include "GPU_extensions.h"
+
/* for passing information between creator and gameengine */
#include "SYS_System.h"
@@ -78,6 +83,10 @@
# include <sys/rtprio.h>
#endif
+#ifdef WITH_BINRELOC
+#include "binreloc.h"
+#endif
+
// from buildinfo.c
#ifdef BUILD_DATE
extern char * build_date;
@@ -87,18 +96,18 @@ extern char * build_type;
#endif
/* Local Function prototypes */
-static void print_help();
-static void print_version();
+static void print_help(void);
+static void print_version(void);
/* for the callbacks: */
extern int pluginapi_force_ref(void); /* from blenpluginapi:pluginapi.c */
char bprogname[FILE_MAXDIR+FILE_MAXFILE]; /* from blenpluginapi:pluginapi.c */
-
+char btempdir[FILE_MAXDIR+FILE_MAXFILE];
/* Initialise callbacks for the modules that need them */
-void setCallbacks(void);
+static void setCallbacks(void);
#if defined(__sgi) || defined(__alpha__)
static void fpe_handler(int sig)
@@ -141,31 +150,38 @@ static void print_version(void)
static void print_help(void)
{
printf ("Blender %d.%02d (sub %d) Build\n", G.version/100, G.version%100, BLENDER_SUBVERSION);
- printf ("Usage: blender [options ...] [file]\n");
-
+ printf ("Usage: blender [args ...] [file] [args ...]\n");
printf ("\nRender options:\n");
- printf (" -b <file>\tRender <file> in background\n");
+ printf (" -b <file>\tRender <file> in background (doesn't load the user defaults .B.blend file)\n");
+ printf (" -a render frames from start to end (inclusive), only works when used after -b\n");
printf (" -S <name>\tSet scene <name>\n");
printf (" -f <frame>\tRender frame <frame> and save it\n");
- printf (" -s <frame>\tSet start to frame <frame> (use with -a)\n");
- printf (" -e <frame>\tSet end to frame (use with -a)<frame>\n");
+ printf (" -s <frame>\tSet start to frame <frame> (use before the -a argument)\n");
+ printf (" -e <frame>\tSet end to frame <frame> (use before the -a argument)\n");
printf (" -o <path>\tSet the render path and file name.\n");
printf (" Use // at the start of the path to\n");
printf (" render relative to the blend file.\n");
+ printf (" The # characters are replaced by the frame number, and used to define zero padding.\n");
+ printf (" ani_##_test.png becomes ani_01_test.png\n");
+ printf (" test-######.png becomes test-000001.png\n");
+ printf (" When the filename has no #, The suffix #### is added to the filename\n");
printf (" The frame number will be added at the end of the filename.\n");
- printf (" eg: blender -b foobar.blend -o //render_ -F PNG -x 1\n");
- printf (" -F <format>\tSet the render format, Valid options are..\n");
- printf (" \tTGA IRIS HAMX FTYPE JPEG MOVIE IRIZ RAWTGA\n");
+ printf (" eg: blender -b foobar.blend -o //render_ -F PNG -x 1 -a\n");
+ printf ("\nFormat options:\n");
+ printf (" -F <format>\tSet the render format, Valid options are...\n");
+ printf (" \tTGA IRIS HAMX JPEG MOVIE IRIZ RAWTGA\n");
printf (" \tAVIRAW AVIJPEG PNG BMP FRAMESERVER\n");
printf (" (formats that can be compiled into blender, not available on all systems)\n");
- printf (" \tHDR TIFF EXR MPEG AVICODEC QUICKTIME CINEON DPX\n");
+ printf (" \tHDR TIFF EXR MULTILAYER MPEG AVICODEC QUICKTIME CINEON DPX DDS\n");
printf (" -x <bool>\tSet option to add the file extension to the end of the file.\n");
- printf (" -t <threads>\tUse amount of <threads> for rendering\n");
- printf ("\nAnimation options:\n");
- printf (" -a <file(s)>\tPlayback <file(s)>\n");
+ printf (" -t <threads>\tUse amount of <threads> for rendering (background mode only).\n");
+ printf (" [1-8], 0 for systems processor count.\n");
+ printf ("\nAnimation playback options:\n");
+ printf (" -a <file(s)>\tPlayback <file(s)>, only operates this way when -b is not used.\n");
printf (" -p <sx> <sy>\tOpen with lower left corner at <sx>, <sy>\n");
printf (" -m\t\tRead from disk (Don't buffer)\n");
printf (" -f <fps> <fps-base>\t\tSpecify FPS to start with\n");
+ printf (" -j <frame>\tSet frame step to <frame>\n");
printf ("\nWindow options:\n");
printf (" -w\t\tForce opening with borders (default)\n");
@@ -182,8 +198,10 @@ static void print_help(void)
printf ("\nMisc options:\n");
printf (" -d\t\tTurn debugging on\n");
printf (" -noaudio\tDisable audio on systems that support audio\n");
+ printf (" -nojoystick\tDisable joystick support\n");
+ printf (" -noglsl\tDisable GLSL shading\n");
printf (" -h\t\tPrint this help text\n");
- printf (" -y\t\tDisable script links, use -Y to find out why its -y\n");
+ printf (" -y\t\tDisable automatic python script execution (scriptlinks, pydrivers, pyconstraints, pynodes)\n");
printf (" -P <filename>\tRun the given Python script (filename or Blender Text)\n");
#ifdef WIN32
printf (" -R\t\tRegister .blend extension\n");
@@ -191,16 +209,53 @@ static void print_help(void)
printf (" -v\t\tPrint Blender version and exit\n");
printf (" --\t\tEnds option processing. Following arguments are \n");
printf (" \t\t passed unchanged. Access via Python's sys.argv\n");
+ printf ("\nEnvironment Variables:\n");
+ printf (" $HOME\t\t\tStore files such as .blender/ .B.blend .Bfs .Blog here.\n");
+#ifdef WIN32
+ printf (" $TEMP\t\tStore temporary files here.\n");
+#else
+ printf (" $TMP or $TMPDIR\tStore temporary files here.\n");
+ printf (" $BF_TIFF_LIB\t\tUse an alternative libtiff.so for loading tiff image files.\n");
+#endif
+#ifndef DISABLE_SDL
+ printf (" $SDL_AUDIODRIVER\tLibSDL audio driver - alsa, esd, alsa, dma.\n");
+#endif
+ printf (" $IMAGEEDITOR\t\tImage editor executable, launch with the IKey from the file selector.\n");
+ printf (" $WINEDITOR\t\tText editor executable, launch with the EKey from the file selector.\n");
+ printf (" $PYTHONHOME\t\tPath to the python directory, eg. /usr/lib/python.\n");
+ printf ("\nNote: Arguments must be separated by white space. eg:\n");
+ printf (" \"blender -ba test.blend\"\n");
+ printf (" ...will ignore the 'a'\n");
+ printf (" \"blender -b test.blend -f8\"\n");
+ printf (" ...will ignore 8 because there is no space between the -f and the frame value\n");
+ printf ("Note: Arguments are executed in the order they are given. eg:\n");
+ printf (" \"blender -b test.blend -f 1 -o /tmp\"\n");
+ printf (" ...may not render to /tmp because '-f 1' renders before the output path is set\n");
+ printf (" \"blender -b -o /tmp test.blend -f 1\"\n");
+ printf (" ...may not render to /tmp because loading the blend file overwrites the output path that was set\n");
+ printf (" \"blender -b test.blend -o /tmp -f 1\" works as expected.\n\n");
}
double PIL_check_seconds_timer(void);
+/* XXX This was here to fix a crash when running python scripts
+ * with -P that used the screen.
+ *
+ * static void main_init_screen( void )
+{
+ setscreen(G.curscreen);
+
+ if(G.main->scene.first==0) {
+ set_scene( add_scene("1") );
+ }
+}*/
+
int main(int argc, char **argv)
{
SYS_SystemHandle syshandle;
bContext *C= MEM_callocN(sizeof(bContext), "creator.c context");
- int a, i, stax, stay, sizx, sizy;
+ int a, i, stax, stay, sizx, sizy /*XXX, scr_init = 0*/;
#if defined(WIN32) || defined (__linux__)
int audio = 1;
@@ -208,6 +263,11 @@ int main(int argc, char **argv)
int audio = 0;
#endif
+
+#ifdef WITH_BINRELOC
+ br_init( NULL );
+#endif
+
setCallbacks();
#ifdef __APPLE__
/* patch to ignore argument finder gives us (pid?) */
@@ -233,10 +293,6 @@ int main(int argc, char **argv)
#ifdef __linux__
#ifdef __alpha__
signal (SIGFPE, fpe_handler);
- #else
- if ( getenv("SDL_AUDIODRIVER") == NULL) {
- setenv("SDL_AUDIODRIVER", "dma", 1);
- }
#endif
#endif
#if defined(__sgi)
@@ -247,7 +303,7 @@ int main(int argc, char **argv)
// need this.
BLI_where_am_i(bprogname, argv[0]);
-
+
/* Hack - force inclusion of the plugin api functions,
* see blenpluginapi:pluginapi.c
*/
@@ -287,7 +343,11 @@ int main(int argc, char **argv)
/* Handle -* switches */
else if(argv[a][0] == '-') {
switch(argv[a][1]) {
- case 'a':
+ case 'a': /* -b was not given, play an animation */
+
+ /* exception here, see below, it probably needs happens after qt init? */
+ libtiff_init();
+
// XXX playanim(argc-1, argv+1);
exit(0);
break;
@@ -335,7 +395,7 @@ int main(int argc, char **argv)
/* for all platforms, even windos has it! */
if(G.background) signal(SIGINT, blender_esc); /* ctrl c out bg render */
-
+
/* background render uses this font too */
//XXX BKE_font_register_builtin(datatoc_Bfont, datatoc_Bfont_size);
@@ -379,6 +439,7 @@ int main(int argc, char **argv)
break;
case 'W':
/* borderless, win + linux XXX OLD CRUFT */
+ /* XXX, fixme mein, borderless on OSX */
break;
case 'R':
/* Registering filetypes only makes sense on windows... */
@@ -398,13 +459,24 @@ int main(int argc, char **argv)
audio = 0;
if (G.f & G_DEBUG) printf("setting audio to: %d\n", audio);
}
+ if (BLI_strcasecmp(argv[a], "-nojoystick") == 0) {
+ /**
+ don't initialize joysticks if user doesn't want to use joysticks
+ failed joystick initialization delays over 5 seconds, before game engine start
+ */
+ SYS_WriteCommandLineInt(syshandle,"nojoystick",1);
+ if (G.f & G_DEBUG) printf("disabling nojoystick\n");
+ }
+ if (BLI_strcasecmp(argv[a], "-noglsl") == 0)
+ GPU_extensions_disable();
break;
}
}
}
+#ifndef DISABLE_PYTHON
BPY_start_python(argc, argv);
-
+#endif
/**
* NOTE: sound_init_audio() *must be* after start_python,
* at least on FreeBSD.
@@ -412,10 +484,25 @@ int main(int argc, char **argv)
*/
WM_init(C);
+
+ // XXX BRECHT SOLVE
+ BLI_where_is_temp( btempdir, 1 ); /* call after loading the .B.blend so we can read U.tempdir */
+#ifndef DISABLE_SDL
+#ifdef __linux__
+ /* On linux the default SDL driver dma often would not play
+ * use alsa if none is set */
+ if ( getenv("SDL_AUDIODRIVER") == NULL) {
+ setenv("SDL_AUDIODRIVER", "alsa", 1);
+ }
+#endif
+#endif
}
else {
+#ifndef DISABLE_PYTHON
BPY_start_python(argc, argv);
+#endif
+ BLI_where_is_temp( btempdir, 0 ); /* call after loading the .B.blend so we can read U.tempdir */
// (ton) Commented out. I have no idea whats thisfor... will mail around!
// SYS_WriteCommandLineInt(syshandle,"noaudio",1);
@@ -423,7 +510,7 @@ int main(int argc, char **argv)
// sound_init_audio();
// if (G.f & G_DEBUG) printf("setting audio to: %d\n", audio);
}
-
+#ifndef DISABLE_PYTHON
/**
* NOTE: the U.pythondir string is NULL until WM_init() is executed,
* so we provide the BPY_ function below to append the user defined
@@ -433,7 +520,8 @@ int main(int argc, char **argv)
* on U.pythondir.
*/
BPY_post_start_python();
-
+#endif
+
#ifdef WITH_QUICKTIME
quicktime_init();
@@ -499,12 +587,12 @@ int main(int argc, char **argv)
/* doMipMap */
if (!strcmp(argv[a],"nomipmap"))
{
-// XXX set_mipmap(0); //doMipMap = 0;
+ GPU_set_mipmap(0); //doMipMap = 0;
}
/* linearMipMap */
if (!strcmp(argv[a],"linearmipmap"))
{
-// XXX set_linear_mipmap(1); //linearMipMap = 1;
+ GPU_set_linear_mipmap(1); //linearMipMap = 1;
}
@@ -518,7 +606,14 @@ int main(int argc, char **argv)
if (a < argc) {
int frame= MIN2(MAXFRAME, MAX2(1, atoi(argv[a])));
Render *re= RE_NewRender(G.scene->id.name);
- RE_BlenderAnim(re, G.scene, frame, frame);
+#ifndef DISABLE_PYTHON
+ if (G.f & G_DOSCRIPTLINKS)
+ BPY_do_all_scripts(SCRIPT_RENDER, 0);
+#endif
+ RE_BlenderAnim(re, G.scene, frame, frame, G.scene->frame_step);
+#ifndef DISABLE_PYTHON
+ BPY_do_all_scripts(SCRIPT_POSTRENDER, 0);
+#endif
}
} else {
printf("\nError: no blend loaded. cannot use '-f'.\n");
@@ -527,7 +622,15 @@ int main(int argc, char **argv)
case 'a':
if (G.scene) {
Render *re= RE_NewRender(G.scene->id.name);
- RE_BlenderAnim(re, G.scene, G.scene->r.sfra, G.scene->r.efra);
+#ifndef DISABLE_PYTHON
+ if (G.f & G_DOSCRIPTLINKS)
+ BPY_do_all_scripts(SCRIPT_RENDER, 1);
+#endif
+ RE_BlenderAnim(re, G.scene, G.scene->r.sfra, G.scene->r.efra, G.scene->frame_step);
+#ifndef DISABLE_PYTHON
+ if (G.f & G_DOSCRIPTLINKS)
+ BPY_do_all_scripts(SCRIPT_POSTRENDER, 1);
+#endif
} else {
printf("\nError: no blend loaded. cannot use '-a'.\n");
}
@@ -555,10 +658,33 @@ int main(int argc, char **argv)
printf("\nError: no blend loaded. cannot use '-e'.\n");
}
break;
+ case 'j':
+ a++;
+ if(G.scene) {
+ int fstep= MIN2(MAXFRAME, MAX2(1, atoi(argv[a])));
+ if (a < argc) (G.scene->frame_step) = fstep;
+ } else {
+ printf("\nError: no blend loaded. cannot use '-j'.\n");
+ }
+ break;
case 'P':
+//XXX
+#if 0
+#ifndef DISABLE_PYTHON
a++;
- if (a < argc) BPY_run_python_script (argv[a]);
+ if (a < argc) {
+ /* If we're not running in background mode, then give python a valid screen */
+ if ((G.background==0) && (scr_init==0)) {
+ main_init_screen();
+ scr_init = 1;
+ }
+ BPY_run_python_script (argv[a]);
+ }
else printf("\nError: you must specify a Python script after '-P '.\n");
+#else
+ printf("This blender was built without python support\n");
+#endif /* DISABLE_PYTHON */
+#endif
break;
case 'o':
a++;
@@ -581,7 +707,9 @@ int main(int argc, char **argv)
if (!strcmp(argv[a],"TGA")) G.scene->r.imtype = R_TARGA;
else if (!strcmp(argv[a],"IRIS")) G.scene->r.imtype = R_IRIS;
else if (!strcmp(argv[a],"HAMX")) G.scene->r.imtype = R_HAMX;
- else if (!strcmp(argv[a],"FTYPE")) G.scene->r.imtype = R_FTYPE;
+#ifdef WITH_DDS
+ else if (!strcmp(argv[a],"DDS")) G.scene->r.imtype = R_DDS;
+#endif
else if (!strcmp(argv[a],"JPEG")) G.scene->r.imtype = R_JPEG90;
else if (!strcmp(argv[a],"MOVIE")) G.scene->r.imtype = R_MOVIE;
else if (!strcmp(argv[a],"IRIZ")) G.scene->r.imtype = R_IRIZ;
@@ -593,13 +721,16 @@ int main(int argc, char **argv)
else if (!strcmp(argv[a],"QUICKTIME")) G.scene->r.imtype = R_QUICKTIME;
else if (!strcmp(argv[a],"BMP")) G.scene->r.imtype = R_BMP;
else if (!strcmp(argv[a],"HDR")) G.scene->r.imtype = R_RADHDR;
- else if (!strcmp(argv[a],"TIFF")) G.scene->r.imtype = R_IRIS;
+ else if (!strcmp(argv[a],"TIFF")) G.scene->r.imtype = R_TIFF;
+#ifdef WITH_OPENEXR
else if (!strcmp(argv[a],"EXR")) G.scene->r.imtype = R_OPENEXR;
+ else if (!strcmp(argv[a],"MULTILAYER")) G.scene->r.imtype = R_MULTILAYER;
+#endif
else if (!strcmp(argv[a],"MPEG")) G.scene->r.imtype = R_FFMPEG;
else if (!strcmp(argv[a],"FRAMESERVER")) G.scene->r.imtype = R_FRAMESERVER;
else if (!strcmp(argv[a],"CINEON")) G.scene->r.imtype = R_CINEON;
else if (!strcmp(argv[a],"DPX")) G.scene->r.imtype = R_DPX;
- else printf("\nError: Format from '-F ' not known.\n");
+ else printf("\nError: Format from '-F' not known or not compiled in this release.\n");
}
} else {
printf("\nError: no blend loaded. cannot use '-x'.\n");
@@ -610,6 +741,8 @@ int main(int argc, char **argv)
a++;
if(G.background) {
RE_set_max_threads(atoi(argv[a]));
+ } else {
+ printf("Warning: threads can only be set in background mode\n");
}
break;
case 'x': /* extension */
@@ -632,10 +765,21 @@ int main(int argc, char **argv)
break;
}
}
- else {
+ else {
+
+ /* Make the path absolute because its needed for relative linked blends to be found */
+ char filename[FILE_MAXDIR + FILE_MAXFILE];
+
+ BLI_strncpy(filename, argv[a], sizeof(filename));
+ BLI_convertstringcwd(filename);
+
if (G.background) {
- BKE_read_file(C, argv[a], NULL);
+ int retval = BKE_read_file(C, argv[a], NULL);
// XXX sound_initialize_sounds();
+
+ /*we successfully loaded a blend file, get sure that
+ pointcache works */
+ if (retval!=0) G.relbase_valid = 1;
/* happens for the UI on file reading too (huh? (ton))*/
// XXX BKE_reset_undo();
@@ -643,8 +787,8 @@ int main(int argc, char **argv)
} else {
/* we are not running in background mode here, but start blender in UI mode with
a file - this should do everything a 'load file' does */
- WM_read_file(C, argv[a]);
- }
+ WM_read_file(C, filename);
+ }
}
}
@@ -655,6 +799,12 @@ int main(int argc, char **argv)
WM_main(C);
+
+ /*XXX if (scr_init==0) {
+ main_init_screen();
+ }
+
+ screenmain();*/ /* main display loop */
return 0;
} /* end of int main(argc,argv) */
@@ -671,7 +821,7 @@ static void mem_error_cb(char *errorStr)
fflush(stderr);
}
-void setCallbacks(void)
+static void setCallbacks(void)
{
/* Error output from the alloc routines: */
MEM_set_error_callback(mem_error_cb);
diff --git a/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp b/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp
index 12c550c52b7..0dab583567d 100644
--- a/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp
+++ b/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp
@@ -33,15 +33,14 @@
#endif
#include <signal.h>
+#include <stdlib.h>
#ifdef WIN32
// don't show stl-warnings
#pragma warning (disable:4786)
#endif
-#ifdef __APPLE__
-#define GL_GLEXT_LEGACY 1
-#endif
+#include "GL/glew.h"
#include "KX_BlenderGL.h"
#include "KX_BlenderCanvas.h"
@@ -56,10 +55,10 @@
#include "KX_PythonInit.h"
#include "KX_PyConstraintBinding.h"
+#include "RAS_GLExtensionManager.h"
#include "RAS_OpenGLRasterizer.h"
#include "RAS_VAOpenGLRasterizer.h"
#include "RAS_ListRasterizer.h"
-#include "RAS_GLExtensionManager.h"
#include "NG_LoopBackNetworkDeviceInterface.h"
#include "SND_DeviceManager.h"
@@ -71,6 +70,7 @@
#include "DNA_view3d_types.h"
#include "DNA_screen_types.h"
#include "BKE_global.h"
+#include "BKE_utildefines.h"
//XXX #include "BIF_screen.h"
//XXX #include "BIF_scrarea.h"
@@ -80,6 +80,8 @@
#include "DNA_scene_types.h"
/***/
+#include "GPU_extensions.h"
+
#ifdef __cplusplus
extern "C" {
#endif
@@ -91,28 +93,10 @@ void update_for_newframe();
static BlendFileData *load_game_data(char *filename) {
BlendReadError error;
- //this doesn't work anymore for relative paths, so use BLO_read_from_memory instead
- //BlendFileData *bfd= BLO_read_from_file(filename, &error);
- FILE* file = fopen(filename,"rb");
- BlendFileData *bfd = 0;
- if (file)
- {
- fseek(file, 0L, SEEK_END);
- int len= ftell(file);
- fseek(file, 0L, SEEK_SET);
- char* filebuffer= new char[len];//MEM_mallocN(len, "text_buffer");
- int sizeread = fread(filebuffer,len,1,file);
- if (sizeread==1)
- {
- bfd = BLO_read_from_memory(filebuffer, len, &error);
- }
- fclose(file);
- }
-
+ BlendFileData *bfd= BLO_read_from_file(filename, &error);
if (!bfd) {
printf("Loading %s failed: %s\n", filename, BLO_bre_as_string(error));
}
-
return bfd;
}
@@ -127,17 +111,26 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
Main* blenderdata = maggie1;
char* startscenename = scenename;
- char pathname[160];
- strcpy (pathname, blenderdata->name);
+ char pathname[FILE_MAXDIR+FILE_MAXFILE], oldsce[FILE_MAXDIR+FILE_MAXFILE];
STR_String exitstring = "";
BlendFileData *bfd= NULL;
- bgl::InitExtensions(1);
+ BLI_strncpy(pathname, blenderdata->name, sizeof(pathname));
+ BLI_strncpy(oldsce, G.sce, sizeof(oldsce));
+ setGamePythonPath(G.sce);
+
+ // Acquire Python's GIL (global interpreter lock)
+ // so we can safely run Python code and API calls
+ PyGILState_STATE gilstate = PyGILState_Ensure();
+
+ PyObject *pyGlobalDict = PyDict_New(); /* python utility storage, spans blend file loading */
+ bgl::InitExtensions(true);
+
do
{
View3D *v3d= (View3D*) area->spacedata.first;
-
+
// get some preferences
SYS_SystemHandle syshandle = SYS_GetSystem();
bool properties = (SYS_GetCommandLineInt(syshandle, "show_properties", 0) != 0);
@@ -146,20 +139,6 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
bool frameRate = (SYS_GetCommandLineInt(syshandle, "show_framerate", 0) != 0);
bool game2ipo = (SYS_GetCommandLineInt(syshandle, "game2ipo", 0) != 0);
bool displaylists = (SYS_GetCommandLineInt(syshandle, "displaylists", 0) != 0);
- bool usemat = false;
-
- #ifdef GL_ARB_multitexture
- if(bgl::RAS_EXT_support._ARB_multitexture && bgl::QueryVersion(1, 1)) {
- usemat = (SYS_GetCommandLineInt(syshandle, "blender_material", 0) != 0);
- int unitmax=0;
- glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, (GLint*)&unitmax);
- bgl::max_texture_units = MAXTEX>unitmax?unitmax:MAXTEX;
- //std::cout << "using(" << bgl::max_texture_units << ") of(" << unitmax << ") texture units." << std::endl;
- } else {
- bgl::max_texture_units = 0;
- }
- #endif
-
// create the canvas, rasterizer and rendertools
RAS_ICanvas* canvas = new KX_BlenderCanvas(area);
@@ -167,16 +146,14 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
RAS_IRenderTools* rendertools = new KX_BlenderRenderTools();
RAS_IRasterizer* rasterizer = NULL;
- // let's see if we want to use vertexarrays or not
- int usevta = SYS_GetCommandLineInt(syshandle,"vertexarrays",1);
- bool useVertexArrays = (usevta > 0);
-
- bool lock_arrays = (displaylists && useVertexArrays);
-
- if(displaylists && !useVertexArrays)
- rasterizer = new RAS_ListRasterizer(canvas);
- else if (useVertexArrays && bgl::QueryVersion(1, 1))
- rasterizer = new RAS_VAOpenGLRasterizer(canvas, lock_arrays);
+ if(displaylists) {
+ if (GLEW_VERSION_1_1)
+ rasterizer = new RAS_ListRasterizer(canvas, true, true);
+ else
+ rasterizer = new RAS_ListRasterizer(canvas);
+ }
+ else if (GLEW_VERSION_1_1)
+ rasterizer = new RAS_VAOpenGLRasterizer(canvas, false);
else
rasterizer = new RAS_OpenGLRasterizer(canvas);
@@ -188,6 +165,13 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
NG_NetworkDeviceInterface* networkdevice = new
NG_LoopBackNetworkDeviceInterface();
+ //
+ SYS_SystemHandle hSystem = SYS_GetSystem();
+ bool noaudio = SYS_GetCommandLineInt(hSystem,"noaudio",0);
+
+ if (noaudio)/*(noaudio) intrr: disable game engine audio (openal) */
+ SND_DeviceManager::SetDeviceType(snd_e_dummydevice);
+
// get an audiodevice
SND_DeviceManager::Subscribe();
SND_IAudioDevice* audiodevice = SND_DeviceManager::Instance();
@@ -211,11 +195,21 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
ketsjiengine->SetUseFixedTime(usefixed);
ketsjiengine->SetTimingDisplay(frameRate, profile, properties);
-
+
+ //lock frame and camera enabled - storing global values
+ int tmp_lay= G.scene->lay;
+ Object *tmp_camera = G.scene->camera;
+
+ if (G.vd->scenelock==0){
+ G.scene->lay= v3d->lay;
+ G.scene->camera= v3d->camera;
+ }
+
// some blender stuff
MT_CmMatrix4x4 projmat;
MT_CmMatrix4x4 viewmat;
+ float camzoom;
int i;
for (i = 0; i < 16; i++)
@@ -229,8 +223,13 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
projmat.setElem(i, projmat_linear[i]);
}
- float camzoom = (1.41421 + (v3d->camzoom / 50.0));
- camzoom *= camzoom;
+ if(v3d->persp==V3D_CAMOB) {
+ camzoom = (1.41421 + (v3d->camzoom / 50.0));
+ camzoom *= camzoom;
+ }
+ else
+ camzoom = 2.0;
+
camzoom = 4.0 / camzoom;
ketsjiengine->SetDrawType(v3d->drawtype);
@@ -242,24 +241,29 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
exitrequested = KX_EXIT_REQUEST_NO_REQUEST;
if (bfd) BLO_blendfiledata_free(bfd);
- char basedpath[160];
+ char basedpath[240];
// base the actuator filename with respect
// to the original file working directory
+
if (exitstring != "")
strcpy(basedpath, exitstring.Ptr());
- BLI_convertstringcode(basedpath, pathname, 0);
+ // load relative to the last loaded file, this used to be relative
+ // to the first file but that makes no sense, relative paths in
+ // blend files should be relative to that file, not some other file
+ // that happened to be loaded first
+ BLI_convertstringcode(basedpath, pathname);
bfd = load_game_data(basedpath);
// if it wasn't loaded, try it forced relative
if (!bfd)
{
// just add "//" in front of it
- char temppath[162];
+ char temppath[242];
strcpy(temppath, "//");
strcat(temppath, basedpath);
- BLI_convertstringcode(temppath, pathname, 0);
+ BLI_convertstringcode(temppath, pathname);
bfd = load_game_data(temppath);
}
@@ -268,6 +272,11 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
{
blenderdata = bfd->main;
startscenename = bfd->curscene->id.name + 2;
+
+ if(blenderdata) {
+ BLI_strncpy(G.sce, blenderdata->name, sizeof(G.sce));
+ BLI_strncpy(pathname, blenderdata->name, sizeof(pathname));
+ }
}
// else forget it, we can't find it
else
@@ -305,12 +314,13 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
if (exitrequested != KX_EXIT_REQUEST_QUIT_GAME)
{
- if (v3d->persp != 2)
+ if (v3d->persp != V3D_CAMOB)
{
ketsjiengine->EnableCameraOverride(startscenename);
- ketsjiengine->SetCameraOverrideUseOrtho((v3d->persp == 0));
+ ketsjiengine->SetCameraOverrideUseOrtho((v3d->persp == V3D_ORTHO));
ketsjiengine->SetCameraOverrideProjectionMatrix(projmat);
ketsjiengine->SetCameraOverrideViewMatrix(viewmat);
+ ketsjiengine->SetCameraOverrideClipping(v3d->near, v3d->far);
}
// create a scene converter, create and convert the startingscene
@@ -319,25 +329,43 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
sceneconverter->addInitFromFrame=false;
if (always_use_expand_framing)
sceneconverter->SetAlwaysUseExpandFraming(true);
-
- if(usemat)
+
+ bool usemat = false, useglslmat = false;
+
+ if(GLEW_ARB_multitexture && GLEW_VERSION_1_1)
+ usemat = true;
+
+ if(GPU_extensions_minimum_support())
+ useglslmat = true;
+ else if(G.fileflags & G_FILE_GAME_MAT_GLSL)
+ usemat = false;
+
+ if(usemat && (G.fileflags & G_FILE_GAME_MAT))
sceneconverter->SetMaterials(true);
+ if(useglslmat && (G.fileflags & G_FILE_GAME_MAT_GLSL))
+ sceneconverter->SetGLSLMaterials(true);
KX_Scene* startscene = new KX_Scene(keyboarddevice,
mousedevice,
networkdevice,
audiodevice,
- startscenename);
+ startscenename,
+ blscene);
// some python things
PyObject* dictionaryobject = initGamePythonScripting("Ketsji", psl_Lowest);
ketsjiengine->SetPythonDictionary(dictionaryobject);
initRasterizer(rasterizer, canvas);
- PyObject *gameLogic = initGameLogic(startscene);
+ PyObject *gameLogic = initGameLogic(ketsjiengine, startscene);
+ PyDict_SetItemString(PyModule_GetDict(gameLogic), "globalDict", pyGlobalDict); // Same as importing the module.
+ PyObject *gameLogic_keys = PyDict_Keys(PyModule_GetDict(gameLogic));
+ PyDict_SetItemString(dictionaryobject, "GameLogic", gameLogic); // Same as importing the module.
+
initGameKeys();
initPythonConstraintBinding();
+ initMathutils();
+ initVideoTexture();
-
if (sceneconverter)
{
// convert and add scene
@@ -356,7 +384,14 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
// start the engine
ketsjiengine->StartEngine(true);
+
+ // Set the animation playback rate for ipo's and actions
+ // the framerate below should patch with FPS macro defined in blendef.h
+ // Could be in StartEngine set the framerate, we need the scene to do this
+ ketsjiengine->SetAnimFrameRate( (((double) blscene->r.frs_sec) / blscene->r.frs_sec_base) );
+
// the mainloop
+ printf("\nBlender Game Engine Started\n\n");
while (!exitrequested)
{
// first check if we want to exit
@@ -392,10 +427,32 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
mousedevice->ConvertBlenderEvent(event,val);
}
}
+ printf("\nBlender Game Engine Finished\n\n");
exitstring = ketsjiengine->GetExitString();
-
+
+
// when exiting the mainloop
- dictionaryClearByHand(gameLogic);
+
+ // Clears the dictionary by hand:
+ // This prevents, extra references to global variables
+ // inside the GameLogic dictionary when the python interpreter is finalized.
+ // which allows the scene to safely delete them :)
+ // see: (space.c)->start_game
+
+ //PyDict_Clear(PyModule_GetDict(gameLogic));
+
+ // Keep original items, means python plugins will autocomplete members
+ int listIndex;
+ PyObject *gameLogic_keys_new = PyDict_Keys(PyModule_GetDict(gameLogic));
+ for (listIndex=0; listIndex < PyList_Size(gameLogic_keys_new); listIndex++) {
+ PyObject* item = PyList_GET_ITEM(gameLogic_keys_new, listIndex);
+ if (!PySequence_Contains(gameLogic_keys, item)) {
+ PyDict_DelItem( PyModule_GetDict(gameLogic), item);
+ }
+ }
+ Py_DECREF(gameLogic_keys_new);
+ gameLogic_keys_new = NULL;
+
ketsjiengine->StopEngine();
exitGamePythonScripting();
networkdevice->Disconnect();
@@ -405,7 +462,16 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
delete sceneconverter;
sceneconverter = NULL;
}
+
+ Py_DECREF(gameLogic_keys);
+ gameLogic_keys = NULL;
+ }
+ //lock frame and camera enabled - restoring global values
+ if (G.vd->scenelock==0){
+ G.scene->lay= tmp_lay;
+ G.scene->camera= tmp_camera;
}
+
// set the cursor back to normal
canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
@@ -457,6 +523,11 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
} while (exitrequested == KX_EXIT_REQUEST_RESTART_GAME || exitrequested == KX_EXIT_REQUEST_START_OTHER_GAME);
if (bfd) BLO_blendfiledata_free(bfd);
+
+ BLI_strncpy(G.sce, oldsce, sizeof(G.sce));
+
+ // Release Python's GIL
+ PyGILState_Release(gilstate);
}
extern "C" void StartKetsjiShellSimulation(struct ScrArea *area,
@@ -470,12 +541,16 @@ extern "C" void StartKetsjiShellSimulation(struct ScrArea *area,
Main* blenderdata = maggie;
char* startscenename = scenename;
- char pathname[160];
- strcpy (pathname, maggie->name);
+ char pathname[FILE_MAXDIR+FILE_MAXFILE];
STR_String exitstring = "";
- BlendFileData *bfd= NULL;
- bgl::InitExtensions(1);
+ BLI_strncpy(pathname, blenderdata->name, sizeof(pathname));
+
+ // Acquire Python's GIL (global interpreter lock)
+ // so we can safely run Python code and API calls
+ PyGILState_STATE gilstate = PyGILState_Ensure();
+
+ bgl::InitExtensions(true);
do
{
@@ -496,16 +571,14 @@ extern "C" void StartKetsjiShellSimulation(struct ScrArea *area,
RAS_IRenderTools* rendertools = new KX_BlenderRenderTools();
RAS_IRasterizer* rasterizer = NULL;
- // let's see if we want to use vertexarrays or not
- int usevta = SYS_GetCommandLineInt(syshandle,"vertexarrays",1);
- bool useVertexArrays = (usevta > 0);
-
- bool lock_arrays = (displaylists && useVertexArrays);
-
- if(displaylists && !useVertexArrays)
- rasterizer = new RAS_ListRasterizer(canvas);
- else if (useVertexArrays && bgl::QueryVersion(1, 1))
- rasterizer = new RAS_VAOpenGLRasterizer(canvas, lock_arrays);
+ if(displaylists) {
+ if (GLEW_VERSION_1_1)
+ rasterizer = new RAS_ListRasterizer(canvas, true, true);
+ else
+ rasterizer = new RAS_ListRasterizer(canvas);
+ }
+ else if (GLEW_VERSION_1_1)
+ rasterizer = new RAS_VAOpenGLRasterizer(canvas, false);
else
rasterizer = new RAS_OpenGLRasterizer(canvas);
@@ -528,24 +601,19 @@ extern "C" void StartKetsjiShellSimulation(struct ScrArea *area,
// create the ketsjiengine
KX_KetsjiEngine* ketsjiengine = new KX_KetsjiEngine(kxsystem);
- int i;
-
Scene *blscene = NULL;
- if (!bfd)
+
+ blscene = (Scene*) maggie->scene.first;
+ for (Scene *sce= (Scene*) maggie->scene.first; sce; sce= (Scene*) sce->id.next)
{
- blscene = (Scene*) maggie->scene.first;
- for (Scene *sce= (Scene*) maggie->scene.first; sce; sce= (Scene*) sce->id.next)
+ if (startscenename == (sce->id.name+2))
{
- if (startscenename == (sce->id.name+2))
- {
- blscene = sce;
- break;
- }
+ blscene = sce;
+ break;
}
- } else {
- blscene = bfd->curscene;
}
- int cframe,startFrame;
+
+ int cframe = 1, startFrame;
if (blscene)
{
cframe=blscene->r.cfra;
@@ -576,14 +644,19 @@ extern "C" void StartKetsjiShellSimulation(struct ScrArea *area,
mousedevice,
networkdevice,
audiodevice,
- startscenename);
+ startscenename,
+ blscene);
+
// some python things
PyObject* dictionaryobject = initGamePythonScripting("Ketsji", psl_Lowest);
ketsjiengine->SetPythonDictionary(dictionaryobject);
initRasterizer(rasterizer, canvas);
- PyObject *gameLogic = initGameLogic(startscene);
+ PyObject *gameLogic = initGameLogic(ketsjiengine, startscene);
+ PyDict_SetItemString(dictionaryobject, "GameLogic", gameLogic); // Same as importing the module
initGameKeys();
initPythonConstraintBinding();
+ initMathutils();
+ initVideoTexture();
if (sceneconverter)
{
@@ -661,5 +734,7 @@ extern "C" void StartKetsjiShellSimulation(struct ScrArea *area,
SND_DeviceManager::Unsubscribe();
} while (exitrequested == KX_EXIT_REQUEST_RESTART_GAME || exitrequested == KX_EXIT_REQUEST_START_OTHER_GAME);
- if (bfd) BLO_blendfiledata_free(bfd);
+
+ // Release Python's GIL
+ PyGILState_Release(gilstate);
}
diff --git a/source/gameengine/BlenderRoutines/CMakeLists.txt b/source/gameengine/BlenderRoutines/CMakeLists.txt
index 11a87460f20..2300323a55e 100644
--- a/source/gameengine/BlenderRoutines/CMakeLists.txt
+++ b/source/gameengine/BlenderRoutines/CMakeLists.txt
@@ -33,8 +33,10 @@ SET(INC
../../../intern/SoundSystem
../../../source/blender/misc
../../../source/blender/blenloader
+ ../../../source/blender/gpu
../../../extern/bullet2/src
../../../extern/solid
+ ../../../extern/glew/include
${PYTHON_INC}
)
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderCanvas.cpp b/source/gameengine/BlenderRoutines/KX_BlenderCanvas.cpp
index a65275dda8f..750a1ef3f93 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderCanvas.cpp
+++ b/source/gameengine/BlenderRoutines/KX_BlenderCanvas.cpp
@@ -101,6 +101,13 @@ int KX_BlenderCanvas::GetHeight(
return 0; //XXX scrarea_get_win_height(m_area);
}
+RAS_Rect &
+KX_BlenderCanvas::
+GetWindowArea(
+){
+ return m_area_rect;
+}
+
void
KX_BlenderCanvas::
SetViewPort(
@@ -112,6 +119,11 @@ SetViewPort(
int minx = 0;//XXX scrarea_get_win_x(m_area);
int miny = 0;//XXX scrarea_get_win_y(m_area);
+ m_area_rect.SetLeft(minx + x1);
+ m_area_rect.SetBottom(miny + y1);
+ m_area_rect.SetRight(minx + x2);
+ m_area_rect.SetTop(miny + y2);
+
glViewport(minx + x1, miny + y1, vp_width, vp_height);
glScissor(minx + x1, miny + y1, vp_width, vp_height);
}
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderCanvas.h b/source/gameengine/BlenderRoutines/KX_BlenderCanvas.h
index 0b3519efdbd..bc202a8558c 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderCanvas.h
+++ b/source/gameengine/BlenderRoutines/KX_BlenderCanvas.h
@@ -32,11 +32,8 @@
#ifdef WIN32
#include <windows.h>
#endif
-#ifdef __APPLE__
-#include <OpenGL/gl.h>
-#else
-#include <GL/gl.h>
-#endif
+
+#include "GL/glew.h"
#include "RAS_ICanvas.h"
#include "RAS_Rect.h"
@@ -120,6 +117,10 @@ public:
return m_displayarea;
};
+ RAS_Rect &
+ GetWindowArea(
+ );
+
void
SetViewPort(
int x1, int y1,
@@ -162,6 +163,7 @@ public:
private:
/** Blender area the game engine is running within */
struct ScrArea* m_area;
+ RAS_Rect m_area_rect;
};
#endif // __KX_BLENDERCANVAS
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderGL.cpp b/source/gameengine/BlenderRoutines/KX_BlenderGL.cpp
index bd3ae4ee912..b3b10e8bf07 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderGL.cpp
+++ b/source/gameengine/BlenderRoutines/KX_BlenderGL.cpp
@@ -44,21 +44,8 @@
#include "BMF_Api.h"
+#include "BIF_gl.h"
-#ifdef __APPLE__
-#define GL_GLEXT_LEGACY 1
-#include <OpenGL/gl.h>
-#include <OpenGL/glu.h>
-#else
-#include <GL/gl.h>
-#if defined(__sun__) && !defined(__sparc__)
-#include <mesa/glu.h>
-#else
-#include <GL/glu.h>
-#endif
-#endif
-#include "RAS_OpenGLRasterizer/RAS_GLExtensionManager.h"
-#include "RAS_OpenGLRasterizer/ARB_multitexture.h"
#include "BL_Material.h" // MAXTEX
/* Data types encoding the game world: */
@@ -77,7 +64,6 @@
#include "BKE_bmfont.h"
#include "BKE_image.h"
-#include "BIF_gl.h"
extern "C" {
//XXX #include "BDR_drawmesh.h"
//XXX #include "BIF_mywindow.h"
@@ -88,12 +74,6 @@ extern "C" {
/* end of blender block */
-#ifdef __APPLE__
-#include <OpenGL/gl.h>
-#else
-#include <GL/gl.h>
-#endif
-
/* was in drawmesh.c */
void spack(unsigned int ucol)
{
@@ -112,103 +92,40 @@ void BL_SwapBuffers()
//XXX myswapbuffers();
}
-void BL_RenderText(int mode,const char* textstr,int textlen,struct MTFace* tface,
- unsigned int *col,float v1[3],float v2[3],float v3[3],float v4[3])
-{
- Image* ima;
-
- if(mode & TF_BMFONT) {
- //char string[MAX_PROPSTRING];
- int characters, index, character;
- float centerx, centery, sizex, sizey, transx, transy, movex, movey, advance;
-
-// bProperty *prop;
-
- // string = "Frank van Beek";
-
- characters = textlen;
-
- ima = (struct Image*) tface->tpage;
- if (ima == NULL) {
- characters = 0;
- }
-
- if(!col) glColor3f(1.0f, 1.0f, 1.0f);
-
- glPushMatrix();
- for (index = 0; index < characters; index++) {
- // lets calculate offset stuff
- character = textstr[index];
-
- // space starts at offset 1
- // character = character - ' ' + 1;
-
- matrixGlyph((ImBuf *)ima->ibufs.first, character, & centerx, &centery, &sizex, &sizey, &transx, &transy, &movex, &movey, &advance);
-
- glBegin(GL_POLYGON);
- // printf(" %c %f %f %f %f\n", character, tface->uv[0][0], tface->uv[0][1], );
- // glTexCoord2f((tface->uv[0][0] - centerx) * sizex + transx, (tface->uv[0][1] - centery) * sizey + transy);
- glTexCoord2f((tface->uv[0][0] - centerx) * sizex + transx, (tface->uv[0][1] - centery) * sizey + transy);
-
- if(col) spack(col[0]);
- // glVertex3fv(v1);
- glVertex3f(sizex * v1[0] + movex, sizey * v1[1] + movey, v1[2]);
-
- glTexCoord2f((tface->uv[1][0] - centerx) * sizex + transx, (tface->uv[1][1] - centery) * sizey + transy);
- if(col) spack(col[1]);
- // glVertex3fv(v2);
- glVertex3f(sizex * v2[0] + movex, sizey * v2[1] + movey, v2[2]);
-
- glTexCoord2f((tface->uv[2][0] - centerx) * sizex + transx, (tface->uv[2][1] - centery) * sizey + transy);
- if(col) spack(col[2]);
- // glVertex3fv(v3);
- glVertex3f(sizex * v3[0] + movex, sizey * v3[1] + movey, v3[2]);
-
- if(v4) {
- // glTexCoord2f((tface->uv[3][0] - centerx) * sizex + transx, 1.0 - (1.0 - tface->uv[3][1]) * sizey - transy);
- glTexCoord2f((tface->uv[3][0] - centerx) * sizex + transx, (tface->uv[3][1] - centery) * sizey + transy);
- if(col) spack(col[3]);
- // glVertex3fv(v4);
- glVertex3f(sizex * v4[0] + movex, sizey * v4[1] + movey, v4[2]);
- }
- glEnd();
-
- glTranslatef(advance, 0.0, 0.0);
- }
- glPopMatrix();
-
- }
-}
-
-
void DisableForText()
{
- if(glIsEnabled(GL_BLEND))
- glDisable(GL_BLEND);
+ if(glIsEnabled(GL_BLEND)) glDisable(GL_BLEND);
+ if(glIsEnabled(GL_ALPHA_TEST)) glDisable(GL_ALPHA_TEST);
if(glIsEnabled(GL_LIGHTING)) {
glDisable(GL_LIGHTING);
glDisable(GL_COLOR_MATERIAL);
}
-#ifdef GL_ARB_multitexture
- for(int i=0; i<MAXTEX; i++) {
- if(bgl::RAS_EXT_support._ARB_multitexture)
- bgl::blActiveTextureARB(GL_TEXTURE0_ARB+i);
-#ifdef GL_ARB_texture_cube_map
- if(bgl::RAS_EXT_support._ARB_texture_cube_map)
- if(glIsEnabled(GL_TEXTURE_CUBE_MAP_ARB))
- glDisable(GL_TEXTURE_CUBE_MAP_ARB);
-#endif
+
+ if(GLEW_ARB_multitexture) {
+ for(int i=0; i<MAXTEX; i++) {
+ glActiveTextureARB(GL_TEXTURE0_ARB+i);
+
+ if(GLEW_ARB_texture_cube_map)
+ if(glIsEnabled(GL_TEXTURE_CUBE_MAP_ARB))
+ glDisable(GL_TEXTURE_CUBE_MAP_ARB);
+
+ if(glIsEnabled(GL_TEXTURE_2D))
+ glDisable(GL_TEXTURE_2D);
+ }
+
+ glActiveTextureARB(GL_TEXTURE0_ARB);
+ }
+ else {
+ if(GLEW_ARB_texture_cube_map)
+ if(glIsEnabled(GL_TEXTURE_CUBE_MAP_ARB))
+ glDisable(GL_TEXTURE_CUBE_MAP_ARB);
+
if(glIsEnabled(GL_TEXTURE_2D))
glDisable(GL_TEXTURE_2D);
}
-#else//GL_ARB_multitexture
- if(glIsEnabled(GL_TEXTURE_2D))
- glDisable(GL_TEXTURE_2D);
-#endif
}
-
void BL_print_gamedebug_line(char* text, int xco, int yco, int width, int height)
{
/* gl prepping */
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderGL.h b/source/gameengine/BlenderRoutines/KX_BlenderGL.h
index c8e0d47afb6..b891a7343c2 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderGL.h
+++ b/source/gameengine/BlenderRoutines/KX_BlenderGL.h
@@ -46,9 +46,6 @@ void BL_HideMouse();
void BL_NormalMouse();
void BL_WaitMouse();
-void BL_RenderText(int mode,const char* textstr,int textlen,struct MTFace* tface,
- unsigned int *col,float v1[3],float v2[3],float v3[3],float v4[3]);
-
void BL_print_gamedebug_line(char* text, int xco, int yco, int width, int height);
void BL_print_gamedebug_line_padded(char* text, int xco, int yco, int width, int height);
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderPolyMaterial.cpp b/source/gameengine/BlenderRoutines/KX_BlenderPolyMaterial.cpp
deleted file mode 100644
index d173b1c66d9..00000000000
--- a/source/gameengine/BlenderRoutines/KX_BlenderPolyMaterial.cpp
+++ /dev/null
@@ -1,114 +0,0 @@
-/**
- * $Id$
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#include "KX_BlenderPolyMaterial.h"
-#include "BKE_mesh.h"
-
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-#if 0
-KX_BlenderPolyMaterial::KX_BlenderPolyMaterial(const STR_String &texname,
- bool ba,
- const STR_String& matname,
- int tile,
- int tilexrep,
- int tileyrep,
- int mode,
- bool transparant,
- bool zsort,
- int lightlayer,
- bool bIsTriangle,
- void* clientobject,
- struct MTFace* tface)
- : RAS_IPolyMaterial(texname,
- false,
- matname,
- tile,
- tilexrep,
- tileyrep,
- mode,
- transparant,
- zsort,
- lightlayer,
- bIsTriangle,
- clientobject),
- m_tface(tface)
-{
-}
-
-void KX_BlenderPolyMaterial::Activate(RAS_IRasterizer* rasty, TCachingInfo& cachingInfo) const
-{
-
-
- if (GetCachingInfo() != cachingInfo)
- {
- if (!cachingInfo)
- {
- set_tpage(NULL);
- }
- cachingInfo = GetCachingInfo();
-
- if ((m_drawingmode & 4)&& (rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED))
- {
- update_realtime_texture((struct MTFace*) m_tface, rasty->GetTime());
- set_tpage(m_tface);
- rasty->EnableTextures(true);
- }
- else
- {
- set_tpage(NULL);
- rasty->EnableTextures(false);
- }
-
- if(m_drawingmode & RAS_IRasterizer::KX_TWOSIDE)
- {
- rasty->SetCullFace(false);
- }
- else
- {
- rasty->SetCullFace(true);
- }
-
- if (m_drawingmode & RAS_IRasterizer::KX_LINES) {
- rasty->SetLines(true);
- }
- else {
- rasty->SetLines(false);
- }
- }
-
- rasty->SetSpecularity(m_specular[0],m_specular[1],m_specular[2],m_specularity);
- rasty->SetShinyness(m_shininess);
- rasty->SetDiffuse(m_diffuse[0], m_diffuse[1],m_diffuse[2], 1.0);
-}
-
-
-#endif
-
-
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderPolyMaterial.h b/source/gameengine/BlenderRoutines/KX_BlenderPolyMaterial.h
deleted file mode 100644
index 35823b2125b..00000000000
--- a/source/gameengine/BlenderRoutines/KX_BlenderPolyMaterial.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/**
- * $Id$
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-#ifndef __KX_BLENDERPOLYMATERIAL
-#define __KX_BLENDERPOLYMATERIAL
-
-#include "RAS_MaterialBucket.h"
-#include "RAS_IRasterizer.h"
-
-struct MTFace;
-extern "C" int set_tpage(MTFace* tface); /* Worst hack ever */
-
-#if 0
-class KX_BlenderPolyMaterial : public RAS_IPolyMaterial
-{
- /** Blender texture face structure. */
- MTFace* m_tface;
-
-public:
-
- KX_BlenderPolyMaterial(const STR_String &texname,
- bool ba,
- const STR_String& matname,
- int tile,
- int tilexrep,
- int tileyrep,
- int mode,
- bool transparant,
- bool zsort,
- int lightlayer,
- bool bIsTriangle,
- void* clientobject,
- struct MTFace* tface);
-
- /**
- * Returns the caching information for this material,
- * This can be used to speed up the rasterizing process.
- * @return The caching information.
- */
- virtual TCachingInfo GetCachingInfo(void) const;
-
- /**
- * Activates the material in the (OpenGL) rasterizer.
- * On entry, the cachingInfo contains info about the last activated material.
- * On exit, the cachingInfo should contain updated info about this material.
- * @param rasty The rasterizer in which the material should be active.
- * @param cachingInfo The information about the material used to speed up rasterizing.
- */
- virtual void Activate(RAS_IRasterizer* rasty, TCachingInfo& cachingInfo) const;
-
- /**
- * Returns the Blender texture face structure that is used for this material.
- * @return The material's texture face.
- */
- MTFace* GetMTFace(void) const;
-protected:
-private:
-};
-
-
-inline MTFace* KX_BlenderPolyMaterial::GetMTFace(void) const
-{
- return m_tface;
-}
-
-inline RAS_IPolyMaterial::TCachingInfo KX_BlenderPolyMaterial::GetCachingInfo(void) const
-{
- return GetMTFace();
-}
-
-#endif
-
-#endif // __KX_BLENDERPOLYMATERIAL
-
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.cpp b/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.cpp
index 6a098cc5491..1797d6c1a0f 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.cpp
+++ b/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.cpp
@@ -26,18 +26,7 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#include "KX_BlenderRenderTools.h"
-
-#ifdef WIN32
-// OpenGL gl.h needs 'windows.h' on windows platforms
-#include <windows.h>
-#endif //WIN32
-#ifdef __APPLE__
-#define GL_GLEXT_LEGACY 1
-#include <OpenGL/gl.h>
-#else
-#include <GL/gl.h>
-#endif
+#include "GL/glew.h"
#include "RAS_IRenderTools.h"
#include "RAS_IRasterizer.h"
@@ -45,24 +34,22 @@
#include "RAS_ICanvas.h"
#include "RAS_GLExtensionManager.h"
-// next two includes/dependencies come from the shadow feature
-// it needs the gameobject and the sumo physics scene for a raycast
#include "KX_GameObject.h"
-
-#include "KX_BlenderPolyMaterial.h"
#include "KX_PolygonMaterial.h"
#include "KX_BlenderMaterial.h"
+#include "KX_RayCast.h"
+#include "KX_IPhysicsController.h"
-#include "Value.h"
+#include "PHY_IPhysicsEnvironment.h"
-#include "KX_BlenderGL.h" // for text printing
#include "STR_String.h"
-#include "RAS_BucketManager.h" // for polymaterial (needed for textprinting)
-#include "KX_RayCast.h"
-#include "KX_IPhysicsController.h"
-#include "PHY_IPhysicsEnvironment.h"
-#include "KX_Scene.h"
+#include "GPU_draw.h"
+
+#include "KX_BlenderGL.h" // for text printing
+#include "KX_BlenderRenderTools.h"
+
+unsigned int KX_BlenderRenderTools::m_numgllights;
KX_BlenderRenderTools::KX_BlenderRenderTools()
{
@@ -71,61 +58,98 @@ KX_BlenderRenderTools::KX_BlenderRenderTools()
m_numgllights = 8;
}
-/**
-ProcessLighting performs lighting on objects. the layer is a bitfield that contains layer information.
-There are 20 'official' layers in blender.
-A light is applied on an object only when they are in the same layer.
-OpenGL has a maximum of 8 lights (simultaneous), so 20 * 8 lights are possible in a scene.
-*/
+KX_BlenderRenderTools::~KX_BlenderRenderTools()
+{
+}
-int KX_BlenderRenderTools::ProcessLighting(int layer)
+void KX_BlenderRenderTools::BeginFrame(RAS_IRasterizer* rasty)
{
-
- int result = false;
+ m_clientobject = NULL;
+ m_lastlightlayer = -1;
+ m_lastlighting = false;
+ DisableOpenGLLights();
+}
- if (layer < 0)
- {
- DisableOpenGLLights();
- result = false;
- } else
+void KX_BlenderRenderTools::EndFrame(RAS_IRasterizer* rasty)
+{
+}
+
+/* ProcessLighting performs lighting on objects. the layer is a bitfield that
+ * contains layer information. There are 20 'official' layers in blender. A
+ * light is applied on an object only when they are in the same layer. OpenGL
+ * has a maximum of 8 lights (simultaneous), so 20 * 8 lights are possible in
+ * a scene. */
+
+void KX_BlenderRenderTools::ProcessLighting(int layer, const MT_Transform& viewmat)
+{
+ if(m_lastlightlayer == layer)
+ return;
+
+ m_lastlightlayer = layer;
+
+ bool enable = false;
+
+ if (layer >= 0)
{
if (m_clientobject)
{
- if (applyLights(layer))
- {
- EnableOpenGLLights();
- result = true;
- } else
- {
- DisableOpenGLLights();
- result = false;
- }
+ if (layer == RAS_LIGHT_OBJECT_LAYER)
+ layer = static_cast<KX_GameObject*>(m_clientobject)->GetLayer();
+
+ enable = applyLights(layer, viewmat);
}
}
- return result;
-
-
+
+ if(enable)
+ EnableOpenGLLights();
+ else
+ DisableOpenGLLights();
}
+void KX_BlenderRenderTools::EnableOpenGLLights()
+{
+ if(m_lastlighting == true)
+ return;
-void KX_BlenderRenderTools::BeginFrame(RAS_IRasterizer* rasty)
+ glEnable(GL_LIGHTING);
+ glEnable(GL_COLOR_MATERIAL);
+
+ glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
+ glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, true);
+ if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2)
+ glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
+
+ m_lastlighting = true;
+}
+
+void KX_BlenderRenderTools::DisableOpenGLLights()
{
- m_clientobject = NULL;
- m_lastblenderobject = NULL;
- m_lastblenderlights = false;
- m_lastlayer = -1;
+ if(m_lastlighting == false)
+ return;
+
+ glDisable(GL_LIGHTING);
+ glDisable(GL_COLOR_MATERIAL);
+
m_lastlighting = false;
- m_modified = true;
- DisableOpenGLLights();
+}
+
+void KX_BlenderRenderTools::SetClientObject(RAS_IRasterizer *rasty, void* obj)
+{
+ if (m_clientobject != obj)
+ {
+ bool ccw = (obj == NULL || !((KX_GameObject*)obj)->IsNegativeScaling());
+ rasty->SetFrontFace(ccw);
+ m_clientobject = obj;
+ }
}
-bool KX_BlenderRenderTools::RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data)
+bool KX_BlenderRenderTools::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data)
{
double* const oglmatrix = (double* const) data;
- MT_Point3 resultpoint(hit_point);
- MT_Vector3 resultnormal(hit_normal);
+ MT_Point3 resultpoint(result->m_hitPoint);
+ MT_Vector3 resultnormal(result->m_hitNormal);
MT_Vector3 left(oglmatrix[0],oglmatrix[1],oglmatrix[2]);
MT_Vector3 dir = -(left.cross(resultnormal)).safe_normalized();
left = (dir.cross(resultnormal)).safe_normalized();
@@ -172,7 +196,7 @@ void KX_BlenderRenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmat
MT_Vector3 dir = (campos - objpos).safe_normalized();
MT_Vector3 up(0,0,1.0);
- KX_GameObject* gameobj = (KX_GameObject*) this->m_clientobject;
+ KX_GameObject* gameobj = (KX_GameObject*)m_clientobject;
// get scaling of halo object
MT_Vector3 size = gameobj->GetSGNode()->GetLocalScale();
@@ -208,7 +232,7 @@ void KX_BlenderRenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmat
{
// shadow must be cast to the ground, physics system needed here!
MT_Point3 frompoint(oglmatrix[12],oglmatrix[13],oglmatrix[14]);
- KX_GameObject *gameobj = (KX_GameObject*) this->m_clientobject;
+ KX_GameObject *gameobj = (KX_GameObject*)m_clientobject;
MT_Vector3 direction = MT_Vector3(0,0,-1);
direction.normalize();
@@ -226,9 +250,8 @@ void KX_BlenderRenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmat
if (parent)
parent->Release();
- MT_Point3 resultpoint;
- MT_Vector3 resultnormal;
- if (!KX_RayCast::RayTest(physics_controller, physics_environment, frompoint, topoint, resultpoint, resultnormal, KX_RayCast::Callback<KX_BlenderRenderTools>(this, oglmatrix)))
+ KX_RayCast::Callback<KX_BlenderRenderTools> callback(this, physics_controller, oglmatrix);
+ if (!KX_RayCast::RayTest(physics_environment, frompoint, topoint, callback))
{
// couldn't find something to cast the shadow on...
glMultMatrixd(oglmatrix);
@@ -243,13 +266,29 @@ void KX_BlenderRenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmat
}
-/**
-Render Text renders text into a (series of) polygon, using a texture font,
-Each character consists of one polygon (one quad or two triangles)
-*/
-void KX_BlenderRenderTools::RenderText(int mode,RAS_IPolyMaterial* polymat,float v1[3],float v2[3],float v3[3],float v4[3])
+void KX_BlenderRenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode,
+ const char* text,
+ int xco,
+ int yco,
+ int width,
+ int height)
+{
+ STR_String tmpstr(text);
+
+ if(mode == RAS_IRenderTools::RAS_TEXT_PADDED)
+ BL_print_gamedebug_line_padded(tmpstr.Ptr(), xco, yco, width, height);
+ else
+ BL_print_gamedebug_line(tmpstr.Ptr(), xco, yco, width, height);
+}
+
+/* Render Text renders text into a (series of) polygon, using a texture font,
+ * Each character consists of one polygon (one quad or two triangles) */
+
+void KX_BlenderRenderTools::RenderText(
+ int mode,
+ RAS_IPolyMaterial* polymat,
+ float v1[3], float v2[3], float v3[3], float v4[3], int glattrib)
{
-
STR_String mytext = ((CValue*)m_clientobject)->GetPropertyText("Text");
const unsigned int flag = polymat->GetFlag();
@@ -266,67 +305,9 @@ void KX_BlenderRenderTools::RenderText(int mode,RAS_IPolyMaterial* polymat,float
col = blenderpoly->GetMCol();
}
- BL_RenderText( mode,mytext,mytext.Length(),tface,col,v1,v2,v3,v4);
-
-}
-
-
-
-KX_BlenderRenderTools::~KX_BlenderRenderTools()
-{
-};
-
-
-void KX_BlenderRenderTools::EndFrame(RAS_IRasterizer* rasty)
-{
-}
-
-
-
-void KX_BlenderRenderTools::DisableOpenGLLights()
-{
- glDisable(GL_LIGHTING);
- glDisable(GL_COLOR_MATERIAL);
-}
-
-
-void KX_BlenderRenderTools::EnableOpenGLLights()
-{
- glEnable(GL_LIGHTING);
-
- glEnable(GL_COLOR_MATERIAL);
- glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
- glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, true);
- if (bgl::QueryExtension(bgl::_GL_EXT_separate_specular_color) || bgl::QueryVersion(1, 2))
- glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
-
-}
-
-
-/**
- * Rendering text using 2D bitmap functionality.
- */
-void KX_BlenderRenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode,
- const char* text,
- int xco,
- int yco,
- int width,
- int height)
-{
- switch (mode) {
- case RAS_IRenderTools::RAS_TEXT_PADDED: {
- STR_String tmpstr(text);
- BL_print_gamedebug_line_padded(tmpstr.Ptr(),xco,yco,width,height);
- break;
- }
- default: {
- STR_String tmpstr(text);
- BL_print_gamedebug_line(tmpstr.Ptr(),xco,yco,width,height);
- }
- }
+ GPU_render_text(tface, mode, mytext, mytext.Length(), col, v1, v2, v3, v4, glattrib);
}
-
void KX_BlenderRenderTools::PushMatrix()
{
@@ -339,14 +320,13 @@ void KX_BlenderRenderTools::PopMatrix()
}
-
-int KX_BlenderRenderTools::applyLights(int objectlayer)
+int KX_BlenderRenderTools::applyLights(int objectlayer, const MT_Transform& viewmat)
{
-// taken from blender source, incompatibility between Blender Object / GameObject
-
+ // taken from blender source, incompatibility between Blender Object / GameObject
+ float glviewmat[16];
unsigned int count;
float vec[4];
-
+
vec[3]= 1.0;
for(count=0; count<m_numgllights; count++)
@@ -354,9 +334,11 @@ int KX_BlenderRenderTools::applyLights(int objectlayer)
//std::vector<struct RAS_LightObject*> m_lights;
std::vector<struct RAS_LightObject*>::iterator lit = m_lights.begin();
+
+ viewmat.getValue(glviewmat);
glPushMatrix();
- glLoadMatrixf(m_viewmat);
+ glLoadMatrixf(glviewmat);
for (lit = m_lights.begin(), count = 0; !(lit==m_lights.end()) && count < m_numgllights; ++lit)
{
RAS_LightObject* lightdata = (*lit);
@@ -424,7 +406,6 @@ int KX_BlenderRenderTools::applyLights(int objectlayer)
glEnable((GLenum)(GL_LIGHT0+count));
count++;
-
}
}
glPopMatrix();
@@ -433,22 +414,6 @@ int KX_BlenderRenderTools::applyLights(int objectlayer)
}
-
-
-RAS_IPolyMaterial* KX_BlenderRenderTools::CreateBlenderPolyMaterial(
- const STR_String &texname,
- bool ba,const STR_String& matname,int tile,int tilexrep,int tileyrep,int mode,bool transparant,bool zsort, int lightlayer
- ,bool bIsTriangle,void* clientobject,void* tface)
-{
- assert(!"Deprecated");
-/* return new KX_BlenderPolyMaterial(
-
- texname,
- ba,matname,tile,tilexrep,tileyrep,mode,transparant,zsort, lightlayer
- ,bIsTriangle,clientobject,(struct MTFace*)tface);*/
- return NULL;
-}
-
void KX_BlenderRenderTools::MotionBlur(RAS_IRasterizer* rasterizer)
{
int state = rasterizer->GetMotionBlurState();
@@ -472,4 +437,13 @@ void KX_BlenderRenderTools::MotionBlur(RAS_IRasterizer* rasterizer)
}
}
-unsigned int KX_BlenderRenderTools::m_numgllights;
+void KX_BlenderRenderTools::Update2DFilter(vector<STR_String>& propNames, void* gameObj, RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode, int pass, STR_String& text)
+{
+ m_filtermanager.EnableFilter(propNames, gameObj, filtermode, pass, text);
+}
+
+void KX_BlenderRenderTools::Render2DFilters(RAS_ICanvas* canvas)
+{
+ m_filtermanager.RenderFilters(canvas);
+}
+
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.h b/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.h
index 117d6a2be54..a7618462c9b 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.h
+++ b/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.h
@@ -26,6 +26,7 @@
*
* ***** END GPL LICENSE BLOCK *****
*/
+
#ifndef __KX_BLENDERRENDERTOOLS
#define __KX_BLENDERRENDERTOOLS
@@ -37,70 +38,65 @@
#include "RAS_IRenderTools.h"
struct KX_ClientObjectInfo;
+class KX_RayCast;
-/**
-BlenderRenderTools are a set of tools to apply 2D/3D graphics effects, which are not
-part of the (polygon) Rasterizer.
-Effects like 2D text, 3D (polygon) text, lighting.
-*/
+/* BlenderRenderTools are a set of tools to apply 2D/3D graphics effects, which
+ * are not part of the (polygon) Rasterizer. Effects like 2D text, 3D (polygon)
+ * text, lighting.
+ *
+ * Most of this code is duplicated in GPC_RenderTools, so this should be
+ * moved to some common location to avoid duplication. */
class KX_BlenderRenderTools : public RAS_IRenderTools
{
- bool m_lastblenderlights;
- void* m_lastblenderobject;
- int m_lastlayer;
+ int m_lastlightlayer;
bool m_lastlighting;
static unsigned int m_numgllights;
-
+
public:
-
KX_BlenderRenderTools();
virtual ~KX_BlenderRenderTools();
- virtual void EndFrame(class RAS_IRasterizer* rasty);
- virtual void BeginFrame(class RAS_IRasterizer* rasty);
- void DisableOpenGLLights();
+ void EndFrame(RAS_IRasterizer* rasty);
+ void BeginFrame(RAS_IRasterizer* rasty);
+
void EnableOpenGLLights();
- int ProcessLighting(int layer);
+ void DisableOpenGLLights();
+ void ProcessLighting(int layer, const MT_Transform& viewmat);
- virtual void RenderText2D(RAS_TEXT_RENDER_MODE mode,
+ void RenderText2D(RAS_TEXT_RENDER_MODE mode,
const char* text,
int xco,
int yco,
int width,
int height);
- virtual void RenderText(int mode,
+ void RenderText(int mode,
class RAS_IPolyMaterial* polymat,
float v1[3],
float v2[3],
float v3[3],
- float v4[3]);
- void applyTransform(class RAS_IRasterizer* rasty,
- double* oglmatrix,
- int objectdrawmode );
- int applyLights(int objectlayer);
- virtual void PushMatrix();
- virtual void PopMatrix();
-
- virtual class RAS_IPolyMaterial* CreateBlenderPolyMaterial(const STR_String &texname,
- bool ba,
- const STR_String& matname,
- int tile,
- int tilexrep,
- int tileyrep,
- int mode,
- bool transparant,
- bool zsort,
- int lightlayer,
- bool bIsTriangle,
- void* clientobject,
- void* tface);
-
- bool RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data);
+ float v4[3],
+ int glattrib);
+
+ void applyTransform(RAS_IRasterizer* rasty, double* oglmatrix, int objectdrawmode);
+ int applyLights(int objectlayer, const MT_Transform& viewmat);
+
+ void PushMatrix();
+ void PopMatrix();
+
+ bool RayHit(KX_ClientObjectInfo* client, class KX_RayCast* result, void * const data);
+ bool NeedRayCast(KX_ClientObjectInfo*) { return true; }
virtual void MotionBlur(RAS_IRasterizer* rasterizer);
+
+ virtual void Update2DFilter(vector<STR_String>& propNames, void* gameObj, RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode, int pass, STR_String& text);
+
+ virtual void Render2DFilters(RAS_ICanvas* canvas);
+
+ virtual void SetClientObject(RAS_IRasterizer *rasty, void* obj);
};
#endif //__KX_BLENDERRENDERTOOLS
+
diff --git a/source/gameengine/BlenderRoutines/Makefile b/source/gameengine/BlenderRoutines/Makefile
index 8d7ed46bc28..7ee825d186b 100644
--- a/source/gameengine/BlenderRoutines/Makefile
+++ b/source/gameengine/BlenderRoutines/Makefile
@@ -35,7 +35,6 @@ include nan_compile.mk
CCFLAGS += $(LEVEL_1_CPP_WARNINGS)
-CPPFLAGS += -I$(OPENGL_HEADERS)
CPPFLAGS += -I$(NAN_SUMO)/include -I$(NAN_SOLID)/include
CPPFLAGS += -I$(NAN_SOLID)
CPPFLAGS += -I$(NAN_STRING)/include
@@ -43,6 +42,8 @@ CPPFLAGS += -I$(NAN_MOTO)/include
CPPFLAGS += -I$(NAN_BMFONT)/include
CPPFLAGS += -I$(NAN_FUZZICS)/include
CPPFLAGS += -I$(NAN_SOUNDSYSTEM)/include
+CPPFLAGS += -I$(NAN_GLEW)/include
+CPPFLAGS += -I$(OPENGL_HEADERS)
# because of kernel dependency on makesdna
CPPFLAGS += -I../../blender/makesdna
CPPFLAGS += -I../../blender/editors/include
@@ -54,6 +55,7 @@ CPPFLAGS += -I../../blender/blenkernel
CPPFLAGS += -I../../blender/render/extern/include
CPPFLAGS += -I../../blender/blenloader
CPPFLAGS += -I../../blender/blenkernel
+CPPFLAGS += -I../../blender/gpu
CPPFLAGS += -I../Converter
CPPFLAGS += -I../Expressions
CPPFLAGS += -I../GameLogic
@@ -66,6 +68,7 @@ CPPFLAGS += -I../Network
CPPFLAGS += -I../Network/LoopBackNetwork
CPPFLAGS += -I../Physics/common
CPPFLAGS += -I../Physics/Sumo
+CPPFLAGS += -I.
ifeq ($(OS),windows)
CPPFLAGS += -I../../blender
diff --git a/source/gameengine/BlenderRoutines/SConscript b/source/gameengine/BlenderRoutines/SConscript
index 52d187cbe20..7722b6f69a6 100644
--- a/source/gameengine/BlenderRoutines/SConscript
+++ b/source/gameengine/BlenderRoutines/SConscript
@@ -15,6 +15,7 @@ incs += ' #source/gameengine/SceneGraph #source/gameengine/Physics/common'
incs += ' #source/gameengine/Physics/Bullet #source/gameengine/Physics/Sumo'
incs += ' #source/gameengine/Physics/Sumo/Fuzzics/include #source/gameengine/Network/LoopBackNetwork'
incs += ' #intern/SoundSystem #source/blender/misc #source/blender/blenloader'
+incs += ' #extern/glew/include #source/blender/gpu'
incs += ' #source/blender/windowmanager'
incs += ' ' + env['BF_PYTHON_INC']
diff --git a/source/gameengine/CMakeLists.txt b/source/gameengine/CMakeLists.txt
index 93de588ba00..3ea788791e2 100644
--- a/source/gameengine/CMakeLists.txt
+++ b/source/gameengine/CMakeLists.txt
@@ -40,6 +40,7 @@ SUBDIRS(
SceneGraph
Physics/Bullet
Physics/Sumo
+ VideoTexture
)
IF(WITH_PLAYER)
diff --git a/source/gameengine/Converter/BL_ActionActuator.cpp b/source/gameengine/Converter/BL_ActionActuator.cpp
index 1055c8771ef..4d748948c27 100644
--- a/source/gameengine/Converter/BL_ActionActuator.cpp
+++ b/source/gameengine/Converter/BL_ActionActuator.cpp
@@ -49,6 +49,8 @@
#include "BLI_arithb.h"
#include "MT_Matrix4x4.h"
#include "BKE_utildefines.h"
+#include "FloatValue.h"
+#include "PyObjectPlus.h"
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -56,24 +58,12 @@
BL_ActionActuator::~BL_ActionActuator()
{
-
- if (m_pose) {
- free_pose_channels(m_pose);
- MEM_freeN(m_pose);
- m_pose = NULL;
- };
-
- if (m_userpose){
- free_pose_channels(m_userpose);
- MEM_freeN(m_userpose);
- m_userpose=NULL;
- }
- if (m_blendpose) {
- free_pose_channels(m_blendpose);
- MEM_freeN(m_blendpose);
- m_blendpose = NULL;
- };
-
+ if (m_pose)
+ game_free_pose(m_pose);
+ if (m_userpose)
+ game_free_pose(m_userpose);
+ if (m_blendpose)
+ game_free_pose(m_blendpose);
}
void BL_ActionActuator::ProcessReplica(){
@@ -134,14 +124,14 @@ void BL_ActionActuator::SetStartTime(float curtime)
float direction = m_startframe < m_endframe ? 1.0 : -1.0;
if (!(m_flag & ACT_FLAG_REVERSE))
- m_starttime = curtime - direction*(m_localtime - m_startframe)/KX_FIXED_FRAME_PER_SEC;
+ m_starttime = curtime - direction*(m_localtime - m_startframe)/KX_KetsjiEngine::GetAnimFrameRate();
else
- m_starttime = curtime - direction*(m_endframe - m_localtime)/KX_FIXED_FRAME_PER_SEC;
+ m_starttime = curtime - direction*(m_endframe - m_localtime)/KX_KetsjiEngine::GetAnimFrameRate();
}
void BL_ActionActuator::SetLocalTime(float curtime)
{
- float delta_time = (curtime - m_starttime)*KX_FIXED_FRAME_PER_SEC;
+ float delta_time = (curtime - m_starttime)*KX_KetsjiEngine::GetAnimFrameRate();
if (m_endframe < m_startframe)
delta_time = -delta_time;
@@ -162,6 +152,8 @@ bool BL_ActionActuator::Update(double curtime, bool frame)
bool apply=true;
int priority;
float newweight;
+
+ curtime -= KX_KetsjiEngine::GetSuspendedDelta();
// result = true if animation has to be continued, false if animation stops
// maybe there are events for us in the queue !
@@ -183,6 +175,11 @@ bool BL_ActionActuator::Update(double curtime, bool frame)
if (bNegativeEvent)
{
+ // dont continue where we left off when restarting
+ if (m_end_reset) {
+ m_flag &= ~ACT_FLAG_LOCKINPUT;
+ }
+
if (!(m_flag & ACT_FLAG_ACTIVE))
return false;
m_flag &= ~ACT_FLAG_ACTIVE;
@@ -348,6 +345,18 @@ bool BL_ActionActuator::Update(double curtime, bool frame)
break;
}
+ /* Set the property if its defined */
+ if (m_framepropname[0] != '\0') {
+ CValue* propowner = GetParent();
+ CValue* oldprop = propowner->GetProperty(m_framepropname);
+ CValue* newval = new CFloatValue(m_localtime);
+ if (oldprop) {
+ oldprop->SetValue(newval);
+ } else {
+ propowner->SetProperty(m_framepropname, newval);
+ }
+ newval->Release();
+ }
if (bNegativeEvent)
m_blendframe=0.0;
@@ -385,7 +394,7 @@ bool BL_ActionActuator::Update(double curtime, bool frame)
blend_poses(m_pose, m_blendpose, 1.0 - newweight, ACTSTRIPMODE_BLEND);
/* Increment current blending percentage */
- m_blendframe = (curtime - m_blendstart)*KX_FIXED_FRAME_PER_SEC;
+ m_blendframe = (curtime - m_blendstart)*KX_KetsjiEngine::GetAnimFrameRate();
if (m_blendframe>m_blendin)
m_blendframe = m_blendin;
@@ -439,26 +448,30 @@ PyParentObject BL_ActionActuator::Parents[] = {
};
PyMethodDef BL_ActionActuator::Methods[] = {
- {"setAction", (PyCFunction) BL_ActionActuator::sPySetAction, METH_VARARGS, SetAction_doc},
- {"setStart", (PyCFunction) BL_ActionActuator::sPySetStart, METH_VARARGS, SetStart_doc},
- {"setEnd", (PyCFunction) BL_ActionActuator::sPySetEnd, METH_VARARGS, SetEnd_doc},
- {"setBlendin", (PyCFunction) BL_ActionActuator::sPySetBlendin, METH_VARARGS, SetBlendin_doc},
- {"setPriority", (PyCFunction) BL_ActionActuator::sPySetPriority, METH_VARARGS, SetPriority_doc},
- {"setFrame", (PyCFunction) BL_ActionActuator::sPySetFrame, METH_VARARGS, SetFrame_doc},
- {"setProperty", (PyCFunction) BL_ActionActuator::sPySetProperty, METH_VARARGS, SetProperty_doc},
- {"setBlendtime", (PyCFunction) BL_ActionActuator::sPySetBlendtime, METH_VARARGS, SetBlendtime_doc},
-
- {"getAction", (PyCFunction) BL_ActionActuator::sPyGetAction, METH_VARARGS, GetAction_doc},
- {"getStart", (PyCFunction) BL_ActionActuator::sPyGetStart, METH_VARARGS, GetStart_doc},
- {"getEnd", (PyCFunction) BL_ActionActuator::sPyGetEnd, METH_VARARGS, GetEnd_doc},
- {"getBlendin", (PyCFunction) BL_ActionActuator::sPyGetBlendin, METH_VARARGS, GetBlendin_doc},
- {"getPriority", (PyCFunction) BL_ActionActuator::sPyGetPriority, METH_VARARGS, GetPriority_doc},
- {"getFrame", (PyCFunction) BL_ActionActuator::sPyGetFrame, METH_VARARGS, GetFrame_doc},
- {"getProperty", (PyCFunction) BL_ActionActuator::sPyGetProperty, METH_VARARGS, GetProperty_doc},
- {"setChannel", (PyCFunction) BL_ActionActuator::sPySetChannel, METH_VARARGS, SetChannel_doc},
+ {"setAction", (PyCFunction) BL_ActionActuator::sPySetAction, METH_VARARGS, (PY_METHODCHAR)SetAction_doc},
+ {"setStart", (PyCFunction) BL_ActionActuator::sPySetStart, METH_VARARGS, (PY_METHODCHAR)SetStart_doc},
+ {"setEnd", (PyCFunction) BL_ActionActuator::sPySetEnd, METH_VARARGS, (PY_METHODCHAR)SetEnd_doc},
+ {"setBlendin", (PyCFunction) BL_ActionActuator::sPySetBlendin, METH_VARARGS, (PY_METHODCHAR)SetBlendin_doc},
+ {"setPriority", (PyCFunction) BL_ActionActuator::sPySetPriority, METH_VARARGS, (PY_METHODCHAR)SetPriority_doc},
+ {"setFrame", (PyCFunction) BL_ActionActuator::sPySetFrame, METH_VARARGS, (PY_METHODCHAR)SetFrame_doc},
+ {"setProperty", (PyCFunction) BL_ActionActuator::sPySetProperty, METH_VARARGS, (PY_METHODCHAR)SetProperty_doc},
+ {"setFrameProperty", (PyCFunction) BL_ActionActuator::sPySetFrameProperty, METH_VARARGS, (PY_METHODCHAR)SetFrameProperty_doc},
+ {"setBlendtime", (PyCFunction) BL_ActionActuator::sPySetBlendtime, METH_VARARGS, (PY_METHODCHAR)SetBlendtime_doc},
+
+ {"getAction", (PyCFunction) BL_ActionActuator::sPyGetAction, METH_VARARGS, (PY_METHODCHAR)GetAction_doc},
+ {"getStart", (PyCFunction) BL_ActionActuator::sPyGetStart, METH_VARARGS, (PY_METHODCHAR)GetStart_doc},
+ {"getEnd", (PyCFunction) BL_ActionActuator::sPyGetEnd, METH_VARARGS, (PY_METHODCHAR)GetEnd_doc},
+ {"getBlendin", (PyCFunction) BL_ActionActuator::sPyGetBlendin, METH_VARARGS, (PY_METHODCHAR)GetBlendin_doc},
+ {"getPriority", (PyCFunction) BL_ActionActuator::sPyGetPriority, METH_VARARGS, (PY_METHODCHAR)GetPriority_doc},
+ {"getFrame", (PyCFunction) BL_ActionActuator::sPyGetFrame, METH_VARARGS, (PY_METHODCHAR)GetFrame_doc},
+ {"getProperty", (PyCFunction) BL_ActionActuator::sPyGetProperty, METH_VARARGS, (PY_METHODCHAR)GetProperty_doc},
+ {"getFrameProperty", (PyCFunction) BL_ActionActuator::sPyGetFrameProperty, METH_VARARGS, (PY_METHODCHAR)GetFrameProperty_doc},
+ {"setChannel", (PyCFunction) BL_ActionActuator::sPySetChannel, METH_VARARGS, (PY_METHODCHAR)SetChannel_doc},
// {"getChannel", (PyCFunction) BL_ActionActuator::sPyGetChannel, METH_VARARGS},
- {"getType", (PyCFunction) BL_ActionActuator::sPyGetType, METH_VARARGS, GetType_doc},
- {"setType", (PyCFunction) BL_ActionActuator::sPySetType, METH_VARARGS, SetType_doc},
+ {"getType", (PyCFunction) BL_ActionActuator::sPyGetType, METH_VARARGS, (PY_METHODCHAR)GetType_doc},
+ {"setType", (PyCFunction) BL_ActionActuator::sPySetType, METH_VARARGS, (PY_METHODCHAR)SetType_doc},
+ {"getContinue", (PyCFunction) BL_ActionActuator::sPyGetContinue, METH_NOARGS, 0},
+ {"setContinue", (PyCFunction) BL_ActionActuator::sPySetContinue, METH_O, 0},
{NULL,NULL} //Sentinel
};
@@ -467,28 +480,21 @@ PyObject* BL_ActionActuator::_getattr(const STR_String& attr) {
}
/* setStart */
-char BL_ActionActuator::GetAction_doc[] =
+const char BL_ActionActuator::GetAction_doc[] =
"getAction()\n"
"\tReturns a string containing the name of the current action.\n";
PyObject* BL_ActionActuator::PyGetAction(PyObject* self,
PyObject* args,
PyObject* kwds) {
- PyObject *result;
-
if (m_action){
- result = Py_BuildValue("s", m_action->id.name+2);
- }
- else{
- Py_INCREF(Py_None);
- result = Py_None;
+ return PyString_FromString(m_action->id.name+2);
}
-
- return result;
+ Py_RETURN_NONE;
}
/* getProperty */
-char BL_ActionActuator::GetProperty_doc[] =
+const char BL_ActionActuator::GetProperty_doc[] =
"getProperty()\n"
"\tReturns the name of the property to be used in FromProp mode.\n";
@@ -502,8 +508,23 @@ PyObject* BL_ActionActuator::PyGetProperty(PyObject* self,
return result;
}
+/* getProperty */
+const char BL_ActionActuator::GetFrameProperty_doc[] =
+"getFrameProperty()\n"
+"\tReturns the name of the property, that is set to the current frame number.\n";
+
+PyObject* BL_ActionActuator::PyGetFrameProperty(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ PyObject *result;
+
+ result = Py_BuildValue("s", (const char *)m_framepropname);
+
+ return result;
+}
+
/* getFrame */
-char BL_ActionActuator::GetFrame_doc[] =
+const char BL_ActionActuator::GetFrame_doc[] =
"getFrame()\n"
"\tReturns the current frame number.\n";
@@ -518,7 +539,7 @@ PyObject* BL_ActionActuator::PyGetFrame(PyObject* self,
}
/* getEnd */
-char BL_ActionActuator::GetEnd_doc[] =
+const char BL_ActionActuator::GetEnd_doc[] =
"getEnd()\n"
"\tReturns the last frame of the action.\n";
@@ -533,7 +554,7 @@ PyObject* BL_ActionActuator::PyGetEnd(PyObject* self,
}
/* getStart */
-char BL_ActionActuator::GetStart_doc[] =
+const char BL_ActionActuator::GetStart_doc[] =
"getStart()\n"
"\tReturns the starting frame of the action.\n";
@@ -548,7 +569,7 @@ PyObject* BL_ActionActuator::PyGetStart(PyObject* self,
}
/* getBlendin */
-char BL_ActionActuator::GetBlendin_doc[] =
+const char BL_ActionActuator::GetBlendin_doc[] =
"getBlendin()\n"
"\tReturns the number of interpolation animation frames to be\n"
"\tgenerated when this actuator is triggered.\n";
@@ -564,7 +585,7 @@ PyObject* BL_ActionActuator::PyGetBlendin(PyObject* self,
}
/* getPriority */
-char BL_ActionActuator::GetPriority_doc[] =
+const char BL_ActionActuator::GetPriority_doc[] =
"getPriority()\n"
"\tReturns the priority for this actuator. Actuators with lower\n"
"\tPriority numbers will override actuators with higher numbers.\n";
@@ -580,7 +601,7 @@ PyObject* BL_ActionActuator::PyGetPriority(PyObject* self,
}
/* setAction */
-char BL_ActionActuator::SetAction_doc[] =
+const char BL_ActionActuator::SetAction_doc[] =
"setAction(action, (reset))\n"
"\t - action : The name of the action to set as the current action.\n"
"\t - reset : Optional parameter indicating whether to reset the\n"
@@ -611,13 +632,15 @@ PyObject* BL_ActionActuator::PySetAction(PyObject* self,
m_blendframe = 0;
}
}
+ else {
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
/* setStart */
-char BL_ActionActuator::SetStart_doc[] =
+const char BL_ActionActuator::SetStart_doc[] =
"setStart(start)\n"
"\t - start : Specifies the starting frame of the animation.\n";
@@ -630,13 +653,15 @@ PyObject* BL_ActionActuator::PySetStart(PyObject* self,
{
m_startframe = start;
}
+ else {
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
/* setEnd */
-char BL_ActionActuator::SetEnd_doc[] =
+const char BL_ActionActuator::SetEnd_doc[] =
"setEnd(end)\n"
"\t - end : Specifies the ending frame of the animation.\n";
@@ -649,13 +674,15 @@ PyObject* BL_ActionActuator::PySetEnd(PyObject* self,
{
m_endframe = end;
}
+ else {
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
/* setBlendin */
-char BL_ActionActuator::SetBlendin_doc[] =
+const char BL_ActionActuator::SetBlendin_doc[] =
"setBlendin(blendin)\n"
"\t - blendin : Specifies the number of frames of animation to generate\n"
"\t when making transitions between actions.\n";
@@ -669,13 +696,15 @@ PyObject* BL_ActionActuator::PySetBlendin(PyObject* self,
{
m_blendin = blendin;
}
+ else {
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
/* setBlendtime */
-char BL_ActionActuator::SetBlendtime_doc[] =
+const char BL_ActionActuator::SetBlendtime_doc[] =
"setBlendtime(blendtime)\n"
"\t - blendtime : Allows the script to directly modify the internal timer\n"
"\t used when generating transitions between actions. This\n"
@@ -694,13 +723,15 @@ PyObject* BL_ActionActuator::PySetBlendtime(PyObject* self,
if (m_blendframe>m_blendin)
m_blendframe = m_blendin;
}
+ else {
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
/* setPriority */
-char BL_ActionActuator::SetPriority_doc[] =
+const char BL_ActionActuator::SetPriority_doc[] =
"setPriority(priority)\n"
"\t - priority : Specifies the new priority. Actuators will lower\n"
"\t priority numbers will override actuators with higher\n"
@@ -715,13 +746,15 @@ PyObject* BL_ActionActuator::PySetPriority(PyObject* self,
{
m_priority = priority;
}
+ else {
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
/* setFrame */
-char BL_ActionActuator::SetFrame_doc[] =
+const char BL_ActionActuator::SetFrame_doc[] =
"setFrame(frame)\n"
"\t - frame : Specifies the new current frame for the animation\n";
@@ -738,13 +771,15 @@ PyObject* BL_ActionActuator::PySetFrame(PyObject* self,
else if (m_localtime>m_endframe)
m_localtime=m_endframe;
}
+ else {
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
/* setProperty */
-char BL_ActionActuator::SetProperty_doc[] =
+const char BL_ActionActuator::SetProperty_doc[] =
"setProperty(prop)\n"
"\t - prop : A string specifying the property name to be used in\n"
"\t FromProp playback mode.\n";
@@ -758,9 +793,32 @@ PyObject* BL_ActionActuator::PySetProperty(PyObject* self,
{
m_propname = string;
}
+ else {
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
+}
+
+/* setFrameProperty */
+const char BL_ActionActuator::SetFrameProperty_doc[] =
+"setFrameProperty(prop)\n"
+"\t - prop : A string specifying the property of the frame set up update.\n";
+
+PyObject* BL_ActionActuator::PySetFrameProperty(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ char *string;
+
+ if (PyArg_ParseTuple(args,"s",&string))
+ {
+ m_framepropname = string;
+ }
+ else {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
}
/*
@@ -773,14 +831,16 @@ PyObject* BL_ActionActuator::PyGetChannel(PyObject* self,
{
m_propname = string;
}
+ else {
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
*/
/* setChannel */
-char BL_ActionActuator::SetChannel_doc[] =
+const char BL_ActionActuator::SetChannel_doc[] =
"setChannel(channel, matrix)\n"
"\t - channel : A string specifying the name of the bone channel.\n"
"\t - matrix : A 4x4 matrix specifying the overriding transformation\n"
@@ -797,7 +857,8 @@ PyObject* BL_ActionActuator::PySetChannel(PyObject* self,
int row,col;
int mode = 0; /* 0 for bone space, 1 for armature/world space */
- PyArg_ParseTuple(args,"sO|i", &string, &pylist, &mode);
+ if (!PyArg_ParseTuple(args,"sO|i", &string, &pylist, &mode))
+ return NULL;
if (pylist->ob_type == &CListValue::Type)
{
@@ -859,12 +920,11 @@ PyObject* BL_ActionActuator::PySetChannel(PyObject* self,
}
}
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
/* getType */
-char BL_ActionActuator::GetType_doc[] =
+const char BL_ActionActuator::GetType_doc[] =
"getType()\n"
"\tReturns the operation mode of the actuator.\n";
PyObject* BL_ActionActuator::PyGetType(PyObject* self,
@@ -874,7 +934,7 @@ PyObject* BL_ActionActuator::PyGetType(PyObject* self,
}
/* setType */
-char BL_ActionActuator::SetType_doc[] =
+const char BL_ActionActuator::SetType_doc[] =
"setType(mode)\n"
"\t - mode: Play (0), Flipper (2), LoopStop (3), LoopEnd (4) or Property (6)\n"
"\tSet the operation mode of the actuator.\n";
@@ -898,7 +958,26 @@ PyObject* BL_ActionActuator::PySetType(PyObject* self,
default:
printf("Invalid type for action actuator: %d\n", typeArg); /* error */
}
+ Py_RETURN_NONE;
+}
+
+PyObject* BL_ActionActuator::PyGetContinue(PyObject* self) {
+ return PyInt_FromLong((long)(m_end_reset==0));
+}
+
+PyObject* BL_ActionActuator::PySetContinue(PyObject* self, PyObject* value) {
+ int param = PyObject_IsTrue( value );
- Py_Return;
+ if( param == -1 ) {
+ PyErr_SetString( PyExc_TypeError, "expected True/False or 0/1" );
+ return NULL;
+ }
+
+ if (param) {
+ m_end_reset = 0;
+ } else {
+ m_end_reset = 1;
+ }
+ Py_RETURN_NONE;
}
diff --git a/source/gameengine/Converter/BL_ActionActuator.h b/source/gameengine/Converter/BL_ActionActuator.h
index 62edcc7fad7..a67b6d29b74 100644
--- a/source/gameengine/Converter/BL_ActionActuator.h
+++ b/source/gameengine/Converter/BL_ActionActuator.h
@@ -40,12 +40,14 @@ public:
Py_Header;
BL_ActionActuator(SCA_IObject* gameobj,
const STR_String& propname,
+ const STR_String& framepropname,
float starttime,
float endtime,
struct bAction *action,
short playtype,
short blendin,
short priority,
+ short end_reset,
float stride,
PyTypeObject* T=&Type)
: SCA_IActuator(gameobj,T),
@@ -63,11 +65,13 @@ public:
m_stridelength(stride),
m_playtype(playtype),
m_priority(priority),
+ m_end_reset(end_reset),
m_pose(NULL),
m_blendpose(NULL),
m_userpose(NULL),
m_action(action),
- m_propname(propname)
+ m_propname(propname),
+ m_framepropname(framepropname)
{
};
virtual ~BL_ActionActuator();
@@ -84,6 +88,7 @@ public:
KX_PYMETHOD_DOC(BL_ActionActuator,SetEnd);
KX_PYMETHOD_DOC(BL_ActionActuator,SetFrame);
KX_PYMETHOD_DOC(BL_ActionActuator,SetProperty);
+ KX_PYMETHOD_DOC(BL_ActionActuator,SetFrameProperty);
KX_PYMETHOD_DOC(BL_ActionActuator,SetBlendtime);
KX_PYMETHOD_DOC(BL_ActionActuator,SetChannel);
@@ -94,9 +99,12 @@ public:
KX_PYMETHOD_DOC(BL_ActionActuator,GetEnd);
KX_PYMETHOD_DOC(BL_ActionActuator,GetFrame);
KX_PYMETHOD_DOC(BL_ActionActuator,GetProperty);
+ KX_PYMETHOD_DOC(BL_ActionActuator,GetFrameProperty);
// KX_PYMETHOD(BL_ActionActuator,GetChannel);
KX_PYMETHOD_DOC(BL_ActionActuator,GetType);
KX_PYMETHOD_DOC(BL_ActionActuator,SetType);
+ KX_PYMETHOD_NOARGS(BL_ActionActuator,GetContinue);
+ KX_PYMETHOD_O(BL_ActionActuator,SetContinue);
virtual PyObject* _getattr(const STR_String& attr);
@@ -133,11 +141,13 @@ protected:
float m_stridelength;
short m_playtype;
short m_priority;
+ short m_end_reset;
struct bPose* m_pose;
struct bPose* m_blendpose;
struct bPose* m_userpose;
struct bAction *m_action;
STR_String m_propname;
+ STR_String m_framepropname;
};
enum {
diff --git a/source/gameengine/Converter/BL_ArmatureObject.cpp b/source/gameengine/Converter/BL_ArmatureObject.cpp
index ff9c6a75aa9..d2001212f7d 100644
--- a/source/gameengine/Converter/BL_ArmatureObject.cpp
+++ b/source/gameengine/Converter/BL_ArmatureObject.cpp
@@ -45,7 +45,6 @@
#include <config.h>
#endif
-
BL_ArmatureObject::BL_ArmatureObject(
void* sgReplicationInfo,
SG_Callbacks callbacks,
@@ -53,15 +52,20 @@ BL_ArmatureObject::BL_ArmatureObject(
: KX_GameObject(sgReplicationInfo,callbacks),
m_objArma(armature),
- m_mrdPose(NULL),
- m_lastframe(0.),
+ m_framePose(NULL),
+ m_lastframe(0.0),
m_activeAct(NULL),
- m_activePriority(999)
+ m_activePriority(999),
+ m_lastapplyframe(0.0)
{
m_armature = get_armature(m_objArma);
- m_pose = m_objArma->pose;
-}
+ /* we make a copy of blender object's pose, and then always swap it with
+ * the original pose before calling into blender functions, to deal with
+ * replica's or other objects using the same blender object */
+ m_pose = NULL;
+ game_copy_pose(&m_pose, m_objArma->pose);
+}
CValue* BL_ArmatureObject::GetReplica()
{
@@ -78,35 +82,37 @@ void BL_ArmatureObject::ProcessReplica(BL_ArmatureObject *replica)
{
KX_GameObject::ProcessReplica(replica);
+ replica->m_pose = NULL;
+ game_copy_pose(&replica->m_pose, m_pose);
}
BL_ArmatureObject::~BL_ArmatureObject()
{
- if (m_mrdPose){
- free_pose_channels(m_mrdPose);
- MEM_freeN(m_mrdPose);
- }
+ if (m_pose)
+ game_free_pose(m_pose);
}
-/* note, you can only call this for exisiting Armature objects, and not mix it with other Armatures */
-/* there is only 1 unique Pose per Armature */
void BL_ArmatureObject::ApplyPose()
{
- if (m_pose){
- // copy to armature object
- extract_pose_from_pose(m_objArma->pose, m_pose);
-
- // is this needed anymore?
- //if (!m_mrdPose)
- // copy_pose (&m_mrdPose, m_pose, 0);
- //else
- // extract_pose_from_pose(m_mrdPose, m_pose);
+ m_armpose = m_objArma->pose;
+ m_objArma->pose = m_pose;
+
+ if(m_lastapplyframe != m_lastframe) {
+ where_is_pose(m_objArma);
+ m_lastapplyframe = m_lastframe;
}
}
+void BL_ArmatureObject::RestorePose()
+{
+ m_objArma->pose = m_armpose;
+ m_armpose = NULL;
+}
+
void BL_ArmatureObject::SetPose(bPose *pose)
{
- m_pose = pose;
+ extract_pose_from_pose(m_pose, pose);
+ m_lastapplyframe = -1.0;
}
bool BL_ArmatureObject::SetActiveAction(BL_ActionActuator *act, short priority, double curtime)
@@ -115,10 +121,15 @@ bool BL_ArmatureObject::SetActiveAction(BL_ActionActuator *act, short priority,
m_activePriority = 9999;
m_lastframe= curtime;
m_activeAct = NULL;
+ // remember the pose at the start of the frame
+ m_framePose = m_pose;
}
if (priority<=m_activePriority)
{
+ if (priority<m_activePriority)
+ // this action overwrites the previous ones, start from initial pose to cancel their effects
+ m_pose = m_framePose;
if (m_activeAct && (m_activeAct!=act))
m_activeAct->SetBlendTime(0.0); /* Reset the blend timer */
m_activeAct = act;
@@ -143,19 +154,22 @@ void BL_ArmatureObject::GetPose(bPose **pose)
{
/* If the caller supplies a null pose, create a new one. */
/* Otherwise, copy the armature's pose channels into the caller-supplied pose */
-
+
if (!*pose) {
/* probably not to good of an idea to
duplicate everying, but it clears up
a crash and memory leakage when
&BL_ActionActuator::m_pose is freed
*/
- int copy_constraint_channels_hack = 1;
- copy_pose(pose, m_pose, copy_constraint_channels_hack);
+ game_copy_pose(pose, m_pose);
}
- else
- extract_pose_from_pose(*pose, m_pose);
+ else {
+ if (*pose == m_pose)
+ // no need to copy if the pointers are the same
+ return;
+ extract_pose_from_pose(*pose, m_pose);
+ }
}
void BL_ArmatureObject::GetMRDPose(bPose **pose)
@@ -163,16 +177,10 @@ void BL_ArmatureObject::GetMRDPose(bPose **pose)
/* If the caller supplies a null pose, create a new one. */
/* Otherwise, copy the armature's pose channels into the caller-supplied pose */
- // is this needed anymore?
- //if (!m_mrdPose){
- // copy_pose (&m_mrdPose, m_pose, 0);
- //}
-
if (!*pose)
- copy_pose(pose, m_objArma->pose, 0);
+ game_copy_pose(pose, m_pose);
else
- extract_pose_from_pose(*pose, m_objArma->pose);
-
+ extract_pose_from_pose(*pose, m_pose);
}
short BL_ArmatureObject::GetActivePriority()
@@ -185,17 +193,17 @@ double BL_ArmatureObject::GetLastFrame()
return m_lastframe;
}
-bool BL_ArmatureObject::GetBoneMatrix(Bone* bone, MT_Matrix4x4& matrix) const
+bool BL_ArmatureObject::GetBoneMatrix(Bone* bone, MT_Matrix4x4& matrix)
{
- Object* par_arma = m_objArma;
- where_is_pose(par_arma);
- bPoseChannel *pchan= get_pose_channel(par_arma->pose, bone->name);
+ bPoseChannel *pchan;
- if(pchan) {
+ ApplyPose();
+ pchan = get_pose_channel(m_objArma->pose, bone->name);
+ if(pchan)
matrix.setValue(&pchan->pose_mat[0][0]);
- return true;
- }
- return false;
+ RestorePose();
+
+ return (pchan != NULL);
}
float BL_ArmatureObject::GetBoneLength(Bone* bone) const
diff --git a/source/gameengine/Converter/BL_ArmatureObject.h b/source/gameengine/Converter/BL_ArmatureObject.h
index 752bd5eb365..d68e37d9e37 100644
--- a/source/gameengine/Converter/BL_ArmatureObject.h
+++ b/source/gameengine/Converter/BL_ArmatureObject.h
@@ -59,7 +59,10 @@ public:
void GetMRDPose(struct bPose **pose);
void GetPose(struct bPose **pose);
void SetPose (struct bPose *pose);
+
void ApplyPose();
+ void RestorePose();
+
bool SetActiveAction(class BL_ActionActuator *act, short priority, double curtime);
struct bArmature * GetArmature() { return m_armature; }
@@ -69,7 +72,7 @@ public:
/// Retrieve the pose matrix for the specified bone.
/// Returns true on success.
- bool GetBoneMatrix(Bone* bone, MT_Matrix4x4& matrix) const;
+ bool GetBoneMatrix(Bone* bone, MT_Matrix4x4& matrix);
/// Returns the bone length. The end of the bone is in the local y direction.
float GetBoneLength(Bone* bone) const;
@@ -79,10 +82,13 @@ protected:
Object *m_objArma;
struct bArmature *m_armature;
struct bPose *m_pose;
- struct bPose *m_mrdPose;
+ struct bPose *m_armpose;
+ struct bPose *m_framePose;
double m_lastframe;
class BL_ActionActuator *m_activeAct;
short m_activePriority;
+
+ double m_lastapplyframe;
};
#endif
diff --git a/source/gameengine/Converter/BL_BlenderDataConversion.cpp b/source/gameengine/Converter/BL_BlenderDataConversion.cpp
index f04aa2eac16..dc2a14e1793 100644
--- a/source/gameengine/Converter/BL_BlenderDataConversion.cpp
+++ b/source/gameengine/Converter/BL_BlenderDataConversion.cpp
@@ -87,7 +87,10 @@
#include "DNA_action_types.h"
#include "BKE_main.h"
#include "BKE_global.h"
+#include "BKE_object.h"
+#include "BKE_scene.h"
#include "BL_SkinMeshObject.h"
+#include "BL_ShapeDeformer.h"
#include "BL_SkinDeformer.h"
#include "BL_MeshDeformer.h"
//#include "BL_ArmatureController.h"
@@ -126,6 +129,7 @@
#include "DNA_sound_types.h"
#include "DNA_key_types.h"
#include "DNA_armature_types.h"
+#include "DNA_object_force.h"
#include "MEM_guardedalloc.h"
#include "BKE_utildefines.h"
@@ -133,8 +137,12 @@
#include "BKE_mesh.h"
#include "MT_Point3.h"
+#include "BLI_arithb.h"
+
extern "C" {
- #include "BKE_customdata.h"
+#include "BKE_customdata.h"
+#include "BKE_cdderivedmesh.h"
+#include "BKE_DerivedMesh.h"
}
#include "BKE_material.h" /* give_current_material */
@@ -221,15 +229,16 @@ static unsigned int KX_Mcol2uint_new(MCol col)
static void SetDefaultFaceType(Scene* scene)
{
default_face_mode = TF_DYNAMIC;
- Base *base = static_cast<Base*>(scene->base.first);
- while(base)
+ Scene *sce;
+ Base *base;
+
+ for(SETLOOPER(scene,base))
{
if (base->object->type == OB_LAMP)
{
default_face_mode = TF_DYNAMIC|TF_LIGHT;
return;
}
- base = base->next;
}
}
@@ -300,38 +309,40 @@ static void GetRGB(short type,
typedef struct MTF_localLayer
{
MTFace *face;
- char *name;
+ const char *name;
}MTF_localLayer;
// ------------------------------------
BL_Material* ConvertMaterial(
- Mesh* mesh,
Material *mat,
MTFace* tface,
+ const char *tfaceName,
MFace* mface,
MCol* mmcol,
int lightlayer,
Object* blenderobj,
- MTF_localLayer *layers)
+ MTF_localLayer *layers,
+ bool glslmat)
{
//this needs some type of manager
BL_Material *material = new BL_Material();
- int numchan = -1;
+ int numchan = -1, texalpha = 0;
bool validmat = (mat!=0);
- bool validface = (mesh->mtface && tface);
+ bool validface = (tface!=0);
short type = 0;
if( validmat )
type = 1; // material color
material->IdMode = DEFAULT_BLENDER;
+ material->glslmat = (validmat)? glslmat: false;
// --------------------------------
if(validmat) {
// use vertex colors by explicitly setting
- if(mat->mode &MA_VERTEXCOLP)
+ if(mat->mode &MA_VERTEXCOLP || glslmat)
type = 0;
// use lighting?
@@ -361,12 +372,14 @@ BL_Material* ConvertMaterial(
if(i==0 && facetex ) {
Image*tmp = (Image*)(tface->tpage);
+
if(tmp) {
material->img[i] = tmp;
material->texname[i] = material->img[i]->id.name;
material->flag[i] |= ( tface->transp &TF_ALPHA )?USEALPHA:0;
material->flag[i] |= ( tface->transp &TF_ADD )?CALCALPHA:0;
- material->ras_mode|= ( tface->transp &(TF_ADD | TF_ALPHA))?TRANSP:0;
+ material->flag[i] |= MIPMAP;
+
if(material->img[i]->flag & IMA_REFLECT)
material->mapping[i].mapping |= USEREFL;
else
@@ -424,6 +437,8 @@ BL_Material* ConvertMaterial(
material->flag[i] |= ( mttmp->mapto & MAP_ALPHA )?TEXALPHA:0;
material->flag[i] |= ( mttmp->texflag& MTEX_NEGATIVE )?TEXNEG:0;
+ if(!glslmat && (material->flag[i] & TEXALPHA))
+ texalpha = 1;
}
}
else if(mttmp->tex->type == TEX_ENVMAP) {
@@ -508,6 +523,7 @@ BL_Material* ConvertMaterial(
}
}
}
+
// above one tex the switches here
// are not used
switch(valid_index) {
@@ -539,20 +555,11 @@ BL_Material* ConvertMaterial(
material->ref = mat->ref;
material->amb = mat->amb;
- // set alpha testing without z-sorting
- if( ( validface && (!tface->transp)) && mat->mode & MA_ZTRA) {
- // sets the RAS_IPolyMaterial::m_flag |RAS_FORCEALPHA
- // this is so we don't have the overhead of the z-sorting code
- material->ras_mode|=ALPHA_TEST;
- }
- else{
- // use regular z-sorting
- material->ras_mode |= ((mat->mode & MA_ZTRA) != 0)?ZSORT:0;
- }
- material->ras_mode |= ((mat->mode & MA_WIRE) != 0)?WIRE:0;
+ material->ras_mode |= (mat->mode & MA_WIRE)? WIRE: 0;
}
else {
int valid = 0;
+
// check for tface tex to fallback on
if( validface ){
@@ -566,7 +573,6 @@ BL_Material* ConvertMaterial(
material->mapping[0].mapping |= ( (material->img[0]->flag & IMA_REFLECT)!=0 )?USEREFL:0;
material->flag[0] |= ( tface->transp &TF_ALPHA )?USEALPHA:0;
material->flag[0] |= ( tface->transp &TF_ADD )?CALCALPHA:0;
- material->ras_mode|= ( tface->transp & (TF_ADD|TF_ALPHA))?TRANSP:0;
valid++;
}
}
@@ -585,6 +591,10 @@ BL_Material* ConvertMaterial(
}
MT_Point2 uv[4];
MT_Point2 uv2[4];
+ const char *uvName = "", *uv2Name = "";
+
+ uv[0]= uv[1]= uv[2]= uv[3]= MT_Point2(0.0f, 0.0f);
+ uv2[0]= uv2[1]= uv2[2]= uv2[3]= MT_Point2(0.0f, 0.0f);
if( validface ) {
@@ -593,12 +603,7 @@ BL_Material* ConvertMaterial(
(tface->mode & TF_INVISIBLE)
)?POLY_VIS:0;
- material->ras_mode |= ( (tface->mode & TF_DYNAMIC)!= 0 )?COLLIDER:0;
material->transp = tface->transp;
-
- if(tface->transp)
- material->ras_mode |= TRANSP;
-
material->tile = tface->tile;
material->mode = tface->mode;
@@ -608,16 +613,33 @@ BL_Material* ConvertMaterial(
if (mface->v4)
uv[3] = MT_Point2(tface->uv[3]);
+
+ uvName = tfaceName;
}
else {
// nothing at all
- material->ras_mode |= (COLLIDER|POLY_VIS| (validmat?0:USE_LIGHT));
+ material->ras_mode |= (POLY_VIS| (validmat?0:USE_LIGHT));
material->mode = default_face_mode;
material->transp = TF_SOLID;
material->tile = 0;
}
+ // with ztransp enabled, enforce alpha blending mode
+ if(validmat && (mat->mode & MA_ZTRA) && (material->transp == TF_SOLID))
+ material->transp = TF_ALPHA;
+ // always zsort alpha + add
+ if((material->transp == TF_ALPHA || material->transp == TF_ADD || texalpha) && (material->transp != TF_CLIP)) {
+ material->ras_mode |= ALPHA;
+ material->ras_mode |= (material->mode & TF_ALPHASORT)? ZSORT: 0;
+ }
+
+ // collider or not?
+ material->ras_mode |= (material->mode & TF_DYNAMIC)? COLLIDER: 0;
+
+ // these flags are irrelevant at this point, remove so they
+ // don't hurt material bucketing
+ material->mode &= ~(TF_DYNAMIC|TF_ALPHASORT|TF_TEX);
// get uv sets
if(validmat)
@@ -629,43 +651,43 @@ BL_Material* ConvertMaterial(
for (int vind = 0; vind<material->num_enabled; vind++)
{
BL_Mapping &map = material->mapping[vind];
+
if (map.uvCoName.IsEmpty())
isFirstSet = false;
else
{
- MT_Point2 uvSet[4];
for (int lay=0; lay<MAX_MTFACE; lay++)
{
MTF_localLayer& layer = layers[lay];
if (layer.face == 0) break;
-
- bool processed = false;
if (strcmp(map.uvCoName.ReadPtr(), layer.name)==0)
{
+ MT_Point2 uvSet[4];
+
uvSet[0] = MT_Point2(layer.face->uv[0]);
uvSet[1] = MT_Point2(layer.face->uv[1]);
uvSet[2] = MT_Point2(layer.face->uv[2]);
if (mface->v4)
uvSet[3] = MT_Point2(layer.face->uv[3]);
+ else
+ uvSet[3] = MT_Point2(0.0f, 0.0f);
- processed = true;
- }
-
- if (!processed) continue;
-
- if (isFirstSet)
- {
- uv[0] = uvSet[0]; uv[1] = uvSet[1];
- uv[2] = uvSet[2]; uv[3] = uvSet[3];
- isFirstSet = false;
- }
- else
- {
- uv2[0] = uvSet[0]; uv2[1] = uvSet[1];
- uv2[2] = uvSet[2]; uv2[3] = uvSet[3];
- map.mapping |= USECUSTOMUV;
+ if (isFirstSet)
+ {
+ uv[0] = uvSet[0]; uv[1] = uvSet[1];
+ uv[2] = uvSet[2]; uv[3] = uvSet[3];
+ isFirstSet = false;
+ uvName = layer.name;
+ }
+ else if(strcmp(layer.name, uvName) != 0)
+ {
+ uv2[0] = uvSet[0]; uv2[1] = uvSet[1];
+ uv2[2] = uvSet[2]; uv2[3] = uvSet[3];
+ map.mapping |= USECUSTOMUV;
+ uv2Name = layer.name;
+ }
}
}
}
@@ -685,11 +707,9 @@ BL_Material* ConvertMaterial(
}
material->SetConversionRGB(rgb);
- material->SetConversionUV(uv);
- material->SetConversionUV2(uv2);
+ material->SetConversionUV(uvName, uv);
+ material->SetConversionUV2(uv2Name, uv2);
-
- material->ras_mode |= (mface->v4==0)?TRIANGLE:0;
if(validmat)
material->matname =(mat->id.name);
@@ -699,399 +719,294 @@ BL_Material* ConvertMaterial(
}
-static void BL_ComputeTriTangentSpace(const MT_Vector3 &v1, const MT_Vector3 &v2, const MT_Vector3 &v3,
- const MT_Vector2 &uv1, const MT_Vector2 &uv2, const MT_Vector2 &uv3,
- MFace* mface, MT_Vector3 *tan1, MT_Vector3 *tan2)
-{
- MT_Vector3 dx1(v2 - v1), dx2(v3 - v1);
- MT_Vector2 duv1(uv2 - uv1), duv2(uv3 - uv1);
-
- MT_Scalar r = 1.0 / (duv1.x() * duv2.y() - duv2.x() * duv1.y());
- duv1 *= r;
- duv2 *= r;
- MT_Vector3 sdir(duv2.y() * dx1 - duv1.y() * dx2);
- MT_Vector3 tdir(duv1.x() * dx2 - duv2.x() * dx1);
-
- tan1[mface->v1] += sdir;
- tan1[mface->v2] += sdir;
- tan1[mface->v3] += sdir;
-
- tan2[mface->v1] += tdir;
- tan2[mface->v2] += tdir;
- tan2[mface->v3] += tdir;
-}
-
-static MT_Vector4* BL_ComputeMeshTangentSpace(Mesh* mesh)
-{
- MFace* mface = static_cast<MFace*>(mesh->mface);
- MTFace* tface = static_cast<MTFace*>(mesh->mtface);
-
- MT_Vector3 *tan1 = new MT_Vector3[mesh->totvert];
- MT_Vector3 *tan2 = new MT_Vector3[mesh->totvert];
-
- unsigned int v;
- for (v = 0; v < mesh->totvert; v++)
- {
- tan1[v] = MT_Vector3(0.0, 0.0, 0.0);
- tan2[v] = MT_Vector3(0.0, 0.0, 0.0);
- }
-
- for (unsigned int p = 0; p < mesh->totface; p++, mface++, tface++)
- {
- MT_Vector3 v1(mesh->mvert[mface->v1].co),
- v2(mesh->mvert[mface->v2].co),
- v3(mesh->mvert[mface->v3].co);
-
- MT_Vector2 uv1(tface->uv[0]),
- uv2(tface->uv[1]),
- uv3(tface->uv[2]);
-
- BL_ComputeTriTangentSpace(v1, v2, v3, uv1, uv2, uv3, mface, tan1, tan2);
- if (mface->v4)
- {
- MT_Vector3 v4(mesh->mvert[mface->v4].co);
- MT_Vector2 uv4(tface->uv[3]);
-
- BL_ComputeTriTangentSpace(v1, v3, v4, uv1, uv3, uv4, mface, tan1, tan2);
- }
- }
-
- MT_Vector4 *tangent = new MT_Vector4[mesh->totvert];
- for (v = 0; v < mesh->totvert; v++)
- {
- const MT_Vector3 no(mesh->mvert[v].no[0]/32767.0,
- mesh->mvert[v].no[1]/32767.0,
- mesh->mvert[v].no[2]/32767.0);
- // Gram-Schmidt orthogonalize
- MT_Vector3 t(tan1[v] - no.cross(no.cross(tan1[v])));
- if (!MT_fuzzyZero(t))
- t /= t.length();
-
- tangent[v].x() = t.x();
- tangent[v].y() = t.y();
- tangent[v].z() = t.z();
- // Calculate handedness
- tangent[v].w() = no.dot(tan1[v].cross(tan2[v])) < 0.0 ? -1.0 : 1.0;
- }
-
- delete [] tan1;
- delete [] tan2;
-
- return tangent;
-}
-
RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools* rendertools, KX_Scene* scene, KX_BlenderSceneConverter *converter)
{
RAS_MeshObject *meshobj;
- bool skinMesh = false;
-
+ bool skinMesh = false;
int lightlayer = blenderobj->lay;
-
- MFace* mface = static_cast<MFace*>(mesh->mface);
- MTFace* tface = static_cast<MTFace*>(mesh->mtface);
- MCol* mmcol = mesh->mcol;
- MT_assert(mface || mesh->totface == 0);
+ // Get DerivedMesh data
+ DerivedMesh *dm = CDDM_from_mesh(mesh, blenderobj);
+
+ MVert *mvert = dm->getVertArray(dm);
+ int totvert = dm->getNumVerts(dm);
+
+ MFace *mface = dm->getFaceArray(dm);
+ MTFace *tface = static_cast<MTFace*>(dm->getFaceDataArray(dm, CD_MTFACE));
+ MCol *mcol = static_cast<MCol*>(dm->getFaceDataArray(dm, CD_MCOL));
+ float (*tangent)[3] = NULL;
+ int totface = dm->getNumFaces(dm);
+ const char *tfaceName = "";
+
+ if(tface) {
+ DM_add_tangent_layer(dm);
+ tangent = (float(*)[3])dm->getFaceDataArray(dm, CD_TANGENT);
+ }
// Determine if we need to make a skinned mesh
- if (mesh->dvert){
- meshobj = new BL_SkinMeshObject(lightlayer);
+ if (mesh->dvert || mesh->key || ((blenderobj->gameflag & OB_SOFT_BODY) != 0))
+ {
+ meshobj = new BL_SkinMeshObject(mesh, lightlayer);
skinMesh = true;
}
- else {
- meshobj = new RAS_MeshObject(lightlayer);
- }
- MT_Vector4 *tangent = 0;
- if (tface)
- tangent = BL_ComputeMeshTangentSpace(mesh);
-
+ else
+ meshobj = new RAS_MeshObject(mesh, lightlayer);
// Extract avaiable layers
MTF_localLayer *layers = new MTF_localLayer[MAX_MTFACE];
- for (int lay=0; lay<MAX_MTFACE; lay++)
- {
+ for (int lay=0; lay<MAX_MTFACE; lay++) {
layers[lay].face = 0;
layers[lay].name = "";
}
-
int validLayers = 0;
- for (int i=0; i<mesh->fdata.totlayer; i++)
+ for (int i=0; i<dm->faceData.totlayer; i++)
{
- if (mesh->fdata.layers[i].type == CD_MTFACE)
+ if (dm->faceData.layers[i].type == CD_MTFACE)
{
assert(validLayers <= 8);
- layers[validLayers].face = (MTFace*)mesh->fdata.layers[i].data;;
- layers[validLayers].name = mesh->fdata.layers[i].name;
+ layers[validLayers].face = (MTFace*)(dm->faceData.layers[i].data);
+ layers[validLayers].name = dm->faceData.layers[i].name;
+ if(tface == layers[validLayers].face)
+ tfaceName = layers[validLayers].name;
validLayers++;
}
}
-
meshobj->SetName(mesh->id.name);
- meshobj->m_xyz_index_to_vertex_index_mapping.resize(mesh->totvert);
- for (int f=0;f<mesh->totface;f++,mface++)
+ meshobj->m_sharedvertex_map.resize(totvert);
+
+ for (int f=0;f<totface;f++,mface++)
{
-
+ Material* ma = 0;
bool collider = true;
-
- // only add valid polygons
- if (mface->v3)
- {
- MT_Point2 uv0(0.0,0.0),uv1(0.0,0.0),uv2(0.0,0.0),uv3(0.0,0.0);
- MT_Point2 uv20(0.0,0.0),uv21(0.0,0.0),uv22(0.0,0.0),uv23(0.0,0.0);
- // rgb3 is set from the adjoint face in a square
- unsigned int rgb0,rgb1,rgb2,rgb3 = 0;
- MT_Vector3 no0(mesh->mvert[mface->v1].no[0], mesh->mvert[mface->v1].no[1], mesh->mvert[mface->v1].no[2]),
- no1(mesh->mvert[mface->v2].no[0], mesh->mvert[mface->v2].no[1], mesh->mvert[mface->v2].no[2]),
- no2(mesh->mvert[mface->v3].no[0], mesh->mvert[mface->v3].no[1], mesh->mvert[mface->v3].no[2]),
- no3(0.0, 0.0, 0.0);
- MT_Point3 pt0(mesh->mvert[mface->v1].co),
- pt1(mesh->mvert[mface->v2].co),
- pt2(mesh->mvert[mface->v3].co),
- pt3(0.0, 0.0, 0.0);
- MT_Vector4 tan0(0.0, 0.0, 0.0, 0.0),
- tan1(0.0, 0.0, 0.0, 0.0),
- tan2(0.0, 0.0, 0.0, 0.0),
- tan3(0.0, 0.0, 0.0, 0.0);
-
- no0 /= 32767.0;
- no1 /= 32767.0;
- no2 /= 32767.0;
- if (mface->v4)
- {
- pt3 = MT_Point3(mesh->mvert[mface->v4].co);
- no3 = MT_Vector3(mesh->mvert[mface->v4].no[0], mesh->mvert[mface->v4].no[1], mesh->mvert[mface->v4].no[2]);
- no3 /= 32767.0;
+ MT_Point2 uv0(0.0,0.0),uv1(0.0,0.0),uv2(0.0,0.0),uv3(0.0,0.0);
+ MT_Point2 uv20(0.0,0.0),uv21(0.0,0.0),uv22(0.0,0.0),uv23(0.0,0.0);
+ unsigned int rgb0,rgb1,rgb2,rgb3 = 0;
+
+ MT_Point3 pt0, pt1, pt2, pt3;
+ MT_Vector3 no0(0,0,0), no1(0,0,0), no2(0,0,0), no3(0,0,0);
+ MT_Vector4 tan0(0,0,0,0), tan1(0,0,0,0), tan2(0,0,0,0), tan3(0,0,0,0);
+
+ /* get coordinates, normals and tangents */
+ pt0 = MT_Point3(mvert[mface->v1].co);
+ pt1 = MT_Point3(mvert[mface->v2].co);
+ pt2 = MT_Point3(mvert[mface->v3].co);
+ pt3 = (mface->v4)? MT_Point3(mvert[mface->v4].co): MT_Point3(0.0, 0.0, 0.0);
+
+ if(mface->flag & ME_SMOOTH) {
+ float n0[3], n1[3], n2[3], n3[3];
+
+ NormalShortToFloat(n0, mvert[mface->v1].no);
+ NormalShortToFloat(n1, mvert[mface->v2].no);
+ NormalShortToFloat(n2, mvert[mface->v3].no);
+ no0 = n0;
+ no1 = n1;
+ no2 = n2;
+
+ if(mface->v4) {
+ NormalShortToFloat(n3, mvert[mface->v4].no);
+ no3 = n3;
}
+ }
+ else {
+ float fno[3];
+
+ if(mface->v4)
+ CalcNormFloat4(mvert[mface->v1].co, mvert[mface->v2].co,
+ mvert[mface->v3].co, mvert[mface->v4].co, fno);
+ else
+ CalcNormFloat(mvert[mface->v1].co, mvert[mface->v2].co,
+ mvert[mface->v3].co, fno);
+
+ no0 = no1 = no2 = no3 = MT_Vector3(fno);
+ }
+
+ if(tangent) {
+ tan0 = tangent[f*4 + 0];
+ tan1 = tangent[f*4 + 1];
+ tan2 = tangent[f*4 + 2];
+
+ if (mface->v4)
+ tan3 = tangent[f*4 + 3];
+ }
+
+ /* get material */
+ ma = give_current_material(blenderobj, mface->mat_nr+1);
- if(!(mface->flag & ME_SMOOTH))
- {
- MT_Vector3 norm = ((pt1-pt0).cross(pt2-pt0)).safe_normalized();
- norm[0] = ((int) (10*norm[0]))/10.0;
- norm[1] = ((int) (10*norm[1]))/10.0;
- norm[2] = ((int) (10*norm[2]))/10.0;
- no0=no1=no2=no3= norm;
-
+ {
+ bool visible = true;
+ RAS_IPolyMaterial* polymat = NULL;
+ BL_Material *bl_mat = NULL;
+
+ if(converter->GetMaterials()) {
+ /* do Blender Multitexture and Blender GLSL materials */
+ unsigned int rgb[4];
+ MT_Point2 uv[4];
+
+ /* first is the BL_Material */
+ bl_mat = ConvertMaterial(ma, tface, tfaceName, mface, mcol,
+ lightlayer, blenderobj, layers, converter->GetGLSLMaterials());
+
+ bl_mat->material_index = (int)mface->mat_nr;
+
+ visible = ((bl_mat->ras_mode & POLY_VIS)!=0);
+ collider = ((bl_mat->ras_mode & COLLIDER)!=0);
+
+ /* vertex colors and uv's were stored in bl_mat temporarily */
+ bl_mat->GetConversionRGB(rgb);
+ rgb0 = rgb[0]; rgb1 = rgb[1];
+ rgb2 = rgb[2]; rgb3 = rgb[3];
+
+ bl_mat->GetConversionUV(uv);
+ uv0 = uv[0]; uv1 = uv[1];
+ uv2 = uv[2]; uv3 = uv[3];
+
+ bl_mat->GetConversionUV2(uv);
+ uv20 = uv[0]; uv21 = uv[1];
+ uv22 = uv[2]; uv23 = uv[3];
+
+ /* then the KX_BlenderMaterial */
+ polymat = new KX_BlenderMaterial(scene, bl_mat, skinMesh, lightlayer);
}
+ else {
+ /* do Texture Face materials */
+ Image* bima = (tface)? (Image*)tface->tpage: NULL;
+ STR_String imastr = (tface)? (bima? (bima)->id.name : "" ) : "";
- {
- Material* ma = 0;
- bool polyvisible = true;
- RAS_IPolyMaterial* polymat = NULL;
-
- if(converter->GetMaterials())
- {
- if(mesh->totcol > 1)
- ma = mesh->mat[mface->mat_nr];
- else
- ma = give_current_material(blenderobj, 1);
-
- BL_Material *bl_mat = ConvertMaterial(mesh, ma, tface, mface, mmcol, lightlayer, blenderobj, layers);
- // set the index were dealing with
- bl_mat->material_index = (int)mface->mat_nr;
-
- polyvisible = ((bl_mat->ras_mode & POLY_VIS)!=0);
- collider = ((bl_mat->ras_mode & COLLIDER)!=0);
+ char transp=0;
+ short mode=0, tile=0;
+ int tilexrep=4,tileyrep = 4;
+
+ if (bima) {
+ tilexrep = bima->xrep;
+ tileyrep = bima->yrep;
+ }
+
+ /* get tface properties if available */
+ if(tface) {
+ /* TF_DYNAMIC means the polygon is a collision face */
+ collider = ((tface->mode & TF_DYNAMIC) != 0);
+ transp = tface->transp;
+ tile = tface->tile;
+ mode = tface->mode;
- polymat = new KX_BlenderMaterial(scene, bl_mat, skinMesh, lightlayer, blenderobj );
- converter->RegisterBlenderMaterial(bl_mat);
+ visible = !((mface->flag & ME_HIDE)||(tface->mode & TF_INVISIBLE));
- unsigned int rgb[4];
- bl_mat->GetConversionRGB(rgb);
- rgb0 = rgb[0]; rgb1 = rgb[1];
- rgb2 = rgb[2]; rgb3 = rgb[3];
- MT_Point2 uv[4];
- bl_mat->GetConversionUV(uv);
- uv0 = uv[0]; uv1 = uv[1];
- uv2 = uv[2]; uv3 = uv[3];
-
- bl_mat->GetConversionUV2(uv);
- uv20 = uv[0]; uv21 = uv[1];
- uv22 = uv[2]; uv23 = uv[3];
-
- if(tangent){
- tan0 = tangent[mface->v1];
- tan1 = tangent[mface->v2];
- tan2 = tangent[mface->v3];
- if (mface->v4)
- tan3 = tangent[mface->v4];
- }
- // this is needed to free up memory afterwards
- converter->RegisterPolyMaterial(polymat);
+ uv0 = MT_Point2(tface->uv[0]);
+ uv1 = MT_Point2(tface->uv[1]);
+ uv2 = MT_Point2(tface->uv[2]);
+
+ if (mface->v4)
+ uv3 = MT_Point2(tface->uv[3]);
+ }
+ else {
+ /* no texfaces, set COLLSION true and everything else FALSE */
+ mode = default_face_mode;
+ transp = TF_SOLID;
+ tile = 0;
}
- else
- {
- ma = give_current_material(blenderobj, 1);
- Image* bima = ((mesh->mtface && tface) ? (Image*) tface->tpage : NULL);
-
- STR_String imastr =
- ((mesh->mtface && tface) ?
- (bima? (bima)->id.name : "" ) : "" );
-
- char transp=0;
- short mode=0, tile=0;
- int tilexrep=4,tileyrep = 4;
+ /* get vertex colors */
+ if (mcol) {
+ /* we have vertex colors */
+ rgb0 = KX_Mcol2uint_new(mcol[0]);
+ rgb1 = KX_Mcol2uint_new(mcol[1]);
+ rgb2 = KX_Mcol2uint_new(mcol[2]);
- if (bima)
- {
- tilexrep = bima->xrep;
- tileyrep = bima->yrep;
-
- }
+ if (mface->v4)
+ rgb3 = KX_Mcol2uint_new(mcol[3]);
+ }
+ else {
+ /* no vertex colors, take from material, otherwise white */
+ unsigned int color = 0xFFFFFFFFL;
- if (mesh->mtface && tface)
+ if (ma)
{
- // Use texface colors if available
- //TF_DYNAMIC means the polygon is a collision face
- collider = ((tface->mode & TF_DYNAMIC) != 0);
- transp = tface->transp;
- tile = tface->tile;
- mode = tface->mode;
-
- polyvisible = !((mface->flag & ME_HIDE)||(tface->mode & TF_INVISIBLE));
+ union
+ {
+ unsigned char cp[4];
+ unsigned int integer;
+ } col_converter;
- uv0 = MT_Point2(tface->uv[0]);
- uv1 = MT_Point2(tface->uv[1]);
- uv2 = MT_Point2(tface->uv[2]);
-
- if (mface->v4)
- uv3 = MT_Point2(tface->uv[3]);
- }
- else
- {
- // no texfaces, set COLLSION true and everything else FALSE
+ col_converter.cp[3] = (unsigned char) (ma->r*255.0);
+ col_converter.cp[2] = (unsigned char) (ma->g*255.0);
+ col_converter.cp[1] = (unsigned char) (ma->b*255.0);
+ col_converter.cp[0] = (unsigned char) (ma->alpha*255.0);
- mode = default_face_mode;
- transp = TF_SOLID;
- tile = 0;
+ color = col_converter.integer;
}
- if (mmcol)
- {
- // Use vertex colors
- rgb0 = KX_Mcol2uint_new(mmcol[0]);
- rgb1 = KX_Mcol2uint_new(mmcol[1]);
- rgb2 = KX_Mcol2uint_new(mmcol[2]);
-
- if (mface->v4)
- rgb3 = KX_Mcol2uint_new(mmcol[3]);
- }
- else {
- // no vertex colors: take from material if we have one,
- // otherwise set to white
- unsigned int color = 0xFFFFFFFFL;
-
- if (ma)
- {
- union
- {
- unsigned char cp[4];
- unsigned int integer;
- } col_converter;
-
- col_converter.cp[3] = (unsigned char) (ma->r*255.0);
- col_converter.cp[2] = (unsigned char) (ma->g*255.0);
- col_converter.cp[1] = (unsigned char) (ma->b*255.0);
- col_converter.cp[0] = (unsigned char) (ma->alpha*255.0);
-
- color = col_converter.integer;
- }
-
- rgb0 = KX_rgbaint2uint_new(color);
- rgb1 = KX_rgbaint2uint_new(color);
- rgb2 = KX_rgbaint2uint_new(color);
-
- if (mface->v4)
- rgb3 = KX_rgbaint2uint_new(color);
- }
+ rgb0 = KX_rgbaint2uint_new(color);
+ rgb1 = KX_rgbaint2uint_new(color);
+ rgb2 = KX_rgbaint2uint_new(color);
- bool istriangle = (mface->v4==0);
- bool zsort = ma?(ma->mode & MA_ZTRA) != 0:false;
-
- polymat = new KX_PolygonMaterial(imastr, ma,
- tile, tilexrep, tileyrep,
- mode, transp, zsort, lightlayer, istriangle, blenderobj, tface, (unsigned int*)mmcol);
-
- if (ma)
- {
- polymat->m_specular = MT_Vector3(ma->specr, ma->specg, ma->specb)*ma->spec;
- polymat->m_shininess = (float)ma->har/4.0; // 0 < ma->har <= 512
- polymat->m_diffuse = MT_Vector3(ma->r, ma->g, ma->b)*(ma->emit + ma->ref);
-
- } else
- {
- polymat->m_specular = MT_Vector3(0.0f,0.0f,0.0f);
- polymat->m_shininess = 35.0;
- }
- // this is needed to free up memory afterwards
- converter->RegisterPolyMaterial(polymat);
-
+ if (mface->v4)
+ rgb3 = KX_rgbaint2uint_new(color);
}
-
- RAS_MaterialBucket* bucket = scene->FindBucket(polymat);
-
- int nverts = mface->v4?4:3;
- int vtxarray = meshobj->FindVertexArray(nverts,polymat);
- RAS_Polygon* poly = new RAS_Polygon(bucket,polyvisible,nverts,vtxarray);
- if (skinMesh) {
- int d1, d2, d3, d4=0;
- bool flat;
-
- /* If the face is set to solid, all fnors are the same */
- if (mface->flag & ME_SMOOTH)
- flat = false;
- else
- flat = true;
-
- d1=((BL_SkinMeshObject*)meshobj)->FindOrAddDeform(vtxarray, mface->v1, &mesh->dvert[mface->v1], polymat);
- d2=((BL_SkinMeshObject*)meshobj)->FindOrAddDeform(vtxarray, mface->v2, &mesh->dvert[mface->v2], polymat);
- d3=((BL_SkinMeshObject*)meshobj)->FindOrAddDeform(vtxarray, mface->v3, &mesh->dvert[mface->v3], polymat);
- if (nverts==4)
- d4=((BL_SkinMeshObject*)meshobj)->FindOrAddDeform(vtxarray, mface->v4, &mesh->dvert[mface->v4], polymat);
- poly->SetVertex(0,((BL_SkinMeshObject*)meshobj)->FindOrAddVertex(vtxarray,pt0,uv0,uv20,tan0,rgb0,no0,d1,flat, polymat));
- poly->SetVertex(1,((BL_SkinMeshObject*)meshobj)->FindOrAddVertex(vtxarray,pt1,uv1,uv21,tan1,rgb1,no1,d2,flat, polymat));
- poly->SetVertex(2,((BL_SkinMeshObject*)meshobj)->FindOrAddVertex(vtxarray,pt2,uv2,uv22,tan2,rgb2,no2,d3,flat, polymat));
- if (nverts==4)
- poly->SetVertex(3,((BL_SkinMeshObject*)meshobj)->FindOrAddVertex(vtxarray,pt3,uv3,uv23,tan3,rgb3,no3,d4, flat,polymat));
+
+ // only zsort alpha + add
+ bool alpha = (transp == TF_ALPHA || transp == TF_ADD);
+ bool zsort = (mode & TF_ALPHASORT)? alpha: 0;
+
+ polymat = new KX_PolygonMaterial(imastr, ma,
+ tile, tilexrep, tileyrep,
+ mode, transp, alpha, zsort, lightlayer, tface, (unsigned int*)mcol);
+
+ if (ma) {
+ polymat->m_specular = MT_Vector3(ma->specr, ma->specg, ma->specb)*ma->spec;
+ polymat->m_shininess = (float)ma->har/4.0; // 0 < ma->har <= 512
+ polymat->m_diffuse = MT_Vector3(ma->r, ma->g, ma->b)*(ma->emit + ma->ref);
}
- else
- {
- poly->SetVertex(0,meshobj->FindOrAddVertex(vtxarray,pt0,uv0,uv20,tan0,rgb0,no0,polymat,mface->v1));
- poly->SetVertex(1,meshobj->FindOrAddVertex(vtxarray,pt1,uv1,uv21,tan1,rgb1,no1,polymat,mface->v2));
- poly->SetVertex(2,meshobj->FindOrAddVertex(vtxarray,pt2,uv2,uv22,tan2,rgb2,no2,polymat,mface->v3));
- if (nverts==4)
- poly->SetVertex(3,meshobj->FindOrAddVertex(vtxarray,pt3,uv3,uv23,tan3,rgb3,no3,polymat,mface->v4));
+ else {
+ polymat->m_specular = MT_Vector3(0.0f,0.0f,0.0f);
+ polymat->m_shininess = 35.0;
}
- meshobj->AddPolygon(poly);
- if (poly->IsCollider())
- {
- RAS_TriangleIndex idx;
- idx.m_index[0] = mface->v1;
- idx.m_index[1] = mface->v2;
- idx.m_index[2] = mface->v3;
- idx.m_collider = collider;
- meshobj->m_triangle_indices.push_back(idx);
- if (nverts==4)
- {
- idx.m_index[0] = mface->v1;
- idx.m_index[1] = mface->v3;
- idx.m_index[2] = mface->v4;
- idx.m_collider = collider;
- meshobj->m_triangle_indices.push_back(idx);
- }
+ }
+
+ /* mark face as flat, so vertices are split */
+ bool flat = (mface->flag & ME_SMOOTH) == 0;
+
+ // see if a bucket was reused or a new one was created
+ // this way only one KX_BlenderMaterial object has to exist per bucket
+ bool bucketCreated;
+ RAS_MaterialBucket* bucket = scene->FindBucket(polymat, bucketCreated);
+ if (bucketCreated) {
+ // this is needed to free up memory afterwards
+ converter->RegisterPolyMaterial(polymat);
+ if(converter->GetMaterials()) {
+ converter->RegisterBlenderMaterial(bl_mat);
}
-
-// poly->SetVisibleWireframeEdges(mface->edcode);
- poly->SetCollider(collider);
+ } else {
+ // delete the material objects since they are no longer needed
+ // from now on, use the polygon material from the material bucket
+ delete polymat;
+ if(converter->GetMaterials()) {
+ delete bl_mat;
+ }
+ polymat = bucket->GetPolyMaterial();
}
+
+ int nverts = (mface->v4)? 4: 3;
+ RAS_Polygon *poly = meshobj->AddPolygon(bucket, nverts);
+
+ poly->SetVisible(visible);
+ poly->SetCollider(collider);
+ //poly->SetEdgeCode(mface->edcode);
+
+ meshobj->AddVertex(poly,0,pt0,uv0,uv20,tan0,rgb0,no0,flat,mface->v1);
+ meshobj->AddVertex(poly,1,pt1,uv1,uv21,tan1,rgb1,no1,flat,mface->v2);
+ meshobj->AddVertex(poly,2,pt2,uv2,uv22,tan2,rgb2,no2,flat,mface->v3);
+
+ if (nverts==4)
+ meshobj->AddVertex(poly,3,pt3,uv3,uv23,tan3,rgb3,no3,flat,mface->v4);
}
+
if (tface)
tface++;
- if (mmcol)
- mmcol+=4;
+ if (mcol)
+ mcol+=4;
for (int lay=0; lay<MAX_MTFACE; lay++)
{
@@ -1101,19 +1016,18 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools*
layer.face++;
}
}
- meshobj->UpdateMaterialList();
+ meshobj->m_sharedvertex_map.clear();
// pre calculate texture generation
- for(RAS_MaterialBucket::Set::iterator mit = meshobj->GetFirstMaterial();
+ for(list<RAS_MeshMaterial>::iterator mit = meshobj->GetFirstMaterial();
mit != meshobj->GetLastMaterial(); ++ mit) {
- (*mit)->GetPolyMaterial()->OnConstruction();
+ mit->m_bucket->GetPolyMaterial()->OnConstruction();
}
- if(tangent)
- delete [] tangent;
-
if (layers)
delete []layers;
+
+ dm->release(dm);
return meshobj;
}
@@ -1367,6 +1281,10 @@ void BL_CreatePhysicsObjectNew(KX_GameObject* gameobj,
//int userigidbody = SYS_GetCommandLineInt(syshandle,"norigidbody",0);
//bool bRigidBody = (userigidbody == 0);
+ // object has physics representation?
+ if (!(blenderobject->gameflag & OB_COLLISION))
+ return;
+
// get Root Parent of blenderobject
struct Object* parent= blenderobject->parent;
while(parent && parent->parent) {
@@ -1398,19 +1316,97 @@ void BL_CreatePhysicsObjectNew(KX_GameObject* gameobj,
objprop.m_isCompoundChild = isCompoundChild;
objprop.m_hasCompoundChildren = (blenderobject->gameflag & OB_CHILD) != 0;
-
- if ((objprop.m_isactor = (blenderobject->gameflag & OB_ACTOR)!=0))
+ objprop.m_margin = blenderobject->margin;
+ // ACTOR is now a separate feature
+ objprop.m_isactor = (blenderobject->gameflag & OB_ACTOR)!=0;
+ objprop.m_dyna = (blenderobject->gameflag & OB_DYNAMIC) != 0;
+ objprop.m_softbody = (blenderobject->gameflag & OB_SOFT_BODY) != 0;
+ objprop.m_angular_rigidbody = (blenderobject->gameflag & OB_RIGID_BODY) != 0;
+
+ if (objprop.m_softbody)
{
- objprop.m_dyna = (blenderobject->gameflag & OB_DYNAMIC) != 0;
- objprop.m_angular_rigidbody = (blenderobject->gameflag & OB_RIGID_BODY) != 0;
- objprop.m_ghost = (blenderobject->gameflag & OB_GHOST) != 0;
- objprop.m_disableSleeping = (blenderobject->gameflag & OB_COLLISION_RESPONSE) != 0;//abuse the OB_COLLISION_RESPONSE flag
- } else {
- objprop.m_dyna = false;
- objprop.m_angular_rigidbody = false;
- objprop.m_ghost = false;
- objprop.m_disableSleeping = false;
+ ///for game soft bodies
+ if (blenderobject->bsoft)
+ {
+ objprop.m_gamesoftFlag = blenderobject->bsoft->flag;
+ ///////////////////
+ objprop.m_soft_linStiff = blenderobject->bsoft->linStiff;
+ objprop.m_soft_angStiff = blenderobject->bsoft->angStiff; /* angular stiffness 0..1 */
+ objprop.m_soft_volume= blenderobject->bsoft->volume; /* volume preservation 0..1 */
+
+ objprop.m_soft_viterations= blenderobject->bsoft->viterations; /* Velocities solver iterations */
+ objprop.m_soft_piterations= blenderobject->bsoft->piterations; /* Positions solver iterations */
+ objprop.m_soft_diterations= blenderobject->bsoft->diterations; /* Drift solver iterations */
+ objprop.m_soft_citerations= blenderobject->bsoft->citerations; /* Cluster solver iterations */
+
+ objprop.m_soft_kSRHR_CL= blenderobject->bsoft->kSRHR_CL; /* Soft vs rigid hardness [0,1] (cluster only) */
+ objprop.m_soft_kSKHR_CL= blenderobject->bsoft->kSKHR_CL; /* Soft vs kinetic hardness [0,1] (cluster only) */
+ objprop.m_soft_kSSHR_CL= blenderobject->bsoft->kSSHR_CL; /* Soft vs soft hardness [0,1] (cluster only) */
+ objprop.m_soft_kSR_SPLT_CL= blenderobject->bsoft->kSR_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
+
+ objprop.m_soft_kSK_SPLT_CL= blenderobject->bsoft->kSK_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
+ objprop.m_soft_kSS_SPLT_CL= blenderobject->bsoft->kSS_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
+ objprop.m_soft_kVCF= blenderobject->bsoft->kVCF; /* Velocities correction factor (Baumgarte) */
+ objprop.m_soft_kDP= blenderobject->bsoft->kDP; /* Damping coefficient [0,1] */
+
+ objprop.m_soft_kDG= blenderobject->bsoft->kDG; /* Drag coefficient [0,+inf] */
+ objprop.m_soft_kLF= blenderobject->bsoft->kLF; /* Lift coefficient [0,+inf] */
+ objprop.m_soft_kPR= blenderobject->bsoft->kPR; /* Pressure coefficient [-inf,+inf] */
+ objprop.m_soft_kVC= blenderobject->bsoft->kVC; /* Volume conversation coefficient [0,+inf] */
+
+ objprop.m_soft_kDF= blenderobject->bsoft->kDF; /* Dynamic friction coefficient [0,1] */
+ objprop.m_soft_kMT= blenderobject->bsoft->kMT; /* Pose matching coefficient [0,1] */
+ objprop.m_soft_kCHR= blenderobject->bsoft->kCHR; /* Rigid contacts hardness [0,1] */
+ objprop.m_soft_kKHR= blenderobject->bsoft->kKHR; /* Kinetic contacts hardness [0,1] */
+
+ objprop.m_soft_kSHR= blenderobject->bsoft->kSHR; /* Soft contacts hardness [0,1] */
+ objprop.m_soft_kAHR= blenderobject->bsoft->kAHR; /* Anchors hardness [0,1] */
+ objprop.m_soft_collisionflags= blenderobject->bsoft->collisionflags; /* Vertex/Face or Signed Distance Field(SDF) or Clusters, Soft versus Soft or Rigid */
+ objprop.m_soft_numclusteriterations= blenderobject->bsoft->numclusteriterations; /* number of iterations to refine collision clusters*/
+
+ } else
+ {
+ objprop.m_gamesoftFlag = OB_BSB_BENDING_CONSTRAINTS | OB_BSB_SHAPE_MATCHING | OB_BSB_AERO_VPOINT;
+
+ objprop.m_soft_linStiff = 0.5;;
+ objprop.m_soft_angStiff = 1.f; /* angular stiffness 0..1 */
+ objprop.m_soft_volume= 1.f; /* volume preservation 0..1 */
+
+
+ objprop.m_soft_viterations= 0;
+ objprop.m_soft_piterations= 1;
+ objprop.m_soft_diterations= 0;
+ objprop.m_soft_citerations= 4;
+
+ objprop.m_soft_kSRHR_CL= 0.1f;
+ objprop.m_soft_kSKHR_CL= 1.f;
+ objprop.m_soft_kSSHR_CL= 0.5;
+ objprop.m_soft_kSR_SPLT_CL= 0.5f;
+
+ objprop.m_soft_kSK_SPLT_CL= 0.5f;
+ objprop.m_soft_kSS_SPLT_CL= 0.5f;
+ objprop.m_soft_kVCF= 1;
+ objprop.m_soft_kDP= 0;
+
+ objprop.m_soft_kDG= 0;
+ objprop.m_soft_kLF= 0;
+ objprop.m_soft_kPR= 0;
+ objprop.m_soft_kVC= 0;
+
+ objprop.m_soft_kDF= 0.2f;
+ objprop.m_soft_kMT= 0.05f;
+ objprop.m_soft_kCHR= 1.0f;
+ objprop.m_soft_kKHR= 0.1f;
+
+ objprop.m_soft_kSHR= 1.f;
+ objprop.m_soft_kAHR= 0.7f;
+ objprop.m_soft_collisionflags= OB_BSB_COL_SDF_RS + OB_BSB_COL_VF_SS;
+ objprop.m_soft_numclusteriterations= 16;
+ }
}
+
+ objprop.m_ghost = (blenderobject->gameflag & OB_GHOST) != 0;
+ objprop.m_disableSleeping = (blenderobject->gameflag & OB_COLLISION_RESPONSE) != 0;//abuse the OB_COLLISION_RESPONSE flag
//mmm, for now, taks this for the size of the dynamicobject
// Blender uses inertia for radius of dynamic object
objprop.m_radius = blenderobject->inertia;
@@ -1418,6 +1414,12 @@ void BL_CreatePhysicsObjectNew(KX_GameObject* gameobj,
objprop.m_dynamic_parent=NULL;
objprop.m_isdeformable = ((blenderobject->gameflag2 & 2)) != 0;
objprop.m_boundclass = objprop.m_dyna?KX_BOUNDSPHERE:KX_BOUNDMESH;
+
+ if ((blenderobject->gameflag & OB_SOFT_BODY) && !(blenderobject->gameflag & OB_BOUNDS))
+ {
+ objprop.m_boundclass = KX_BOUNDMESH;
+ }
+
KX_BoxBounds bb;
my_get_local_bounds(blenderobject,objprop.m_boundobject.box.m_center,bb.m_extends);
if (blenderobject->gameflag & OB_BOUNDS)
@@ -1511,14 +1513,15 @@ void BL_CreatePhysicsObjectNew(KX_GameObject* gameobj,
default:
break;
}
-
+ delete shapeprops;
+ delete smmaterial;
}
-static KX_LightObject *gamelight_from_blamp(Lamp *la, unsigned int layerflag, KX_Scene *kxscene, RAS_IRenderTools *rendertools, KX_BlenderSceneConverter *converter) {
+static KX_LightObject *gamelight_from_blamp(Object *ob, Lamp *la, unsigned int layerflag, KX_Scene *kxscene, RAS_IRenderTools *rendertools, KX_BlenderSceneConverter *converter) {
RAS_LightObject lightobj;
KX_LightObject *gamelight;
@@ -1550,15 +1553,18 @@ static KX_LightObject *gamelight_from_blamp(Lamp *la, unsigned int layerflag, KX
} else {
lightobj.m_type = RAS_LightObject::LIGHT_NORMAL;
}
-
- gamelight = new KX_LightObject(kxscene, KX_Scene::m_callbacks, rendertools, lightobj);
+
+ gamelight = new KX_LightObject(kxscene, KX_Scene::m_callbacks, rendertools,
+ lightobj, converter->GetGLSLMaterials());
+
BL_ConvertLampIpos(la, gamelight, converter);
return gamelight;
}
-static KX_Camera *gamecamera_from_bcamera(Camera *ca, KX_Scene *kxscene, KX_BlenderSceneConverter *converter) {
- RAS_CameraData camdata(ca->lens, ca->clipsta, ca->clipend, ca->type == CAM_PERSP);
+static KX_Camera *gamecamera_from_bcamera(Object *ob, KX_Scene *kxscene, KX_BlenderSceneConverter *converter) {
+ Camera* ca = static_cast<Camera*>(ob->data);
+ RAS_CameraData camdata(ca->lens, ca->clipsta, ca->clipend, ca->type == CAM_PERSP, dof_camera(ob));
KX_Camera *gamecamera;
gamecamera= new KX_Camera(kxscene, KX_Scene::m_callbacks, camdata);
@@ -1582,21 +1588,22 @@ static KX_GameObject *gameobject_from_blenderobject(
{
case OB_LAMP:
{
- KX_LightObject* gamelight= gamelight_from_blamp(static_cast<Lamp*>(ob->data), ob->lay, kxscene, rendertools, converter);
+ KX_LightObject* gamelight= gamelight_from_blamp(ob, static_cast<Lamp*>(ob->data), ob->lay, kxscene, rendertools, converter);
gameobj = gamelight;
gamelight->AddRef();
kxscene->GetLightList()->Add(gamelight);
-
+
break;
}
case OB_CAMERA:
{
- KX_Camera* gamecamera = gamecamera_from_bcamera(static_cast<Camera*>(ob->data), kxscene, converter);
+ KX_Camera* gamecamera = gamecamera_from_bcamera(ob, kxscene, converter);
gameobj = gamecamera;
- gamecamera->AddRef();
+ //don't add a reference: the camera list in kxscene->m_cameras is not released at the end
+ //gamecamera->AddRef();
kxscene->AddCamera(gamecamera);
break;
@@ -1617,7 +1624,7 @@ static KX_GameObject *gameobject_from_blenderobject(
// needed for python scripting
kxscene->GetLogicManager()->RegisterMeshName(meshobj->GetName(),meshobj);
- gameobj = new BL_DeformableGameObject(kxscene,KX_Scene::m_callbacks);
+ gameobj = new BL_DeformableGameObject(ob,kxscene,KX_Scene::m_callbacks);
// set transformation
gameobj->AddMesh(meshobj);
@@ -1628,14 +1635,30 @@ static KX_GameObject *gameobject_from_blenderobject(
((ob->gameflag2 & OB_NEVER_DO_ACTIVITY_CULLING)!=0);
gameobj->SetIgnoreActivityCulling(ignoreActivityCulling);
- // If this is a skin object, make Skin Controller
- if (ob->parent && ob->parent->type == OB_ARMATURE && ob->partype==PARSKEL && ((Mesh*)ob->data)->dvert){
- BL_SkinDeformer *dcont = new BL_SkinDeformer(ob, (BL_SkinMeshObject*)meshobj );
- ((BL_DeformableGameObject*)gameobj)->m_pDeformer = dcont;
- }
- else if (((Mesh*)ob->data)->dvert){
- BL_MeshDeformer *dcont = new BL_MeshDeformer(ob, (BL_SkinMeshObject*)meshobj );
- ((BL_DeformableGameObject*)gameobj)->m_pDeformer = dcont;
+ // two options exists for deform: shape keys and armature
+ // only support relative shape key
+ bool bHasShapeKey = mesh->key != NULL && mesh->key->type==KEY_RELATIVE;
+ bool bHasDvert = mesh->dvert != NULL && ob->defbase.first;
+ bool bHasArmature = (ob->parent && ob->parent->type == OB_ARMATURE && ob->partype==PARSKEL && bHasDvert);
+
+ if (bHasShapeKey) {
+ // not that we can have shape keys without dvert!
+ BL_ShapeDeformer *dcont = new BL_ShapeDeformer((BL_DeformableGameObject*)gameobj,
+ ob, (BL_SkinMeshObject*)meshobj);
+ ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
+ if (bHasArmature)
+ dcont->LoadShapeDrivers(ob->parent);
+ } else if (bHasArmature) {
+ BL_SkinDeformer *dcont = new BL_SkinDeformer((BL_DeformableGameObject*)gameobj,
+ ob, (BL_SkinMeshObject*)meshobj);
+ ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
+ } else if (bHasDvert) {
+ // this case correspond to a mesh that can potentially deform but not with the
+ // object to which it is attached for the moment. A skin mesh was created in
+ // BL_ConvertMesh() so must create a deformer too!
+ BL_MeshDeformer *dcont = new BL_MeshDeformer((BL_DeformableGameObject*)gameobj,
+ ob, (BL_SkinMeshObject*)meshobj);
+ ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
}
MT_Point3 min = MT_Point3(center) - MT_Vector3(extents);
@@ -1665,7 +1688,14 @@ static KX_GameObject *gameobject_from_blenderobject(
break;
}
}
-
+ if (gameobj)
+ {
+ gameobj->SetPhysicsEnvironment(kxscene->GetPhysicsEnvironment());
+ gameobj->SetLayer(ob->lay);
+ gameobj->SetBlenderObject(ob);
+ /* set the visibility state based on the objects render option in the outliner */
+ if(ob->restrictflag & OB_RESTRICT_RENDER) gameobj->SetVisible(0, 0);
+ }
return gameobj;
}
@@ -1674,20 +1704,6 @@ struct parentChildLink {
SG_Node* m_gamechildnode;
};
- /**
- * Find the specified scene by name, or the first
- * scene if nothing matches (shouldn't happen).
- */
-static struct Scene *GetSceneForName(struct Main *maggie, const STR_String& scenename) {
- Scene *sce;
-
- for (sce= (Scene*) maggie->scene.first; sce; sce= (Scene*) sce->id.next)
- if (scenename == (sce->id.name+2))
- return sce;
-
- return (Scene*) maggie->scene.first;
-}
-
#include "DNA_constraint_types.h"
//XXX #include "BIF_editconstraint.h"
@@ -1770,7 +1786,7 @@ KX_GameObject* getGameOb(STR_String busc,CListValue* sumolist){
return 0;
}
-#include "BLI_arithb.h"
+
// convert blender objects into ketsji gameobjects
void BL_ConvertBlenderObjects(struct Main* maggie,
const STR_String& scenename,
@@ -1786,7 +1802,10 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
)
{
- Scene *blenderscene = GetSceneForName(maggie, scenename);
+ Scene *blenderscene = converter->GetBlenderSceneForName(scenename);
+ // for SETLOOPER
+ Scene *sce;
+ Base *base;
// Get the frame settings of the canvas.
// Get the aspect ratio of the canvas as designed by the user.
@@ -1795,7 +1814,10 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
int aspect_width;
int aspect_height;
vector<MT_Vector3> inivel,iniang;
-
+ set<Group*> grouplist; // list of groups to be converted
+ set<Object*> allblobj; // all objects converted
+ set<Object*> groupobj; // objects from groups (never in active layer)
+
if (alwaysUseExpandFraming) {
frame_type = RAS_FrameSettings::e_frame_extend;
aspect_width = canvas->GetWidth();
@@ -1842,6 +1864,7 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
vector<parentChildLink> vec_parent_child;
CListValue* objectlist = kxscene->GetObjectList();
+ CListValue* inactivelist = kxscene->GetInactiveList();
CListValue* parentlist = kxscene->GetRootParentList();
SCA_LogicManager* logicmgr = kxscene->GetLogicManager();
@@ -1849,7 +1872,7 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
CListValue* logicbrick_conversionlist = new CListValue();
- SG_TreeFactory tf;
+ //SG_TreeFactory tf;
// Convert actions to actionmap
bAction *curAct;
@@ -1859,11 +1882,15 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
}
SetDefaultFaceType(blenderscene);
-
- Base *base = static_cast<Base*>(blenderscene->base.first);
- while(base)
+ // Let's support scene set.
+ // Beware of name conflict in linked data, it will not crash but will create confusion
+ // in Python scripting and in certain actuators (replace mesh). Linked scene *should* have
+ // no conflicting name for Object, Object data and Action.
+ for (SETLOOPER(blenderscene, base))
{
Object* blenderobject = base->object;
+ allblobj.insert(blenderobject);
+
KX_GameObject* gameobj = gameobject_from_blenderobject(
base->object,
kxscene,
@@ -1877,7 +1904,7 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
if (converter->addInitFromFrame)
if (!isInActiveLayer)
addobj=false;
-
+
if (gameobj&&addobj)
{
MT_Point3 posPrev;
@@ -1929,10 +1956,8 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
gameobj->NodeUpdateGS(0,true);
BL_ConvertIpos(blenderobject,gameobj,converter);
- // TODO: expand to multiple ipos per mesh
- Material *mat = give_current_material(blenderobject, 1);
- if(mat) BL_ConvertMaterialIpos(mat, gameobj, converter);
-
+ BL_ConvertMaterialIpos(blenderobject, gameobj, converter);
+
sumolist->Add(gameobj->AddRef());
BL_ConvertProperties(blenderobject,gameobj,timemgr,kxscene,isInActiveLayer);
@@ -1961,7 +1986,29 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
float* fl = (float*) blenderobject->parentinv;
MT_Transform parinvtrans(fl);
parentinversenode->SetLocalPosition(parinvtrans.getOrigin());
- parentinversenode->SetLocalOrientation(parinvtrans.getBasis());
+ // problem here: the parent inverse transform combines scaling and rotation
+ // in the basis but the scenegraph needs separate rotation and scaling.
+ // This is not important for OpenGL (it uses 4x4 matrix) but it is important
+ // for the physic engine that needs a separate scaling
+ //parentinversenode->SetLocalOrientation(parinvtrans.getBasis());
+
+ // Extract the rotation and the scaling from the basis
+ MT_Matrix3x3 ori(parinvtrans.getBasis());
+ MT_Vector3 x(ori.getColumn(0));
+ MT_Vector3 y(ori.getColumn(1));
+ MT_Vector3 z(ori.getColumn(2));
+ MT_Vector3 scale(x.length(), y.length(), z.length());
+ if (!MT_fuzzyZero(scale[0]))
+ x /= scale[0];
+ if (!MT_fuzzyZero(scale[1]))
+ y /= scale[1];
+ if (!MT_fuzzyZero(scale[2]))
+ z /= scale[2];
+ ori.setColumn(0, x);
+ ori.setColumn(1, y);
+ ori.setColumn(2, z);
+ parentinversenode->SetLocalOrientation(ori);
+ parentinversenode->SetLocalScale(scale);
parentinversenode->AddChild(gameobj->GetSGNode());
}
@@ -1969,8 +2016,8 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
// needed for python scripting
logicmgr->RegisterGameObjectName(gameobj->GetName(),gameobj);
- // needed for dynamic object morphing
- logicmgr->RegisterGameObj(gameobj, blenderobject);
+ // needed for group duplication
+ logicmgr->RegisterGameObj(blenderobject, gameobj);
for (int i = 0; i < gameobj->GetMeshCount(); i++)
logicmgr->RegisterGameMeshName(gameobj->GetMesh(i)->GetName(), blenderobject);
@@ -1987,40 +2034,258 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
if (isInActiveLayer)
{
objectlist->Add(gameobj->AddRef());
- tf.Add(gameobj->GetSGNode());
+ //tf.Add(gameobj->GetSGNode());
gameobj->NodeUpdateGS(0,true);
- gameobj->Bucketize();
-
+ gameobj->AddMeshUser();
+
}
+ else
+ {
+ //we must store this object otherwise it will be deleted
+ //at the end of this function if it is not a root object
+ inactivelist->Add(gameobj->AddRef());
+ }
+ if (gameobj->IsDupliGroup())
+ grouplist.insert(blenderobject->dup_group);
if (converter->addInitFromFrame){
gameobj->NodeSetLocalPosition(posPrev);
gameobj->NodeSetLocalOrientation(angor);
}
}
-
- base = base->next;
+ /* Note about memory leak issues:
+ When a CValue derived class is created, m_refcount is initialized to 1
+ so the class must be released after being used to make sure that it won't
+ hang in memory. If the object needs to be stored for a long time,
+ use AddRef() so that this Release() does not free the object.
+ Make sure that for any AddRef() there is a Release()!!!!
+ Do the same for any object derived from CValue, CExpression and NG_NetworkMessage
+ */
+ if (gameobj)
+ gameobj->Release();
+
+ }
+
+ if (!grouplist.empty())
+ {
+ // now convert the group referenced by dupli group object
+ // keep track of all groups already converted
+ set<Group*> allgrouplist = grouplist;
+ set<Group*> tempglist;
+ // recurse
+ while (!grouplist.empty())
+ {
+ set<Group*>::iterator git;
+ tempglist.clear();
+ tempglist.swap(grouplist);
+ for (git=tempglist.begin(); git!=tempglist.end(); git++)
+ {
+ Group* group = *git;
+ GroupObject* go;
+ for(go=(GroupObject*)group->gobject.first; go; go=(GroupObject*)go->next)
+ {
+ Object* blenderobject = go->ob;
+ if (converter->FindGameObject(blenderobject) == NULL)
+ {
+ allblobj.insert(blenderobject);
+ groupobj.insert(blenderobject);
+ KX_GameObject* gameobj = gameobject_from_blenderobject(
+ blenderobject,
+ kxscene,
+ rendertools,
+ converter,
+ blenderscene);
+
+ // this code is copied from above except that
+ // object from groups are never in active layer
+ bool isInActiveLayer = false;
+ bool addobj=true;
+
+ if (converter->addInitFromFrame)
+ if (!isInActiveLayer)
+ addobj=false;
+
+ if (gameobj&&addobj)
+ {
+ MT_Point3 posPrev;
+ MT_Matrix3x3 angor;
+ if (converter->addInitFromFrame)
+ blenderscene->r.cfra=blenderscene->r.sfra;
+
+ MT_Point3 pos = MT_Point3(
+ blenderobject->loc[0]+blenderobject->dloc[0],
+ blenderobject->loc[1]+blenderobject->dloc[1],
+ blenderobject->loc[2]+blenderobject->dloc[2]
+ );
+ MT_Vector3 eulxyz = MT_Vector3(
+ blenderobject->rot[0],
+ blenderobject->rot[1],
+ blenderobject->rot[2]
+ );
+ MT_Vector3 scale = MT_Vector3(
+ blenderobject->size[0],
+ blenderobject->size[1],
+ blenderobject->size[2]
+ );
+ if (converter->addInitFromFrame){//rcruiz
+ float eulxyzPrev[3];
+ blenderscene->r.cfra=blenderscene->r.sfra-1;
+ update_for_newframe();
+ MT_Vector3 tmp=pos-MT_Point3(blenderobject->loc[0]+blenderobject->dloc[0],
+ blenderobject->loc[1]+blenderobject->dloc[1],
+ blenderobject->loc[2]+blenderobject->dloc[2]
+ );
+ eulxyzPrev[0]=blenderobject->rot[0];
+ eulxyzPrev[1]=blenderobject->rot[1];
+ eulxyzPrev[2]=blenderobject->rot[2];
+
+ double fps = (double) blenderscene->r.frs_sec/
+ (double) blenderscene->r.frs_sec_base;
+
+ tmp.scale(fps, fps, fps);
+ inivel.push_back(tmp);
+ tmp=eulxyz-eulxyzPrev;
+ tmp.scale(fps, fps, fps);
+ iniang.push_back(tmp);
+ blenderscene->r.cfra=blenderscene->r.sfra;
+ update_for_newframe();
+ }
+
+ gameobj->NodeSetLocalPosition(pos);
+ gameobj->NodeSetLocalOrientation(MT_Matrix3x3(eulxyz));
+ gameobj->NodeSetLocalScale(scale);
+ gameobj->NodeUpdateGS(0,true);
+
+ BL_ConvertIpos(blenderobject,gameobj,converter);
+ BL_ConvertMaterialIpos(blenderobject,gameobj, converter);
+
+ sumolist->Add(gameobj->AddRef());
+
+ BL_ConvertProperties(blenderobject,gameobj,timemgr,kxscene,isInActiveLayer);
+
+
+ gameobj->SetName(blenderobject->id.name);
+
+ // templist to find Root Parents (object with no parents)
+ templist->Add(gameobj->AddRef());
+
+ // update children/parent hierarchy
+ if ((blenderobject->parent != 0)&&(!converter->addInitFromFrame))
+ {
+ // blender has an additional 'parentinverse' offset in each object
+ SG_Node* parentinversenode = new SG_Node(NULL,NULL,SG_Callbacks());
+
+ // define a normal parent relationship for this node.
+ KX_NormalParentRelation * parent_relation = KX_NormalParentRelation::New();
+ parentinversenode->SetParentRelation(parent_relation);
+
+ parentChildLink pclink;
+ pclink.m_blenderchild = blenderobject;
+ pclink.m_gamechildnode = parentinversenode;
+ vec_parent_child.push_back(pclink);
+
+ float* fl = (float*) blenderobject->parentinv;
+ MT_Transform parinvtrans(fl);
+ parentinversenode->SetLocalPosition(parinvtrans.getOrigin());
+
+ // Extract the rotation and the scaling from the basis
+ MT_Matrix3x3 ori(parinvtrans.getBasis());
+ MT_Vector3 x(ori.getColumn(0));
+ MT_Vector3 y(ori.getColumn(1));
+ MT_Vector3 z(ori.getColumn(2));
+ MT_Vector3 scale(x.length(), y.length(), z.length());
+ if (!MT_fuzzyZero(scale[0]))
+ x /= scale[0];
+ if (!MT_fuzzyZero(scale[1]))
+ y /= scale[1];
+ if (!MT_fuzzyZero(scale[2]))
+ z /= scale[2];
+ ori.setColumn(0, x);
+ ori.setColumn(1, y);
+ ori.setColumn(2, z);
+ parentinversenode->SetLocalOrientation(ori);
+ parentinversenode->SetLocalScale(scale);
+
+ parentinversenode->AddChild(gameobj->GetSGNode());
+ }
+
+ // needed for python scripting
+ logicmgr->RegisterGameObjectName(gameobj->GetName(),gameobj);
+
+ // needed for group duplication
+ logicmgr->RegisterGameObj(blenderobject, gameobj);
+ for (int i = 0; i < gameobj->GetMeshCount(); i++)
+ logicmgr->RegisterGameMeshName(gameobj->GetMesh(i)->GetName(), blenderobject);
+
+ converter->RegisterGameObject(gameobj, blenderobject);
+ // this was put in rapidly, needs to be looked at more closely
+ // only draw/use objects in active 'blender' layers
+
+ logicbrick_conversionlist->Add(gameobj->AddRef());
+
+ if (converter->addInitFromFrame){
+ posPrev=gameobj->NodeGetWorldPosition();
+ angor=gameobj->NodeGetWorldOrientation();
+ }
+ if (isInActiveLayer)
+ {
+ objectlist->Add(gameobj->AddRef());
+ //tf.Add(gameobj->GetSGNode());
+
+ gameobj->NodeUpdateGS(0,true);
+ gameobj->AddMeshUser();
+ }
+ else
+ {
+ //we must store this object otherwise it will be deleted
+ //at the end of this function if it is not a root object
+ inactivelist->Add(gameobj->AddRef());
+
+ }
+ if (gameobj->IsDupliGroup())
+ {
+ // check that the group is not already converted
+ if (allgrouplist.insert(blenderobject->dup_group).second)
+ grouplist.insert(blenderobject->dup_group);
+ }
+ if (converter->addInitFromFrame){
+ gameobj->NodeSetLocalPosition(posPrev);
+ gameobj->NodeSetLocalOrientation(angor);
+ }
+
+ }
+ if (gameobj)
+ gameobj->Release();
+ }
+ }
+ }
+ }
}
- if (blenderscene->camera) {
+ // non-camera objects not supported as camera currently
+ if (blenderscene->camera && blenderscene->camera->type == OB_CAMERA) {
KX_Camera *gamecamera= (KX_Camera*) converter->FindGameObject(blenderscene->camera);
- kxscene->SetActiveCamera(gamecamera);
+ if(gamecamera)
+ kxscene->SetActiveCamera(gamecamera);
}
// Set up armatures
- for (base = static_cast<Base*>(blenderscene->base.first); base; base=base->next){
- if (base->object->type==OB_MESH){
- Mesh *me = (Mesh*)base->object->data;
+ set<Object*>::iterator oit;
+ for(oit=allblobj.begin(); oit!=allblobj.end(); oit++)
+ {
+ Object* blenderobj = *oit;
+ if (blenderobj->type==OB_MESH) {
+ Mesh *me = (Mesh*)blenderobj->data;
if (me->dvert){
- KX_GameObject *obj = converter->FindGameObject(base->object);
+ BL_DeformableGameObject *obj = (BL_DeformableGameObject*)converter->FindGameObject(blenderobj);
- if (base->object->parent && base->object->parent->type==OB_ARMATURE && base->object->partype==PARSKEL){
- KX_GameObject *par = converter->FindGameObject(base->object->parent);
- if (par)
- ((BL_SkinDeformer*)(((BL_DeformableGameObject*)obj)->m_pDeformer))->SetArmature((BL_ArmatureObject*) par);
+ if (obj && blenderobj->parent && blenderobj->parent->type==OB_ARMATURE && blenderobj->partype==PARSKEL){
+ KX_GameObject *par = converter->FindGameObject(blenderobj->parent);
+ if (par && obj->GetDeformer())
+ ((BL_SkinDeformer*)obj->GetDeformer())->SetArmature((BL_ArmatureObject*) par);
}
}
}
@@ -2034,6 +2299,41 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
{
struct Object* blenderchild = pcit->m_blenderchild;
+ struct Object* blenderparent = blenderchild->parent;
+ KX_GameObject* parentobj = converter->FindGameObject(blenderparent);
+ KX_GameObject* childobj = converter->FindGameObject(blenderchild);
+
+ assert(childobj);
+
+ if (!parentobj || objectlist->SearchValue(childobj) != objectlist->SearchValue(parentobj))
+ {
+ // special case: the parent and child object are not in the same layer.
+ // This weird situation is used in Apricot for test purposes.
+ // Resolve it by not converting the child
+ childobj->GetSGNode()->DisconnectFromParent();
+ delete pcit->m_gamechildnode;
+ // Now destroy the child object but also all its descendent that may already be linked
+ // Remove the child reference in the local list!
+ // Note: there may be descendents already if the children of the child were processed
+ // by this loop before the child. In that case, we must remove the children also
+ CListValue* childrenlist = (CListValue*)childobj->PyGetChildrenRecursive(childobj);
+ childrenlist->Add(childobj->AddRef());
+ for ( i=0;i<childrenlist->GetCount();i++)
+ {
+ KX_GameObject* obj = static_cast<KX_GameObject*>(childrenlist->GetValue(i));
+ if (templist->RemoveValue(obj))
+ obj->Release();
+ if (sumolist->RemoveValue(obj))
+ obj->Release();
+ if (logicbrick_conversionlist->RemoveValue(obj))
+ obj->Release();
+ }
+ childrenlist->Release();
+ // now destroy recursively
+ kxscene->RemoveObject(childobj);
+ continue;
+ }
+
switch (blenderchild->partype)
{
case PARVERT1:
@@ -2054,8 +2354,11 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
{
// parent this to a bone
Bone *parent_bone = get_named_bone(get_armature(blenderchild->parent), blenderchild->parsubstr);
- KX_BoneParentRelation *bone_parent_relation = KX_BoneParentRelation::New(parent_bone);
- pcit->m_gamechildnode->SetParentRelation(bone_parent_relation);
+
+ if(parent_bone) {
+ KX_BoneParentRelation *bone_parent_relation = KX_BoneParentRelation::New(parent_bone);
+ pcit->m_gamechildnode->SetParentRelation(bone_parent_relation);
+ }
break;
}
@@ -2070,12 +2373,7 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
break;
}
- struct Object* blenderparent = blenderchild->parent;
- KX_GameObject* parentobj = converter->FindGameObject(blenderparent);
- if (parentobj)
- {
- parentobj-> GetSGNode()->AddChild(pcit->m_gamechildnode);
- }
+ parentobj-> GetSGNode()->AddChild(pcit->m_gamechildnode);
}
vec_parent_child.clear();
@@ -2103,7 +2401,8 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
{
meshobj = gameobj->GetMesh(0);
}
- BL_CreatePhysicsObjectNew(gameobj,blenderobject,meshobj,kxscene,activeLayerBitInfo,physics_engine,converter,processCompoundChildren);
+ int layerMask = (groupobj.find(blenderobject) == groupobj.end()) ? activeLayerBitInfo : 0;
+ BL_CreatePhysicsObjectNew(gameobj,blenderobject,meshobj,kxscene,layerMask,physics_engine,converter,processCompoundChildren);
}
processCompoundChildren = true;
@@ -2118,7 +2417,8 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
{
meshobj = gameobj->GetMesh(0);
}
- BL_CreatePhysicsObjectNew(gameobj,blenderobject,meshobj,kxscene,activeLayerBitInfo,physics_engine,converter,processCompoundChildren);
+ int layerMask = (groupobj.find(blenderobject) == groupobj.end()) ? activeLayerBitInfo : 0;
+ BL_CreatePhysicsObjectNew(gameobj,blenderobject,meshobj,kxscene,layerMask,physics_engine,converter,processCompoundChildren);
}
@@ -2140,70 +2440,71 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
{
KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
struct Object* blenderobject = converter->FindBlenderObject(gameobj);
- int nummeshes = gameobj->GetMeshCount();
- RAS_MeshObject* meshobj = 0;
- ListBase *conlist;
- bConstraint *curcon;
- conlist = get_active_constraints2(blenderobject);
- if (conlist) {
- for (curcon = (bConstraint *)conlist->first; curcon; curcon=(bConstraint *)curcon->next) {
- if (curcon->type==CONSTRAINT_TYPE_RIGIDBODYJOINT){
- bRigidBodyJointConstraint *dat=(bRigidBodyJointConstraint *)curcon->data;
- //if (dat->tar)
- if (!dat->child){
- PHY_IPhysicsController* physctr2 = 0;
- if (dat->tar)
- {
- KX_GameObject *gotar=getGameOb(dat->tar->id.name,sumolist);
- if (gotar && gotar->GetPhysicsController())
- physctr2 = (PHY_IPhysicsController*) gotar->GetPhysicsController()->GetUserData();
- }
+ ListBase *conlist;
+ bConstraint *curcon;
+ conlist = get_active_constraints2(blenderobject);
- if (gameobj->GetPhysicsController())
- {
- float radsPerDeg = 6.283185307179586232f / 360.f;
+ if (conlist) {
+ for (curcon = (bConstraint *)conlist->first; curcon; curcon=(bConstraint *)curcon->next) {
+ if (curcon->type==CONSTRAINT_TYPE_RIGIDBODYJOINT){
+
+ bRigidBodyJointConstraint *dat=(bRigidBodyJointConstraint *)curcon->data;
+
+ if (!dat->child){
+
+ PHY_IPhysicsController* physctr2 = 0;
- PHY_IPhysicsController* physctrl = (PHY_IPhysicsController*) gameobj->GetPhysicsController()->GetUserData();
- //we need to pass a full constraint frame, not just axis
+ if (dat->tar)
+ {
+ KX_GameObject *gotar=getGameOb(dat->tar->id.name,sumolist);
+ if (gotar && gotar->GetPhysicsController())
+ physctr2 = (PHY_IPhysicsController*) gotar->GetPhysicsController()->GetUserData();
+ }
+
+ if (gameobj->GetPhysicsController())
+ {
+ float radsPerDeg = 6.283185307179586232f / 360.f;
+
+ PHY_IPhysicsController* physctrl = (PHY_IPhysicsController*) gameobj->GetPhysicsController()->GetUserData();
+ //we need to pass a full constraint frame, not just axis
- //localConstraintFrameBasis
- MT_Matrix3x3 localCFrame(MT_Vector3(radsPerDeg*dat->axX,radsPerDeg*dat->axY,radsPerDeg*dat->axZ));
- MT_Vector3 axis0 = localCFrame.getColumn(0);
- MT_Vector3 axis1 = localCFrame.getColumn(1);
- MT_Vector3 axis2 = localCFrame.getColumn(2);
+ //localConstraintFrameBasis
+ MT_Matrix3x3 localCFrame(MT_Vector3(radsPerDeg*dat->axX,radsPerDeg*dat->axY,radsPerDeg*dat->axZ));
+ MT_Vector3 axis0 = localCFrame.getColumn(0);
+ MT_Vector3 axis1 = localCFrame.getColumn(1);
+ MT_Vector3 axis2 = localCFrame.getColumn(2);
- int constraintId = kxscene->GetPhysicsEnvironment()->createConstraint(physctrl,physctr2,(PHY_ConstraintType)dat->type,(float)dat->pivX,(float)dat->pivY,(float)dat->pivZ,
+ int constraintId = kxscene->GetPhysicsEnvironment()->createConstraint(physctrl,physctr2,(PHY_ConstraintType)dat->type,(float)dat->pivX,
+ (float)dat->pivY,(float)dat->pivZ,
(float)axis0.x(),(float)axis0.y(),(float)axis0.z(),
(float)axis1.x(),(float)axis1.y(),(float)axis1.z(),
- (float)axis2.x(),(float)axis2.y(),(float)axis2.z()
- );
- if (constraintId)
+ (float)axis2.x(),(float)axis2.y(),(float)axis2.z(),dat->flag);
+ if (constraintId)
+ {
+ //if it is a generic 6DOF constraint, set all the limits accordingly
+ if (dat->type == PHY_GENERIC_6DOF_CONSTRAINT)
{
- //if it is a generic 6DOF constraint, set all the limits accordingly
- if (dat->type == PHY_GENERIC_6DOF_CONSTRAINT)
+ int dof;
+ int dofbit=1;
+ for (dof=0;dof<6;dof++)
{
- int dof;
- int dofbit=1;
- for (dof=0;dof<6;dof++)
+ if (dat->flag & dofbit)
+ {
+ kxscene->GetPhysicsEnvironment()->setConstraintParam(constraintId,dof,dat->minLimit[dof],dat->maxLimit[dof]);
+ } else
{
- if (dat->flag & dofbit)
- {
- kxscene->GetPhysicsEnvironment()->setConstraintParam(constraintId,dof,dat->minLimit[dof],dat->maxLimit[dof]);
- } else
- {
- //minLimit > maxLimit means free(disabled limit) for this degree of freedom
- kxscene->GetPhysicsEnvironment()->setConstraintParam(constraintId,dof,1,-1);
- }
- dofbit<<=1;
+ //minLimit > maxLimit means free(disabled limit) for this degree of freedom
+ kxscene->GetPhysicsEnvironment()->setConstraintParam(constraintId,dof,1,-1);
}
+ dofbit<<=1;
}
}
}
- }
- }
- }
- }
-
+ }
+ }
+ }
+ }
+ }
}
templist->Release();
@@ -2239,23 +2540,35 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
{
KX_GameObject* gameobj = static_cast<KX_GameObject*>(logicbrick_conversionlist->GetValue(i));
struct Object* blenderobj = converter->FindBlenderObject(gameobj);
- bool isInActiveLayer = (blenderobj->lay & activeLayerBitInfo)!=0;
- BL_ConvertActuators(maggie->name, blenderobj,gameobj,logicmgr,kxscene,ketsjiEngine,executePriority, activeLayerBitInfo,isInActiveLayer,rendertools,converter);
+ int layerMask = (groupobj.find(blenderobj) == groupobj.end()) ? activeLayerBitInfo : 0;
+ bool isInActiveLayer = (blenderobj->lay & layerMask)!=0;
+ BL_ConvertActuators(maggie->name, blenderobj,gameobj,logicmgr,kxscene,ketsjiEngine,executePriority, layerMask,isInActiveLayer,rendertools,converter);
}
for ( i=0;i<logicbrick_conversionlist->GetCount();i++)
{
KX_GameObject* gameobj = static_cast<KX_GameObject*>(logicbrick_conversionlist->GetValue(i));
struct Object* blenderobj = converter->FindBlenderObject(gameobj);
- bool isInActiveLayer = (blenderobj->lay & activeLayerBitInfo)!=0;
- BL_ConvertControllers(blenderobj,gameobj,logicmgr,pythondictionary,executePriority,activeLayerBitInfo,isInActiveLayer,converter);
+ int layerMask = (groupobj.find(blenderobj) == groupobj.end()) ? activeLayerBitInfo : 0;
+ bool isInActiveLayer = (blenderobj->lay & layerMask)!=0;
+ BL_ConvertControllers(blenderobj,gameobj,logicmgr,pythondictionary,executePriority,layerMask,isInActiveLayer,converter);
}
for ( i=0;i<logicbrick_conversionlist->GetCount();i++)
{
KX_GameObject* gameobj = static_cast<KX_GameObject*>(logicbrick_conversionlist->GetValue(i));
struct Object* blenderobj = converter->FindBlenderObject(gameobj);
- bool isInActiveLayer = (blenderobj->lay & activeLayerBitInfo)!=0;
- BL_ConvertSensors(blenderobj,gameobj,logicmgr,kxscene,keydev,executePriority,activeLayerBitInfo,isInActiveLayer,canvas,converter);
+ int layerMask = (groupobj.find(blenderobj) == groupobj.end()) ? activeLayerBitInfo : 0;
+ bool isInActiveLayer = (blenderobj->lay & layerMask)!=0;
+ BL_ConvertSensors(blenderobj,gameobj,logicmgr,kxscene,ketsjiEngine,keydev,executePriority,layerMask,isInActiveLayer,canvas,converter);
+ // set the init state to all objects
+ gameobj->SetInitState((blenderobj->init_state)?blenderobj->init_state:blenderobj->state);
}
+ // apply the initial state to controllers, only on the active objects as this registers the sensors
+ for ( i=0;i<objectlist->GetCount();i++)
+ {
+ KX_GameObject* gameobj = static_cast<KX_GameObject*>(objectlist->GetValue(i));
+ gameobj->ResetState();
+ }
+
#endif //CONVERT_LOGIC
logicbrick_conversionlist->Release();
@@ -2263,5 +2576,24 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
// Calculate the scene btree -
// too slow - commented out.
//kxscene->SetNodeTree(tf.MakeTree());
+
+ // instantiate dupli group, we will loop trough the object
+ // that are in active layers. Note that duplicating group
+ // has the effect of adding objects at the end of objectlist.
+ // Only loop through the first part of the list.
+ int objcount = objectlist->GetCount();
+ for (i=0;i<objcount;i++)
+ {
+ KX_GameObject* gameobj = (KX_GameObject*) objectlist->GetValue(i);
+ if (gameobj->IsDupliGroup())
+ {
+ kxscene->DupliGroupRecurse(gameobj, 0);
+ }
+ }
+
+ KX_Camera *activecam = kxscene->GetActiveCamera();
+ MT_Scalar distance = (activecam)? activecam->GetCameraFar() - activecam->GetCameraNear(): 100.0f;
+ RAS_BucketManager *bucketmanager = kxscene->GetBucketManager();
+ bucketmanager->OptimizeBuckets(distance);
}
diff --git a/source/gameengine/Converter/BL_DeformableGameObject.cpp b/source/gameengine/Converter/BL_DeformableGameObject.cpp
index 68a2e41ca47..e2610d2b405 100644
--- a/source/gameengine/Converter/BL_DeformableGameObject.cpp
+++ b/source/gameengine/Converter/BL_DeformableGameObject.cpp
@@ -28,6 +28,8 @@
*/
#include "BL_DeformableGameObject.h"
+#include "BL_ShapeDeformer.h"
+#include "BL_ShapeActionActuator.h"
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -39,12 +41,14 @@ BL_DeformableGameObject::~BL_DeformableGameObject()
delete m_pDeformer; // __NLA : Temporary until we decide where to put this
}
-void BL_DeformableGameObject::ProcessReplica(KX_GameObject* replica)
+void BL_DeformableGameObject::ProcessReplica(KX_GameObject* replica)
{
+ BL_MeshDeformer *deformer;
KX_GameObject::ProcessReplica(replica);
- if (m_pDeformer){
- ((BL_DeformableGameObject*)replica)->m_pDeformer = m_pDeformer->GetReplica();
+ if (m_pDeformer) {
+ deformer = (BL_MeshDeformer*)m_pDeformer->GetReplica(replica);
+ ((BL_DeformableGameObject*)replica)->m_pDeformer = deformer;
}
}
@@ -60,3 +64,48 @@ CValue* BL_DeformableGameObject::GetReplica()
ProcessReplica(replica);
return replica;
}
+
+bool BL_DeformableGameObject::SetActiveAction(BL_ShapeActionActuator *act, short priority, double curtime)
+{
+ if (curtime != m_lastframe){
+ m_activePriority = 9999;
+ m_lastframe= curtime;
+ m_activeAct = NULL;
+ }
+
+ if (priority<=m_activePriority)
+ {
+ if (m_activeAct && (m_activeAct!=act))
+ m_activeAct->SetBlendTime(0.0f); /* Reset the blend timer */
+ m_activeAct = act;
+ m_activePriority = priority;
+ m_lastframe = curtime;
+
+ return true;
+ }
+ else{
+ act->SetBlendTime(0.0f);
+ return false;
+ }
+}
+
+bool BL_DeformableGameObject::GetShape(vector<float> &shape)
+{
+ shape.clear();
+ if (m_pDeformer)
+ {
+ Mesh* mesh = ((BL_MeshDeformer*)m_pDeformer)->GetMesh();
+ // this check is normally superfluous: a shape deformer can only be created if the mesh
+ // has relative keys
+ if (mesh && mesh->key && mesh->key->type==KEY_RELATIVE)
+ {
+ KeyBlock *kb;
+ for (kb = (KeyBlock*)mesh->key->block.first; kb; kb = (KeyBlock*)kb->next)
+ {
+ shape.push_back(kb->curval);
+ }
+ }
+ }
+ return !shape.empty();
+}
+
diff --git a/source/gameengine/Converter/BL_DeformableGameObject.h b/source/gameengine/Converter/BL_DeformableGameObject.h
index d943cc7388a..126a1fcb1e7 100644
--- a/source/gameengine/Converter/BL_DeformableGameObject.h
+++ b/source/gameengine/Converter/BL_DeformableGameObject.h
@@ -34,29 +34,74 @@
#pragma warning (disable:4786) // get rid of stupid stl-visual compiler debug warning
#endif //WIN32
+#include "DNA_mesh_types.h"
#include "KX_GameObject.h"
-#include "RAS_Deformer.h"
+#include "BL_MeshDeformer.h"
+#include <vector>
+
+class BL_ShapeActionActuator;
+struct Key;
class BL_DeformableGameObject : public KX_GameObject
{
public:
- RAS_Deformer *m_pDeformer;
CValue* GetReplica();
+
+ double GetLastFrame ()
+ {
+ return m_lastframe;
+ }
+ Object* GetBlendObject()
+ {
+ return m_blendobj;
+ }
virtual void Relink(GEN_Map<GEN_HashedPtr, void*>*map)
{
if (m_pDeformer)
m_pDeformer->Relink (map);
+ KX_GameObject::Relink(map);
};
void ProcessReplica(KX_GameObject* replica);
- BL_DeformableGameObject(void* sgReplicationInfo, SG_Callbacks callbacks) :
+ BL_DeformableGameObject(Object* blendobj, void* sgReplicationInfo, SG_Callbacks callbacks) :
KX_GameObject(sgReplicationInfo,callbacks),
- m_pDeformer(NULL)
+ m_pDeformer(NULL),
+ m_activeAct(NULL),
+ m_lastframe(0.),
+ m_blendobj(blendobj),
+ m_activePriority(9999)
{
m_isDeformable = true;
};
virtual ~BL_DeformableGameObject();
+ bool SetActiveAction(class BL_ShapeActionActuator *act, short priority, double curtime);
+
+ bool GetShape(vector<float> &shape);
+ Key* GetKey()
+ {
+ return (m_pDeformer) ? ((BL_MeshDeformer*)m_pDeformer)->GetMesh()->key : NULL;
+ }
+
+ virtual void SetDeformer(class RAS_Deformer* deformer)
+ {
+ m_pDeformer = deformer;
+ }
+ virtual class RAS_Deformer* GetDeformer()
+ {
+ return m_pDeformer;
+ }
+
+public:
+
+protected:
+
+ RAS_Deformer *m_pDeformer;
+
+ class BL_ShapeActionActuator *m_activeAct;
+ double m_lastframe;
+ Object* m_blendobj;
+ short m_activePriority;
};
diff --git a/source/gameengine/Converter/BL_MeshDeformer.cpp b/source/gameengine/Converter/BL_MeshDeformer.cpp
index ab31179b047..fa3b8185fe2 100644
--- a/source/gameengine/Converter/BL_MeshDeformer.cpp
+++ b/source/gameengine/Converter/BL_MeshDeformer.cpp
@@ -39,118 +39,193 @@
#endif
#include "RAS_IPolygonMaterial.h"
+#include "BL_DeformableGameObject.h"
#include "BL_MeshDeformer.h"
#include "BL_SkinMeshObject.h"
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
-#include "BLI_arithb.h"
#include "GEN_Map.h"
#include "STR_HashedString.h"
-
-bool BL_MeshDeformer::Apply(RAS_IPolyMaterial *mat)
+bool BL_MeshDeformer::Apply(RAS_IPolyMaterial*)
{
- size_t i, j, index;
- vecVertexArray array;
- vecIndexArrays mvarray;
- vecIndexArrays diarray;
-
- RAS_TexVert *tv;
- MVert *mvert;
-
- // For each material
- array = m_pMeshObject->GetVertexCache(mat);
- mvarray = m_pMeshObject->GetMVertCache(mat);
- diarray = m_pMeshObject->GetDIndexCache(mat);
-
- // For each array
- for (i=0; i<array.size(); i++){
- // For each vertex
- for (j=0; j<array[i]->size(); j++){
- tv = &((*array[i])[j]);
- index = ((*diarray[i])[j]);
-
- mvert = &(m_bmesh->mvert[((*mvarray[i])[index])]);
- tv->SetXYZ(MT_Point3(mvert->co));
+ size_t i;
+ float *co;
+
+ // only apply once per frame if the mesh is actually modified
+ if(m_pMeshObject->MeshModified() &&
+ m_lastDeformUpdate != m_gameobj->GetLastFrame()) {
+ // For each material
+ for(list<RAS_MeshMaterial>::iterator mit= m_pMeshObject->GetFirstMaterial();
+ mit != m_pMeshObject->GetLastMaterial(); ++ mit) {
+ if(!mit->m_slots[(void*)m_gameobj])
+ continue;
+
+ RAS_MeshSlot *slot = *mit->m_slots[(void*)m_gameobj];
+ RAS_MeshSlot::iterator it;
+
+ // for each array
+ for(slot->begin(it); !slot->end(it); slot->next(it)) {
+ // For each vertex
+ for(i=it.startvertex; i<it.endvertex; i++) {
+ RAS_TexVert& v = it.vertex[i];
+ co = m_bmesh->mvert[v.getOrigIndex()].co;
+ v.SetXYZ(MT_Point3(co));
+ }
+ }
}
+
+ m_lastDeformUpdate = m_gameobj->GetLastFrame();
+
+ return true;
}
- return true;
+
+ return false;
}
BL_MeshDeformer::~BL_MeshDeformer()
{
if (m_transverts)
- delete []m_transverts;
+ delete [] m_transverts;
if (m_transnors)
- delete []m_transnors;
-};
+ delete [] m_transnors;
+}
+
+void BL_MeshDeformer::Relink(GEN_Map<class GEN_HashedPtr, void*>*map)
+{
+ void **h_obj = (*map)[m_gameobj];
+
+ if (h_obj)
+ m_gameobj = (BL_DeformableGameObject*)(*h_obj);
+ else
+ m_gameobj = NULL;
+}
/**
* @warning This function is expensive!
*/
void BL_MeshDeformer::RecalcNormals()
{
- int v, f;
- float fnor[3], co1[3], co2[3], co3[3], co4[3];
+ /* We don't normalize for performance, not doing it for faces normals
+ * gives area-weight normals which often look better anyway, and use
+ * GL_NORMALIZE so we don't have to do per vertex normalization either
+ * since the GPU can do it faster */
+ list<RAS_MeshMaterial>::iterator mit;
+ RAS_MeshSlot::iterator it;
+ size_t i;
- /* Clear all vertex normal accumulators */
- for (v =0; v<m_bmesh->totvert; v++){
- m_transnors[v]=MT_Point3(0,0,0);
- }
-
- /* Find the face normals */
- for (f = 0; f<m_bmesh->totface; f++){
- // Make new face normal based on the transverts
- MFace *mf= &((MFace*)m_bmesh->mface)[f];
-
- if (mf->v3) {
- for (int vl=0; vl<3; vl++){
- co1[vl]=m_transverts[mf->v1][vl];
- co2[vl]=m_transverts[mf->v2][vl];
- co3[vl]=m_transverts[mf->v3][vl];
- if (mf->v4)
- co4[vl]=m_transverts[mf->v4][vl];
+ /* set vertex normals to zero */
+ memset(m_transnors, 0, sizeof(float)*3*m_bmesh->totvert);
+
+ /* add face normals to vertices. */
+ for(mit = m_pMeshObject->GetFirstMaterial();
+ mit != m_pMeshObject->GetLastMaterial(); ++ mit) {
+ if(!mit->m_slots[(void*)m_gameobj])
+ continue;
+
+ RAS_MeshSlot *slot = *mit->m_slots[(void*)m_gameobj];
+
+ for(slot->begin(it); !slot->end(it); slot->next(it)) {
+ int nvert = (int)it.array->m_type;
+
+ for(i=0; i<it.totindex; i+=nvert) {
+ RAS_TexVert& v1 = it.vertex[it.index[i]];
+ RAS_TexVert& v2 = it.vertex[it.index[i+1]];
+ RAS_TexVert& v3 = it.vertex[it.index[i+2]];
+ RAS_TexVert *v4 = NULL;
+
+ const float *co1 = v1.getXYZ();
+ const float *co2 = v2.getXYZ();
+ const float *co3 = v3.getXYZ();
+ const float *co4 = NULL;
+
+ /* compute face normal */
+ float fnor[3], n1[3], n2[3];
+
+ if(nvert == 4) {
+ v4 = &it.vertex[it.index[i+3]];
+ co4 = v4->getXYZ();
+
+ n1[0]= co1[0]-co3[0];
+ n1[1]= co1[1]-co3[1];
+ n1[2]= co1[2]-co3[2];
+
+ n2[0]= co2[0]-co4[0];
+ n2[1]= co2[1]-co4[1];
+ n2[2]= co2[2]-co4[2];
+ }
+ else {
+ n1[0]= co1[0]-co2[0];
+ n2[0]= co2[0]-co3[0];
+ n1[1]= co1[1]-co2[1];
+
+ n2[1]= co2[1]-co3[1];
+ n1[2]= co1[2]-co2[2];
+ n2[2]= co2[2]-co3[2];
+ }
+
+ fnor[0]= n1[1]*n2[2] - n1[2]*n2[1];
+ fnor[1]= n1[2]*n2[0] - n1[0]*n2[2];
+ fnor[2]= n1[0]*n2[1] - n1[1]*n2[0];
+
+ /* add to vertices for smooth normals */
+ float *vn1 = m_transnors[v1.getOrigIndex()];
+ float *vn2 = m_transnors[v2.getOrigIndex()];
+ float *vn3 = m_transnors[v3.getOrigIndex()];
+
+ vn1[0] += fnor[0]; vn1[1] += fnor[1]; vn1[2] += fnor[2];
+ vn2[0] += fnor[0]; vn2[1] += fnor[1]; vn2[2] += fnor[2];
+ vn3[0] += fnor[0]; vn3[1] += fnor[1]; vn3[2] += fnor[2];
+
+ if(v4) {
+ float *vn4 = m_transnors[v4->getOrigIndex()];
+ vn4[0] += fnor[0]; vn4[1] += fnor[1]; vn4[2] += fnor[2];
+ }
+
+ /* in case of flat - just assign, the vertices are split */
+ if(v1.getFlag() & RAS_TexVert::FLAT) {
+ v1.SetNormal(fnor);
+ v2.SetNormal(fnor);
+ v3.SetNormal(fnor);
+ if(v4)
+ v4->SetNormal(fnor);
+ }
}
+ }
+ }
+
+ /* assign smooth vertex normals */
+ for(mit = m_pMeshObject->GetFirstMaterial();
+ mit != m_pMeshObject->GetLastMaterial(); ++ mit) {
+ if(!mit->m_slots[(void*)m_gameobj])
+ continue;
+
+ RAS_MeshSlot *slot = *mit->m_slots[(void*)m_gameobj];
+
+ for(slot->begin(it); !slot->end(it); slot->next(it)) {
+ for(i=it.startvertex; i<it.endvertex; i++) {
+ RAS_TexVert& v = it.vertex[i];
- /* FIXME: Use moto */
- if (mf->v4)
- CalcNormFloat4(co1, co2, co3, co4, fnor);
- else
- CalcNormFloat(co1, co2, co3, fnor);
-
- /* Decide which normals are affected by this face's normal */
- m_transnors[mf->v1]+=MT_Point3(fnor);
- m_transnors[mf->v2]+=MT_Point3(fnor);
- m_transnors[mf->v3]+=MT_Point3(fnor);
- if (mf->v4)
- m_transnors[mf->v4]+=MT_Point3(fnor);
+ if(!(v.getFlag() & RAS_TexVert::FLAT))
+ v.SetNormal(m_transnors[v.getOrigIndex()]); //.safe_normalized()
+ }
}
}
-
- for (v =0; v<m_bmesh->totvert; v++){
-// float nor[3];
-
- m_transnors[v]=m_transnors[v].safe_normalized();
-// nor[0]=m_transnors[v][0];
-// nor[1]=m_transnors[v][1];
-// nor[2]=m_transnors[v][2];
-
- };
}
void BL_MeshDeformer::VerifyStorage()
{
/* Ensure that we have the right number of verts assigned */
- if (m_tvtot!=m_bmesh->totvert+m_bmesh->totface){
+ if (m_tvtot!=m_bmesh->totvert){
if (m_transverts)
- delete []m_transverts;
+ delete [] m_transverts;
if (m_transnors)
- delete []m_transnors;
+ delete [] m_transnors;
- m_transnors =new MT_Point3[m_bmesh->totvert+m_bmesh->totface];
- m_transverts=new float[(sizeof(*m_transverts)*m_bmesh->totvert)][3];
+ m_transverts=new float[m_bmesh->totvert][3];
+ m_transnors=new float[m_bmesh->totvert][3];
m_tvtot = m_bmesh->totvert;
}
}
-
+
diff --git a/source/gameengine/Converter/BL_MeshDeformer.h b/source/gameengine/Converter/BL_MeshDeformer.h
index a6be11d786e..8de59c1cdf3 100644
--- a/source/gameengine/Converter/BL_MeshDeformer.h
+++ b/source/gameengine/Converter/BL_MeshDeformer.h
@@ -32,6 +32,7 @@
#include "RAS_Deformer.h"
#include "DNA_object_types.h"
+#include "DNA_key_types.h"
#include "MT_Point3.h"
#include <stdlib.h>
@@ -39,38 +40,47 @@
#pragma warning (disable:4786) // get rid of stupid stl-visual compiler debug warning
#endif //WIN32
+class BL_DeformableGameObject;
+
class BL_MeshDeformer : public RAS_Deformer
{
public:
void VerifyStorage();
void RecalcNormals();
- virtual void Relink(GEN_Map<class GEN_HashedPtr, void*>*map){};
- BL_MeshDeformer(struct Object* obj, class BL_SkinMeshObject *meshobj ):
+ virtual void Relink(GEN_Map<class GEN_HashedPtr, void*>*map);
+ BL_MeshDeformer(BL_DeformableGameObject *gameobj,
+ struct Object* obj,
+ class BL_SkinMeshObject *meshobj ):
m_pMeshObject(meshobj),
m_bmesh((struct Mesh*)(obj->data)),
+ m_transverts(0),
+ m_transnors(0),
m_objMesh(obj),
- m_transnors(NULL),
- m_transverts(NULL),
- m_tvtot(0)
+ m_tvtot(0),
+ m_gameobj(gameobj),
+ m_lastDeformUpdate(-1)
{};
virtual ~BL_MeshDeformer();
virtual void SetSimulatedTime(double time){};
virtual bool Apply(class RAS_IPolyMaterial *mat);
- virtual void Update(void){};
- virtual RAS_Deformer* GetReplica(){return NULL;};
+ virtual bool Update(void){ return false; };
+ virtual RAS_Deformer* GetReplica(class KX_GameObject* replica){return NULL;};
+ struct Mesh* GetMesh() { return m_bmesh; };
// virtual void InitDeform(double time){};
+
protected:
class BL_SkinMeshObject* m_pMeshObject;
struct Mesh* m_bmesh;
- MT_Point3* m_transnors;
- //MT_Point3* m_transverts;
// this is so m_transverts doesn't need to be converted
// before deformation
float (*m_transverts)[3];
+ float (*m_transnors)[3];
struct Object* m_objMesh;
// --
int m_tvtot;
+ BL_DeformableGameObject* m_gameobj;
+ double m_lastDeformUpdate;
};
#endif
diff --git a/source/gameengine/Converter/BL_ShapeActionActuator.cpp b/source/gameengine/Converter/BL_ShapeActionActuator.cpp
new file mode 100644
index 00000000000..46f3141be29
--- /dev/null
+++ b/source/gameengine/Converter/BL_ShapeActionActuator.cpp
@@ -0,0 +1,842 @@
+/**
+* $Id$
+*
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+*/
+
+#if defined (__sgi)
+#include <math.h>
+#else
+#include <cmath>
+#endif
+
+#include "SCA_LogicManager.h"
+#include "BL_ShapeActionActuator.h"
+#include "BL_ActionActuator.h"
+#include "BL_ShapeDeformer.h"
+#include "KX_GameObject.h"
+#include "STR_HashedString.h"
+#include "DNA_action_types.h"
+#include "DNA_nla_types.h"
+#include "DNA_actuator_types.h"
+#include "BKE_action.h"
+#include "DNA_armature_types.h"
+#include "MEM_guardedalloc.h"
+#include "BLI_blenlib.h"
+#include "BLI_arithb.h"
+#include "MT_Matrix4x4.h"
+#include "BKE_utildefines.h"
+#include "FloatValue.h"
+#include "PyObjectPlus.h"
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+BL_ShapeActionActuator::~BL_ShapeActionActuator()
+{
+}
+
+void BL_ShapeActionActuator::ProcessReplica()
+{
+ m_localtime=m_startframe;
+ m_lastUpdate=-1;
+}
+
+void BL_ShapeActionActuator::SetBlendTime (float newtime)
+{
+ m_blendframe = newtime;
+}
+
+CValue* BL_ShapeActionActuator::GetReplica()
+{
+ BL_ShapeActionActuator* replica = new BL_ShapeActionActuator(*this);//m_float,GetName());
+ replica->ProcessReplica();
+
+ // this will copy properties and so on...
+ CValue::AddDataToReplica(replica);
+ return replica;
+}
+
+bool BL_ShapeActionActuator::ClampLocalTime()
+{
+ if (m_startframe < m_endframe) {
+ if (m_localtime < m_startframe)
+ {
+ m_localtime = m_startframe;
+ return true;
+ }
+ else if (m_localtime > m_endframe)
+ {
+ m_localtime = m_endframe;
+ return true;
+ }
+ } else {
+ if (m_localtime > m_startframe)
+ {
+ m_localtime = m_startframe;
+ return true;
+ }
+ else if (m_localtime < m_endframe)
+ {
+ m_localtime = m_endframe;
+ return true;
+ }
+ }
+ return false;
+}
+
+void BL_ShapeActionActuator::SetStartTime(float curtime)
+{
+ float direction = m_startframe < m_endframe ? 1.0 : -1.0;
+
+ if (!(m_flag & ACT_FLAG_REVERSE))
+ m_starttime = curtime - direction*(m_localtime - m_startframe)/KX_KetsjiEngine::GetAnimFrameRate();
+ else
+ m_starttime = curtime - direction*(m_endframe - m_localtime)/KX_KetsjiEngine::GetAnimFrameRate();
+}
+
+void BL_ShapeActionActuator::SetLocalTime(float curtime)
+{
+ float delta_time = (curtime - m_starttime)*KX_KetsjiEngine::GetAnimFrameRate();
+
+ if (m_endframe < m_startframe)
+ delta_time = -delta_time;
+
+ if (!(m_flag & ACT_FLAG_REVERSE))
+ m_localtime = m_startframe + delta_time;
+ else
+ m_localtime = m_endframe - delta_time;
+}
+
+void BL_ShapeActionActuator::BlendShape(Key* key, float srcweight)
+{
+ vector<float>::const_iterator it;
+ float dstweight;
+ KeyBlock *kb;
+
+ dstweight = 1.0F - srcweight;
+
+ for (it=m_blendshape.begin(), kb = (KeyBlock*)key->block.first;
+ kb && it != m_blendshape.end();
+ kb = (KeyBlock*)kb->next, it++) {
+ kb->curval = kb->curval * dstweight + (*it) * srcweight;
+ }
+}
+
+bool BL_ShapeActionActuator::Update(double curtime, bool frame)
+{
+ bool bNegativeEvent = false;
+ bool bPositiveEvent = false;
+ bool keepgoing = true;
+ bool wrap = false;
+ bool apply=true;
+ int priority;
+ float newweight;
+
+ curtime -= KX_KetsjiEngine::GetSuspendedDelta();
+
+ // result = true if animation has to be continued, false if animation stops
+ // maybe there are events for us in the queue !
+ if (frame)
+ {
+ for (vector<CValue*>::iterator i=m_events.begin(); !(i==m_events.end());i++)
+ {
+ if ((*i)->GetNumber() == 0.0f)
+ bNegativeEvent = true;
+ else
+ bPositiveEvent= true;
+ (*i)->Release();
+
+ }
+ m_events.clear();
+
+ if (bPositiveEvent)
+ m_flag |= ACT_FLAG_ACTIVE;
+
+ if (bNegativeEvent)
+ {
+ if (!(m_flag & ACT_FLAG_ACTIVE))
+ return false;
+ m_flag &= ~ACT_FLAG_ACTIVE;
+ }
+ }
+
+ /* This action can only be attached to a deform object */
+ BL_DeformableGameObject *obj = (BL_DeformableGameObject*)GetParent();
+ float length = m_endframe - m_startframe;
+
+ priority = m_priority;
+
+ /* Determine pre-incrementation behaviour and set appropriate flags */
+ switch (m_playtype){
+ case ACT_ACTION_MOTION:
+ if (bNegativeEvent){
+ keepgoing=false;
+ apply=false;
+ };
+ break;
+ case ACT_ACTION_FROM_PROP:
+ if (bNegativeEvent){
+ apply=false;
+ keepgoing=false;
+ }
+ break;
+ case ACT_ACTION_LOOP_END:
+ if (bPositiveEvent){
+ if (!(m_flag & ACT_FLAG_LOCKINPUT)){
+ m_flag &= ~ACT_FLAG_KEYUP;
+ m_flag &= ~ACT_FLAG_REVERSE;
+ m_flag |= ACT_FLAG_LOCKINPUT;
+ m_localtime = m_startframe;
+ m_starttime = curtime;
+ }
+ }
+ if (bNegativeEvent){
+ m_flag |= ACT_FLAG_KEYUP;
+ }
+ break;
+ case ACT_ACTION_LOOP_STOP:
+ if (bPositiveEvent){
+ if (!(m_flag & ACT_FLAG_LOCKINPUT)){
+ m_flag &= ~ACT_FLAG_REVERSE;
+ m_flag &= ~ACT_FLAG_KEYUP;
+ m_flag |= ACT_FLAG_LOCKINPUT;
+ SetStartTime(curtime);
+ }
+ }
+ if (bNegativeEvent){
+ m_flag |= ACT_FLAG_KEYUP;
+ m_flag &= ~ACT_FLAG_LOCKINPUT;
+ keepgoing=false;
+ apply=false;
+ }
+ break;
+ case ACT_ACTION_FLIPPER:
+ if (bPositiveEvent){
+ if (!(m_flag & ACT_FLAG_LOCKINPUT)){
+ m_flag &= ~ACT_FLAG_REVERSE;
+ m_flag |= ACT_FLAG_LOCKINPUT;
+ SetStartTime(curtime);
+ }
+ }
+ else if (bNegativeEvent){
+ m_flag |= ACT_FLAG_REVERSE;
+ m_flag &= ~ACT_FLAG_LOCKINPUT;
+ SetStartTime(curtime);
+ }
+ break;
+ case ACT_ACTION_PLAY:
+ if (bPositiveEvent){
+ if (!(m_flag & ACT_FLAG_LOCKINPUT)){
+ m_flag &= ~ACT_FLAG_REVERSE;
+ m_localtime = m_starttime;
+ m_starttime = curtime;
+ m_flag |= ACT_FLAG_LOCKINPUT;
+ }
+ }
+ break;
+ default:
+ break;
+ }
+
+ /* Perform increment */
+ if (keepgoing){
+ if (m_playtype == ACT_ACTION_MOTION){
+ MT_Point3 newpos;
+ MT_Point3 deltapos;
+
+ newpos = obj->NodeGetWorldPosition();
+
+ /* Find displacement */
+ deltapos = newpos-m_lastpos;
+ m_localtime += (length/m_stridelength) * deltapos.length();
+ m_lastpos = newpos;
+ }
+ else{
+ SetLocalTime(curtime);
+ }
+ }
+
+ /* Check if a wrapping response is needed */
+ if (length){
+ if (m_localtime < m_startframe || m_localtime > m_endframe)
+ {
+ m_localtime = m_startframe + fmod(m_localtime, length);
+ wrap = true;
+ }
+ }
+ else
+ m_localtime = m_startframe;
+
+ /* Perform post-increment tasks */
+ switch (m_playtype){
+ case ACT_ACTION_FROM_PROP:
+ {
+ CValue* propval = GetParent()->GetProperty(m_propname);
+ if (propval)
+ m_localtime = propval->GetNumber();
+
+ if (bNegativeEvent){
+ keepgoing=false;
+ }
+ }
+ break;
+ case ACT_ACTION_MOTION:
+ break;
+ case ACT_ACTION_LOOP_STOP:
+ break;
+ case ACT_ACTION_FLIPPER:
+ if (wrap){
+ if (!(m_flag & ACT_FLAG_REVERSE)){
+ m_localtime=m_endframe;
+ //keepgoing = false;
+ }
+ else {
+ m_localtime=m_startframe;
+ keepgoing = false;
+ }
+ }
+ break;
+ case ACT_ACTION_LOOP_END:
+ if (wrap){
+ if (m_flag & ACT_FLAG_KEYUP){
+ keepgoing = false;
+ m_localtime = m_endframe;
+ m_flag &= ~ACT_FLAG_LOCKINPUT;
+ }
+ SetStartTime(curtime);
+ }
+ break;
+ case ACT_ACTION_PLAY:
+ if (wrap){
+ m_localtime = m_endframe;
+ keepgoing = false;
+ m_flag &= ~ACT_FLAG_LOCKINPUT;
+ }
+ break;
+ default:
+ keepgoing = false;
+ break;
+ }
+
+ /* Set the property if its defined */
+ if (m_framepropname[0] != '\0') {
+ CValue* propowner = GetParent();
+ CValue* oldprop = propowner->GetProperty(m_framepropname);
+ CValue* newval = new CFloatValue(m_localtime);
+ if (oldprop) {
+ oldprop->SetValue(newval);
+ } else {
+ propowner->SetProperty(m_framepropname, newval);
+ }
+ newval->Release();
+ }
+
+ if (bNegativeEvent)
+ m_blendframe=0.0f;
+
+ /* Apply the pose if necessary*/
+ if (apply) {
+
+ /* Priority test */
+ if (obj->SetActiveAction(this, priority, curtime)){
+ Key *key = obj->GetKey();
+
+ if (!key) {
+ // this could happen if the mesh was changed in the middle of an action
+ // and the new mesh has no key, stop the action
+ keepgoing = false;
+ }
+ else {
+ ListBase tchanbase= {NULL, NULL};
+
+ if (m_blendin && m_blendframe==0.0f){
+ // this is the start of the blending, remember the startup shape
+ obj->GetShape(m_blendshape);
+ m_blendstart = curtime;
+ }
+ // only interested in shape channel
+ extract_ipochannels_from_action(&tchanbase, &key->id, m_action, "Shape", m_localtime);
+
+ if (!execute_ipochannels(&tchanbase)) {
+ // no update, this is possible if action does not match the keys, stop the action
+ keepgoing = false;
+ }
+ else {
+ // the key have changed, apply blending if needed
+ if (m_blendin && (m_blendframe<m_blendin)){
+ newweight = (m_blendframe/(float)m_blendin);
+
+ BlendShape(key, 1.0f - newweight);
+
+ /* Increment current blending percentage */
+ m_blendframe = (curtime - m_blendstart)*KX_KetsjiEngine::GetAnimFrameRate();
+ if (m_blendframe>m_blendin)
+ m_blendframe = m_blendin;
+ }
+ m_lastUpdate = m_localtime;
+ }
+ BLI_freelistN(&tchanbase);
+ }
+ }
+ else{
+ m_blendframe = 0.0f;
+ }
+ }
+
+ if (!keepgoing){
+ m_blendframe = 0.0f;
+ }
+ return keepgoing;
+};
+
+/* ------------------------------------------------------------------------- */
+/* Python functions */
+/* ------------------------------------------------------------------------- */
+
+/* Integration hooks ------------------------------------------------------- */
+
+PyTypeObject BL_ShapeActionActuator::Type = {
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0,
+ "BL_ShapeActionActuator",
+ sizeof(BL_ShapeActionActuator),
+ 0,
+ PyDestructor,
+ 0,
+ __getattr,
+ __setattr,
+ 0, //&MyPyCompare,
+ __repr,
+ 0, //&cvalue_as_number,
+ 0,
+ 0,
+ 0,
+ 0
+};
+
+PyParentObject BL_ShapeActionActuator::Parents[] = {
+ &BL_ShapeActionActuator::Type,
+ &SCA_IActuator::Type,
+ &SCA_ILogicBrick::Type,
+ &CValue::Type,
+ NULL
+};
+
+PyMethodDef BL_ShapeActionActuator::Methods[] = {
+ {"setAction", (PyCFunction) BL_ShapeActionActuator::sPySetAction, METH_VARARGS, (PY_METHODCHAR)SetAction_doc},
+ {"setStart", (PyCFunction) BL_ShapeActionActuator::sPySetStart, METH_VARARGS, (PY_METHODCHAR)SetStart_doc},
+ {"setEnd", (PyCFunction) BL_ShapeActionActuator::sPySetEnd, METH_VARARGS, (PY_METHODCHAR)SetEnd_doc},
+ {"setBlendin", (PyCFunction) BL_ShapeActionActuator::sPySetBlendin, METH_VARARGS, (PY_METHODCHAR)SetBlendin_doc},
+ {"setPriority", (PyCFunction) BL_ShapeActionActuator::sPySetPriority, METH_VARARGS, (PY_METHODCHAR)SetPriority_doc},
+ {"setFrame", (PyCFunction) BL_ShapeActionActuator::sPySetFrame, METH_VARARGS, (PY_METHODCHAR)SetFrame_doc},
+ {"setProperty", (PyCFunction) BL_ShapeActionActuator::sPySetProperty, METH_VARARGS, (PY_METHODCHAR)SetProperty_doc},
+ {"setFrameProperty", (PyCFunction) BL_ShapeActionActuator::sPySetFrameProperty, METH_VARARGS, (PY_METHODCHAR)SetFrameProperty_doc},
+ {"setBlendtime", (PyCFunction) BL_ShapeActionActuator::sPySetBlendtime, METH_VARARGS, (PY_METHODCHAR)SetBlendtime_doc},
+
+ {"getAction", (PyCFunction) BL_ShapeActionActuator::sPyGetAction, METH_NOARGS, (PY_METHODCHAR)GetAction_doc},
+ {"getStart", (PyCFunction) BL_ShapeActionActuator::sPyGetStart, METH_NOARGS, (PY_METHODCHAR)GetStart_doc},
+ {"getEnd", (PyCFunction) BL_ShapeActionActuator::sPyGetEnd, METH_NOARGS, (PY_METHODCHAR)GetEnd_doc},
+ {"getBlendin", (PyCFunction) BL_ShapeActionActuator::sPyGetBlendin, METH_NOARGS, (PY_METHODCHAR)GetBlendin_doc},
+ {"getPriority", (PyCFunction) BL_ShapeActionActuator::sPyGetPriority, METH_NOARGS, (PY_METHODCHAR)GetPriority_doc},
+ {"getFrame", (PyCFunction) BL_ShapeActionActuator::sPyGetFrame, METH_NOARGS, (PY_METHODCHAR)GetFrame_doc},
+ {"getProperty", (PyCFunction) BL_ShapeActionActuator::sPyGetProperty, METH_NOARGS, (PY_METHODCHAR)GetProperty_doc},
+ {"getFrameProperty", (PyCFunction) BL_ShapeActionActuator::sPyGetFrameProperty, METH_NOARGS, (PY_METHODCHAR)GetFrameProperty_doc},
+ {"getType", (PyCFunction) BL_ShapeActionActuator::sPyGetType, METH_NOARGS, (PY_METHODCHAR)GetType_doc},
+ {"setType", (PyCFunction) BL_ShapeActionActuator::sPySetType, METH_NOARGS, (PY_METHODCHAR)SetType_doc},
+ {NULL,NULL} //Sentinel
+};
+
+PyObject* BL_ShapeActionActuator::_getattr(const STR_String& attr) {
+ _getattr_up(SCA_IActuator);
+}
+
+/* setStart */
+const char BL_ShapeActionActuator::GetAction_doc[] =
+"getAction()\n"
+"\tReturns a string containing the name of the current action.\n";
+
+PyObject* BL_ShapeActionActuator::PyGetAction(PyObject* self) {
+ if (m_action){
+ return PyString_FromString(m_action->id.name+2);
+ }
+ Py_RETURN_NONE;
+}
+
+/* getProperty */
+const char BL_ShapeActionActuator::GetProperty_doc[] =
+"getProperty()\n"
+"\tReturns the name of the property to be used in FromProp mode.\n";
+
+PyObject* BL_ShapeActionActuator::PyGetProperty(PyObject* self) {
+ PyObject *result;
+
+ result = Py_BuildValue("s", (const char *)m_propname);
+
+ return result;
+}
+
+/* getFrame */
+const char BL_ShapeActionActuator::GetFrame_doc[] =
+"getFrame()\n"
+"\tReturns the current frame number.\n";
+
+PyObject* BL_ShapeActionActuator::PyGetFrame(PyObject* self) {
+ PyObject *result;
+
+ result = Py_BuildValue("f", m_localtime);
+
+ return result;
+}
+
+/* getEnd */
+const char BL_ShapeActionActuator::GetEnd_doc[] =
+"getEnd()\n"
+"\tReturns the last frame of the action.\n";
+
+PyObject* BL_ShapeActionActuator::PyGetEnd(PyObject* self) {
+ PyObject *result;
+
+ result = Py_BuildValue("f", m_endframe);
+
+ return result;
+}
+
+/* getStart */
+const char BL_ShapeActionActuator::GetStart_doc[] =
+"getStart()\n"
+"\tReturns the starting frame of the action.\n";
+
+PyObject* BL_ShapeActionActuator::PyGetStart(PyObject* self) {
+ PyObject *result;
+
+ result = Py_BuildValue("f", m_startframe);
+
+ return result;
+}
+
+/* getBlendin */
+const char BL_ShapeActionActuator::GetBlendin_doc[] =
+"getBlendin()\n"
+"\tReturns the number of interpolation animation frames to be\n"
+"\tgenerated when this actuator is triggered.\n";
+
+PyObject* BL_ShapeActionActuator::PyGetBlendin(PyObject* self) {
+ PyObject *result;
+
+ result = Py_BuildValue("f", m_blendin);
+
+ return result;
+}
+
+/* getPriority */
+const char BL_ShapeActionActuator::GetPriority_doc[] =
+"getPriority()\n"
+"\tReturns the priority for this actuator. Actuators with lower\n"
+"\tPriority numbers will override actuators with higher numbers.\n";
+
+PyObject* BL_ShapeActionActuator::PyGetPriority(PyObject* self) {
+ PyObject *result;
+
+ result = Py_BuildValue("i", m_priority);
+
+ return result;
+}
+
+/* setAction */
+const char BL_ShapeActionActuator::SetAction_doc[] =
+"setAction(action, (reset))\n"
+"\t - action : The name of the action to set as the current action.\n"
+"\t Should be an action with Shape channels.\n"
+"\t - reset : Optional parameter indicating whether to reset the\n"
+"\t blend timer or not. A value of 1 indicates that the\n"
+"\t timer should be reset. A value of 0 will leave it\n"
+"\t unchanged. If reset is not specified, the timer will"
+"\t be reset.\n";
+
+PyObject* BL_ShapeActionActuator::PySetAction(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ char *string;
+ int reset = 1;
+
+ if (PyArg_ParseTuple(args,"s|i",&string, &reset))
+ {
+ bAction *action;
+
+ action = (bAction*)SCA_ILogicBrick::m_sCurrentLogicManager->GetActionByName(STR_String(string));
+
+ if (!action){
+ /* NOTE! Throw an exception or something */
+ // printf ("setAction failed: Action not found\n", string);
+ }
+ else{
+ m_action=action;
+ if (reset)
+ m_blendframe = 0.f;
+ }
+ }
+ else {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
+}
+
+/* setStart */
+const char BL_ShapeActionActuator::SetStart_doc[] =
+"setStart(start)\n"
+"\t - start : Specifies the starting frame of the animation.\n";
+
+PyObject* BL_ShapeActionActuator::PySetStart(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ float start;
+
+ if (PyArg_ParseTuple(args,"f",&start))
+ {
+ m_startframe = start;
+ }
+ else {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
+}
+
+/* setEnd */
+const char BL_ShapeActionActuator::SetEnd_doc[] =
+"setEnd(end)\n"
+"\t - end : Specifies the ending frame of the animation.\n";
+
+PyObject* BL_ShapeActionActuator::PySetEnd(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ float end;
+
+ if (PyArg_ParseTuple(args,"f",&end))
+ {
+ m_endframe = end;
+ }
+ else {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
+}
+
+/* setBlendin */
+const char BL_ShapeActionActuator::SetBlendin_doc[] =
+"setBlendin(blendin)\n"
+"\t - blendin : Specifies the number of frames of animation to generate\n"
+"\t when making transitions between actions.\n";
+
+PyObject* BL_ShapeActionActuator::PySetBlendin(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ float blendin;
+
+ if (PyArg_ParseTuple(args,"f",&blendin))
+ {
+ m_blendin = blendin;
+ }
+ else {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
+}
+
+/* setBlendtime */
+const char BL_ShapeActionActuator::SetBlendtime_doc[] =
+"setBlendtime(blendtime)\n"
+"\t - blendtime : Allows the script to directly modify the internal timer\n"
+"\t used when generating transitions between actions. This\n"
+"\t parameter must be in the range from 0.0 to 1.0.\n";
+
+PyObject* BL_ShapeActionActuator::PySetBlendtime(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ float blendframe;
+
+ if (PyArg_ParseTuple(args,"f",&blendframe))
+ {
+ m_blendframe = blendframe * m_blendin;
+ if (m_blendframe<0.f)
+ m_blendframe = 0.f;
+ if (m_blendframe>m_blendin)
+ m_blendframe = m_blendin;
+ }
+ else {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
+}
+
+/* setPriority */
+const char BL_ShapeActionActuator::SetPriority_doc[] =
+"setPriority(priority)\n"
+"\t - priority : Specifies the new priority. Actuators will lower\n"
+"\t priority numbers will override actuators with higher\n"
+"\t numbers.\n";
+
+PyObject* BL_ShapeActionActuator::PySetPriority(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ int priority;
+
+ if (PyArg_ParseTuple(args,"i",&priority))
+ {
+ m_priority = priority;
+ }
+ else {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
+}
+
+/* getProperty */
+const char BL_ShapeActionActuator::GetFrameProperty_doc[] =
+"getFrameProperty()\n"
+"\tReturns the name of the property, that is set to the current frame number.\n";
+
+PyObject* BL_ShapeActionActuator::PyGetFrameProperty(PyObject* self) {
+ PyObject *result;
+
+ result = Py_BuildValue("s", (const char *)m_framepropname);
+
+ return result;
+}
+
+
+/* setFrame */
+const char BL_ShapeActionActuator::SetFrame_doc[] =
+"setFrame(frame)\n"
+"\t - frame : Specifies the new current frame for the animation\n";
+
+PyObject* BL_ShapeActionActuator::PySetFrame(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ float frame;
+
+ if (PyArg_ParseTuple(args,"f",&frame))
+ {
+ m_localtime = frame;
+ if (m_localtime<m_startframe)
+ m_localtime=m_startframe;
+ else if (m_localtime>m_endframe)
+ m_localtime=m_endframe;
+ }
+ else {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
+}
+
+/* setProperty */
+const char BL_ShapeActionActuator::SetProperty_doc[] =
+"setProperty(prop)\n"
+"\t - prop : A string specifying the property name to be used in\n"
+"\t FromProp playback mode.\n";
+
+PyObject* BL_ShapeActionActuator::PySetProperty(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ char *string;
+
+ if (PyArg_ParseTuple(args,"s",&string))
+ {
+ m_propname = string;
+ }
+ else {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
+}
+
+/* setFrameProperty */
+const char BL_ShapeActionActuator::SetFrameProperty_doc[] =
+"setFrameProperty(prop)\n"
+"\t - prop : A string specifying the property of the frame set up update.\n";
+
+PyObject* BL_ShapeActionActuator::PySetFrameProperty(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ char *string;
+
+ if (PyArg_ParseTuple(args,"s",&string))
+ {
+ m_framepropname = string;
+ }
+ else {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
+}
+
+/* getType */
+const char BL_ShapeActionActuator::GetType_doc[] =
+"getType()\n"
+"\tReturns the operation mode of the actuator.\n";
+PyObject* BL_ShapeActionActuator::PyGetType(PyObject* self) {
+ return Py_BuildValue("h", m_playtype);
+}
+
+/* setType */
+const char BL_ShapeActionActuator::SetType_doc[] =
+"setType(mode)\n"
+"\t - mode: Play (0), Flipper (2), LoopStop (3), LoopEnd (4) or Property (6)\n"
+"\tSet the operation mode of the actuator.\n";
+PyObject* BL_ShapeActionActuator::PySetType(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ short typeArg;
+
+ if (!PyArg_ParseTuple(args, "h", &typeArg)) {
+ return NULL;
+ }
+
+ switch (typeArg) {
+ case ACT_ACTION_PLAY:
+ case ACT_ACTION_FLIPPER:
+ case ACT_ACTION_LOOP_STOP:
+ case ACT_ACTION_LOOP_END:
+ case ACT_ACTION_FROM_PROP:
+ m_playtype = typeArg;
+ break;
+ default:
+ printf("Invalid type for action actuator: %d\n", typeArg); /* error */
+ }
+
+ Py_Return;
+}
+
diff --git a/source/gameengine/Converter/BL_ShapeActionActuator.h b/source/gameengine/Converter/BL_ShapeActionActuator.h
new file mode 100644
index 00000000000..30b2d41fc67
--- /dev/null
+++ b/source/gameengine/Converter/BL_ShapeActionActuator.h
@@ -0,0 +1,138 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef BL_SHAPEACTIONACTUATOR
+#define BL_SHAPEACTIONACTUATOR
+
+#include "GEN_HashedPtr.h"
+#include "SCA_IActuator.h"
+#include "MT_Point3.h"
+#include <vector>
+
+struct Key;
+class BL_ShapeActionActuator : public SCA_IActuator
+{
+public:
+ Py_Header;
+ BL_ShapeActionActuator(SCA_IObject* gameobj,
+ const STR_String& propname,
+ const STR_String& framepropname,
+ float starttime,
+ float endtime,
+ struct bAction *action,
+ short playtype,
+ short blendin,
+ short priority,
+ float stride,
+ PyTypeObject* T=&Type)
+ : SCA_IActuator(gameobj,T),
+
+ m_lastpos(0, 0, 0),
+ m_blendframe(0),
+ m_flag(0),
+ m_startframe (starttime),
+ m_endframe(endtime) ,
+ m_starttime(0),
+ m_localtime(starttime),
+ m_lastUpdate(-1),
+ m_blendin(blendin),
+ m_blendstart(0),
+ m_stridelength(stride),
+ m_playtype(playtype),
+ m_priority(priority),
+ m_action(action),
+ m_framepropname(framepropname),
+ m_propname(propname)
+ {
+ };
+ virtual ~BL_ShapeActionActuator();
+ virtual bool Update(double curtime, bool frame);
+ virtual CValue* GetReplica();
+ virtual void ProcessReplica();
+
+ void SetBlendTime (float newtime);
+ void BlendShape(struct Key* key, float weigth);
+
+ KX_PYMETHOD_DOC(BL_ShapeActionActuator,SetAction);
+ KX_PYMETHOD_DOC(BL_ShapeActionActuator,SetBlendin);
+ KX_PYMETHOD_DOC(BL_ShapeActionActuator,SetPriority);
+ KX_PYMETHOD_DOC(BL_ShapeActionActuator,SetStart);
+ KX_PYMETHOD_DOC(BL_ShapeActionActuator,SetEnd);
+ KX_PYMETHOD_DOC(BL_ShapeActionActuator,SetFrame);
+ KX_PYMETHOD_DOC(BL_ShapeActionActuator,SetProperty);
+ KX_PYMETHOD_DOC(BL_ShapeActionActuator,SetFrameProperty);
+ KX_PYMETHOD_DOC(BL_ShapeActionActuator,SetBlendtime);
+ KX_PYMETHOD_DOC(BL_ShapeActionActuator,SetChannel);
+
+ KX_PYMETHOD_DOC_NOARGS(BL_ShapeActionActuator,GetAction);
+ KX_PYMETHOD_DOC_NOARGS(BL_ShapeActionActuator,GetBlendin);
+ KX_PYMETHOD_DOC_NOARGS(BL_ShapeActionActuator,GetPriority);
+ KX_PYMETHOD_DOC_NOARGS(BL_ShapeActionActuator,GetStart);
+ KX_PYMETHOD_DOC_NOARGS(BL_ShapeActionActuator,GetEnd);
+ KX_PYMETHOD_DOC_NOARGS(BL_ShapeActionActuator,GetFrame);
+ KX_PYMETHOD_DOC_NOARGS(BL_ShapeActionActuator,GetProperty);
+ KX_PYMETHOD_DOC_NOARGS(BL_ShapeActionActuator,GetFrameProperty);
+// KX_PYMETHOD(BL_ActionActuator,GetChannel);
+ KX_PYMETHOD_DOC_NOARGS(BL_ShapeActionActuator,GetType);
+ KX_PYMETHOD_DOC(BL_ShapeActionActuator,SetType);
+
+ virtual PyObject* _getattr(const STR_String& attr);
+
+protected:
+
+ void SetStartTime(float curtime);
+ void SetLocalTime(float curtime);
+ bool ClampLocalTime();
+
+ MT_Point3 m_lastpos;
+ float m_blendframe;
+ int m_flag;
+ /** The frame this action starts */
+ float m_startframe;
+ /** The frame this action ends */
+ float m_endframe;
+ /** The time this action started */
+ float m_starttime;
+ /** The current time of the action */
+ float m_localtime;
+
+ float m_lastUpdate;
+ float m_blendin;
+ float m_blendstart;
+ float m_stridelength;
+ short m_playtype;
+ short m_priority;
+ struct bAction *m_action;
+ STR_String m_propname;
+ STR_String m_framepropname;
+ vector<float> m_blendshape;
+};
+
+#endif
+
diff --git a/source/gameengine/Converter/BL_ShapeDeformer.cpp b/source/gameengine/Converter/BL_ShapeDeformer.cpp
new file mode 100644
index 00000000000..fc6498579ad
--- /dev/null
+++ b/source/gameengine/Converter/BL_ShapeDeformer.cpp
@@ -0,0 +1,182 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifdef WIN32
+#pragma warning (disable : 4786)
+#endif //WIN32
+
+#include "MEM_guardedalloc.h"
+#include "BL_ShapeDeformer.h"
+#include "GEN_Map.h"
+#include "STR_HashedString.h"
+#include "RAS_IPolygonMaterial.h"
+#include "BL_SkinMeshObject.h"
+
+//#include "BL_ArmatureController.h"
+#include "DNA_armature_types.h"
+#include "DNA_action_types.h"
+#include "DNA_key_types.h"
+#include "DNA_mesh_types.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_ipo_types.h"
+#include "DNA_curve_types.h"
+#include "BKE_armature.h"
+#include "BKE_action.h"
+#include "BKE_key.h"
+#include "BKE_ipo.h"
+#include "MT_Point3.h"
+
+extern "C"{
+ #include "BKE_lattice.h"
+}
+ #include "BKE_utildefines.h"
+
+#include "BLI_blenlib.h"
+#include "BLI_arithb.h"
+
+#define __NLA_DEFNORMALS
+//#undef __NLA_DEFNORMALS
+
+
+BL_ShapeDeformer::~BL_ShapeDeformer()
+{
+};
+
+RAS_Deformer *BL_ShapeDeformer::GetReplica(class KX_GameObject* replica)
+{
+ BL_ShapeDeformer *result;
+
+ result = new BL_ShapeDeformer(*this);
+ result->ProcessReplica();
+ return result;
+}
+
+void BL_ShapeDeformer::ProcessReplica()
+{
+}
+
+bool BL_ShapeDeformer::LoadShapeDrivers(Object* arma)
+{
+ IpoCurve *icu;
+
+ m_shapeDrivers.clear();
+ // check if this mesh has armature driven shape keys
+ if (m_bmesh->key->ipo) {
+ for(icu= (IpoCurve*)m_bmesh->key->ipo->curve.first; icu; icu= (IpoCurve*)icu->next) {
+ if(icu->driver &&
+ (icu->flag & IPO_MUTE) == 0 &&
+ icu->driver->type == IPO_DRIVER_TYPE_NORMAL &&
+ icu->driver->ob == arma &&
+ icu->driver->blocktype == ID_AR) {
+ // this shape key ipo curve has a driver on the parent armature
+ // record this curve in the shape deformer so that the corresponding
+ m_shapeDrivers.push_back(icu);
+ }
+ }
+ }
+ return !m_shapeDrivers.empty();
+}
+
+bool BL_ShapeDeformer::ExecuteShapeDrivers(void)
+{
+ if (!m_shapeDrivers.empty() && PoseUpdated()) {
+ vector<IpoCurve*>::iterator it;
+ void *poin;
+ int type;
+
+ // the shape drivers use the bone matrix as input. Must
+ // update the matrix now
+ m_armobj->ApplyPose();
+
+ for (it=m_shapeDrivers.begin(); it!=m_shapeDrivers.end(); it++) {
+ // no need to set a specific time: this curve has a driver
+ IpoCurve *icu = *it;
+ calc_icu(icu, 1.0f);
+ poin = get_ipo_poin((ID*)m_bmesh->key, icu, &type);
+ if (poin)
+ write_ipo_poin(poin, type, icu->curval);
+ }
+
+ ForceUpdate();
+ m_armobj->RestorePose();
+
+ return true;
+ }
+ return false;
+}
+
+bool BL_ShapeDeformer::Update(void)
+{
+ bool bShapeUpdate = false;
+ bool bSkinUpdate = false;
+
+ ExecuteShapeDrivers();
+
+ /* See if the object shape has changed */
+ if (m_lastShapeUpdate != m_gameobj->GetLastFrame()) {
+ /* the key coefficient have been set already, we just need to blend the keys */
+ Object* blendobj = m_gameobj->GetBlendObject();
+
+ // make sure the vertex weight cache is in line with this object
+ m_pMeshObject->CheckWeightCache(blendobj);
+
+ /* we will blend the key directly in mvert array: it is used by armature as the start position */
+ do_rel_key(0, m_bmesh->totvert, m_bmesh->totvert, (char *)m_bmesh->mvert->co, m_bmesh->key, 0);
+
+ // Don't release the weight array as in Blender, it will most likely be reusable on next frame
+ // The weight array are ultimately deleted when the skin mesh is destroyed
+
+ /* Update the current frame */
+ m_lastShapeUpdate=m_gameobj->GetLastFrame();
+
+ // As we have changed, the mesh, the skin deformer must update as well.
+ // This will force the update
+ BL_SkinDeformer::ForceUpdate();
+ bShapeUpdate = true;
+ }
+ // check for armature deform
+ bSkinUpdate = BL_SkinDeformer::Update();
+
+ if (!bSkinUpdate && bShapeUpdate) {
+ // this means that there is no armature, we still need to copy the vertex to m_transverts
+ // and update the normal (was not done after shape key calculation)
+
+ /* store verts locally */
+ VerifyStorage();
+
+ for (int v =0; v<m_bmesh->totvert; v++)
+ VECCOPY(m_transverts[v], m_bmesh->mvert[v].co);
+
+#ifdef __NLA_DEFNORMALS
+ RecalcNormals();
+#endif
+ bSkinUpdate = true;
+ }
+ return bSkinUpdate;
+}
diff --git a/source/gameengine/Converter/BL_ShapeDeformer.h b/source/gameengine/Converter/BL_ShapeDeformer.h
new file mode 100644
index 00000000000..90b9f5caea1
--- /dev/null
+++ b/source/gameengine/Converter/BL_ShapeDeformer.h
@@ -0,0 +1,88 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef BL_SHAPEDEFORMER
+#define BL_SHAPEDEFORMER
+
+#ifdef WIN32
+#pragma warning (disable:4786) // get rid of stupid stl-visual compiler debug warning
+#endif //WIN32
+
+#include "BL_SkinDeformer.h"
+#include "BL_DeformableGameObject.h"
+#include <vector>
+
+struct IpoCurve;
+
+class BL_ShapeDeformer : public BL_SkinDeformer
+{
+public:
+ BL_ShapeDeformer(BL_DeformableGameObject *gameobj,
+ Object *bmeshobj,
+ BL_SkinMeshObject *mesh)
+ :
+ BL_SkinDeformer(gameobj,bmeshobj, mesh),
+ m_lastShapeUpdate(-1)
+ {
+ };
+
+ /* this second constructor is needed for making a mesh deformable on the fly. */
+ BL_ShapeDeformer(BL_DeformableGameObject *gameobj,
+ struct Object *bmeshobj_old,
+ struct Object *bmeshobj_new,
+ class BL_SkinMeshObject *mesh,
+ bool release_object,
+ BL_ArmatureObject* arma = NULL)
+ :
+ BL_SkinDeformer(gameobj, bmeshobj_old, bmeshobj_new, mesh, release_object, arma),
+ m_lastShapeUpdate(-1)
+ {
+ };
+
+ virtual void ProcessReplica();
+ virtual RAS_Deformer *GetReplica(class KX_GameObject* replica);
+ virtual ~BL_ShapeDeformer();
+
+ bool Update (void);
+ bool LoadShapeDrivers(Object* arma);
+ bool ExecuteShapeDrivers(void);
+
+ void ForceUpdate()
+ {
+ m_lastShapeUpdate = -1.0;
+ };
+
+protected:
+ vector<IpoCurve*> m_shapeDrivers;
+ double m_lastShapeUpdate;
+
+};
+
+#endif
+
diff --git a/source/gameengine/Converter/BL_SkinDeformer.cpp b/source/gameengine/Converter/BL_SkinDeformer.cpp
index d6aee363a16..d8563763954 100644
--- a/source/gameengine/Converter/BL_SkinDeformer.cpp
+++ b/source/gameengine/Converter/BL_SkinDeformer.cpp
@@ -57,86 +57,96 @@ extern "C"{
#define __NLA_DEFNORMALS
//#undef __NLA_DEFNORMALS
-BL_SkinDeformer::~BL_SkinDeformer()
+BL_SkinDeformer::BL_SkinDeformer(BL_DeformableGameObject *gameobj,
+ struct Object *bmeshobj,
+ class BL_SkinMeshObject *mesh,
+ BL_ArmatureObject* arma)
+ : //
+ BL_MeshDeformer(gameobj, bmeshobj, mesh),
+ m_armobj(arma),
+ m_lastArmaUpdate(-1),
+ m_defbase(&bmeshobj->defbase),
+ m_releaseobject(false),
+ m_poseApplied(false)
{
- if(m_releaseobject && m_armobj)
- m_armobj->Release();
+ Mat4CpyMat4(m_obmat, bmeshobj->obmat);
};
-/* XXX note, this __NLA_OLDDEFORM define seems to be obsolete */
+BL_SkinDeformer::BL_SkinDeformer(
+ BL_DeformableGameObject *gameobj,
+ struct Object *bmeshobj_old, // Blender object that owns the new mesh
+ struct Object *bmeshobj_new, // Blender object that owns the original mesh
+ class BL_SkinMeshObject *mesh,
+ bool release_object,
+ BL_ArmatureObject* arma) :
+ BL_MeshDeformer(gameobj, bmeshobj_old, mesh),
+ m_armobj(arma),
+ m_lastArmaUpdate(-1),
+ m_defbase(&bmeshobj_old->defbase),
+ m_releaseobject(release_object)
+ {
+ // this is needed to ensure correct deformation of mesh:
+ // the deformation is done with Blender's armature_deform_verts() function
+ // that takes an object as parameter and not a mesh. The object matrice is used
+ // in the calculation, so we must use the matrix of the original object to
+ // simulate a pure replacement of the mesh.
+ Mat4CpyMat4(m_obmat, bmeshobj_new->obmat);
+ }
-bool BL_SkinDeformer::Apply(RAS_IPolyMaterial *mat)
+BL_SkinDeformer::~BL_SkinDeformer()
{
- size_t i, j, index;
- vecVertexArray array;
-#ifdef __NLA_OLDDEFORM
- vecMVertArray mvarray;
-#else
- vecIndexArrays mvarray;
-#endif
- vecMDVertArray dvarray;
- vecIndexArrays diarray;
+ if(m_releaseobject && m_armobj)
+ m_armobj->Release();
+}
- RAS_TexVert *tv;
-#ifdef __NLA_OLDDEFORM
- MVert *mvert;
- MDeformVert *dvert;
-#endif
- MT_Point3 pt;
-// float co[3];
+void BL_SkinDeformer::Relink(GEN_Map<class GEN_HashedPtr, void*>*map)
+{
+ if (m_armobj) {
+ void **h_obj = (*map)[m_armobj];
- if (!m_armobj)
- return false;
+ if (h_obj)
+ SetArmature( (BL_ArmatureObject*)(*h_obj) );
+ else
+ m_armobj=NULL;
+ }
- Update();
+ BL_MeshDeformer::Relink(map);
+}
- array = m_pMeshObject->GetVertexCache(mat);
-#ifdef __NLA_OLDDEFORM
- dvarray = m_pMeshObject->GetDVertCache(mat);
-#endif
- mvarray = m_pMeshObject->GetMVertCache(mat);
- diarray = m_pMeshObject->GetDIndexCache(mat);
-
+bool BL_SkinDeformer::Apply(RAS_IPolyMaterial *mat)
+{
+ RAS_MeshSlot::iterator it;
+ RAS_MeshMaterial *mmat;
+ RAS_MeshSlot *slot;
+ size_t i;
- // For each array
- for (i=0; i<array.size(); i++){
- // For each vertex
- for (j=0; j<array[i]->size(); j++){
-
- tv = &((*array[i])[j]);
-
- index = ((*diarray[i])[j]);
-#ifdef __NLA_OLDDEFORM
- pt = tv->xyz();
- mvert = ((*mvarray[i])[index]);
- dvert = ((*dvarray[i])[index]);
-#endif
-
- // Copy the untransformed data from the original mvert
-#ifdef __NLA_OLDDEFORM
- co[0]=mvert->co[0];
- co[1]=mvert->co[1];
- co[2]=mvert->co[2];
-
- // Do the deformation
-/* XXX note, doesnt exist anymore */
-// GB_calc_armature_deform(co, dvert);
- tv->SetXYZ(co);
-#else
- // Set the data
- tv->SetXYZ(m_transverts[((*mvarray[i])[index])]);
-#ifdef __NLA_DEFNORMALS
+ // update the vertex in m_transverts
+ Update();
- tv->SetNormal(m_transnors[((*mvarray[i])[index])]);
-#endif
-#endif
+ // The vertex cache can only be updated for this deformer:
+ // Duplicated objects with more than one ploymaterial (=multiple mesh slot per object)
+ // share the same mesh (=the same cache). As the rendering is done per polymaterial
+ // cycling through the objects, the entire mesh cache cannot be updated in one shot.
+ mmat = m_pMeshObject->GetMeshMaterial(mat);
+ if(!mmat->m_slots[(void*)m_gameobj])
+ return true;
+
+ slot = *mmat->m_slots[(void*)m_gameobj];
+
+ // for each array
+ for(slot->begin(it); !slot->end(it); slot->next(it)) {
+ // for each vertex
+ // copy the untransformed data from the original mvert
+ for(i=it.startvertex; i<it.endvertex; i++) {
+ RAS_TexVert& v = it.vertex[i];
+ v.SetXYZ(m_transverts[v.getOrigIndex()]);
}
}
-
+
return true;
}
-RAS_Deformer *BL_SkinDeformer::GetReplica()
+RAS_Deformer *BL_SkinDeformer::GetReplica(class KX_GameObject* replica)
{
BL_SkinDeformer *result;
@@ -151,19 +161,15 @@ void BL_SkinDeformer::ProcessReplica()
//void where_is_pose (Object *ob);
//void armature_deform_verts(Object *armOb, Object *target, float (*vertexCos)[3], int numVerts, int deformflag);
-void BL_SkinDeformer::Update(void)
+bool BL_SkinDeformer::Update(void)
{
/* See if the armature has been updated for this frame */
- if (m_lastUpdate!=m_armobj->GetLastFrame()){
-
- /* Do all of the posing necessary */
- m_armobj->ApplyPose();
-
+ if (PoseUpdated()){
+ float obmat[4][4]; // the original object matrice
+
/* XXX note: where_is_pose() (from BKE_armature.h) calculates all matrices needed to start deforming */
/* but it requires the blender object pointer... */
-
Object* par_arma = m_armobj->GetArmatureObject();
- where_is_pose( par_arma );
/* store verts locally */
VerifyStorage();
@@ -172,12 +178,32 @@ void BL_SkinDeformer::Update(void)
for (int v =0; v<m_bmesh->totvert; v++)
VECCOPY(m_transverts[v], m_bmesh->mvert[v].co);
+ m_armobj->ApplyPose();
+
+ // save matrix first
+ Mat4CpyMat4(obmat, m_objMesh->obmat);
+ // set reference matrix
+ Mat4CpyMat4(m_objMesh->obmat, m_obmat);
+
armature_deform_verts( par_arma, m_objMesh, NULL, m_transverts, NULL, m_bmesh->totvert, ARM_DEF_VGROUP, NULL, NULL );
+
+ // restore matrix
+ Mat4CpyMat4(m_objMesh->obmat, obmat);
+
+#ifdef __NLA_DEFNORMALS
RecalcNormals();
+#endif
/* Update the current frame */
- m_lastUpdate=m_armobj->GetLastFrame();
+ m_lastArmaUpdate=m_armobj->GetLastFrame();
+
+ m_armobj->RestorePose();
+
+ /* indicate that the m_transverts and normals are up to date */
+ return true;
}
+
+ return false;
}
/* XXX note: I propose to drop this function */
diff --git a/source/gameengine/Converter/BL_SkinDeformer.h b/source/gameengine/Converter/BL_SkinDeformer.h
index f14baf09651..f87860021c6 100644
--- a/source/gameengine/Converter/BL_SkinDeformer.h
+++ b/source/gameengine/Converter/BL_SkinDeformer.h
@@ -50,56 +50,48 @@ class BL_SkinDeformer : public BL_MeshDeformer
{
public:
// void SetArmatureController (BL_ArmatureController *cont);
- virtual void Relink(GEN_Map<class GEN_HashedPtr, void*>*map)
- {
- void **h_obj = (*map)[m_armobj];
- if (h_obj){
- SetArmature( (BL_ArmatureObject*)(*h_obj) );
- }
- else
- m_armobj=NULL;
- }
+ virtual void Relink(GEN_Map<class GEN_HashedPtr, void*>*map);
void SetArmature (class BL_ArmatureObject *armobj);
- BL_SkinDeformer(struct Object *bmeshobj,
+ BL_SkinDeformer(BL_DeformableGameObject *gameobj,
+ struct Object *bmeshobj,
class BL_SkinMeshObject *mesh,
- BL_ArmatureObject* arma = NULL)
- : //
- BL_MeshDeformer(bmeshobj, mesh),
- m_armobj(arma),
- m_lastUpdate(-1),
- m_defbase(&bmeshobj->defbase),
- m_releaseobject(false)
- {
- };
+ BL_ArmatureObject* arma = NULL);
/* this second constructor is needed for making a mesh deformable on the fly. */
- BL_SkinDeformer(struct Object *bmeshobj_old,
+ BL_SkinDeformer(BL_DeformableGameObject *gameobj,
+ struct Object *bmeshobj_old,
struct Object *bmeshobj_new,
class BL_SkinMeshObject *mesh,
bool release_object,
- BL_ArmatureObject* arma = NULL)
- : //
- BL_MeshDeformer(bmeshobj_old, mesh),
- m_armobj(arma),
- m_lastUpdate(-1),
- m_defbase(&bmeshobj_old->defbase),
- m_releaseobject(release_object)
- {
- };
+ BL_ArmatureObject* arma = NULL);
virtual void ProcessReplica();
- virtual RAS_Deformer *GetReplica();
+ virtual RAS_Deformer *GetReplica(class KX_GameObject* replica);
virtual ~BL_SkinDeformer();
- void Update (void);
+ bool Update (void);
bool Apply (class RAS_IPolyMaterial *polymat);
+ bool PoseUpdated(void)
+ {
+ if (m_armobj && m_lastArmaUpdate!=m_armobj->GetLastFrame()) {
+ return true;
+ }
+ return false;
+ }
+
+ void ForceUpdate()
+ {
+ m_lastArmaUpdate = -1.0;
+ };
protected:
BL_ArmatureObject* m_armobj; // Our parent object
float m_time;
- double m_lastUpdate;
+ double m_lastArmaUpdate;
ListBase* m_defbase;
+ float m_obmat[4][4]; // the reference matrix for skeleton deform
bool m_releaseobject;
+ bool m_poseApplied;
};
diff --git a/source/gameengine/Converter/BL_SkinMeshObject.cpp b/source/gameengine/Converter/BL_SkinMeshObject.cpp
index 8bc78c7f757..eb3f9d0588d 100644
--- a/source/gameengine/Converter/BL_SkinMeshObject.cpp
+++ b/source/gameengine/Converter/BL_SkinMeshObject.cpp
@@ -28,127 +28,129 @@
* Deformer that supports armature skinning
*/
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
#ifdef WIN32
#pragma warning (disable:4786) // get rid of stupid stl-visual compiler debug warning
#endif //WIN32
-#include "RAS_IPolygonMaterial.h"
-#include "BL_SkinMeshObject.h"
-#include "BL_DeformableGameObject.h"
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_key_types.h"
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
-#include "KX_GameObject.h"
+
#include "RAS_BucketManager.h"
+#include "RAS_IPolygonMaterial.h"
-void BL_SkinMeshObject::AddPolygon(RAS_Polygon* poly)
-{
- /* We're overriding this so that we can eventually associate faces with verts somehow */
+#include "KX_GameObject.h"
- // For vertIndex in poly:
- // find the appropriate normal
+#include "BL_SkinMeshObject.h"
+#include "BL_DeformableGameObject.h"
- RAS_MeshObject::AddPolygon(poly);
-}
+BL_SkinMeshObject::BL_SkinMeshObject(Mesh* mesh, int lightlayer)
+ : RAS_MeshObject (mesh, lightlayer)
+{
+ m_bDeformed = true;
-#ifdef __NLA_OLDDEFORM
-int BL_SkinMeshObject::FindOrAddDeform(int vtxarray, struct MVert *mv, struct MDeformVert *dv, RAS_IPolyMaterial* mat)
-#else
-int BL_SkinMeshObject::FindOrAddDeform(unsigned int vtxarray, unsigned int mv, struct MDeformVert *dv, RAS_IPolyMaterial* mat)
-#endif
-{
- BL_SkinArrayOptimizer* ao = (BL_SkinArrayOptimizer*)GetArrayOptimizer(mat);//*(m_matVertexArrays[*mat]);
- int numvert = ao->m_MvertArrayCache1[vtxarray]->size();
-
- /* Check to see if this has already been pushed */
- for (unsigned int i=0; i<ao->m_MvertArrayCache1[vtxarray]->size(); i++){
- if (mv == (*ao->m_MvertArrayCache1[vtxarray])[i])
- return i;
+ if (m_mesh && m_mesh->key)
+ {
+ KeyBlock *kb;
+ int count=0;
+ // initialize weight cache for shape objects
+ // count how many keys in this mesh
+ for(kb= (KeyBlock*)m_mesh->key->block.first; kb; kb= (KeyBlock*)kb->next)
+ count++;
+ m_cacheWeightIndex.resize(count,-1);
}
+}
- ao->m_MvertArrayCache1[vtxarray]->push_back(mv);
- ao->m_DvertArrayCache1[vtxarray]->push_back(dv);
-
- return numvert;
-};
-
-int BL_SkinMeshObject::FindVertexArray(int numverts,RAS_IPolyMaterial* polymat)
+BL_SkinMeshObject::~BL_SkinMeshObject()
{
- int array=-1;
-
- BL_SkinArrayOptimizer* ao = (BL_SkinArrayOptimizer*)GetArrayOptimizer(polymat);
-
-
- for (size_t i=0;i<ao->m_VertexArrayCache1.size();i++)
+ if (m_mesh && m_mesh->key)
{
- if ( (ao->m_TriangleArrayCount[i] + (numverts-2)) < BUCKET_MAX_TRIANGLES)
- {
- if((ao->m_VertexArrayCache1[i]->size()+numverts < BUCKET_MAX_INDICES))
- {
- array = i;
- ao->m_TriangleArrayCount[array]+=numverts-2;
- break;
- }
+ KeyBlock *kb;
+ // remove the weight cache to avoid memory leak
+ for(kb= (KeyBlock*)m_mesh->key->block.first; kb; kb= (KeyBlock*)kb->next) {
+ if(kb->weights)
+ MEM_freeN(kb->weights);
+ kb->weights= NULL;
}
}
-
+}
- if (array == -1)
- {
- array = ao->m_VertexArrayCache1.size();
-
- vector<RAS_TexVert>* va = new vector<RAS_TexVert>;
- ao->m_VertexArrayCache1.push_back(va);
-
- KX_IndexArray *ia = new KX_IndexArray();
- ao->m_IndexArrayCache1.push_back(ia);
+void BL_SkinMeshObject::UpdateBuckets(void* clientobj,double* oglmatrix,bool useObjectColor,const MT_Vector4& rgbavec, bool visible, bool culled)
+{
+ list<RAS_MeshMaterial>::iterator it;
+ list<RAS_MeshSlot*>::iterator sit;
-#ifdef __NLA_OLDDEFORM
- BL_MVertArray *bva = new BL_MVertArray();
-#else
- KX_IndexArray *bva = new KX_IndexArray();
-#endif
- ao->m_MvertArrayCache1.push_back(bva);
+ for(it = m_materials.begin();it!=m_materials.end();++it) {
+ if(!it->m_slots[clientobj])
+ continue;
- BL_DeformVertArray *dva = new BL_DeformVertArray();
- ao->m_DvertArrayCache1.push_back(dva);
+ RAS_MeshSlot *slot = *it->m_slots[clientobj];
+ slot->m_pDeformer = ((BL_DeformableGameObject*)clientobj)->GetDeformer();
+ }
- KX_IndexArray *da = new KX_IndexArray();
- ao->m_DIndexArrayCache1.push_back(da);
+ RAS_MeshObject::UpdateBuckets(clientobj, oglmatrix, useObjectColor, rgbavec, visible, culled);
+}
- ao->m_TriangleArrayCount.push_back(numverts-2);
+static int get_def_index(Object* ob, const char* vgroup)
+{
+ bDeformGroup *curdef;
+ int index = 0;
- }
+ for (curdef = (bDeformGroup*)ob->defbase.first; curdef; curdef=(bDeformGroup*)curdef->next, index++)
+ if (!strcmp(curdef->name, vgroup))
+ return index;
-
- return array;
+ return -1;
}
-
-//void BL_SkinMeshObject::Bucketize(double* oglmatrix,void* clientobj,bool useObjectColor,const MT_Vector4& rgbavec,RAS_BucketManager* bucketmgr)
-void BL_SkinMeshObject::Bucketize(double* oglmatrix,void* clientobj,bool useObjectColor,const MT_Vector4& rgbavec)
+void BL_SkinMeshObject::CheckWeightCache(Object* obj)
{
+ KeyBlock *kb;
+ int kbindex, defindex;
+ MDeformVert *dvert= NULL;
+ int totvert, i, j;
+ float *weights;
- KX_MeshSlot ms;
- ms.m_clientObj = clientobj;
- ms.m_mesh = this;
- ms.m_OpenGLMatrix = oglmatrix;
- ms.m_bObjectColor = useObjectColor;
- ms.m_RGBAcolor = rgbavec;
- ms.m_pDeformer = ((BL_DeformableGameObject*)clientobj)->m_pDeformer;
-
- for (RAS_MaterialBucket::Set::iterator it = m_materials.begin();it!=m_materials.end();it++)
- {
-
- RAS_MaterialBucket* materialbucket = (*it);
+ if (!m_mesh->key)
+ return;
-// KX_ArrayOptimizer* oa = GetArrayOptimizer(materialbucket->GetPolyMaterial());
- materialbucket->SetMeshSlot(ms);
+ for(kbindex=0, kb= (KeyBlock*)m_mesh->key->block.first; kb; kb= (KeyBlock*)kb->next, kbindex++)
+ {
+ // first check the cases where the weight must be cleared
+ if (kb->vgroup[0] == 0 ||
+ m_mesh->dvert == NULL ||
+ (defindex = get_def_index(obj, kb->vgroup)) == -1) {
+ if (kb->weights) {
+ MEM_freeN(kb->weights);
+ kb->weights = NULL;
+ }
+ m_cacheWeightIndex[kbindex] = -1;
+ } else if (m_cacheWeightIndex[kbindex] != defindex) {
+ // a weight array is required but the cache is not matching
+ if (kb->weights) {
+ MEM_freeN(kb->weights);
+ kb->weights = NULL;
+ }
+
+ dvert= m_mesh->dvert;
+ totvert= m_mesh->totvert;
+
+ weights= (float*)MEM_callocN(totvert*sizeof(float), "weights");
+
+ for (i=0; i < totvert; i++, dvert++) {
+ for(j=0; j<dvert->totweight; j++) {
+ if (dvert->dw[j].def_nr == defindex) {
+ weights[i]= dvert->dw[j].weight;
+ break;
+ }
+ }
+ }
+ kb->weights = weights;
+ m_cacheWeightIndex[kbindex] = defindex;
+ }
}
-
}
-
diff --git a/source/gameengine/Converter/BL_SkinMeshObject.h b/source/gameengine/Converter/BL_SkinMeshObject.h
index 0ca7428c0f0..8544a2b958c 100644
--- a/source/gameengine/Converter/BL_SkinMeshObject.h
+++ b/source/gameengine/Converter/BL_SkinMeshObject.h
@@ -40,138 +40,20 @@
#include "BL_MeshDeformer.h"
-#include "DNA_mesh_types.h"
-#include "DNA_meshdata_types.h"
-
-typedef vector<struct MVert*> BL_MVertArray;
-typedef vector<struct MDeformVert*> BL_DeformVertArray;
-typedef vector<class BL_TexVert> BL_VertexArray;
-
-
-typedef vector<vector<struct MDeformVert*>*> vecMDVertArray;
-typedef vector<vector<class BL_TexVert>*> vecBVertexArray;
-
-class BL_SkinArrayOptimizer : public KX_ArrayOptimizer
-{
-public:
- BL_SkinArrayOptimizer(int index)
- :KX_ArrayOptimizer (index) {};
- virtual ~BL_SkinArrayOptimizer(){
-
- for (vector<KX_IndexArray*>::iterator itv = m_MvertArrayCache1.begin();
- !(itv == m_MvertArrayCache1.end());itv++)
- {
- delete (*itv);
- }
- for (vector<BL_DeformVertArray*>::iterator itd = m_DvertArrayCache1.begin();
- !(itd == m_DvertArrayCache1.end());itd++)
- {
- delete (*itd);
- }
- for (vector<KX_IndexArray*>::iterator iti = m_DIndexArrayCache1.begin();
- !(iti == m_DIndexArrayCache1.end());iti++)
- {
- delete (*iti);
- }
-
- m_MvertArrayCache1.clear();
- m_DvertArrayCache1.clear();
- m_DIndexArrayCache1.clear();
- };
-
- vector<KX_IndexArray*> m_MvertArrayCache1;
- vector<BL_DeformVertArray*> m_DvertArrayCache1;
- vector<KX_IndexArray*> m_DIndexArrayCache1;
-
-};
-
class BL_SkinMeshObject : public RAS_MeshObject
{
-
-// enum { BUCKET_MAX_INDICES = 16384};//2048};//8192};
-// enum { BUCKET_MAX_TRIANGLES = 4096};
-
- KX_ArrayOptimizer* GetArrayOptimizer(RAS_IPolyMaterial* polymat)
- {
- KX_ArrayOptimizer** aop = (m_matVertexArrayS[*polymat]);
- if (aop)
- return *aop;
- int numelements = m_matVertexArrayS.size();
- m_sortedMaterials.push_back(polymat);
-
- BL_SkinArrayOptimizer* ao = new BL_SkinArrayOptimizer(numelements);
- m_matVertexArrayS.insert(*polymat,ao);
- return ao;
- }
-
protected:
-public:
- void Bucketize(double* oglmatrix,void* clientobj,bool useObjectColor,const MT_Vector4& rgbavec);
-// void Bucketize(double* oglmatrix,void* clientobj,bool useObjectColor,const MT_Vector4& rgbavec,class RAS_BucketManager* bucketmgr);
-
- int FindVertexArray(int numverts,RAS_IPolyMaterial* polymat);
- BL_SkinMeshObject(int lightlayer) : RAS_MeshObject (lightlayer)
- { m_class = 1;};
+ vector<int> m_cacheWeightIndex;
- virtual ~BL_SkinMeshObject(){
- };
+public:
+ BL_SkinMeshObject(Mesh* mesh, int lightlayer);
+ ~BL_SkinMeshObject();
- const vecIndexArrays& GetDIndexCache (RAS_IPolyMaterial* mat)
- {
- BL_SkinArrayOptimizer* ao = (BL_SkinArrayOptimizer*)GetArrayOptimizer(mat);//*(m_matVertexArrays[*mat]);
- return ao->m_DIndexArrayCache1;
- }
- const vecMDVertArray& GetDVertCache (RAS_IPolyMaterial* mat)
- {
- BL_SkinArrayOptimizer* ao = (BL_SkinArrayOptimizer*)GetArrayOptimizer(mat);//*(m_matVertexArrays[*mat]);
- return ao->m_DvertArrayCache1;
- }
- const vecIndexArrays& GetMVertCache (RAS_IPolyMaterial* mat)
- {
- BL_SkinArrayOptimizer* ao = (BL_SkinArrayOptimizer*)GetArrayOptimizer(mat);//*(m_matVertexArrays[*mat]);
- return ao->m_MvertArrayCache1;
- }
+ void UpdateBuckets(void* clientobj, double* oglmatrix,
+ bool useObjectColor, const MT_Vector4& rgbavec, bool visible, bool culled);
- void AddPolygon(RAS_Polygon* poly);
- int FindOrAddDeform(unsigned int vtxarray, unsigned int mv, struct MDeformVert *dv, RAS_IPolyMaterial* mat);
- int FindOrAddVertex(int vtxarray,const MT_Point3& xyz,
- const MT_Point2& uv,
- const MT_Point2& uv2,
- const MT_Vector4& tangent,
- const unsigned int rgbacolor,
- const MT_Vector3& normal, int defnr, bool flat, RAS_IPolyMaterial* mat)
- {
- RAS_TexVert tempvert(xyz,uv,uv2, tangent,rgbacolor,normal,flat ? TV_CALCFACENORMAL : 0);
-
- // KX_ArrayOptimizer* ao = GetArrayOptimizer(mat);//*(m_matVertexArrays[*mat]);
- BL_SkinArrayOptimizer* ao = (BL_SkinArrayOptimizer*)GetArrayOptimizer(mat);//*(m_matVertexArrays[*mat]);
-
- int numverts = ao->m_VertexArrayCache1[vtxarray]->size();//m_VertexArrayCount[vtxarray];
-
- int index=-1;
-
- for (int i=0;i<numverts;i++)
- {
- const RAS_TexVert& vtx = (*ao->m_VertexArrayCache1[vtxarray])[i];
- if (tempvert.closeTo(&vtx))
- {
- index = i;
- break;
- }
-
- }
- if (index >= 0)
- return index;
-
- // no vertex found, add one
- ao->m_VertexArrayCache1[vtxarray]->push_back(tempvert);
- ao->m_DIndexArrayCache1[vtxarray]->push_back(defnr);
-
- return numverts;
-
-
- }
-
+ // for shape keys,
+ void CheckWeightCache(struct Object* obj);
};
#endif
diff --git a/source/gameengine/Converter/CMakeLists.txt b/source/gameengine/Converter/CMakeLists.txt
index 1b8aa73bf1f..a5219b9e759 100644
--- a/source/gameengine/Converter/CMakeLists.txt
+++ b/source/gameengine/Converter/CMakeLists.txt
@@ -65,6 +65,7 @@ SET(INC
../../../source/gameengine/Network/LoopBackNetwork
../../../source/blender/misc
../../../source/blender/blenloader
+ ../../../source/blender/gpu
../../../extern/bullet2/src
../../../extern/solid
${PYTHON_INC}
diff --git a/source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp b/source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp
index f58d60b026a..4d79febb7b4 100644
--- a/source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp
+++ b/source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp
@@ -28,13 +28,10 @@
#include "KX_BlenderScalarInterpolator.h"
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-extern "C" int IPO_GetChannels(struct Ipo *ipo, short *channels);
-extern "C" float IPO_GetFloatValue(struct Ipo *ipo, /*IPO_Channel*/ short channel, float ctime);
-
+extern "C" {
+#include "DNA_ipo_types.h"
+#include "BKE_ipo.h"
+}
static const int BL_MAX_CHANNELS = 32;
@@ -42,7 +39,7 @@ float BL_ScalarInterpolator::GetValue(float currentTime) const {
return IPO_GetFloatValue(m_blender_ipo, m_channel, currentTime);
}
-typedef short IPO_Channel;
+
BL_InterpolatorList::BL_InterpolatorList(struct Ipo *ipo) {
IPO_Channel channels[BL_MAX_CHANNELS];
diff --git a/source/gameengine/Converter/KX_BlenderSceneConverter.cpp b/source/gameengine/Converter/KX_BlenderSceneConverter.cpp
index 067fce3eefe..3fcb4765c67 100644
--- a/source/gameengine/Converter/KX_BlenderSceneConverter.cpp
+++ b/source/gameengine/Converter/KX_BlenderSceneConverter.cpp
@@ -100,7 +100,8 @@ KX_BlenderSceneConverter::KX_BlenderSceneConverter(
m_sipo(sipo),
m_ketsjiEngine(engine),
m_alwaysUseExpandFraming(false),
- m_usemat(false)
+ m_usemat(false),
+ m_useglslmat(false)
{
m_newfilename = "";
}
@@ -120,29 +121,29 @@ KX_BlenderSceneConverter::~KX_BlenderSceneConverter()
delete (ipoList);
}
- vector<KX_WorldInfo*>::iterator itw = m_worldinfos.begin();
+ vector<pair<KX_Scene*,KX_WorldInfo*> >::iterator itw = m_worldinfos.begin();
while (itw != m_worldinfos.end()) {
- delete (*itw);
+ delete (*itw).second;
itw++;
}
- vector<RAS_IPolyMaterial*>::iterator itp = m_polymaterials.begin();
+ vector<pair<KX_Scene*,RAS_IPolyMaterial*> >::iterator itp = m_polymaterials.begin();
while (itp != m_polymaterials.end()) {
- delete (*itp);
+ delete (*itp).second;
itp++;
}
// delete after RAS_IPolyMaterial
- vector<BL_Material *>::iterator itmat = m_materials.begin();
+ vector<pair<KX_Scene*,BL_Material *> >::iterator itmat = m_materials.begin();
while (itmat != m_materials.end()) {
- delete (*itmat);
+ delete (*itmat).second;
itmat++;
}
- vector<RAS_MeshObject*>::iterator itm = m_meshobjects.begin();
+ vector<pair<KX_Scene*,RAS_MeshObject*> >::iterator itm = m_meshobjects.begin();
while (itm != m_meshobjects.end()) {
- delete (*itm);
+ delete (*itm).second;
itm++;
}
@@ -183,20 +184,21 @@ bool KX_BlenderSceneConverter::TryAndLoadNewFile()
return result;
}
-
+Scene *KX_BlenderSceneConverter::GetBlenderSceneForName(const STR_String& name)
+{
+ Scene *sce;
/**
* Find the specified scene by name, or the first
* scene if nothing matches (shouldn't happen).
*/
-static struct Scene *GetSceneForName2(struct Main *maggie, const STR_String& scenename) {
- Scene *sce;
- for (sce= (Scene*) maggie->scene.first; sce; sce= (Scene*) sce->id.next)
- if (scenename == (sce->id.name+2))
+ for (sce= (Scene*) m_maggie->scene.first; sce; sce= (Scene*) sce->id.next)
+ if (name == (sce->id.name+2))
return sce;
- return (Scene*) maggie->scene.first;
+ return (Scene*)m_maggie->scene.first;
+
}
#include "KX_PythonInit.h"
@@ -244,6 +246,11 @@ struct BlenderDebugDraw : public btIDebugDraw
{
return m_debugMode;
}
+ ///todo: find out if Blender can do this
+ virtual void draw3dText(const btVector3& location,const char* textString)
+ {
+
+ }
};
@@ -257,9 +264,12 @@ void KX_BlenderSceneConverter::ConvertScene(const STR_String& scenename,
class RAS_ICanvas* canvas)
{
//find out which physics engine
- Scene *blenderscene = GetSceneForName2(m_maggie, scenename);
+ Scene *blenderscene = GetBlenderSceneForName(scenename);
e_PhysicsEngine physics_engine = UseBullet;
+ // hook for registration function during conversion.
+ m_currentScene = destinationscene;
+ destinationscene->SetSceneConverter(this);
if (blenderscene)
{
@@ -357,21 +367,102 @@ void KX_BlenderSceneConverter::ConvertScene(const STR_String& scenename,
m_alwaysUseExpandFraming
);
+ //These lookup are not needed during game
m_map_blender_to_gameactuator.clear();
m_map_blender_to_gamecontroller.clear();
-
m_map_blender_to_gameobject.clear();
- m_map_mesh_to_gamemesh.clear();
- //don't clear it yet, it is needed for the baking physics into ipo animation
+ //Clearing this lookup table has the effect of disabling the cache of meshes
+ //between scenes, even if they are shared in the blend file.
+ //This cache mecanism is buggy so I leave it disable and the memory leak
+ //that would result from this is fixed in RemoveScene()
+ m_map_mesh_to_gamemesh.clear();
+ //Don't clear this lookup, it is needed for the baking physics into ipo animation
+ //To avoid it's infinite grows, object will be unregister when they are deleted
+ //see KX_Scene::NewRemoveObject
//m_map_gameobject_to_blender.clear();
}
+// This function removes all entities stored in the converter for that scene
+// It should be used instead of direct delete scene
+// Note that there was some provision for sharing entities (meshes...) between
+// scenes but that is now disabled so all scene will have their own copy
+// and we can delete them here. If the sharing is reactivated, change this code too..
+// (see KX_BlenderSceneConverter::ConvertScene)
+void KX_BlenderSceneConverter::RemoveScene(KX_Scene *scene)
+{
+ int i, size;
+ // delete the scene first as it will stop the use of entities
+ delete scene;
+ // delete the entities of this scene
+ vector<pair<KX_Scene*,KX_WorldInfo*> >::iterator worldit;
+ size = m_worldinfos.size();
+ for (i=0, worldit=m_worldinfos.begin(); i<size; ) {
+ if ((*worldit).first == scene) {
+ delete (*worldit).second;
+ *worldit = m_worldinfos.back();
+ m_worldinfos.pop_back();
+ size--;
+ } else {
+ i++;
+ worldit++;
+ }
+ }
+
+ vector<pair<KX_Scene*,RAS_IPolyMaterial*> >::iterator polymit;
+ size = m_polymaterials.size();
+ for (i=0, polymit=m_polymaterials.begin(); i<size; ) {
+ if ((*polymit).first == scene) {
+ delete (*polymit).second;
+ *polymit = m_polymaterials.back();
+ m_polymaterials.pop_back();
+ size--;
+ } else {
+ i++;
+ polymit++;
+ }
+ }
+
+ vector<pair<KX_Scene*,BL_Material*> >::iterator matit;
+ size = m_materials.size();
+ for (i=0, matit=m_materials.begin(); i<size; ) {
+ if ((*matit).first == scene) {
+ delete (*matit).second;
+ *matit = m_materials.back();
+ m_materials.pop_back();
+ size--;
+ } else {
+ i++;
+ matit++;
+ }
+ }
+
+ vector<pair<KX_Scene*,RAS_MeshObject*> >::iterator meshit;
+ size = m_meshobjects.size();
+ for (i=0, meshit=m_meshobjects.begin(); i<size; ) {
+ if ((*meshit).first == scene) {
+ delete (*meshit).second;
+ *meshit = m_meshobjects.back();
+ m_meshobjects.pop_back();
+ size--;
+ } else {
+ i++;
+ meshit++;
+ }
+ }
+}
// use blender materials
void KX_BlenderSceneConverter::SetMaterials(bool val)
{
m_usemat = val;
+ m_useglslmat = false;
+}
+
+void KX_BlenderSceneConverter::SetGLSLMaterials(bool val)
+{
+ m_usemat = val;
+ m_useglslmat = val;
}
bool KX_BlenderSceneConverter::GetMaterials()
@@ -379,10 +470,14 @@ bool KX_BlenderSceneConverter::GetMaterials()
return m_usemat;
}
+bool KX_BlenderSceneConverter::GetGLSLMaterials()
+{
+ return m_useglslmat;
+}
void KX_BlenderSceneConverter::RegisterBlenderMaterial(BL_Material *mat)
{
- m_materials.push_back(mat);
+ m_materials.push_back(pair<KX_Scene*,BL_Material *>(m_currentScene,mat));
}
@@ -403,6 +498,21 @@ void KX_BlenderSceneConverter::RegisterGameObject(
m_map_blender_to_gameobject.insert(CHashedPtr(for_blenderobject),gameobject);
}
+void KX_BlenderSceneConverter::UnregisterGameObject(
+ KX_GameObject *gameobject)
+{
+ CHashedPtr gptr(gameobject);
+ struct Object **bobp= m_map_gameobject_to_blender[gptr];
+ if (bobp) {
+ CHashedPtr bptr(*bobp);
+ KX_GameObject **gobp= m_map_blender_to_gameobject[bptr];
+ if (gobp && *gobp == gameobject)
+ // also maintain m_map_blender_to_gameobject if the gameobject
+ // being removed is matching the blender object
+ m_map_blender_to_gameobject.remove(bptr);
+ m_map_gameobject_to_blender.remove(gptr);
+ }
+}
KX_GameObject *KX_BlenderSceneConverter::FindGameObject(
@@ -430,7 +540,7 @@ void KX_BlenderSceneConverter::RegisterGameMesh(
struct Mesh *for_blendermesh)
{
m_map_mesh_to_gamemesh.insert(CHashedPtr(for_blendermesh),gamemesh);
- m_meshobjects.push_back(gamemesh);
+ m_meshobjects.push_back(pair<KX_Scene*,RAS_MeshObject*>(m_currentScene,gamemesh));
}
@@ -455,7 +565,7 @@ RAS_MeshObject *KX_BlenderSceneConverter::FindGameMesh(
void KX_BlenderSceneConverter::RegisterPolyMaterial(RAS_IPolyMaterial *polymat)
{
- m_polymaterials.push_back(polymat);
+ m_polymaterials.push_back(pair<KX_Scene*,RAS_IPolyMaterial*>(m_currentScene,polymat));
}
@@ -520,7 +630,7 @@ SCA_IController *KX_BlenderSceneConverter::FindGameController(
void KX_BlenderSceneConverter::RegisterWorldInfo(
KX_WorldInfo *worldinfo)
{
- m_worldinfos.push_back(worldinfo);
+ m_worldinfos.push_back(pair<KX_Scene*,KX_WorldInfo*>(m_currentScene,worldinfo));
}
/*
@@ -552,13 +662,13 @@ extern "C"
{
Ipo *add_ipo( char *name, int idcode );
char *getIpoCurveName( IpoCurve * icu );
- struct IpoCurve *verify_ipocurve(struct ID *, short, char *, char *, char *, int);
+ struct IpoCurve *verify_ipocurve(struct ID *, short, char *, char *, char *, int, short);
void testhandles_ipocurve(struct IpoCurve *icu);
+ void insert_vert_icu(struct IpoCurve *, float, float, short);
void Mat3ToEul(float tmat[][3], float *eul);
-
}
-IpoCurve* findIpoCurve(IpoCurve* first,char* searchName)
+IpoCurve* findIpoCurve(IpoCurve* first, const char* searchName)
{
IpoCurve* icu1;
for( icu1 = first; icu1; icu1 = icu1->next )
@@ -726,7 +836,7 @@ void KX_BlenderSceneConverter::WritePhysicsObjectToAnimationIpo(int frameNumber)
KX_GameObject* gameObj = (KX_GameObject*)parentList->GetValue(g);
if (gameObj->IsDynamic())
{
- KX_IPhysicsController* physCtrl = gameObj->GetPhysicsController();
+ //KX_IPhysicsController* physCtrl = gameObj->GetPhysicsController();
Object* blenderObject = FindBlenderObject(gameObj);
if (blenderObject)
@@ -754,7 +864,7 @@ void KX_BlenderSceneConverter::WritePhysicsObjectToAnimationIpo(int frameNumber)
- const MT_Vector3& scale = gameObj->NodeGetWorldScaling();
+ //const MT_Vector3& scale = gameObj->NodeGetWorldScaling();
const MT_Point3& position = gameObj->NodeGetWorldPosition();
Ipo* ipo = blenderObject->ipo;
@@ -765,27 +875,27 @@ void KX_BlenderSceneConverter::WritePhysicsObjectToAnimationIpo(int frameNumber)
IpoCurve *icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"LocX");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_X);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_X, 1);
icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"LocY");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Y);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Y, 1);
icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"LocZ");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Z);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Z, 1);
icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"RotX");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_X);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_X, 1);
icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"RotY");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Y);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Y, 1);
icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"RotZ");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Z);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Z, 1);
@@ -882,7 +992,7 @@ void KX_BlenderSceneConverter::TestHandlesPhysicsObjectToAnimationIpo()
KX_GameObject* gameObj = (KX_GameObject*)parentList->GetValue(g);
if (gameObj->IsDynamic())
{
- KX_IPhysicsController* physCtrl = gameObj->GetPhysicsController();
+ //KX_IPhysicsController* physCtrl = gameObj->GetPhysicsController();
Object* blenderObject = FindBlenderObject(gameObj);
if (blenderObject)
@@ -910,8 +1020,8 @@ void KX_BlenderSceneConverter::TestHandlesPhysicsObjectToAnimationIpo()
- const MT_Vector3& scale = gameObj->NodeGetWorldScaling();
- const MT_Point3& position = gameObj->NodeGetWorldPosition();
+ //const MT_Vector3& scale = gameObj->NodeGetWorldScaling();
+ //const MT_Point3& position = gameObj->NodeGetWorldPosition();
Ipo* ipo = blenderObject->ipo;
if (ipo)
@@ -921,27 +1031,27 @@ void KX_BlenderSceneConverter::TestHandlesPhysicsObjectToAnimationIpo()
IpoCurve *icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"LocX");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_X);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_X, 1);
icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"LocY");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Y);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Y, 1);
icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"LocZ");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Z);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Z, 1);
icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"RotX");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_X);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_X, 1);
icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"RotY");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Y);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Y, 1);
icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"RotZ");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Z);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Z, 1);
diff --git a/source/gameengine/Converter/KX_BlenderSceneConverter.h b/source/gameengine/Converter/KX_BlenderSceneConverter.h
index 971b45fc786..2317e952a0a 100644
--- a/source/gameengine/Converter/KX_BlenderSceneConverter.h
+++ b/source/gameengine/Converter/KX_BlenderSceneConverter.h
@@ -45,13 +45,17 @@ class BL_Material;
struct IpoCurve;
struct Main;
struct SpaceIpo;
+struct Scene;
class KX_BlenderSceneConverter : public KX_ISceneConverter
{
- vector<KX_WorldInfo*> m_worldinfos;
- vector<RAS_IPolyMaterial*> m_polymaterials;
- vector<RAS_MeshObject*> m_meshobjects;
- vector<BL_Material *> m_materials;
+ // Use vector of pairs to allow removal of entities between scene switch
+ vector<pair<KX_Scene*,KX_WorldInfo*> > m_worldinfos;
+ vector<pair<KX_Scene*,RAS_IPolyMaterial*> > m_polymaterials;
+ vector<pair<KX_Scene*,RAS_MeshObject*> > m_meshobjects;
+ vector<pair<KX_Scene*,BL_Material *> > m_materials;
+ // Should also have a list of collision shapes.
+ // For the time being this is held in KX_Scene::m_shapes
GEN_Map<CHashedPtr,struct Object*> m_map_gameobject_to_blender;
GEN_Map<CHashedPtr,KX_GameObject*> m_map_blender_to_gameobject;
@@ -69,8 +73,10 @@ class KX_BlenderSceneConverter : public KX_ISceneConverter
STR_String m_newfilename;
class KX_KetsjiEngine* m_ketsjiEngine;
+ class KX_Scene* m_currentScene; // Scene being converted
bool m_alwaysUseExpandFraming;
bool m_usemat;
+ bool m_useglslmat;
void localDel_ipoCurve ( IpoCurve * icu ,struct SpaceIpo* sipo);
// struct Ipo* findIpoForName(char* objName);
@@ -96,6 +102,7 @@ public:
class RAS_IRenderTools* rendertools,
class RAS_ICanvas* canvas
);
+ virtual void RemoveScene(class KX_Scene *scene);
void SetNewFileName(const STR_String& filename);
bool TryAndLoadNewFile();
@@ -103,6 +110,7 @@ public:
void SetAlwaysUseExpandFraming(bool to_what);
void RegisterGameObject(KX_GameObject *gameobject, struct Object *for_blenderobject);
+ void UnregisterGameObject(KX_GameObject *gameobject);
KX_GameObject *FindGameObject(struct Object *for_blenderobject);
struct Object *FindBlenderObject(KX_GameObject *for_gameobject);
@@ -140,6 +148,11 @@ public:
virtual void SetMaterials(bool val);
virtual bool GetMaterials();
+ // use blender glsl materials
+ virtual void SetGLSLMaterials(bool val);
+ virtual bool GetGLSLMaterials();
+
+ struct Scene* GetBlenderSceneForName(const STR_String& name);
};
#endif //__KX_BLENDERSCENECONVERTER_H
diff --git a/source/gameengine/Converter/KX_ConvertActuators.cpp b/source/gameengine/Converter/KX_ConvertActuators.cpp
index 02c07a8eb94..4f152acc918 100644
--- a/source/gameengine/Converter/KX_ConvertActuators.cpp
+++ b/source/gameengine/Converter/KX_ConvertActuators.cpp
@@ -34,6 +34,8 @@
#define BLENDER_HACK_DTIME 0.02
+#include "MEM_guardedalloc.h"
+
#include "KX_BlenderSceneConverter.h"
#include "KX_ConvertActuators.h"
@@ -42,7 +44,7 @@
#include "SCA_PropertyActuator.h"
#include "SCA_LogicManager.h"
#include "SCA_RandomActuator.h"
-
+#include "SCA_2DFilterActuator.h"
// Ketsji specific logicbricks
#include "KX_SceneActuator.h"
@@ -54,10 +56,13 @@
#include "KX_ConstraintActuator.h"
#include "KX_CameraActuator.h"
#include "KX_GameActuator.h"
+#include "KX_StateActuator.h"
#include "KX_VisibilityActuator.h"
#include "KX_SCA_AddObjectActuator.h"
#include "KX_SCA_EndObjectActuator.h"
#include "KX_SCA_ReplaceMeshActuator.h"
+#include "KX_ParentActuator.h"
+#include "KX_SCA_DynamicActuator.h"
#include "KX_Scene.h"
#include "KX_KetsjiEngine.h"
@@ -66,9 +71,11 @@
#include "KX_GameObject.h"
/* This little block needed for linking to Blender... */
-
+#include "BKE_text.h"
#include "BLI_blenlib.h"
+#define FILE_MAX 240 // repeated here to avoid dependency from BKE_utildefines.h
+
#include "KX_NetworkMessageActuator.h"
#ifdef WIN32
@@ -81,6 +88,7 @@
#include "DNA_actuator_types.h"
#include "DNA_packedFile_types.h"
#include "BL_ActionActuator.h"
+#include "BL_ShapeActionActuator.h"
/* end of blender include block */
#include "BL_BlenderDataConversion.h"
@@ -132,6 +140,7 @@ void BL_ConvertActuators(char* maggiename,
MT_Vector3 angvelvec ( KX_BLENDERTRUNC(obact->angularvelocity[0]),
KX_BLENDERTRUNC(obact->angularvelocity[1]),
KX_BLENDERTRUNC(obact->angularvelocity[2]));
+ short damping = obact->damping;
drotvec /= BLENDER_HACK_DTIME;
//drotvec /= BLENDER_HACK_DTIME;
@@ -152,7 +161,7 @@ void BL_ConvertActuators(char* maggiename,
bitLocalFlag.DRot = bool((obact->flag & ACT_DROT_LOCAL)!=0);
bitLocalFlag.LinearVelocity = bool((obact->flag & ACT_LIN_VEL_LOCAL)!=0);
bitLocalFlag.AngularVelocity = bool((obact->flag & ACT_ANG_VEL_LOCAL)!=0);
-
+ bitLocalFlag.ServoControl = bool(obact->type == ACT_OBJECT_SERVO);
bitLocalFlag.AddOrSetLinV = bool((obact->flag & ACT_ADD_LIN_VEL)!=0);
@@ -163,6 +172,7 @@ void BL_ConvertActuators(char* maggiename,
drotvec.getValue(),
linvelvec.getValue(),
angvelvec.getValue(),
+ damping,
bitLocalFlag
);
baseact = tmpbaseact;
@@ -173,16 +183,19 @@ void BL_ConvertActuators(char* maggiename,
if (blenderobject->type==OB_ARMATURE){
bActionActuator* actact = (bActionActuator*) bact->data;
STR_String propname = (actact->name ? actact->name : "");
+ STR_String propframe = (actact->frameProp ? actact->frameProp : "");
BL_ActionActuator* tmpbaseact = new BL_ActionActuator(
gameobj,
propname,
+ propframe,
actact->sta,
actact->end,
actact->act,
actact->type, // + 1, because Blender starts to count at zero,
actact->blendin,
actact->priority,
+ actact->end_reset,
actact->stridelength
// Ketsji at 1, because zero is reserved for "NoDef"
);
@@ -192,26 +205,55 @@ void BL_ConvertActuators(char* maggiename,
else
printf ("Discarded action actuator from non-armature object [%s]\n", blenderobject->id.name+2);
}
+ case ACT_SHAPEACTION:
+ {
+ if (blenderobject->type==OB_MESH){
+ bActionActuator* actact = (bActionActuator*) bact->data;
+ STR_String propname = (actact->name ? actact->name : "");
+ STR_String propframe = (actact->frameProp ? actact->frameProp : "");
+
+ BL_ShapeActionActuator* tmpbaseact = new BL_ShapeActionActuator(
+ gameobj,
+ propname,
+ propframe,
+ actact->sta,
+ actact->end,
+ actact->act,
+ actact->type, // + 1, because Blender starts to count at zero,
+ actact->blendin,
+ actact->priority,
+ actact->stridelength
+ // Ketsji at 1, because zero is reserved for "NoDef"
+ );
+ baseact= tmpbaseact;
+ break;
+ }
+ else
+ printf ("Discarded shape action actuator from non-mesh object [%s]\n", blenderobject->id.name+2);
+ }
case ACT_IPO:
{
bIpoActuator* ipoact = (bIpoActuator*) bact->data;
bool ipochild = (ipoact->flag & ACT_IPOCHILD) !=0;
- STR_String propname = ( ipoact->name ? ipoact->name : "");
+ STR_String propname = ipoact->name;
+ STR_String frameProp = ipoact->frameProp;
// first bit?
bool ipo_as_force = (ipoact->flag & ACT_IPOFORCE);
- bool force_local = (ipoact->flag & ACT_IPOFORCE_LOCAL);
+ bool local = (ipoact->flag & ACT_IPOLOCAL);
+ bool ipo_add = (ipoact->flag & ACT_IPOADD);
KX_IpoActuator* tmpbaseact = new KX_IpoActuator(
gameobj,
propname ,
+ frameProp,
ipoact->sta,
ipoact->end,
ipochild,
ipoact->type + 1, // + 1, because Blender starts to count at zero,
// Ketsji at 1, because zero is reserved for "NoDef"
ipo_as_force,
- force_local
- );
+ ipo_add,
+ local);
baseact = tmpbaseact;
break;
}
@@ -249,15 +291,19 @@ void BL_ConvertActuators(char* maggiename,
STR_String toPropName = (msgAct->toPropName
? (char*) msgAct->toPropName
: "");
- /**
- * Get the Message Subject to send.
+ /* BGE Wants "OB" prefix */
+ if (toPropName != "")
+ toPropName = "OB" + toPropName;
+
+ /**
+ * Get the Message Subject to send.
*/
STR_String subject = (msgAct->subject
? (char*) msgAct->subject
: "");
- /**
- * Get the bodyType
+ /**
+ * Get the bodyType
*/
int bodyType = msgAct->bodyType;
@@ -319,22 +365,26 @@ void BL_ConvertActuators(char* maggiename,
if (soundActuatorType != KX_SoundActuator::KX_SOUNDACT_NODEF)
{
- SND_SoundObject* sndobj = NULL;
+ SND_Scene* soundscene = scene->GetSoundScene();
+ STR_String samplename = "";
+ bool sampleisloaded = false;
- if (soundact->sound)
- {
- SND_Scene* soundscene = scene->GetSoundScene();
- STR_String samplename = soundact->sound->name;
+ if (soundact->sound) {
+ /* Need to convert the samplename into absolute path
+ * before checking if its loaded */
+ char fullpath[FILE_MAX];
- bool sampleisloaded = false;
+ /* dont modify soundact->sound->name, only change a copy */
+ BLI_strncpy(fullpath, soundact->sound->name, sizeof(fullpath));
+ BLI_convertstringcode(fullpath, maggiename);
+ samplename = fullpath;
/* let's see if the sample was already loaded */
if (soundscene->IsSampleLoaded(samplename))
{
sampleisloaded = true;
}
- else
- {
+ else {
/* if not, make it so */
PackedFile* pf = soundact->sound->newpackedfile;
@@ -347,21 +397,33 @@ void BL_ConvertActuators(char* maggiename,
/* or else load it from disk */
else
{
- /* but we need to convert the samplename into absolute pathname first */
- BLI_convertstringcode(soundact->sound->name, maggiename, 0);
- samplename = soundact->sound->name;
-
- /* and now we can load it */
- if (soundscene->LoadSample(samplename, NULL, 0) > -1)
+ if (soundscene->LoadSample(samplename, NULL, 0) > -1) {
sampleisloaded = true;
+ }
+ else {
+ std::cout << "WARNING: Sound actuator \"" << bact->name <<
+ "\" from object \"" << blenderobject->id.name+2 <<
+ "\" failed to load sample." << std::endl;
+ }
}
}
-
- if (sampleisloaded)
- {
- sndobj = new SND_SoundObject();
- sndobj->SetSampleName(samplename.Ptr());
- sndobj->SetObjectName(bact->name);
+ } else {
+ std::cout << "WARNING: Sound actuator \"" << bact->name <<
+ "\" from object \"" << blenderobject->id.name+2 <<
+ "\" has no sound datablock." << std::endl;
+ }
+
+ /* Note, allowing actuators for sounds that are not there was added since 2.47
+ * This is because python may expect the actuator and raise an exception if it dosnt find it
+ * better just to add a dummy sound actuator. */
+ SND_SoundObject* sndobj = NULL;
+ if (sampleisloaded)
+ {
+ /* setup the SND_SoundObject */
+ sndobj = new SND_SoundObject();
+ sndobj->SetSampleName(samplename.Ptr());
+ sndobj->SetObjectName(bact->name);
+ if (soundact->sound) {
sndobj->SetRollOffFactor(soundact->sound->attenuation);
sndobj->SetGain(soundact->sound->volume);
sndobj->SetPitch(exp((soundact->sound->pitch / 12.0) * log(2.0)));
@@ -374,8 +436,9 @@ void BL_ConvertActuators(char* maggiename,
else
sndobj->SetLoopMode(SND_LOOP_NORMAL);
}
- else
+ else {
sndobj->SetLoopMode(SND_LOOP_OFF);
+ }
if (soundact->sound->flags & SOUND_FLAGS_PRIORITY)
sndobj->SetHighPriority(true);
@@ -386,22 +449,30 @@ void BL_ConvertActuators(char* maggiename,
sndobj->Set3D(true);
else
sndobj->Set3D(false);
-
- KX_SoundActuator* tmpsoundact =
- new KX_SoundActuator(gameobj,
- sndobj,
- scene->GetSoundScene(), // needed for replication!
- soundActuatorType,
- startFrame,
- stopFrame);
-
- tmpsoundact->SetName(bact->name);
- baseact = tmpsoundact;
- soundscene->AddObject(sndobj);
- } else {
- std::cout << "WARNING: Sound actuator " << bact->name << " failed to load sample." << std::endl;
+ }
+ else {
+ /* dummy values for a NULL sound
+ * see editsound.c - defaults are unlikely to change soon */
+ sndobj->SetRollOffFactor(1.0);
+ sndobj->SetGain(1.0);
+ sndobj->SetPitch(1.0);
+ sndobj->SetLoopMode(SND_LOOP_OFF);
+ sndobj->SetHighPriority(false);
+ sndobj->Set3D(false);
}
}
+ KX_SoundActuator* tmpsoundact =
+ new KX_SoundActuator(gameobj,
+ sndobj,
+ scene->GetSoundScene(), // needed for replication!
+ soundActuatorType,
+ startFrame,
+ stopFrame);
+
+ tmpsoundact->SetName(bact->name);
+ baseact = tmpsoundact;
+ if (sndobj)
+ soundscene->AddObject(sndobj);
}
break;
}
@@ -467,7 +538,7 @@ void BL_ConvertActuators(char* maggiename,
case ACT_PROPERTY:
{
bPropertyActuator* propact = (bPropertyActuator*) bact->data;
- CValue* destinationObj = NULL;
+ SCA_IObject* destinationObj = NULL;
/*
here the destinationobject is searched. problem with multiple scenes: other scenes
@@ -503,14 +574,27 @@ void BL_ConvertActuators(char* maggiename,
// does the 'original' for replication exists, and
// is it in a non-active layer ?
- CValue* originalval = NULL;
- if (editobact->ob && !(editobact->ob->lay & activeLayerBitInfo))
- originalval = converter->FindGameObject(editobact->ob);
-
- MT_Vector3 linvelvec ( KX_BLENDERTRUNC(editobact->linVelocity[0]),
+ SCA_IObject* originalval = NULL;
+ if (editobact->ob)
+ {
+ if (editobact->ob->lay & activeLayerBitInfo)
+ {
+ fprintf(stderr, "Warning, object \"%s\" from AddObject actuator \"%s\" is not in a hidden layer.\n", objectname.Ptr(), uniquename.Ptr());
+ }
+ else {
+ originalval = converter->FindGameObject(editobact->ob);
+ }
+ }
+ MT_Vector3 linvelvec (
+ KX_BLENDERTRUNC(editobact->linVelocity[0]),
KX_BLENDERTRUNC(editobact->linVelocity[1]),
KX_BLENDERTRUNC(editobact->linVelocity[2]));
-
+
+ MT_Vector3 angvelvec (
+ KX_BLENDERTRUNC(editobact->angVelocity[0]),
+ KX_BLENDERTRUNC(editobact->angVelocity[1]),
+ KX_BLENDERTRUNC(editobact->angVelocity[2]));
+
KX_SCA_AddObjectActuator* tmpaddact =
new KX_SCA_AddObjectActuator(
gameobj,
@@ -518,7 +602,9 @@ void BL_ConvertActuators(char* maggiename,
editobact->time,
scene,
linvelvec.getValue(),
- editobact->localflag!=0
+ (editobact->localflag & ACT_EDOB_LOCAL_LINV)!=0,
+ angvelvec.getValue(),
+ (editobact->localflag & ACT_EDOB_LOCAL_ANGV)!=0
);
//editobact->ob to gameobj
@@ -569,6 +655,15 @@ void BL_ConvertActuators(char* maggiename,
blenderobject->upflag
);
baseact = tmptrackact;
+ break;
+ }
+ case ACT_EDOB_DYNAMICS:
+ {
+ KX_SCA_DynamicActuator* tmpdynact
+ = new KX_SCA_DynamicActuator(gameobj,
+ editobact->dyn_operation
+ );
+ baseact = tmpdynact;
}
}
break;
@@ -576,51 +671,141 @@ void BL_ConvertActuators(char* maggiename,
case ACT_CONSTRAINT:
{
float min = 0.0, max = 0.0;
+ char *prop = NULL;
KX_ConstraintActuator::KX_CONSTRAINTTYPE locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_NODEF;
bConstraintActuator *conact
= (bConstraintActuator*) bact->data;
/* convert settings... degrees in the ui become radians */
/* internally */
- switch (conact->flag) {
- case ACT_CONST_LOCX:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCX;
- min = conact->minloc[0];
- max = conact->maxloc[0];
- break;
- case ACT_CONST_LOCY:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCY;
- min = conact->minloc[1];
- max = conact->maxloc[1];
- break;
- case ACT_CONST_LOCZ:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCZ;
- min = conact->minloc[2];
- max = conact->maxloc[2];
- break;
- case ACT_CONST_ROTX:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTX;
- min = MT_2_PI * conact->minrot[0] / 360.0;
- max = MT_2_PI * conact->maxrot[0] / 360.0;
- break;
- case ACT_CONST_ROTY:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTY;
- min = MT_2_PI * conact->minrot[1] / 360.0;
- max = MT_2_PI * conact->maxrot[1] / 360.0;
- break;
- case ACT_CONST_ROTZ:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTZ;
- min = MT_2_PI * conact->minrot[2] / 360.0;
- max = MT_2_PI * conact->maxrot[2] / 360.0;
- break;
- default:
- ; /* error */
+ if (conact->type == ACT_CONST_TYPE_ORI) {
+ min = (MT_2_PI * conact->minloc[0])/360.0;
+ max = (MT_2_PI * conact->maxloc[0])/360.0;
+ switch (conact->mode) {
+ case ACT_CONST_DIRPX:
+ locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIX;
+ break;
+ case ACT_CONST_DIRPY:
+ locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIY;
+ break;
+ case ACT_CONST_DIRPZ:
+ locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIZ;
+ break;
+ }
+ } else if (conact->type == ACT_CONST_TYPE_DIST) {
+ switch (conact->mode) {
+ case ACT_CONST_DIRPX:
+ locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPX;
+ min = conact->minloc[0];
+ max = conact->maxloc[0];
+ break;
+ case ACT_CONST_DIRPY:
+ locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPY;
+ min = conact->minloc[1];
+ max = conact->maxloc[1];
+ break;
+ case ACT_CONST_DIRPZ:
+ locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPZ;
+ min = conact->minloc[2];
+ max = conact->maxloc[2];
+ break;
+ case ACT_CONST_DIRNX:
+ locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNX;
+ min = conact->minloc[0];
+ max = conact->maxloc[0];
+ break;
+ case ACT_CONST_DIRNY:
+ locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNY;
+ min = conact->minloc[1];
+ max = conact->maxloc[1];
+ break;
+ case ACT_CONST_DIRNZ:
+ locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNZ;
+ min = conact->minloc[2];
+ max = conact->maxloc[2];
+ break;
+ }
+ prop = conact->matprop;
+ } else if (conact->type == ACT_CONST_TYPE_FH) {
+ switch (conact->mode) {
+ case ACT_CONST_DIRPX:
+ locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPX;
+ min = conact->minloc[0];
+ max = conact->maxloc[0];
+ break;
+ case ACT_CONST_DIRPY:
+ locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPY;
+ min = conact->minloc[1];
+ max = conact->maxloc[1];
+ break;
+ case ACT_CONST_DIRPZ:
+ locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPZ;
+ min = conact->minloc[2];
+ max = conact->maxloc[2];
+ break;
+ case ACT_CONST_DIRNX:
+ locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNX;
+ min = conact->minloc[0];
+ max = conact->maxloc[0];
+ break;
+ case ACT_CONST_DIRNY:
+ locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNY;
+ min = conact->minloc[1];
+ max = conact->maxloc[1];
+ break;
+ case ACT_CONST_DIRNZ:
+ locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNZ;
+ min = conact->minloc[2];
+ max = conact->maxloc[2];
+ break;
+ }
+ prop = conact->matprop;
+ } else {
+ switch (conact->flag) {
+ case ACT_CONST_LOCX:
+ locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCX;
+ min = conact->minloc[0];
+ max = conact->maxloc[0];
+ break;
+ case ACT_CONST_LOCY:
+ locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCY;
+ min = conact->minloc[1];
+ max = conact->maxloc[1];
+ break;
+ case ACT_CONST_LOCZ:
+ locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCZ;
+ min = conact->minloc[2];
+ max = conact->maxloc[2];
+ break;
+ case ACT_CONST_ROTX:
+ locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTX;
+ min = MT_2_PI * conact->minrot[0] / 360.0;
+ max = MT_2_PI * conact->maxrot[0] / 360.0;
+ break;
+ case ACT_CONST_ROTY:
+ locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTY;
+ min = MT_2_PI * conact->minrot[1] / 360.0;
+ max = MT_2_PI * conact->maxrot[1] / 360.0;
+ break;
+ case ACT_CONST_ROTZ:
+ locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTZ;
+ min = MT_2_PI * conact->minrot[2] / 360.0;
+ max = MT_2_PI * conact->maxrot[2] / 360.0;
+ break;
+ default:
+ ; /* error */
+ }
}
KX_ConstraintActuator *tmpconact
= new KX_ConstraintActuator(gameobj,
- conact->damp,
- min,
- max,
- locrot);
+ conact->damp,
+ conact->rotdamp,
+ min,
+ max,
+ conact->maxrot,
+ locrot,
+ conact->time,
+ conact->flag,
+ prop);
baseact = tmpconact;
break;
}
@@ -678,15 +863,11 @@ void BL_ConvertActuators(char* maggiename,
break;
}
case ACT_SCENE_CAMERA:
+ mode = KX_SceneActuator::KX_SCENE_SET_CAMERA;
if (sceneact->camera)
{
- mode = KX_SceneActuator::KX_SCENE_SET_CAMERA;
cam = (KX_Camera*) converter->FindGameObject(sceneact->camera);
}
- else
- {
- // TODO:warn user
- }
break;
case ACT_SCENE_RESTART:
{
@@ -739,6 +920,16 @@ void BL_ConvertActuators(char* maggiename,
mode = KX_GameActuator::KX_GAME_QUIT;
break;
}
+ case ACT_GAME_SAVECFG:
+ {
+ mode = KX_GameActuator::KX_GAME_SAVECFG;
+ break;
+ }
+ case ACT_GAME_LOADCFG:
+ {
+ mode = KX_GameActuator::KX_GAME_LOADCFG;
+ break;
+ }
default:
; /* flag error */
}
@@ -825,15 +1016,129 @@ void BL_ConvertActuators(char* maggiename,
bVisibilityActuator *vis_act = (bVisibilityActuator *) bact->data;
KX_VisibilityActuator * tmp_vis_act = NULL;
bool v = ((vis_act->flag & ACT_VISIBILITY_INVISIBLE) != 0);
+ bool recursive = ((vis_act->flag & ACT_VISIBILITY_RECURSIVE) != 0);
- tmp_vis_act =
- new KX_VisibilityActuator(gameobj,
- !v);
+ tmp_vis_act = new KX_VisibilityActuator(gameobj, !v, recursive);
baseact = tmp_vis_act;
}
break;
+ case ACT_STATE:
+ {
+ bStateActuator *sta_act = (bStateActuator *) bact->data;
+ KX_StateActuator * tmp_sta_act = NULL;
+
+ tmp_sta_act =
+ new KX_StateActuator(gameobj, sta_act->type, sta_act->mask);
+
+ baseact = tmp_sta_act;
+ }
+ break;
+
+ case ACT_2DFILTER:
+ {
+ bTwoDFilterActuator *_2dfilter = (bTwoDFilterActuator*) bact->data;
+ SCA_2DFilterActuator *tmp = NULL;
+
+ RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode;
+ switch(_2dfilter->type)
+ {
+ case ACT_2DFILTER_MOTIONBLUR:
+ filtermode = RAS_2DFilterManager::RAS_2DFILTER_MOTIONBLUR;
+ break;
+ case ACT_2DFILTER_BLUR:
+ filtermode = RAS_2DFilterManager::RAS_2DFILTER_BLUR;
+ break;
+ case ACT_2DFILTER_SHARPEN:
+ filtermode = RAS_2DFilterManager::RAS_2DFILTER_SHARPEN;
+ break;
+ case ACT_2DFILTER_DILATION:
+ filtermode = RAS_2DFilterManager::RAS_2DFILTER_DILATION;
+ break;
+ case ACT_2DFILTER_EROSION:
+ filtermode = RAS_2DFilterManager::RAS_2DFILTER_EROSION;
+ break;
+ case ACT_2DFILTER_LAPLACIAN:
+ filtermode = RAS_2DFilterManager::RAS_2DFILTER_LAPLACIAN;
+ break;
+ case ACT_2DFILTER_SOBEL:
+ filtermode = RAS_2DFilterManager::RAS_2DFILTER_SOBEL;
+ break;
+ case ACT_2DFILTER_PREWITT:
+ filtermode = RAS_2DFilterManager::RAS_2DFILTER_PREWITT;
+ break;
+ case ACT_2DFILTER_GRAYSCALE:
+ filtermode = RAS_2DFilterManager::RAS_2DFILTER_GRAYSCALE;
+ break;
+ case ACT_2DFILTER_SEPIA:
+ filtermode = RAS_2DFilterManager::RAS_2DFILTER_SEPIA;
+ break;
+ case ACT_2DFILTER_INVERT:
+ filtermode = RAS_2DFilterManager::RAS_2DFILTER_INVERT;
+ break;
+ case ACT_2DFILTER_CUSTOMFILTER:
+ filtermode = RAS_2DFilterManager::RAS_2DFILTER_CUSTOMFILTER;
+ break;
+ case ACT_2DFILTER_NOFILTER:
+ filtermode = RAS_2DFilterManager::RAS_2DFILTER_NOFILTER;
+ break;
+ case ACT_2DFILTER_DISABLED:
+ filtermode = RAS_2DFilterManager::RAS_2DFILTER_DISABLED;
+ break;
+ case ACT_2DFILTER_ENABLED:
+ filtermode = RAS_2DFilterManager::RAS_2DFILTER_ENABLED;
+ break;
+ default:
+ filtermode = RAS_2DFilterManager::RAS_2DFILTER_NOFILTER;
+ break;
+ }
+
+ tmp = new SCA_2DFilterActuator(gameobj, filtermode, _2dfilter->flag,
+ _2dfilter->float_arg,_2dfilter->int_arg,ketsjiEngine->GetRasterizer(),rendertools);
+
+ if (_2dfilter->text)
+ {
+ char *buf;
+ // this is some blender specific code
+ buf = txt_to_buf(_2dfilter->text);
+ if (buf)
+ {
+ tmp->SetShaderText(STR_String(buf));
+ MEM_freeN(buf);
+ }
+ }
+
+ baseact = tmp;
+
+ }
+ break;
+ case ACT_PARENT:
+ {
+ bParentActuator *parAct = (bParentActuator *) bact->data;
+ int mode = KX_ParentActuator::KX_PARENT_NODEF;
+ KX_GameObject *tmpgob = NULL;
+
+ switch(parAct->type)
+ {
+ case ACT_PARENT_SET:
+ mode = KX_ParentActuator::KX_PARENT_SET;
+ tmpgob = converter->FindGameObject(parAct->ob);
+ break;
+ case ACT_PARENT_REMOVE:
+ mode = KX_ParentActuator::KX_PARENT_REMOVE;
+ tmpgob = NULL;
+ break;
+ }
+
+ KX_ParentActuator *tmpparact
+ = new KX_ParentActuator(gameobj,
+ mode,
+ tmpgob);
+ baseact = tmpparact;
+ break;
+ }
+
default:
; /* generate some error */
}
@@ -851,9 +1156,12 @@ void BL_ConvertActuators(char* maggiename,
gameobj->AddActuator(baseact);
converter->RegisterGameActuator(baseact, bact);
+ // done with baseact, release it
+ baseact->Release();
}
bact = bact->next;
}
}
+
diff --git a/source/gameengine/Converter/KX_ConvertControllers.cpp b/source/gameengine/Converter/KX_ConvertControllers.cpp
index a6ac2707db6..da490b4ee85 100644
--- a/source/gameengine/Converter/KX_ConvertControllers.cpp
+++ b/source/gameengine/Converter/KX_ConvertControllers.cpp
@@ -35,6 +35,10 @@
// Controller
#include "SCA_ANDController.h"
#include "SCA_ORController.h"
+#include "SCA_NANDController.h"
+#include "SCA_NORController.h"
+#include "SCA_XORController.h"
+#include "SCA_XNORController.h"
#include "SCA_PythonController.h"
#include "SCA_ExpressionController.h"
@@ -112,6 +116,30 @@ void BL_ConvertControllers(
LinkControllerToActuators(gamecontroller,bcontr,logicmgr,converter);
break;
}
+ case CONT_LOGIC_NAND:
+ {
+ gamecontroller = new SCA_NANDController(gameobj);
+ LinkControllerToActuators(gamecontroller,bcontr,logicmgr,converter);
+ break;
+ }
+ case CONT_LOGIC_NOR:
+ {
+ gamecontroller = new SCA_NORController(gameobj);
+ LinkControllerToActuators(gamecontroller,bcontr,logicmgr,converter);
+ break;
+ }
+ case CONT_LOGIC_XOR:
+ {
+ gamecontroller = new SCA_XORController(gameobj);
+ LinkControllerToActuators(gamecontroller,bcontr,logicmgr,converter);
+ break;
+ }
+ case CONT_LOGIC_XNOR:
+ {
+ gamecontroller = new SCA_XNORController(gameobj);
+ LinkControllerToActuators(gamecontroller,bcontr,logicmgr,converter);
+ break;
+ }
case CONT_EXPRESSION:
{
bExpressionCont* bexpcont = (bExpressionCont*) bcontr->data;
@@ -161,6 +189,7 @@ void BL_ConvertControllers(
if (gamecontroller)
{
gamecontroller->SetExecutePriority(executePriority++);
+ gamecontroller->SetState(bcontr->state_mask);
STR_String uniquename = bcontr->name;
uniquename += "#CONTR#";
uniqueint++;
@@ -171,6 +200,8 @@ void BL_ConvertControllers(
gameobj->AddController(gamecontroller);
converter->RegisterGameController(gamecontroller, bcontr);
+ //done with gamecontroller
+ gamecontroller->Release();
}
bcontr = bcontr->next;
diff --git a/source/gameengine/Converter/KX_ConvertProperties.cpp b/source/gameengine/Converter/KX_ConvertProperties.cpp
index 13fa5708e16..dfbc6f0c48d 100644
--- a/source/gameengine/Converter/KX_ConvertProperties.cpp
+++ b/source/gameengine/Converter/KX_ConvertProperties.cpp
@@ -102,8 +102,9 @@ void BL_ConvertProperties(Object* object,KX_GameObject* gameobj,SCA_TimeEventMan
// set a subproperty called 'timer' so that
// we can register the replica of this property
// at the time a game object is replicated (AddObjectActuator triggers this)
-
- timeval->SetProperty("timer",new CBoolValue(true));
+ CValue *bval = new CBoolValue(true);
+ timeval->SetProperty("timer",bval);
+ bval->Release();
if (isInActiveLayer)
{
timemgr->AddTimeProperty(timeval);
@@ -125,10 +126,16 @@ void BL_ConvertProperties(Object* object,KX_GameObject* gameobj,SCA_TimeEventMan
{
scene->AddDebugProperty(gameobj,STR_String(prop->name));
}
+ // done with propval, release it
+ propval->Release();
}
prop = prop->next;
}
-
-
+ // check if state needs to be debugged
+ if (object->scaflag & OB_DEBUGSTATE)
+ {
+ // reserve name for object state
+ scene->AddDebugProperty(gameobj,STR_String("__state__"));
+ }
}
diff --git a/source/gameengine/Converter/KX_ConvertSensors.cpp b/source/gameengine/Converter/KX_ConvertSensors.cpp
index 1ac80df1ee7..4cf302b1f64 100644
--- a/source/gameengine/Converter/KX_ConvertSensors.cpp
+++ b/source/gameengine/Converter/KX_ConvertSensors.cpp
@@ -65,6 +65,8 @@ probably misplaced */
#include "KX_MouseFocusSensor.h"
#include "SCA_JoystickSensor.h"
#include "KX_NetworkMessageSensor.h"
+#include "SCA_ActuatorSensor.h"
+#include "SCA_DelaySensor.h"
#include "SCA_PropertySensor.h"
@@ -91,6 +93,7 @@ void BL_ConvertSensors(struct Object* blenderobject,
class KX_GameObject* gameobj,
SCA_LogicManager* logicmgr,
KX_Scene* kxscene,
+ KX_KetsjiEngine* kxengine,
SCA_IInputDevice* keydev,
int & executePriority,
int activeLayerBitInfo,
@@ -260,6 +263,7 @@ void BL_ConvertSensors(struct Object* blenderobject,
bool neg_pulsemode = false;
int frequency = 0;
bool invert = false;
+ bool level = false;
while(sens)
{
@@ -272,7 +276,8 @@ void BL_ConvertSensors(struct Object* blenderobject,
frequency = sens->freq;
invert = !(sens->invert == 0);
-
+ level = !(sens->level == 0);
+
switch (sens->type)
{
case SENS_ALWAYS:
@@ -287,6 +292,22 @@ void BL_ConvertSensors(struct Object* blenderobject,
break;
}
+ case SENS_DELAY:
+ {
+ // we can reuse the Always event manager for the delay sensor
+ SCA_EventManager* eventmgr = logicmgr->FindEventManager(SCA_EventManager::ALWAYS_EVENTMGR);
+ if (eventmgr)
+ {
+ bDelaySensor* delaysensor = (bDelaySensor*)sens->data;
+ gamesensor = new SCA_DelaySensor(eventmgr,
+ gameobj,
+ delaysensor->delay,
+ delaysensor->duration,
+ (delaysensor->flag & SENS_DELAY_REPEAT) != 0);
+ }
+ break;
+ }
+
case SENS_COLLISION:
{
SCA_EventManager* eventmgr = logicmgr->FindEventManager(SCA_EventManager::TOUCH_EVENTMGR);
@@ -392,8 +413,9 @@ void BL_ConvertSensors(struct Object* blenderobject,
bool bFindMaterial = false;
PHY_IPhysicsController* physCtrl = kxscene->GetPhysicsEnvironment()->CreateSphereController(radius,pos);
- if (isInActiveLayer)
- kxscene->GetPhysicsEnvironment()->addSensor(physCtrl);
+ //will be done in KX_TouchEventManager::RegisterSensor()
+ //if (isInActiveLayer)
+ // kxscene->GetPhysicsEnvironment()->addSensor(physCtrl);
@@ -420,8 +442,8 @@ void BL_ConvertSensors(struct Object* blenderobject,
{
gamesensor = new SCA_KeyboardSensor(eventmgr,
gReverseKeyTranslateTable[blenderkeybdsensor->key],
- blenderkeybdsensor->qual,
- blenderkeybdsensor->qual2,
+ gReverseKeyTranslateTable[blenderkeybdsensor->qual],
+ gReverseKeyTranslateTable[blenderkeybdsensor->qual2],
(blenderkeybdsensor->type == SENS_ALL_KEYS),
blenderkeybdsensor->targetName,
blenderkeybdsensor->toggleName,
@@ -496,6 +518,7 @@ void BL_ConvertSensors(struct Object* blenderobject,
trackfocus,
canvas,
kxscene,
+ kxengine,
gameobj);
}
} else {
@@ -544,6 +567,19 @@ void BL_ConvertSensors(struct Object* blenderobject,
break;
}
+ case SENS_ACTUATOR:
+ {
+ bActuatorSensor* blenderactsensor = (bActuatorSensor*) sens->data;
+ // we will reuse the property event manager, there is nothing special with this sensor
+ SCA_EventManager* eventmgr
+ = logicmgr->FindEventManager(SCA_EventManager::ACTUATOR_EVENTMGR);
+ if (eventmgr)
+ {
+ STR_String propname=blenderactsensor->name;
+ gamesensor = new SCA_ActuatorSensor(eventmgr,gameobj,propname);
+ }
+ break;
+ }
case SENS_RADAR:
{
@@ -608,6 +644,7 @@ void BL_ConvertSensors(struct Object* blenderobject,
if (eventmgr)
{
bool bFindMaterial = (blenderraysensor->mode & SENS_COLLISION_MATERIAL);
+ bool bXRay = (blenderraysensor->mode & SENS_RAY_XRAY);
STR_String checkname = (bFindMaterial? blenderraysensor->matname : blenderraysensor->propname);
@@ -620,6 +657,7 @@ void BL_ConvertSensors(struct Object* blenderobject,
gameobj,
checkname,
bFindMaterial,
+ bXRay,
distance,
axis,
kxscene);
@@ -656,7 +694,6 @@ void BL_ConvertSensors(struct Object* blenderobject,
int axis =0;
int axisf =0;
int button =0;
- int buttonf =0;
int hat =0;
int hatf =0;
int prec =0;
@@ -671,7 +708,6 @@ void BL_ConvertSensors(struct Object* blenderobject,
break;
case SENS_JOY_BUTTON:
button = bjoy->button;
- buttonf = bjoy->buttonf;
joysticktype = SCA_JoystickSensor::KX_JOYSENSORMODE_BUTTON;
break;
case SENS_JOY_HAT:
@@ -686,11 +722,13 @@ void BL_ConvertSensors(struct Object* blenderobject,
gamesensor = new SCA_JoystickSensor(
eventmgr,
gameobj,
+ bjoy->joyindex,
joysticktype,
axis,axisf,
prec,
- button,buttonf,
- hat,hatf);
+ button,
+ hat,hatf,
+ (bjoy->flag & SENS_JOY_ANY_EVENT));
}
else
{
@@ -719,25 +757,49 @@ void BL_ConvertSensors(struct Object* blenderobject,
neg_pulsemode,
frequency);
gamesensor->SetInvert(invert);
+ gamesensor->SetLevel(level);
gamesensor->SetName(STR_String(sens->name));
gameobj->AddSensor(gamesensor);
// only register to manager if it's in an active layer
-
- if (isInActiveLayer)
- gamesensor->RegisterToManager();
+ // Make registration dynamic: only when sensor is activated
+ //if (isInActiveLayer)
+ // gamesensor->RegisterToManager();
for (int i=0;i<sens->totlinks;i++)
{
bController* linkedcont = (bController*) sens->links[i];
- SCA_IController* gamecont = converter->FindGameController(linkedcont);
+ if (linkedcont) {
+ SCA_IController* gamecont = converter->FindGameController(linkedcont);
- if (gamecont) {
- logicmgr->RegisterToSensor(gamecont,gamesensor);
+ if (gamecont) {
+ logicmgr->RegisterToSensor(gamecont,gamesensor);
+ } else {
+ printf(
+ "Warning, sensor \"%s\" could not find its controller "
+ "(link %d of %d) from object \"%s\"\n"
+ "\tthere has been an error converting the blender controller for the game engine,"
+ "logic may be incorrect\n", sens->name, i+1, sens->totlinks, blenderobject->id.name+2);
+ }
+ } else {
+ printf(
+ "Warning, sensor \"%s\" has lost a link to a controller "
+ "(link %d of %d) from object \"%s\"\n"
+ "\tpossible causes are partially appended objects or an error reading the file,"
+ "logic may be incorrect\n", sens->name, i+1, sens->totlinks, blenderobject->id.name+2);
}
}
+ // special case: Keyboard sensor with no link
+ // this combination is usually used for key logging.
+ if (sens->type == SENS_KEYBOARD && sens->totlinks == 0) {
+ // Force the registration so that the sensor runs
+ gamesensor->IncLink();
+ }
+
+ // done with gamesensor
+ gamesensor->Release();
}
sens=sens->next;
diff --git a/source/gameengine/Converter/KX_ConvertSensors.h b/source/gameengine/Converter/KX_ConvertSensors.h
index 73da51f47f0..b18ffc10a2a 100644
--- a/source/gameengine/Converter/KX_ConvertSensors.h
+++ b/source/gameengine/Converter/KX_ConvertSensors.h
@@ -33,6 +33,7 @@ void BL_ConvertSensors(struct Object* blenderobject,
class KX_GameObject* gameobj,
class SCA_LogicManager* logicmgr,
class KX_Scene* kxscene,
+ class KX_KetsjiEngine* kxengine,
class SCA_IInputDevice* keydev,
int & executePriority ,
int activeLayerBitInfo,
diff --git a/source/gameengine/Converter/KX_IpoConvert.cpp b/source/gameengine/Converter/KX_IpoConvert.cpp
index 4d1fb7323f3..ce004fa0504 100644
--- a/source/gameengine/Converter/KX_IpoConvert.cpp
+++ b/source/gameengine/Converter/KX_IpoConvert.cpp
@@ -36,6 +36,7 @@
#pragma warning (disable:4786)
#endif
+#include "BKE_material.h" /* give_current_material */
#include "KX_GameObject.h"
#include "KX_IpoConvert.h"
@@ -68,6 +69,8 @@
#include "SG_Node.h"
+#include "STR_HashedString.h"
+
static BL_InterpolatorList *GetIpoList(struct Ipo *for_ipo, KX_BlenderSceneConverter *converter) {
BL_InterpolatorList *ipoList= converter->FindInterpolatorList(for_ipo);
@@ -97,9 +100,9 @@ void BL_ConvertIpos(struct Object* blenderobject,KX_GameObject* gameobj,KX_Blend
ipocontr->GetIPOTransform().SetPosition(
MT_Point3(
- blenderobject->loc[0]+blenderobject->dloc[0],
- blenderobject->loc[1]+blenderobject->dloc[1],
- blenderobject->loc[2]+blenderobject->dloc[2]
+ blenderobject->loc[0]/*+blenderobject->dloc[0]*/,
+ blenderobject->loc[1]/*+blenderobject->dloc[1]*/,
+ blenderobject->loc[2]/*+blenderobject->dloc[2]*/
)
);
ipocontr->GetIPOTransform().SetEulerAngles(
@@ -131,7 +134,7 @@ void BL_ConvertIpos(struct Object* blenderobject,KX_GameObject* gameobj,KX_Blend
&(ipocontr->GetIPOTransform().GetPosition()[0]),
ipo);
ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyPosition(true);
+ ipocontr->SetIPOChannelActive(OB_LOC_X, true);
}
@@ -142,7 +145,7 @@ void BL_ConvertIpos(struct Object* blenderobject,KX_GameObject* gameobj,KX_Blend
&(ipocontr->GetIPOTransform().GetPosition()[1]),
ipo);
ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyPosition(true);
+ ipocontr->SetIPOChannelActive(OB_LOC_Y, true);
}
ipo = ipoList->GetScalarInterpolator(OB_LOC_Z);
@@ -152,7 +155,7 @@ void BL_ConvertIpos(struct Object* blenderobject,KX_GameObject* gameobj,KX_Blend
&(ipocontr->GetIPOTransform().GetPosition()[2]),
ipo);
ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyPosition(true);
+ ipocontr->SetIPOChannelActive(OB_LOC_Z, true);
}
// Master the art of cut & paste programming...
@@ -164,7 +167,7 @@ void BL_ConvertIpos(struct Object* blenderobject,KX_GameObject* gameobj,KX_Blend
&(ipocontr->GetIPOTransform().GetDeltaPosition()[0]),
ipo);
ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyPosition(true);
+ ipocontr->SetIPOChannelActive(OB_DLOC_X, true);
}
ipo = ipoList->GetScalarInterpolator(OB_DLOC_Y);
@@ -174,7 +177,7 @@ void BL_ConvertIpos(struct Object* blenderobject,KX_GameObject* gameobj,KX_Blend
&(ipocontr->GetIPOTransform().GetDeltaPosition()[1]),
ipo);
ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyPosition(true);
+ ipocontr->SetIPOChannelActive(OB_DLOC_Y, true);
}
ipo = ipoList->GetScalarInterpolator(OB_DLOC_Z);
@@ -184,7 +187,7 @@ void BL_ConvertIpos(struct Object* blenderobject,KX_GameObject* gameobj,KX_Blend
&(ipocontr->GetIPOTransform().GetDeltaPosition()[2]),
ipo);
ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyPosition(true);
+ ipocontr->SetIPOChannelActive(OB_DLOC_Z, true);
}
// Explore the finesse of reuse and slight modification
@@ -196,7 +199,7 @@ void BL_ConvertIpos(struct Object* blenderobject,KX_GameObject* gameobj,KX_Blend
&(ipocontr->GetIPOTransform().GetEulerAngles()[0]),
ipo);
ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyOrientation(true);
+ ipocontr->SetIPOChannelActive(OB_ROT_X, true);
}
ipo = ipoList->GetScalarInterpolator(OB_ROT_Y);
if (ipo) {
@@ -205,7 +208,7 @@ void BL_ConvertIpos(struct Object* blenderobject,KX_GameObject* gameobj,KX_Blend
&(ipocontr->GetIPOTransform().GetEulerAngles()[1]),
ipo);
ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyOrientation(true);
+ ipocontr->SetIPOChannelActive(OB_ROT_Y, true);
}
ipo = ipoList->GetScalarInterpolator(OB_ROT_Z);
if (ipo) {
@@ -214,7 +217,7 @@ void BL_ConvertIpos(struct Object* blenderobject,KX_GameObject* gameobj,KX_Blend
&(ipocontr->GetIPOTransform().GetEulerAngles()[2]),
ipo);
ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyOrientation(true);
+ ipocontr->SetIPOChannelActive(OB_ROT_Z, true);
}
// Hmmm, the need for a macro comes to mind...
@@ -226,7 +229,7 @@ void BL_ConvertIpos(struct Object* blenderobject,KX_GameObject* gameobj,KX_Blend
&(ipocontr->GetIPOTransform().GetDeltaEulerAngles()[0]),
ipo);
ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyOrientation(true);
+ ipocontr->SetIPOChannelActive(OB_DROT_X, true);
}
ipo = ipoList->GetScalarInterpolator(OB_DROT_Y);
if (ipo) {
@@ -235,7 +238,7 @@ void BL_ConvertIpos(struct Object* blenderobject,KX_GameObject* gameobj,KX_Blend
&(ipocontr->GetIPOTransform().GetDeltaEulerAngles()[1]),
ipo);
ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyOrientation(true);
+ ipocontr->SetIPOChannelActive(OB_DROT_Y, true);
}
ipo = ipoList->GetScalarInterpolator(OB_DROT_Z);
if (ipo) {
@@ -244,7 +247,7 @@ void BL_ConvertIpos(struct Object* blenderobject,KX_GameObject* gameobj,KX_Blend
&(ipocontr->GetIPOTransform().GetDeltaEulerAngles()[2]),
ipo);
ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyOrientation(true);
+ ipocontr->SetIPOChannelActive(OB_DROT_Z, true);
}
// Hang on, almost there...
@@ -256,7 +259,7 @@ void BL_ConvertIpos(struct Object* blenderobject,KX_GameObject* gameobj,KX_Blend
&(ipocontr->GetIPOTransform().GetScaling()[0]),
ipo);
ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyScaling(true);
+ ipocontr->SetIPOChannelActive(OB_SIZE_X, true);
}
ipo = ipoList->GetScalarInterpolator(OB_SIZE_Y);
if (ipo) {
@@ -265,7 +268,7 @@ void BL_ConvertIpos(struct Object* blenderobject,KX_GameObject* gameobj,KX_Blend
&(ipocontr->GetIPOTransform().GetScaling()[1]),
ipo);
ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyScaling(true);
+ ipocontr->SetIPOChannelActive(OB_SIZE_Y, true);
}
ipo = ipoList->GetScalarInterpolator(OB_SIZE_Z);
if (ipo) {
@@ -274,7 +277,7 @@ void BL_ConvertIpos(struct Object* blenderobject,KX_GameObject* gameobj,KX_Blend
&(ipocontr->GetIPOTransform().GetScaling()[2]),
ipo);
ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyScaling(true);
+ ipocontr->SetIPOChannelActive(OB_SIZE_Z, true);
}
// The last few...
@@ -286,7 +289,7 @@ void BL_ConvertIpos(struct Object* blenderobject,KX_GameObject* gameobj,KX_Blend
&(ipocontr->GetIPOTransform().GetDeltaScaling()[0]),
ipo);
ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyScaling(true);
+ ipocontr->SetIPOChannelActive(OB_DSIZE_X, true);
}
ipo = ipoList->GetScalarInterpolator(OB_DSIZE_Y);
if (ipo) {
@@ -295,7 +298,7 @@ void BL_ConvertIpos(struct Object* blenderobject,KX_GameObject* gameobj,KX_Blend
&(ipocontr->GetIPOTransform().GetDeltaScaling()[1]),
ipo);
ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyScaling(true);
+ ipocontr->SetIPOChannelActive(OB_DSIZE_Y, true);
}
ipo = ipoList->GetScalarInterpolator(OB_DSIZE_Z);
if (ipo) {
@@ -304,7 +307,7 @@ void BL_ConvertIpos(struct Object* blenderobject,KX_GameObject* gameobj,KX_Blend
&(ipocontr->GetIPOTransform().GetDeltaScaling()[2]),
ipo);
ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyScaling(true);
+ ipocontr->SetIPOChannelActive(OB_DSIZE_Z, true);
}
{
@@ -560,16 +563,15 @@ void BL_ConvertWorldIpos(struct World* blenderworld,KX_BlenderSceneConverter *co
}
}
-
-void BL_ConvertMaterialIpos(
- Material* blendermaterial,
+static void ConvertMaterialIpos(
+ Material* blendermaterial,
+ dword matname_hash,
KX_GameObject* gameobj,
KX_BlenderSceneConverter *converter
)
{
if (blendermaterial->ipo) {
-
- KX_MaterialIpoController* ipocontr = new KX_MaterialIpoController();
+ KX_MaterialIpoController* ipocontr = new KX_MaterialIpoController(matname_hash);
gameobj->GetSGNode()->AddSGController(ipocontr);
ipocontr->SetObject(gameobj->GetSGNode());
@@ -596,7 +598,7 @@ void BL_ConvertMaterialIpos(
ipo = ipoList->GetScalarInterpolator(MA_COL_R);
if (ipo) {
if (!ipocontr) {
- ipocontr = new KX_MaterialIpoController();
+ ipocontr = new KX_MaterialIpoController(matname_hash);
gameobj->GetSGNode()->AddSGController(ipocontr);
ipocontr->SetObject(gameobj->GetSGNode());
}
@@ -610,7 +612,7 @@ void BL_ConvertMaterialIpos(
ipo = ipoList->GetScalarInterpolator(MA_COL_G);
if (ipo) {
if (!ipocontr) {
- ipocontr = new KX_MaterialIpoController();
+ ipocontr = new KX_MaterialIpoController(matname_hash);
gameobj->GetSGNode()->AddSGController(ipocontr);
ipocontr->SetObject(gameobj->GetSGNode());
}
@@ -624,7 +626,7 @@ void BL_ConvertMaterialIpos(
ipo = ipoList->GetScalarInterpolator(MA_COL_B);
if (ipo) {
if (!ipocontr) {
- ipocontr = new KX_MaterialIpoController();
+ ipocontr = new KX_MaterialIpoController(matname_hash);
gameobj->GetSGNode()->AddSGController(ipocontr);
ipocontr->SetObject(gameobj->GetSGNode());
}
@@ -638,7 +640,7 @@ void BL_ConvertMaterialIpos(
ipo = ipoList->GetScalarInterpolator(MA_ALPHA);
if (ipo) {
if (!ipocontr) {
- ipocontr = new KX_MaterialIpoController();
+ ipocontr = new KX_MaterialIpoController(matname_hash);
gameobj->GetSGNode()->AddSGController(ipocontr);
ipocontr->SetObject(gameobj->GetSGNode());
}
@@ -653,7 +655,7 @@ void BL_ConvertMaterialIpos(
ipo = ipoList->GetScalarInterpolator(MA_SPEC_R );
if (ipo) {
if (!ipocontr) {
- ipocontr = new KX_MaterialIpoController();
+ ipocontr = new KX_MaterialIpoController(matname_hash);
gameobj->GetSGNode()->AddSGController(ipocontr);
ipocontr->SetObject(gameobj->GetSGNode());
}
@@ -667,7 +669,7 @@ void BL_ConvertMaterialIpos(
ipo = ipoList->GetScalarInterpolator(MA_SPEC_G);
if (ipo) {
if (!ipocontr) {
- ipocontr = new KX_MaterialIpoController();
+ ipocontr = new KX_MaterialIpoController(matname_hash);
gameobj->GetSGNode()->AddSGController(ipocontr);
ipocontr->SetObject(gameobj->GetSGNode());
}
@@ -681,7 +683,7 @@ void BL_ConvertMaterialIpos(
ipo = ipoList->GetScalarInterpolator(MA_SPEC_B);
if (ipo) {
if (!ipocontr) {
- ipocontr = new KX_MaterialIpoController();
+ ipocontr = new KX_MaterialIpoController(matname_hash);
gameobj->GetSGNode()->AddSGController(ipocontr);
ipocontr->SetObject(gameobj->GetSGNode());
}
@@ -696,7 +698,7 @@ void BL_ConvertMaterialIpos(
ipo = ipoList->GetScalarInterpolator(MA_HARD);
if (ipo) {
if (!ipocontr) {
- ipocontr = new KX_MaterialIpoController();
+ ipocontr = new KX_MaterialIpoController(matname_hash);
gameobj->GetSGNode()->AddSGController(ipocontr);
ipocontr->SetObject(gameobj->GetSGNode());
}
@@ -710,7 +712,7 @@ void BL_ConvertMaterialIpos(
ipo = ipoList->GetScalarInterpolator(MA_SPEC);
if (ipo) {
if (!ipocontr) {
- ipocontr = new KX_MaterialIpoController();
+ ipocontr = new KX_MaterialIpoController(matname_hash);
gameobj->GetSGNode()->AddSGController(ipocontr);
ipocontr->SetObject(gameobj->GetSGNode());
}
@@ -725,7 +727,7 @@ void BL_ConvertMaterialIpos(
ipo = ipoList->GetScalarInterpolator(MA_REF);
if (ipo) {
if (!ipocontr) {
- ipocontr = new KX_MaterialIpoController();
+ ipocontr = new KX_MaterialIpoController(matname_hash);
gameobj->GetSGNode()->AddSGController(ipocontr);
ipocontr->SetObject(gameobj->GetSGNode());
}
@@ -739,7 +741,7 @@ void BL_ConvertMaterialIpos(
ipo = ipoList->GetScalarInterpolator(MA_EMIT);
if (ipo) {
if (!ipocontr) {
- ipocontr = new KX_MaterialIpoController();
+ ipocontr = new KX_MaterialIpoController(matname_hash);
gameobj->GetSGNode()->AddSGController(ipocontr);
ipocontr->SetObject(gameobj->GetSGNode());
}
@@ -752,3 +754,31 @@ void BL_ConvertMaterialIpos(
}
}
+void BL_ConvertMaterialIpos(
+ struct Object* blenderobject,
+ KX_GameObject* gameobj,
+ KX_BlenderSceneConverter *converter
+ )
+{
+ if (blenderobject->totcol==1)
+ {
+ Material *mat = give_current_material(blenderobject, 1);
+ // if there is only one material attached to the mesh then set material_index in BL_ConvertMaterialIpos to NULL
+ // --> this makes the UpdateMaterialData function in KX_GameObject.cpp use the old hack of using SetObjectColor
+ // because this yields a better performance as not all the vertex colors need to be edited
+ if(mat) ConvertMaterialIpos(mat, 0, gameobj, converter);
+ }
+ else
+ {
+ for (int material_index=1; material_index <= blenderobject->totcol; material_index++)
+ {
+ Material *mat = give_current_material(blenderobject, material_index);
+ STR_HashedString matname;
+ if(mat) {
+ matname= mat->id.name;
+ ConvertMaterialIpos(mat, matname.hash(), gameobj, converter);
+ }
+ }
+ }
+}
+
diff --git a/source/gameengine/Converter/KX_IpoConvert.h b/source/gameengine/Converter/KX_IpoConvert.h
index afcb1b22821..4ec9bd31062 100644
--- a/source/gameengine/Converter/KX_IpoConvert.h
+++ b/source/gameengine/Converter/KX_IpoConvert.h
@@ -46,7 +46,7 @@ void BL_ConvertCameraIpos(struct Camera* blendercamera,
class KX_GameObject* cameraobj,
class KX_BlenderSceneConverter *converter);
-void BL_ConvertMaterialIpos(struct Material* blendermaterial,
+void BL_ConvertMaterialIpos(struct Object* blenderobject,
class KX_GameObject* materialobj,
class KX_BlenderSceneConverter *converter);
diff --git a/source/gameengine/Converter/Makefile b/source/gameengine/Converter/Makefile
index 4a76b661d4f..938994e8b62 100644
--- a/source/gameengine/Converter/Makefile
+++ b/source/gameengine/Converter/Makefile
@@ -52,6 +52,7 @@ CPPFLAGS += -I../../blender/editors/include
CPPFLAGS += -I../../blender/blenlib
CPPFLAGS += -I../../blender/blenkernel
CPPFLAGS += -I../../blender/render/extern/include
+CPPFLAGS += -I../../blender/gpu
CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include
CPPFLAGS += -I../Expressions -I../Rasterizer -I../GameLogic
CPPFLAGS += -I../Ketsji -I../BlenderRoutines -I../SceneGraph
diff --git a/source/gameengine/Converter/SConscript b/source/gameengine/Converter/SConscript
index a63881f3ef0..434fad0f544 100644
--- a/source/gameengine/Converter/SConscript
+++ b/source/gameengine/Converter/SConscript
@@ -16,7 +16,7 @@ incs += ' #source/gameengine/Expressions #source/gameengine/Network #source/game
incs += ' #source/gameengine/Physics/common #source/gameengine/Physics/Bullet #source/gameengine/Physics/BlOde'
incs += ' #source/gameengine/Physics/Dummy #source/gameengine/Physics/Sumo'
incs += ' #source/gameengine/Physics/Sumo/Fuzzics/include #source/gameengine/Network/LoopBackNetwork'
-incs += ' #source/blender/misc #source/blender/blenloader'
+incs += ' #source/blender/misc #source/blender/blenloader #source/blender/gpu'
incs += ' #source/blender/windowmanager'
incs += ' ' + env['BF_PYTHON_INC']
diff --git a/source/gameengine/Expressions/Expression.cpp b/source/gameengine/Expressions/Expression.cpp
index 5c5e1abea34..f16f572c322 100644
--- a/source/gameengine/Expressions/Expression.cpp
+++ b/source/gameengine/Expressions/Expression.cpp
@@ -22,7 +22,9 @@
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
-
+#ifdef _DEBUG
+//int gRefCountExpr;
+#endif
CExpression::CExpression()// : m_cached_calculate(NULL)
{
m_refcount = 1;
diff --git a/source/gameengine/Expressions/InputParser.cpp b/source/gameengine/Expressions/InputParser.cpp
index 24033dd21a2..32a9de32e21 100644
--- a/source/gameengine/Expressions/InputParser.cpp
+++ b/source/gameengine/Expressions/InputParser.cpp
@@ -631,7 +631,8 @@ void CParser::SetContext(CValue* context)
PyObject* CParserPyMake(PyObject* ignored,PyObject* args)
{
char* txt;
- Py_Try(PyArg_ParseTuple(args,"s",&txt));
+ if (!PyArg_ParseTuple(args,"s",&txt))
+ return NULL;
CParser parser;
CExpression* expr = parser.ProcessText(txt);
CValue* val = expr->Calculate();
@@ -641,7 +642,7 @@ PyObject* CParserPyMake(PyObject* ignored,PyObject* args)
static PyMethodDef CParserMethods[] =
{
- { "calc", CParserPyMake , Py_NEWARGS},
+ { "calc", CParserPyMake , METH_VARARGS},
{ NULL,NULL} // Sentinel
};
diff --git a/source/gameengine/Expressions/ListValue.cpp b/source/gameengine/Expressions/ListValue.cpp
index bbf58a8a06e..9ffdbb1223c 100644
--- a/source/gameengine/Expressions/ListValue.cpp
+++ b/source/gameengine/Expressions/ListValue.cpp
@@ -43,7 +43,7 @@ PyObject* listvalue_buffer_item(PyObject* list,Py_ssize_t index)
return ((CListValue*) list)->GetValue(index)->AddRef();
}
- Py_Error(PyExc_IndexError, "Python ListIndex out of range");
+ PyErr_SetString(PyExc_IndexError, "Python ListIndex out of range");
return NULL;
}
@@ -130,9 +130,10 @@ listvalue_buffer_concat(PyObject * self, PyObject * other)
}
}
- if (error)
- Py_Error(PyExc_SystemError, "Python Error: couldn't add one or more items to a list");
-
+ if (error) {
+ PyErr_SetString(PyExc_SystemError, "Python Error: couldn't add one or more items to a list");
+ return NULL;
+ }
} else
{
@@ -155,8 +156,8 @@ listvalue_buffer_concat(PyObject * self, PyObject * other)
listval->Add(objval);
} else
{
- Py_Error(PyExc_SystemError, "Python Error: couldn't add item to a list");
- // bad luck
+ PyErr_SetString(PyExc_SystemError, "Python Error: couldn't add item to a list");
+ return NULL;
}
}
}
diff --git a/source/gameengine/Expressions/Makefile b/source/gameengine/Expressions/Makefile
index e9c02eedcf2..6736149bbcd 100644
--- a/source/gameengine/Expressions/Makefile
+++ b/source/gameengine/Expressions/Makefile
@@ -36,6 +36,7 @@ include nan_compile.mk
CCFLAGS += $(LEVEL_1_CPP_WARNINGS)
CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION)
+CPPFLAGS += -I../../blender/makesdna
CPPFLAGS += -I$(NAN_STRING)/include
CPPFLAGS += -I$(NAN_MOTO)/include
diff --git a/source/gameengine/Expressions/PyObjectPlus.cpp b/source/gameengine/Expressions/PyObjectPlus.cpp
index aabcd6cb71d..1eca527151a 100644
--- a/source/gameengine/Expressions/PyObjectPlus.cpp
+++ b/source/gameengine/Expressions/PyObjectPlus.cpp
@@ -94,7 +94,7 @@ PyObjectPlus::PyObjectPlus(PyTypeObject *T) // constructor
* PyObjectPlus Methods -- Every class, even the abstract one should have a Methods
------------------------------*/
PyMethodDef PyObjectPlus::Methods[] = {
- {"isA", (PyCFunction) sPy_isA, Py_NEWARGS},
+ {"isA", (PyCFunction) sPy_isA, METH_VARARGS},
{NULL, NULL} /* Sentinel */
};
@@ -119,6 +119,7 @@ PyObject *PyObjectPlus::_getattr(const STR_String& attr)
int PyObjectPlus::_delattr(const STR_String& attr)
{
+ PyErr_SetString(PyExc_AttributeError, "attribute cant be deleted");
return 1;
}
@@ -126,7 +127,8 @@ int PyObjectPlus::_setattr(const STR_String& attr, PyObject *value)
{
//return PyObject::_setattr(attr,value);
//cerr << "Unknown attribute" << endl;
- return 1;
+ PyErr_SetString(PyExc_AttributeError, "attribute cant be set");
+ return 1;
}
/*------------------------------
@@ -134,7 +136,8 @@ int PyObjectPlus::_setattr(const STR_String& attr, PyObject *value)
------------------------------*/
PyObject *PyObjectPlus::_repr(void)
{
- Py_Error(PyExc_SystemError, "Representation not overridden by object.");
+ PyErr_SetString(PyExc_SystemError, "Representation not overridden by object.");
+ return NULL;
}
/*------------------------------
@@ -164,11 +167,12 @@ bool PyObjectPlus::isA(const char *mytypename) // check typename of each parent
PyObject *PyObjectPlus::Py_isA(PyObject *args) // Python wrapper for isA
{
char *mytypename;
- Py_Try(PyArg_ParseTuple(args, "s", &mytypename));
+ if (!PyArg_ParseTuple(args, "s", &mytypename))
+ return NULL;
if(isA(mytypename))
- {Py_INCREF(Py_True); return Py_True;}
+ Py_RETURN_TRUE;
else
- {Py_INCREF(Py_False); return Py_False;};
+ Py_RETURN_FALSE;
}
#endif //NO_EXP_PYTHON_EMBEDDING
diff --git a/source/gameengine/Expressions/PyObjectPlus.h b/source/gameengine/Expressions/PyObjectPlus.h
index de89ed9b5c8..3a054454a0b 100644
--- a/source/gameengine/Expressions/PyObjectPlus.h
+++ b/source/gameengine/Expressions/PyObjectPlus.h
@@ -43,25 +43,39 @@
* Python defines
------------------------------*/
+/*
+ Py_RETURN_NONE
+ Python 2.4 macro.
+ defined here until we switch to 2.4
+ also in api2_2x/gen_utils.h
+*/
+#ifndef Py_RETURN_NONE
+#define Py_RETURN_NONE return Py_BuildValue("O", Py_None)
+#endif
+#ifndef Py_RETURN_FALSE
+#define Py_RETURN_FALSE return PyBool_FromLong(0)
+#endif
+#ifndef Py_RETURN_TRUE
+#define Py_RETURN_TRUE return PyBool_FromLong(1)
+#endif
+
+/* for pre Py 2.5 */
+#if PY_VERSION_HEX < 0x02050000
+typedef int Py_ssize_t;
+#define PY_SSIZE_T_MAX INT_MAX
+#define PY_SSIZE_T_MIN INT_MIN
+#define PY_METHODCHAR char *
+#else
+/* Py 2.5 and later */
+#define intargfunc ssizeargfunc
+#define intintargfunc ssizessizeargfunc
+#define PY_METHODCHAR const char *
+#endif
+
// some basic python macros
-#define Py_NEWARGS 1
#define Py_Return { Py_INCREF(Py_None); return Py_None;}
-static inline PyObject* Py_Success(bool truth)
-{
- if (truth)
- {
- Py_INCREF(Py_True);
- return Py_True;
- }
- Py_INCREF(Py_False);
- return Py_False;
-}
-
-#define Py_Error(E, M) {PyErr_SetString(E, M); return NULL;}
-#define Py_Try(F) {if (!(F)) return NULL;}
-#define Py_Assert(A,E,M) {if (!(A)) {PyErr_SetString(E, M); return NULL;}}
-static inline void Py_Fatal(char *M) {
+static inline void Py_Fatal(const char *M) {
//cout << M << endl;
exit(-1);
};
@@ -76,18 +90,36 @@ static inline void Py_Fatal(char *M) {
virtual PyTypeObject *GetType(void) {return &Type;}; \
virtual PyParentObject *GetParents(void) {return Parents;}
+
// This defines the _getattr_up macro
// which allows attribute and method calls
// to be properly passed up the hierarchy.
#define _getattr_up(Parent) \
- PyObject *rvalue = Py_FindMethod(Methods, this, const_cast<char*>(attr.ReadPtr())); \
- if (rvalue == NULL) \
- { \
+ PyObject *rvalue = NULL; \
+ if (attr=="__methods__") { \
+ PyObject *_attr_string = NULL; \
+ PyMethodDef *meth = Methods; \
+ rvalue = Parent::_getattr(attr); \
+ if (rvalue==NULL) { \
+ PyErr_Clear(); \
+ rvalue = PyList_New(0); \
+ } \
+ if (meth) { \
+ for (; meth->ml_name != NULL; meth++) { \
+ _attr_string = PyString_FromString(meth->ml_name); \
+ PyList_Append(rvalue, _attr_string); \
+ Py_DECREF(_attr_string); \
+ } \
+ } \
+ } else { \
+ rvalue = Py_FindMethod(Methods, this, const_cast<char*>(attr.ReadPtr())); \
+ if (rvalue == NULL) { \
PyErr_Clear(); \
- return Parent::_getattr(attr); \
+ rvalue = Parent::_getattr(attr); \
} \
- else \
- return rvalue
+ } \
+ return rvalue; \
+
/**
* These macros are helpfull when embedding Python routines. The second
@@ -99,27 +131,73 @@ static inline void Py_Fatal(char *M) {
return ((class_name*) self)->Py##method_name(self, args, kwds); \
}; \
+#define KX_PYMETHOD_VARARGS(class_name, method_name) \
+ PyObject* Py##method_name(PyObject* self, PyObject* args); \
+ static PyObject* sPy##method_name( PyObject* self, PyObject* args) { \
+ return ((class_name*) self)->Py##method_name(self, args); \
+ }; \
+
+#define KX_PYMETHOD_NOARGS(class_name, method_name) \
+ PyObject* Py##method_name(PyObject* self); \
+ static PyObject* sPy##method_name( PyObject* self) { \
+ return ((class_name*) self)->Py##method_name(self); \
+ }; \
+
+#define KX_PYMETHOD_O(class_name, method_name) \
+ PyObject* Py##method_name(PyObject* self, PyObject* value); \
+ static PyObject* sPy##method_name( PyObject* self, PyObject* value) { \
+ return ((class_name*) self)->Py##method_name(self, value); \
+ }; \
+
#define KX_PYMETHOD_DOC(class_name, method_name) \
PyObject* Py##method_name(PyObject* self, PyObject* args, PyObject* kwds); \
static PyObject* sPy##method_name( PyObject* self, PyObject* args, PyObject* kwds) { \
return ((class_name*) self)->Py##method_name(self, args, kwds); \
}; \
- static char method_name##_doc[]; \
+ static const char method_name##_doc[]; \
+
+#define KX_PYMETHOD_DOC_VARARGS(class_name, method_name) \
+ PyObject* Py##method_name(PyObject* self, PyObject* args); \
+ static PyObject* sPy##method_name( PyObject* self, PyObject* args) { \
+ return ((class_name*) self)->Py##method_name(self, args); \
+ }; \
+ static const char method_name##_doc[]; \
+
+#define KX_PYMETHOD_DOC_O(class_name, method_name) \
+ PyObject* Py##method_name(PyObject* self, PyObject* value); \
+ static PyObject* sPy##method_name( PyObject* self, PyObject* value) { \
+ return ((class_name*) self)->Py##method_name(self, value); \
+ }; \
+ static const char method_name##_doc[]; \
+
+#define KX_PYMETHOD_DOC_NOARGS(class_name, method_name) \
+ PyObject* Py##method_name(PyObject* self); \
+ static PyObject* sPy##method_name( PyObject* self) { \
+ return ((class_name*) self)->Py##method_name(self); \
+ }; \
+ static const char method_name##_doc[]; \
+
/* The line above should remain empty */
/**
* Method table macro (with doc)
*/
#define KX_PYMETHODTABLE(class_name, method_name) \
- {#method_name , (PyCFunction) class_name::sPy##method_name, METH_VARARGS, class_name::method_name##_doc}
+ {#method_name , (PyCFunction) class_name::sPy##method_name, METH_VARARGS, (PY_METHODCHAR)class_name::method_name##_doc}
+
+#define KX_PYMETHODTABLE_NOARG(class_name, method_name) \
+ {#method_name , (PyCFunction) class_name::sPy##method_name, METH_NOARGS, (PY_METHODCHAR)class_name::method_name##_doc}
/**
* Function implementation macro
*/
#define KX_PYMETHODDEF_DOC(class_name, method_name, doc_string) \
-char class_name::method_name##_doc[] = doc_string; \
+const char class_name::method_name##_doc[] = doc_string; \
PyObject* class_name::Py##method_name(PyObject*, PyObject* args, PyObject*)
+#define KX_PYMETHODDEF_DOC_NOARG(class_name, method_name, doc_string) \
+const char class_name::method_name##_doc[] = doc_string; \
+PyObject* class_name::Py##method_name(PyObject*)
/*------------------------------
* PyObjectPlus
diff --git a/source/gameengine/Expressions/Value.cpp b/source/gameengine/Expressions/Value.cpp
index 48898dfc1f5..7296dfbec10 100644
--- a/source/gameengine/Expressions/Value.cpp
+++ b/source/gameengine/Expressions/Value.cpp
@@ -158,18 +158,38 @@ PyParentObject CValue::Parents[] = {
};
PyMethodDef CValue::Methods[] = {
-// { "printHello", (PyCFunction) CValue::sPyPrintHello, Py_NEWARGS},
- { "getName", (PyCFunction) CValue::sPyGetName, Py_NEWARGS},
+// { "printHello", (PyCFunction) CValue::sPyPrintHello, METH_VARARGS},
+ { "getName", (PyCFunction) CValue::sPyGetName, METH_NOARGS},
{NULL,NULL} //Sentinel
};
-PyObject* CValue::PyGetName(PyObject* self,PyObject* args,PyObject* kwds)
+PyObject* CValue::PyGetName(PyObject* self)
{
- PyObject* pyname = PyString_FromString(this->GetName());
- return pyname;
+ return PyString_FromString(this->GetName());
}
+/*#define CVALUE_DEBUG*/
+#ifdef CVALUE_DEBUG
+int gRefCount;
+struct SmartCValueRef
+{
+ CValue *m_ref;
+ int m_count;
+ SmartCValueRef(CValue *ref)
+ {
+ m_ref = ref;
+ m_count = gRefCount++;
+ }
+};
+
+#include <vector>
+std::vector<SmartCValueRef> gRefList;
+#endif
+
+#ifdef _DEBUG
+//int gRefCountValue;
+#endif
CValue::CValue(PyTypeObject *T)
: PyObjectPlus(T),
@@ -186,6 +206,12 @@ effect: constucts a CValue
*/
{
//debug(gRefCountValue++) // debugging
+#ifdef _DEBUG
+ //gRefCountValue++;
+#ifdef CVALUE_DEBUG
+ gRefList.push_back(SmartCValueRef(this));
+#endif
+#endif
}
@@ -199,6 +225,18 @@ effect: deletes the object
ClearProperties();
assertd (m_refcount==0);
+#ifdef CVALUE_DEBUG
+ std::vector<SmartCValueRef>::iterator it;
+ for (it=gRefList.begin(); it!=gRefList.end(); it++)
+ {
+ if (it->m_ref == this)
+ {
+ *it = gRefList.back();
+ gRefList.pop_back();
+ break;
+ }
+ }
+#endif
}
@@ -293,7 +331,7 @@ void CValue::SetProperty(const STR_String & name,CValue* ioProperty)
}
// Add property at end of array
- (*m_pNamedPropertyArray)[name] = ioProperty;//->Add(ioProperty);
+ (*m_pNamedPropertyArray)[name] = ioProperty->AddRef();//->Add(ioProperty);
}
@@ -353,17 +391,40 @@ float CValue::GetPropertyNumber(const STR_String& inName,float defnumber)
bool CValue::RemoveProperty(const STR_String & inName)
{
// Check if there are properties at all which can be removed
- if (m_pNamedPropertyArray == NULL)
- return false;
-
- // Scan all properties, as soon as we find one with <inName> -> Remove it
-// CValue* val = (*m_pNamedPropertyArray)[inName];
- if (m_pNamedPropertyArray->erase(inName)) return true;
+ if (m_pNamedPropertyArray) {
+ CValue* val = GetProperty(inName);
+ if (NULL != val)
+ {
+ val->Release();
+ m_pNamedPropertyArray->erase(inName);
+ return true;
+ }
+ }
+ char err[128];
+ if (m_pNamedPropertyArray)
+ sprintf(err, "attribute \"%s\" dosnt exist", inName.ReadPtr());
+ else
+ sprintf(err, "attribute \"%s\" dosnt exist (no property array)", inName.ReadPtr());
+
+ PyErr_SetString(PyExc_AttributeError, err);
return false;
}
-
+//
+// Get Property Names
+//
+vector<STR_String> CValue::GetPropertyNames()
+{
+ vector<STR_String> result;
+ if(!m_pNamedPropertyArray) return result;
+ for ( std::map<STR_String,CValue*>::iterator it = m_pNamedPropertyArray->begin();
+ !(it == m_pNamedPropertyArray->end());it++)
+ {
+ result.push_back((*it).first);
+ }
+ return result;
+}
//
// Clear all properties
@@ -379,7 +440,7 @@ void CValue::ClearProperties()
!(it == m_pNamedPropertyArray->end());it++)
{
CValue* tmpval = (*it).second;
- STR_String name = (*it).first;
+ //STR_String name = (*it).first;
tmpval->Release();
}
@@ -469,19 +530,15 @@ void CValue::CloneProperties(CValue *replica)
for ( std::map<STR_String,CValue*>::iterator it = m_pNamedPropertyArray->begin();
!(it == m_pNamedPropertyArray->end());it++)
{
-
- replica->SetProperty((*it).first,(*it).second->GetReplica());
+ CValue *val = (*it).second->GetReplica();
+ replica->SetProperty((*it).first,val);
+ val->Release();
}
}
}
-
-
-
-
-
double* CValue::GetVector3(bool bGetTransformedVec)
{
assertd(false); // don;t get vector from me
@@ -489,10 +546,6 @@ double* CValue::GetVector3(bool bGetTransformedVec)
}
-
-
-
-
/*---------------------------------------------------------------------------------------------------------------------
Reference Counting
---------------------------------------------------------------------------------------------------------------------*/
@@ -504,6 +557,9 @@ CValue *CValue::AddRef()
// Increase global reference count, used to see at the end of the program
// if all CValue-derived classes have been dereferenced to 0
//debug(gRefCountValue++);
+#ifdef _DEBUG
+ //gRefCountValue++;
+#endif
m_refcount++;
return this;
}
@@ -518,7 +574,9 @@ int CValue::Release()
// Decrease global reference count, used to see at the end of the program
// if all CValue-derived classes have been dereferenced to 0
//debug(gRefCountValue--);
-
+#ifdef _DEBUG
+ //gRefCountValue--;
+#endif
// Decrease local reference count, if it reaches 0 the object should be freed
if (--m_refcount > 0)
{
@@ -546,6 +604,9 @@ void CValue::DisableRefCount()
m_refcount--;
//debug(gRefCountValue--);
+#ifdef _DEBUG
+ //gRefCountValue--;
+#endif
m_ValFlags.RefCountDisabled=true;
}
@@ -590,11 +651,14 @@ CValue* CValue::FindIdentifier(const STR_String& identifiername)
} else
{
result = GetProperty(identifiername);
+ if (result)
+ return result->AddRef();
+ }
+ if (!result)
+ {
+ // warning here !!!
+ result = new CErrorValue(identifiername+" not found");
}
- if (result)
- return result->AddRef();
- // warning here !!!
- result = new CErrorValue(identifiername+" not found");
return result;
}
@@ -604,7 +668,7 @@ CValue* CValue::FindIdentifier(const STR_String& identifiername)
static PyMethodDef CValueMethods[] =
{
- //{ "new", CValue::PyMake , Py_NEWARGS},
+ //{ "new", CValue::PyMake , METH_VARARGS},
{ NULL,NULL} // Sentinel
};
@@ -642,9 +706,7 @@ CValue* CValue::ConvertPythonToValue(PyObject* pyobj)
CValue* vallie = NULL;
- PyTypeObject* type = pyobj->ob_type;
-
- if (type == &PyList_Type)
+ if (PyList_Check(pyobj))
{
CListValue* listval = new CListValue();
bool error = false;
@@ -674,26 +736,25 @@ CValue* CValue::ConvertPythonToValue(PyObject* pyobj)
}
} else
- if (type == &PyFloat_Type)
+ if (PyFloat_Check(pyobj))
{
- float fl;
- PyArg_Parse(pyobj,"f",&fl);
- vallie = new CFloatValue(fl);
+ vallie = new CFloatValue( (float)PyFloat_AsDouble(pyobj) );
} else
- if (type==&PyInt_Type)
+ if (PyInt_Check(pyobj))
{
- int innie;
- PyArg_Parse(pyobj,"i",&innie);
- vallie = new CIntValue(innie);
+ vallie = new CIntValue( (int)PyInt_AS_LONG(pyobj) );
} else
-
- if (type==&PyString_Type)
+ if (PyString_Check(pyobj))
{
vallie = new CStringValue(PyString_AsString(pyobj),"");
} else
- if (type==&CValue::Type || type==&CListValue::Type)
+ if (pyobj->ob_type==&CValue::Type || pyobj->ob_type==&CListValue::Type)
{
vallie = ((CValue*) pyobj)->AddRef();
+ } else
+ {
+ /* return an error value from the caller */
+ PyErr_SetString(PyExc_TypeError, "This python value could not be assigned to a game engine property");
}
return vallie;
@@ -701,7 +762,8 @@ CValue* CValue::ConvertPythonToValue(PyObject* pyobj)
int CValue::_delattr(const STR_String& attr)
{
- RemoveProperty(attr);
+ if (!RemoveProperty(attr)) /* sets error */
+ return 1;
return 0;
}
@@ -717,21 +779,42 @@ int CValue::_setattr(const STR_String& attr,PyObject* pyobj)
oldprop->SetValue(vallie);
} else
{
- SetProperty(attr,vallie->AddRef());
+ SetProperty(attr,vallie);
}
vallie->Release();
+ } else
+ {
+ return 1; /* ConvertPythonToValue sets the error message */
}
//PyObjectPlus::_setattr(attr,value);
return 0;
};
+
+PyObject* CValue::ConvertKeysToPython( void )
+{
+ PyObject *pylist = PyList_New( 0 );
+ PyObject *pystr;
+
+ if (m_pNamedPropertyArray)
+ {
+ for ( std::map<STR_String,CValue*>::iterator it = m_pNamedPropertyArray->begin();
+ !(it == m_pNamedPropertyArray->end());it++)
+ {
+ pystr = PyString_FromString( (*it).first );
+ PyList_Append(pylist, pystr);
+ Py_DECREF( pystr );
+ }
+ }
+ return pylist;
+}
+
/*
PyObject* CValue::PyMake(PyObject* ignored,PyObject* args)
{
- //Py_Try(PyArg_ParseTuple(args,"s",&name));
- Py_INCREF(Py_None);
- return Py_None;//new CValue();
+ //if (!PyArg_ParseTuple(args,"s",&name)) return NULL;
+ Py_RETURN_NONE;//new CValue();
}
*/
diff --git a/source/gameengine/Expressions/Value.h b/source/gameengine/Expressions/Value.h
index ccb9c34749d..74fcdae5756 100644
--- a/source/gameengine/Expressions/Value.h
+++ b/source/gameengine/Expressions/Value.h
@@ -253,7 +253,9 @@ public:
virtual int _delattr(const STR_String& attr);
virtual int _setattr(const STR_String& attr,PyObject* value);
- KX_PYMETHOD(CValue,GetName);
+ virtual PyObject* ConvertKeysToPython( void );
+
+ KX_PYMETHOD_NOARGS(CValue,GetName);
#else
CValue();
@@ -284,6 +286,7 @@ public:
STR_String GetPropertyText(const STR_String & inName,const STR_String& deftext=""); // Get text description of property with name <inName>, returns an empty string if there is no property named <inName>
float GetPropertyNumber(const STR_String& inName,float defnumber);
virtual bool RemoveProperty(const STR_String & inName); // Remove the property named <inName>, returns true if the property was succesfully removed, false if property was not found or could not be removed
+ virtual vector<STR_String> GetPropertyNames();
virtual void ClearProperties(); // Clear all properties
virtual void SetPropertiesModified(bool inModified); // Set all properties' modified flag to <inModified>
diff --git a/source/gameengine/GameLogic/CMakeLists.txt b/source/gameengine/GameLogic/CMakeLists.txt
index 6af37b746da..a7519196d50 100644
--- a/source/gameengine/GameLogic/CMakeLists.txt
+++ b/source/gameengine/GameLogic/CMakeLists.txt
@@ -32,6 +32,7 @@ SET(INC
../../../intern/string
../../../source/gameengine/Expressions
../../../intern/moto/include
+ ../../../source/gameengine/Rasterizer
${PYTHON_INC}
${SDL_INC}
)
diff --git a/source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp b/source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp
index aa5fc9eb8f3..e8e29fb2769 100644
--- a/source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp
+++ b/source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp
@@ -24,14 +24,18 @@
*
* ***** END GPL LICENSE BLOCK *****
*/
+#ifndef DISABLE_SDL
#include <SDL.h>
+#endif
+
+#include <stdio.h>
#include "SCA_Joystick.h"
#include "SCA_JoystickPrivate.h"
-
-SCA_Joystick::SCA_Joystick()
+SCA_Joystick::SCA_Joystick(short int index)
:
+ m_joyindex(index),
m_axis10(0),
m_axis11(0),
m_axis20(0),
@@ -40,78 +44,100 @@ SCA_Joystick::SCA_Joystick()
m_buttonnum(-2),
m_hatdir(-2),
m_isinit(0),
- m_istrig(0)
+ m_istrig_axis(0),
+ m_istrig_button(0),
+ m_istrig_hat(0),
+ m_axismax(-1),
+ m_buttonmax(-1),
+ m_hatmax(-1)
{
+#ifndef DISABLE_SDL
m_private = new PrivateData();
+#endif
}
SCA_Joystick::~SCA_Joystick()
{
+#ifndef DISABLE_SDL
delete m_private;
+#endif
}
+SCA_Joystick *SCA_Joystick::m_instance[JOYINDEX_MAX];
+int SCA_Joystick::m_refCount = 0;
-bool SCA_Joystick::CreateJoystickDevice()
+SCA_Joystick *SCA_Joystick::GetInstance( short int joyindex )
{
- bool init = false;
- init = pCreateJoystickDevice();
- return init;
-}
-
+#ifdef DISABLE_SDL
+ return NULL;
+#else
+ if (joyindex < 0 || joyindex >= JOYINDEX_MAX) {
+ echo("Error-invalid joystick index: " << joyindex);
+ return NULL;
+ }
-void SCA_Joystick::DestroyJoystickDevice()
-{
- if(m_isinit)
- pDestroyJoystickDevice();
+ if (m_refCount == 0)
+ {
+ int i;
+ // do this once only
+ if(SDL_InitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_VIDEO ) == -1 ){
+ echo("Error-Initializing-SDL: " << SDL_GetError());
+ return NULL;
+ }
+ for (i=0; i<JOYINDEX_MAX; i++) {
+ m_instance[i] = new SCA_Joystick(i);
+ m_instance[i]->CreateJoystickDevice();
+ }
+ m_refCount = 1;
+ }
+ else
+ {
+ m_refCount++;
+ }
+ return m_instance[joyindex];
+#endif
}
-
-void SCA_Joystick::HandleEvents()
+void SCA_Joystick::ReleaseInstance()
{
- if(m_isinit)
+ if (--m_refCount == 0)
{
- if(SDL_PollEvent(&m_private->m_event))
- {
- switch(m_private->m_event.type)
- {
- case SDL_JOYAXISMOTION:
- HANDLE_AXISMOTION(OnAxisMotion);
- break;
- case SDL_JOYHATMOTION:
- HANDLE_HATMOTION(OnHatMotion);
- break;
- case SDL_JOYBUTTONUP:
- HANDLE_BUTTONUP(OnButtonUp);
- break;
- case SDL_JOYBUTTONDOWN:
- HANDLE_BUTTONDOWN(OnButtonDown);
- break;
- case SDL_JOYBALLMOTION:
- HANDLE_BALLMOTION(OnBallMotion);
- break;
- default:
- HANDLE_NOEVENT(OnNothing);
- break;
+#ifndef DISABLE_SDL
+ int i;
+ for (i=0; i<JOYINDEX_MAX; i++) {
+ if (m_instance[i]) {
+ m_instance[i]->DestroyJoystickDevice();
+ delete m_instance[i];
}
+ m_instance[i]= NULL;
}
+
+ SDL_QuitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_VIDEO );
+#endif
}
}
-
void SCA_Joystick::cSetPrecision(int val)
{
m_prec = val;
}
+bool SCA_Joystick::aAnyAxisIsPositive(int axis)
+{
+ bool result;
+ int res = pAxisTest(axis);
+ res > m_prec? result = true: result = false;
+ return result;
+}
+
bool SCA_Joystick::aRightAxisIsPositive(int axis)
{
bool result;
int res = pGetAxis(axis,1);
res > m_prec? result = true: result = false;
- m_istrig = result;
return result;
}
@@ -121,7 +147,6 @@ bool SCA_Joystick::aUpAxisIsPositive(int axis)
bool result;
int res = pGetAxis(axis,0);
res < -m_prec? result = true : result = false;
- m_istrig = result;
return result;
}
@@ -131,7 +156,6 @@ bool SCA_Joystick::aLeftAxisIsPositive(int axis)
bool result;
int res = pGetAxis(axis,1);
res < -m_prec ? result = true : result = false;
- m_istrig = result;
return result;
}
@@ -141,26 +165,40 @@ bool SCA_Joystick::aDownAxisIsPositive(int axis)
bool result;
int res = pGetAxis(axis,0);
res > m_prec ? result = true:result = false;
- m_istrig = result;
return result;
}
+bool SCA_Joystick::aAnyButtonPressIsPositive(void)
+{
+ return (m_buttonnum==-2) ? false : true;
+}
+
+bool SCA_Joystick::aAnyButtonReleaseIsPositive(void)
+{
+ return (m_buttonnum==-2) ? true : false;
+}
bool SCA_Joystick::aButtonPressIsPositive(int button)
{
+#ifdef DISABLE_SDL
+ return false;
+#else
bool result;
SDL_JoystickGetButton(m_private->m_joystick, button)? result = true:result = false;
- m_istrig = result;
return result;
+#endif
}
bool SCA_Joystick::aButtonReleaseIsPositive(int button)
{
+#ifdef DISABLE_SDL
+ return false;
+#else
bool result;
SDL_JoystickGetButton(m_private->m_joystick, button)? result = false : result = true;
- m_istrig = result;
return result;
+#endif
}
@@ -169,27 +207,9 @@ bool SCA_Joystick::aHatIsPositive(int dir)
bool result;
int res = pGetHat(dir);
res == dir? result = true : result = false;
- m_istrig = result;
return result;
}
-
-int SCA_Joystick::pGetButtonPress(int button)
-{
- if(button == m_buttonnum)
- return m_buttonnum;
- return -2;
-}
-
-
-int SCA_Joystick::pGetButtonRelease(int button)
-{
- if(button == m_buttonnum)
- return m_buttonnum;
- return -2;
-}
-
-
int SCA_Joystick::pGetHat(int direction)
{
if(direction == m_hatdir){
@@ -198,174 +218,121 @@ int SCA_Joystick::pGetHat(int direction)
return 0;
}
-
-bool SCA_Joystick::GetJoyAxisMotion()
-{
- bool result = false;
- if(m_isinit){
- if(SDL_PollEvent(&m_private->m_event)){
- switch(m_private->m_event.type)
- {
- case SDL_JOYAXISMOTION:
- result = true;
- break;
- }
- }
- }
- return result;
-}
-
-
-bool SCA_Joystick::GetJoyButtonPress()
-{
- bool result = false;
- if(m_isinit){
- if(SDL_PollEvent(&m_private->m_event)){
- switch(m_private->m_event.type)
- {
- case SDL_JOYBUTTONDOWN:
- result = true;
- break;
- }
- }
- }
- return result;
-}
-
-
-bool SCA_Joystick::GetJoyButtonRelease()
-{
- bool result = false;
- if(m_isinit)
- {
- if(SDL_PollEvent(&m_private->m_event)){
- switch(m_private->m_event.type)
- {
- case SDL_JOYBUTTONUP:
- result = true;
- break;
- }
- }
- }
- return result;
-}
-
-
-bool SCA_Joystick::GetJoyHatMotion()
-{
- bool result = false;
- if(m_isinit){
- if(SDL_PollEvent(&m_private->m_event)){
- switch(m_private->m_event.type)
- {
- case SDL_JOYHATMOTION:
- result = true;
- break;
- }
- }
- }
- return 0;
-}
-
-
int SCA_Joystick::GetNumberOfAxes()
{
- int number;
- if(m_isinit){
- if(m_private->m_joystick){
- number = SDL_JoystickNumAxes(m_private->m_joystick);
- return number;
- }
- }
- return -1;
+ return m_axismax;
}
int SCA_Joystick::GetNumberOfButtons()
{
- int number;
- if(m_isinit){
- if(m_private->m_joystick){
- number = SDL_JoystickNumButtons(m_private->m_joystick);
- return number;
- }
- }
- return -1;
+ return m_buttonmax;
}
int SCA_Joystick::GetNumberOfHats()
{
- int number;
- if(m_isinit){
- if(m_private->m_joystick){
- number = SDL_JoystickNumHats(m_private->m_joystick);
- return number;
- }
- }
- return -1;
+ return m_hatmax;
}
-bool SCA_Joystick::pCreateJoystickDevice()
+bool SCA_Joystick::CreateJoystickDevice(void)
{
+#ifdef DISABLE_SDL
+ return false;
+#else
if(m_isinit == false){
- if(SDL_InitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_VIDEO ) == -1 ){
- echo("Error-Initializing-SDL: " << SDL_GetError());
- return false;
- }
- if(SDL_NumJoysticks() > 0){
- for(int i=0; i<SDL_NumJoysticks();i++){
- m_private->m_joystick = SDL_JoystickOpen(i);
- SDL_JoystickEventState(SDL_ENABLE);
- m_numjoys = i;
- }
- echo("Joystick-initialized");
- m_isinit = true;
- return true;
- }else{
- echo("Joystick-Error: " << SDL_NumJoysticks() << " avaiable joystick(s)");
+ if (m_joyindex>=SDL_NumJoysticks()) {
+ // don't print a message, because this is done anyway
+ //echo("Joystick-Error: " << SDL_NumJoysticks() << " avaiable joystick(s)");
return false;
}
+
+ m_private->m_joystick = SDL_JoystickOpen(m_joyindex);
+ SDL_JoystickEventState(SDL_ENABLE);
+ m_isinit = true;
+
+ echo("Joystick " << m_joyindex << " initialized");
+
+ /* must run after being initialized */
+ m_axismax = SDL_JoystickNumAxes(m_private->m_joystick);
+ m_buttonmax = SDL_JoystickNumButtons(m_private->m_joystick);
+ m_hatmax = SDL_JoystickNumHats(m_private->m_joystick);
}
- return false;
+ return true;
+#endif
}
-void SCA_Joystick::pDestroyJoystickDevice()
+void SCA_Joystick::DestroyJoystickDevice(void)
{
- echo("Closing-");
- for(int i=0; i<SDL_NumJoysticks(); i++){
- if(SDL_JoystickOpened(i)){
+#ifndef DISABLE_SDL
+ if (m_isinit){
+ if(SDL_JoystickOpened(m_joyindex)){
+ echo("Closing-joystick " << m_joyindex);
SDL_JoystickClose(m_private->m_joystick);
}
+ m_isinit = false;
}
- SDL_QuitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_VIDEO );
+#endif
}
+int SCA_Joystick::Connected(void)
+{
+#ifndef DISABLE_SDL
+ if (m_isinit && SDL_JoystickOpened(m_joyindex))
+ return 1;
+#endif
+ return 0;
+}
void SCA_Joystick::pFillAxes()
{
- if(GetNumberOfAxes() == 1){
+#ifndef DISABLE_SDL
+ if(m_axismax == 1){
m_axis10 = SDL_JoystickGetAxis(m_private->m_joystick, 0);
m_axis11 = SDL_JoystickGetAxis(m_private->m_joystick, 1);
- }else if(GetNumberOfAxes() > 1){
+ }else if(m_axismax > 1){
m_axis10 = SDL_JoystickGetAxis(m_private->m_joystick, 0);
m_axis11 = SDL_JoystickGetAxis(m_private->m_joystick, 1);
m_axis20 = SDL_JoystickGetAxis(m_private->m_joystick, 2);
m_axis21 = SDL_JoystickGetAxis(m_private->m_joystick, 3);
}else{
- m_axis10 = 0;m_axis11 = 0;
- m_axis20 = 0;m_axis21 = 0;
+ m_axis10 = m_axis11 = m_axis20 = m_axis21 = 0;
}
+#endif
}
int SCA_Joystick::pGetAxis(int axisnum, int udlr)
{
+#ifndef DISABLE_SDL
if(axisnum == 1 && udlr == 1)return m_axis10; //u/d
if(axisnum == 1 && udlr == 0)return m_axis11; //l/r
if(axisnum == 2 && udlr == 0)return m_axis20; //...
if(axisnum == 2 && udlr == 1)return m_axis21;
+#endif
+ return 0;
+}
+
+int SCA_Joystick::pAxisTest(int axisnum)
+{
+#ifndef DISABLE_SDL
+ short i1,i2;
+ if(axisnum == 1) {
+ i1 = m_axis10; i2 = m_axis11;
+ }
+ else if(axisnum == 2) {
+ i1 = m_axis20; i2 = m_axis21;
+ }
+ /* long winded way to do
+ * return MAX2(abs(i1), abs(i2))
+ * avoid abs from math.h */
+ if (i1 < 0) i1 = -i1;
+ if (i2 < 0) i2 = -i2;
+ if (i1 <i2) return i2;
+ else return i1;
+#else
return 0;
+#endif
}
diff --git a/source/gameengine/GameLogic/Joystick/SCA_Joystick.h b/source/gameengine/GameLogic/Joystick/SCA_Joystick.h
index a76edc73b44..8335d5538ad 100644
--- a/source/gameengine/GameLogic/Joystick/SCA_Joystick.h
+++ b/source/gameengine/GameLogic/Joystick/SCA_Joystick.h
@@ -1,304 +1,189 @@
/**
-
* ***** BEGIN GPL LICENSE BLOCK *****
-
*
-
* This program is free software; you can redistribute it and/or
-
* modify it under the terms of the GNU General Public License
-
* as published by the Free Software Foundation; either version 2
-
* of the License, or (at your option) any later version.
-
-
-
-
*
-
* This program is distributed in the hope that it will be useful,
-
* but WITHOUT ANY WARRANTY; without even the implied warranty of
-
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-
* GNU General Public License for more details.
-
*
-
* You should have received a copy of the GNU General Public License
-
* along with this program; if not, write to the Free Software Foundation,
-
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-
*
-
* The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
-
* All rights reserved.
-
*
-
* The Original Code is: all of this file.
-
*
-
* Contributor(s): snailrose.
-
*
-
* ***** END GPL LICENSE BLOCK *****
-
*/
#ifndef _SCA_JOYSTICK_H_
-
#define _SCA_JOYSTICK_H_
-
-
#include "SCA_JoystickDefines.h"
-
-
-
-
+#ifndef DISABLE_SDL
+#include "SDL.h"
+#endif
/*
-
* Basic Joystick class
-
+ * I will make this class a singleton because there should be only one joystick
+ * even if there are more than one scene using it and count how many scene are using it.
+ * The underlying joystick should only be removed when the last scene is removed
*/
class SCA_Joystick
{
+ static SCA_Joystick *m_instance[JOYINDEX_MAX];
+ static int m_refCount;
class PrivateData;
-
+#ifndef DISABLE_SDL
PrivateData *m_private;
-
+#endif
int m_joyindex;
- /*!
-
- * the number of avail joysticks
-
- */
-
- int m_numjoys;
-
/*
-
*support for 2 axes
-
*/
int m_axis10,m_axis11;
-
int m_axis20,m_axis21;
- /*
-
+ /*
* Precision or range of the axes
-
*/
-
int m_prec;
/*
-
* multiple axis values stored here
-
*/
-
int m_axisnum;
-
int m_axisvalue;
/*
-
* max # of axes avail
-
*/
-
/*disabled
-
int m_axismax;
-
*/
/*
-
* button values stored here
-
*/
-
int m_buttonnum;
/*
-
* max # of buttons avail
-
*/
-
+
+ int m_axismax;
int m_buttonmax;
-
- /*
-
+ int m_hatmax;
+
+ /*
* hat values stored here
-
*/
-
int m_hatnum;
-
int m_hatdir;
/*
* max # of hats avail
-
disabled
-
int m_hatmax;
-
*/
-
/* is the joystick initialized ?*/
-
bool m_isinit;
+ /* is triggered for each event type */
+ bool m_istrig_axis;
+ bool m_istrig_button;
+ bool m_istrig_hat;
- /* is triggered */
-
- bool m_istrig;
-
+#ifndef DISABLE_SDL
/*
-
- * Open the joystick
-
+ * event callbacks
*/
-
- bool pCreateJoystickDevice(void);
-
+ void OnAxisMotion(SDL_Event *sdl_event);
+ void OnHatMotion(SDL_Event *sdl_event);
+ void OnButtonUp(SDL_Event *sdl_event);
+ void OnButtonDown(SDL_Event *sdl_event);
+ void OnNothing(SDL_Event *sdl_event);
+ void OnBallMotion(SDL_Event *sdl_event){}
+#endif
/*
-
- * Close the joystick
-
+ * Open the joystick
*/
-
- void pDestroyJoystickDevice(void);
-
-
+ bool CreateJoystickDevice(void);
/*
-
- * event callbacks
-
+ * Close the joystick
*/
-
- void OnAxisMotion(void);
-
- void OnHatMotion(void);
-
- void OnButtonUp(void);
-
- void OnButtonDown(void);
-
- void OnNothing(void);
-
- void OnBallMotion(void){}
+ void DestroyJoystickDevice(void);
/*
-
* fills the axis mnember values
-
*/
-
void pFillAxes(void);
-
-
-
void pFillButtons(void);
/*
-
* returns m_axis10,m_axis11...
-
*/
- int pGetAxis(int axisnum, int udlr);
-
+ int pAxisTest(int axisnum);
/*
-
- * gets the current button
-
- */
-
- int pGetButtonPress(int button);
-
- /*
-
- * returns if no button is pressed
-
+ * returns m_axis10,m_axis11...
*/
-
- int pGetButtonRelease(int button);
+ int pGetAxis(int axisnum, int udlr);
/*
-
* gets the current hat direction
-
*/
-
int pGetHat(int direction);
-
-
-public:
-
- SCA_Joystick();
+ SCA_Joystick(short int index);
~SCA_Joystick();
-
+public:
- bool CreateJoystickDevice(void);
-
- void DestroyJoystickDevice(void);
-
- void HandleEvents();
+ static SCA_Joystick *GetInstance( short int joyindex );
+ static void HandleEvents( void );
+ void ReleaseInstance();
+
/*
-
*/
-
+ bool aAnyAxisIsPositive(int axis);
bool aUpAxisIsPositive(int axis);
-
bool aDownAxisIsPositive(int axis);
-
bool aLeftAxisIsPositive(int axis);
-
bool aRightAxisIsPositive(int axis);
+ bool aAnyButtonPressIsPositive(void);
+ bool aAnyButtonReleaseIsPositive(void);
bool aButtonPressIsPositive(int button);
-
bool aButtonReleaseIsPositive(int button);
-
bool aHatIsPositive(int dir);
/*
-
* precision is default '3200' which is overridden by input
-
*/
void cSetPrecision(int val);
-
-
int GetAxis10(void){
return m_axis10;
@@ -306,80 +191,57 @@ public:
}
int GetAxis11(void){
-
return m_axis11;
-
}
int GetAxis20(void){
-
return m_axis20;
-
}
int GetAxis21(void){
-
return m_axis21;
-
}
int GetButton(void){
-
return m_buttonnum;
-
}
int GetHat(void){
-
return m_hatdir;
-
}
int GetThreshold(void){
-
return m_prec;
-
}
- bool IsTrig(void){
-
- return m_istrig;
-
+ bool IsTrigAxis(void){
+ return m_istrig_axis;
}
-
+ bool IsTrigButton(void){
+ return m_istrig_button;
+ }
+
+ bool IsTrigHat(void){
+ return m_istrig_hat;
+ }
/*
-
- * returns true if an event is being processed
-
- */
-
- bool GetJoyAxisMotion(void);
-
- bool GetJoyButtonPress(void);
-
- bool GetJoyButtonRelease(void);
-
- bool GetJoyHatMotion(void);
-
- /*
-
* returns the # of...
-
*/
int GetNumberOfAxes(void);
-
int GetNumberOfButtons(void);
-
int GetNumberOfHats(void);
-
-
+ /*
+ * Test if the joystick is connected
+ */
+ int Connected(void);
};
-
-
+#ifndef DISABLE_SDL
+void Joystick_HandleEvents( void );
+#endif
#endif
diff --git a/source/gameengine/GameLogic/Joystick/SCA_JoystickDefines.h b/source/gameengine/GameLogic/Joystick/SCA_JoystickDefines.h
index 15a421188b9..73ffe1406d9 100644
--- a/source/gameengine/GameLogic/Joystick/SCA_JoystickDefines.h
+++ b/source/gameengine/GameLogic/Joystick/SCA_JoystickDefines.h
@@ -38,12 +38,6 @@
#define echo(x) std::cout << x << std::endl;
#endif
-/* function callbacks */
-#define HANDLE_AXISMOTION(fn) ((fn)(), 0L)
-#define HANDLE_HATMOTION(fn) ((fn)(), 0L)
-#define HANDLE_BUTTONUP(fn) ((fn)(), 0L)
-#define HANDLE_BUTTONDOWN(fn) ((fn)(), 0L)
-#define HANDLE_BALLMOTION(fn) ((fn)(), 0L)
-#define HANDLE_NOEVENT(fn) ((fn)(), 0L)
+#define JOYINDEX_MAX 8
#endif
diff --git a/source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp b/source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp
index ab523470e21..73ca288861d 100644
--- a/source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp
+++ b/source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp
@@ -24,47 +24,100 @@
*
* ***** END GPL LICENSE BLOCK *****
*/
+#ifndef DISABLE_SDL
#include <SDL.h>
+#endif
+
#include "SCA_Joystick.h"
#include "SCA_JoystickPrivate.h"
-
-void SCA_Joystick::OnAxisMotion(void)
+#ifndef DISABLE_SDL
+void SCA_Joystick::OnAxisMotion(SDL_Event* sdl_event)
{
pFillAxes();
- m_axisnum = m_private->m_event.jaxis.axis;
- m_axisvalue = m_private->m_event.jaxis.value;
- m_istrig = 1;
+ m_axisnum = sdl_event->jaxis.axis;
+ m_axisvalue = sdl_event->jaxis.value;
+ m_istrig_axis = 1;
}
-void SCA_Joystick::OnHatMotion(void)
+void SCA_Joystick::OnHatMotion(SDL_Event* sdl_event)
{
- m_hatdir = m_private->m_event.jhat.value;
- m_hatnum = m_private->m_event.jhat.hat;
- m_istrig = 1;
+ m_hatdir = sdl_event->jhat.value;
+ m_hatnum = sdl_event->jhat.hat;
+ m_istrig_hat = 1;
}
-
-void SCA_Joystick::OnButtonUp(void)
+void SCA_Joystick::OnButtonUp(SDL_Event* sdl_event)
{
+ m_istrig_button = 1;
+
+ /* this is needed for the "all events" option
+ * so we know if there are no buttons pressed */
+ int i;
+ for (i=0; i<m_buttonmax; i++) {
+ if (SDL_JoystickGetButton(m_private->m_joystick, i)) {
+ m_buttonnum = i;
+ return;
+ }
+ }
m_buttonnum = -2;
}
-void SCA_Joystick::OnButtonDown(void)
+void SCA_Joystick::OnButtonDown(SDL_Event* sdl_event)
{
- m_buttonmax = GetNumberOfButtons();
- if(m_private->m_event.jbutton.button >= 1 || m_private->m_event.jbutton.button <= m_buttonmax)
+ if(sdl_event->jbutton.button >= 0 || sdl_event->jbutton.button <= m_buttonmax)
{
- m_istrig = 1;
- m_buttonnum = m_private->m_event.jbutton.button;
+ m_istrig_button = 1;
+ m_buttonnum = sdl_event->jbutton.button;
}
}
-void SCA_Joystick::OnNothing(void)
+void SCA_Joystick::OnNothing(SDL_Event* sdl_event)
{
- m_istrig = 0;
+ m_istrig_axis = m_istrig_button = m_istrig_hat = 0;
+}
+
+/* only handle events for 1 joystick */
+
+void SCA_Joystick::HandleEvents(void)
+{
+ SDL_Event sdl_event;
+
+ int i;
+ for (i=0; i<JOYINDEX_MAX; i++) {
+ if(SCA_Joystick::m_instance[i])
+ SCA_Joystick::m_instance[i]->OnNothing(&sdl_event);
+ }
+
+ if(SDL_PollEvent(&sdl_event))
+ {
+ /* Note! m_instance[sdl_event.jaxis.which]
+ * will segfault if over JOYINDEX_MAX, not too nice but what are the chances? */
+ switch(sdl_event.type)
+ {
+ case SDL_JOYAXISMOTION:
+ SCA_Joystick::m_instance[sdl_event.jaxis.which]->OnAxisMotion(&sdl_event);
+ break;
+ case SDL_JOYHATMOTION:
+ SCA_Joystick::m_instance[sdl_event.jhat.which]->OnHatMotion(&sdl_event);
+ break;
+ case SDL_JOYBUTTONUP:
+ SCA_Joystick::m_instance[sdl_event.jbutton.which]->OnButtonUp(&sdl_event);
+ break;
+ case SDL_JOYBUTTONDOWN:
+ SCA_Joystick::m_instance[sdl_event.jbutton.which]->OnButtonDown(&sdl_event);
+ break;
+ case SDL_JOYBALLMOTION:
+ SCA_Joystick::m_instance[sdl_event.jball.which]->OnBallMotion(&sdl_event);
+ break;
+ default:
+ printf("SCA_Joystick::HandleEvents, Unknown SDL event, this should not happen\n");
+ break;
+ }
+ }
}
+#endif
diff --git a/source/gameengine/GameLogic/Joystick/SCA_JoystickPrivate.h b/source/gameengine/GameLogic/Joystick/SCA_JoystickPrivate.h
index 23fad3cd55d..acbbcae9cd7 100644
--- a/source/gameengine/GameLogic/Joystick/SCA_JoystickPrivate.h
+++ b/source/gameengine/GameLogic/Joystick/SCA_JoystickPrivate.h
@@ -29,14 +29,11 @@
#define __SCA_JOYSTICKPRIVATE_H__
#include "SCA_Joystick.h"
+#ifndef DISABLE_SDL
class SCA_Joystick::PrivateData
{
public:
/*
- * SDL events structure
- */
- SDL_Event m_event;
- /*
* The Joystick
*/
SDL_Joystick* m_joystick;
@@ -47,3 +44,5 @@ public:
}
};
#endif
+
+#endif
diff --git a/source/gameengine/GameLogic/Makefile b/source/gameengine/GameLogic/Makefile
index bf4cb5afea7..355ece6e8bd 100644
--- a/source/gameengine/GameLogic/Makefile
+++ b/source/gameengine/GameLogic/Makefile
@@ -39,8 +39,10 @@ include nan_compile.mk
CCFLAGS += $(LEVEL_1_CPP_WARNINGS)
CPPFLAGS += -I../Expressions
+CPPFLAGS += -I../Rasterizer
CPPFLAGS += -I$(NAN_STRING)/include
CPPFLAGS += -I$(NAN_MOTO)/include
+CPPFLAGS += -I../../blender/makesdna
CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION)
CPPFLAGS += $(NAN_SDLCFLAGS)
diff --git a/source/gameengine/GameLogic/SCA_2DFilterActuator.cpp b/source/gameengine/GameLogic/SCA_2DFilterActuator.cpp
new file mode 100644
index 00000000000..9ec4ea00337
--- /dev/null
+++ b/source/gameengine/GameLogic/SCA_2DFilterActuator.cpp
@@ -0,0 +1,118 @@
+#include "SCA_IActuator.h"
+
+#include "SCA_2DFilterActuator.h"
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include <iostream>
+
+SCA_2DFilterActuator::~SCA_2DFilterActuator()
+{
+}
+
+SCA_2DFilterActuator::SCA_2DFilterActuator(
+ SCA_IObject *gameobj,
+ RAS_2DFilterManager::RAS_2DFILTER_MODE type,
+ short flag,
+ float float_arg,
+ int int_arg,
+ RAS_IRasterizer* rasterizer,
+ RAS_IRenderTools* rendertools,
+ PyTypeObject* T)
+ : SCA_IActuator(gameobj, T),
+ m_type(type),
+ m_flag(flag),
+ m_float_arg(float_arg),
+ m_int_arg(int_arg),
+ m_rasterizer(rasterizer),
+ m_rendertools(rendertools)
+{
+ m_gameObj = NULL;
+ if(gameobj){
+ m_propNames = gameobj->GetPropertyNames();
+ m_gameObj = gameobj;
+ }
+}
+
+void SCA_2DFilterActuator::SetShaderText(STR_String text)
+{
+ m_shaderText = text;
+}
+
+
+
+CValue* SCA_2DFilterActuator::GetReplica()
+{
+ SCA_2DFilterActuator* replica = new SCA_2DFilterActuator(*this);
+ replica->ProcessReplica();
+ CValue::AddDataToReplica(replica);
+
+ return replica;
+}
+
+
+bool SCA_2DFilterActuator::Update()
+{
+ bool bNegativeEvent = IsNegativeEvent();
+ RemoveAllEvents();
+
+
+ if (bNegativeEvent)
+ return false; // do nothing on negative events
+
+ if( m_type == RAS_2DFilterManager::RAS_2DFILTER_MOTIONBLUR )
+ {
+ if(!m_flag)
+ m_rasterizer->EnableMotionBlur(m_float_arg);
+ else
+ m_rasterizer->DisableMotionBlur();
+
+ return false;
+ }
+ else if(m_type < RAS_2DFilterManager::RAS_2DFILTER_NUMBER_OF_FILTERS)
+ {
+ m_rendertools->Update2DFilter(m_propNames, m_gameObj, m_type, m_int_arg, m_shaderText);
+ }
+ return true;
+}
+
+
+PyTypeObject SCA_2DFilterActuator::Type = {
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0,
+ "SCA_2DFilterActuator",
+ sizeof(SCA_2DFilterActuator),
+ 0,
+ PyDestructor,
+ 0,
+ __getattr,
+ __setattr,
+ 0,
+ __repr,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+};
+
+
+PyParentObject SCA_2DFilterActuator::Parents[] = {
+ &SCA_2DFilterActuator::Type,
+ &SCA_IActuator::Type,
+ &SCA_ILogicBrick::Type,
+ &CValue::Type,
+ NULL
+};
+
+
+PyMethodDef SCA_2DFilterActuator::Methods[] = {
+ /* add python functions to deal with m_msg... */
+ {NULL,NULL}
+};
+
+
+PyObject* SCA_2DFilterActuator::_getattr(const STR_String& attr) {
+ _getattr_up(SCA_IActuator);
+}
diff --git a/source/gameengine/GameLogic/SCA_2DFilterActuator.h b/source/gameengine/GameLogic/SCA_2DFilterActuator.h
new file mode 100644
index 00000000000..7ec07cf5b19
--- /dev/null
+++ b/source/gameengine/GameLogic/SCA_2DFilterActuator.h
@@ -0,0 +1,44 @@
+#ifndef __SCA_2DFILETRACTUATOR_H__
+#define __SCA_2DFILETRACTUATOR_H__
+
+#include "RAS_IRasterizer.h"
+#include "RAS_IRenderTools.h"
+#include "SCA_IActuator.h"
+
+class SCA_2DFilterActuator : public SCA_IActuator
+{
+ Py_Header;
+
+private:
+ vector<STR_String> m_propNames;
+ void * m_gameObj;
+ RAS_2DFilterManager::RAS_2DFILTER_MODE m_type;
+ short m_flag;
+ float m_float_arg;
+ int m_int_arg;
+ STR_String m_shaderText;
+ RAS_IRasterizer* m_rasterizer;
+ RAS_IRenderTools* m_rendertools;
+
+public:
+
+ SCA_2DFilterActuator(
+ class SCA_IObject* gameobj,
+ RAS_2DFilterManager::RAS_2DFILTER_MODE type,
+ short flag,
+ float float_arg,
+ int int_arg,
+ RAS_IRasterizer* rasterizer,
+ RAS_IRenderTools* rendertools,
+ PyTypeObject* T=&Type
+ );
+
+ void SetShaderText(STR_String text);
+ virtual ~SCA_2DFilterActuator();
+ virtual bool Update();
+
+ virtual CValue* GetReplica();
+ virtual PyObject* _getattr(const STR_String& attr);
+
+};
+#endif
diff --git a/source/gameengine/GameLogic/SCA_ActuatorEventManager.cpp b/source/gameengine/GameLogic/SCA_ActuatorEventManager.cpp
new file mode 100644
index 00000000000..768a3a45937
--- /dev/null
+++ b/source/gameengine/GameLogic/SCA_ActuatorEventManager.cpp
@@ -0,0 +1,67 @@
+/**
+ * $Id$
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "SCA_ISensor.h"
+#include "SCA_ActuatorEventManager.h"
+#include "SCA_ActuatorSensor.h"
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+
+SCA_ActuatorEventManager::SCA_ActuatorEventManager(class SCA_LogicManager* logicmgr)
+ : SCA_EventManager(ACTUATOR_EVENTMGR),
+ m_logicmgr(logicmgr)
+{
+}
+
+
+
+SCA_ActuatorEventManager::~SCA_ActuatorEventManager()
+{
+
+}
+
+void SCA_ActuatorEventManager::NextFrame()
+{
+ // check for changed actuator
+ for (set<SCA_ISensor*>::const_iterator it = m_sensors.begin();!(it==m_sensors.end());it++)
+ {
+ (*it)->Activate(m_logicmgr,NULL);
+ }
+}
+
+void SCA_ActuatorEventManager::UpdateFrame()
+{
+ // update the state of actuator before executing them
+ for (set<SCA_ISensor*>::const_iterator it = m_sensors.begin();!(it==m_sensors.end());it++)
+ {
+ ((SCA_ActuatorSensor*)(*it))->Update();
+ }
+} \ No newline at end of file
diff --git a/source/gameengine/GameLogic/SCA_ActuatorEventManager.h b/source/gameengine/GameLogic/SCA_ActuatorEventManager.h
new file mode 100644
index 00000000000..a7d61627c23
--- /dev/null
+++ b/source/gameengine/GameLogic/SCA_ActuatorEventManager.h
@@ -0,0 +1,51 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef __KX_ACTUATOREVENTMANAGER
+#define __KX_ACTUATOREVENTMANAGER
+
+#include "SCA_EventManager.h"
+
+#include <vector>
+
+using namespace std;
+
+class SCA_ActuatorEventManager : public SCA_EventManager
+{
+ class SCA_LogicManager* m_logicmgr;
+
+public:
+ SCA_ActuatorEventManager(class SCA_LogicManager* logicmgr);
+ virtual ~SCA_ActuatorEventManager();
+ virtual void NextFrame();
+ virtual void UpdateFrame();
+ //SCA_LogicManager* GetLogicManager() { return m_logicmgr;}
+};
+
+#endif //__KX_ACTUATOREVENTMANAGER
+
diff --git a/source/gameengine/GameLogic/SCA_ActuatorSensor.cpp b/source/gameengine/GameLogic/SCA_ActuatorSensor.cpp
new file mode 100644
index 00000000000..7c37b237d60
--- /dev/null
+++ b/source/gameengine/GameLogic/SCA_ActuatorSensor.cpp
@@ -0,0 +1,196 @@
+/**
+ * Actuator sensor
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include <iostream>
+#include "SCA_ActuatorSensor.h"
+#include "SCA_EventManager.h"
+#include "SCA_LogicManager.h"
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+SCA_ActuatorSensor::SCA_ActuatorSensor(SCA_EventManager* eventmgr,
+ SCA_IObject* gameobj,
+ const STR_String& actname,
+ PyTypeObject* T )
+ : SCA_ISensor(gameobj,eventmgr,T),
+ m_checkactname(actname)
+{
+ m_actuator = GetParent()->FindActuator(m_checkactname);
+ Init();
+}
+
+void SCA_ActuatorSensor::Init()
+{
+ m_lastresult = m_invert?true:false;
+ m_midresult = m_lastresult;
+ m_reset = true;
+}
+
+CValue* SCA_ActuatorSensor::GetReplica()
+{
+ SCA_ActuatorSensor* replica = new SCA_ActuatorSensor(*this);
+ // m_range_expr must be recalculated on replica!
+ CValue::AddDataToReplica(replica);
+ replica->Init();
+
+ return replica;
+}
+
+void SCA_ActuatorSensor::ReParent(SCA_IObject* parent)
+{
+ m_actuator = parent->FindActuator(m_checkactname);
+ SCA_ISensor::ReParent(parent);
+}
+
+bool SCA_ActuatorSensor::IsPositiveTrigger()
+{
+ bool result = m_lastresult;
+ if (m_invert)
+ result = !result;
+
+ return result;
+}
+
+
+
+SCA_ActuatorSensor::~SCA_ActuatorSensor()
+{
+}
+
+
+
+bool SCA_ActuatorSensor::Evaluate(CValue* event)
+{
+ if (m_actuator)
+ {
+ bool result = m_actuator->IsActive();
+ bool reset = m_reset && m_level;
+
+ m_reset = false;
+ if (m_lastresult != result || m_midresult != result)
+ {
+ m_lastresult = m_midresult = result;
+ return true;
+ }
+ return (reset) ? true : false;
+ }
+ return false;
+}
+
+void SCA_ActuatorSensor::Update()
+{
+ if (m_actuator)
+ {
+ m_midresult = m_actuator->IsActive() && !m_actuator->IsNegativeEvent();
+ }
+}
+
+
+/* ------------------------------------------------------------------------- */
+/* Python functions */
+/* ------------------------------------------------------------------------- */
+
+/* Integration hooks ------------------------------------------------------- */
+PyTypeObject SCA_ActuatorSensor::Type = {
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0,
+ "SCA_ActuatorSensor",
+ sizeof(SCA_ActuatorSensor),
+ 0,
+ PyDestructor,
+ 0,
+ __getattr,
+ __setattr,
+ 0, //&MyPyCompare,
+ __repr,
+ 0, //&cvalue_as_number,
+ 0,
+ 0,
+ 0,
+ 0
+};
+
+PyParentObject SCA_ActuatorSensor::Parents[] = {
+ &SCA_ActuatorSensor::Type,
+ &SCA_ISensor::Type,
+ &SCA_ILogicBrick::Type,
+ &CValue::Type,
+ NULL
+};
+
+PyMethodDef SCA_ActuatorSensor::Methods[] = {
+ {"getActuator", (PyCFunction) SCA_ActuatorSensor::sPyGetActuator, METH_NOARGS, (PY_METHODCHAR)GetActuator_doc},
+ {"setActuator", (PyCFunction) SCA_ActuatorSensor::sPySetActuator, METH_VARARGS, (PY_METHODCHAR)SetActuator_doc},
+ {NULL,NULL} //Sentinel
+};
+
+PyObject* SCA_ActuatorSensor::_getattr(const STR_String& attr) {
+ _getattr_up(SCA_ISensor); /* implicit return! */
+}
+
+/* 3. getActuator */
+const char SCA_ActuatorSensor::GetActuator_doc[] =
+"getActuator()\n"
+"\tReturn the Actuator with which the sensor operates.\n";
+PyObject* SCA_ActuatorSensor::PyGetActuator(PyObject* self)
+{
+ return PyString_FromString(m_checkactname);
+}
+
+/* 4. setActuator */
+const char SCA_ActuatorSensor::SetActuator_doc[] =
+"setActuator(name)\n"
+"\t- name: string\n"
+"\tSets the Actuator with which to operate. If there is no Actuator\n"
+"\tof this name, the call is ignored.\n";
+PyObject* SCA_ActuatorSensor::PySetActuator(PyObject* self, PyObject* args, PyObject* kwds)
+{
+ /* We should query whether the name exists. Or should we create a prop */
+ /* on the fly? */
+ char *actNameArg = NULL;
+
+ if (!PyArg_ParseTuple(args, "s", &actNameArg)) {
+ return NULL;
+ }
+
+ SCA_IActuator* act = GetParent()->FindActuator(STR_String(actNameArg));
+ if (act) {
+ m_checkactname = actNameArg;
+ m_actuator = act;
+ } else {
+ ; /* error: bad actuator name */
+ }
+ Py_Return;
+}
+
+/* eof */
diff --git a/source/gameengine/GameLogic/SCA_ActuatorSensor.h b/source/gameengine/GameLogic/SCA_ActuatorSensor.h
new file mode 100644
index 00000000000..a71145f6852
--- /dev/null
+++ b/source/gameengine/GameLogic/SCA_ActuatorSensor.h
@@ -0,0 +1,74 @@
+/**
+ * Actuator sensor
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __KX_ACTUATORSENSOR
+#define __KX_ACTUATORSENSOR
+
+#include "SCA_ISensor.h"
+#include "SCA_IActuator.h"
+
+class SCA_ActuatorSensor : public SCA_ISensor
+{
+ Py_Header;
+ STR_String m_checkactname;
+ bool m_lastresult;
+ bool m_midresult;
+ protected:
+ SCA_IActuator* m_actuator;
+public:
+ SCA_ActuatorSensor(class SCA_EventManager* eventmgr,
+ SCA_IObject* gameobj,
+ const STR_String& actname,
+ PyTypeObject* T=&Type );
+
+ virtual ~SCA_ActuatorSensor();
+ virtual CValue* GetReplica();
+ virtual void Init();
+ virtual bool Evaluate(CValue* event);
+ virtual bool IsPositiveTrigger();
+ virtual void ReParent(SCA_IObject* parent);
+ void Update();
+
+ /* --------------------------------------------------------------------- */
+ /* Python interface ---------------------------------------------------- */
+ /* --------------------------------------------------------------------- */
+
+ virtual PyObject* _getattr(const STR_String& attr);
+
+ /* 3. setProperty */
+ KX_PYMETHOD_DOC(SCA_ActuatorSensor,SetActuator);
+ /* 4. getProperty */
+ KX_PYMETHOD_DOC_NOARGS(SCA_ActuatorSensor,GetActuator);
+
+};
+
+#endif
+
diff --git a/source/gameengine/GameLogic/SCA_AlwaysEventManager.cpp b/source/gameengine/GameLogic/SCA_AlwaysEventManager.cpp
index ab3bc2cc4ee..4cd2dfba994 100644
--- a/source/gameengine/GameLogic/SCA_AlwaysEventManager.cpp
+++ b/source/gameengine/GameLogic/SCA_AlwaysEventManager.cpp
@@ -51,16 +51,9 @@ SCA_AlwaysEventManager::SCA_AlwaysEventManager(class SCA_LogicManager* logicmgr)
void SCA_AlwaysEventManager::NextFrame()
{
- for (vector<class SCA_ISensor*>::const_iterator i= m_sensors.begin();!(i==m_sensors.end());i++)
+ for (set<class SCA_ISensor*>::const_iterator i= m_sensors.begin();!(i==m_sensors.end());i++)
{
- SCA_ISensor* sensor = *i;
- sensor->Activate(m_logicmgr, NULL);
+ (*i)->Activate(m_logicmgr, NULL);
}
}
-
-
-void SCA_AlwaysEventManager::RegisterSensor(SCA_ISensor* sensor)
-{
- m_sensors.push_back(sensor);
-}
diff --git a/source/gameengine/GameLogic/SCA_AlwaysEventManager.h b/source/gameengine/GameLogic/SCA_AlwaysEventManager.h
index 28c71512875..a619eecddd4 100644
--- a/source/gameengine/GameLogic/SCA_AlwaysEventManager.h
+++ b/source/gameengine/GameLogic/SCA_AlwaysEventManager.h
@@ -39,7 +39,6 @@ class SCA_AlwaysEventManager : public SCA_EventManager
public:
SCA_AlwaysEventManager(class SCA_LogicManager* logicmgr);
virtual void NextFrame();
- virtual void RegisterSensor(SCA_ISensor* sensor);
};
diff --git a/source/gameengine/GameLogic/SCA_AlwaysSensor.cpp b/source/gameengine/GameLogic/SCA_AlwaysSensor.cpp
index 67df5d091ab..f9fbf2387c4 100644
--- a/source/gameengine/GameLogic/SCA_AlwaysSensor.cpp
+++ b/source/gameengine/GameLogic/SCA_AlwaysSensor.cpp
@@ -53,10 +53,13 @@ SCA_AlwaysSensor::SCA_AlwaysSensor(class SCA_EventManager* eventmgr,
: SCA_ISensor(gameobj,eventmgr, T)
{
//SetDrawColor(255,0,0);
- m_alwaysresult = true;
+ Init();
}
-
+void SCA_AlwaysSensor::Init()
+{
+ m_alwaysresult = true;
+}
SCA_AlwaysSensor::~SCA_AlwaysSensor()
{
diff --git a/source/gameengine/GameLogic/SCA_AlwaysSensor.h b/source/gameengine/GameLogic/SCA_AlwaysSensor.h
index 474ed025432..8bf2a8aa98e 100644
--- a/source/gameengine/GameLogic/SCA_AlwaysSensor.h
+++ b/source/gameengine/GameLogic/SCA_AlwaysSensor.h
@@ -45,6 +45,8 @@ public:
virtual CValue* GetReplica();
virtual bool Evaluate(CValue* event);
virtual bool IsPositiveTrigger();
+ virtual void Init();
+
/* --------------------------------------------------------------------- */
/* Python interface ---------------------------------------------------- */
diff --git a/source/gameengine/GameLogic/SCA_DelaySensor.cpp b/source/gameengine/GameLogic/SCA_DelaySensor.cpp
new file mode 100644
index 00000000000..f15d4c7249f
--- /dev/null
+++ b/source/gameengine/GameLogic/SCA_DelaySensor.cpp
@@ -0,0 +1,257 @@
+/**
+ * Delay trigger
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#ifdef WIN32
+// This warning tells us about truncation of __long__ stl-generated names.
+// It can occasionally cause DevStudio to have internal compiler warnings.
+#pragma warning( disable : 4786 )
+#endif
+
+#include "SCA_DelaySensor.h"
+#include "SCA_LogicManager.h"
+#include "SCA_EventManager.h"
+
+/* ------------------------------------------------------------------------- */
+/* Native functions */
+/* ------------------------------------------------------------------------- */
+
+SCA_DelaySensor::SCA_DelaySensor(class SCA_EventManager* eventmgr,
+ SCA_IObject* gameobj,
+ int delay,
+ int duration,
+ bool repeat,
+ PyTypeObject* T)
+ : SCA_ISensor(gameobj,eventmgr, T),
+ m_delay(delay),
+ m_duration(duration),
+ m_repeat(repeat)
+{
+ Init();
+}
+
+void SCA_DelaySensor::Init()
+{
+ m_lastResult = false;
+ m_frameCount = -1;
+ m_reset = true;
+}
+
+SCA_DelaySensor::~SCA_DelaySensor()
+{
+ /* intentionally empty */
+}
+
+CValue* SCA_DelaySensor::GetReplica()
+{
+ CValue* replica = new SCA_DelaySensor(*this);
+ // this will copy properties and so on...
+ CValue::AddDataToReplica(replica);
+
+ return replica;
+}
+
+
+
+bool SCA_DelaySensor::IsPositiveTrigger()
+{
+ return (m_invert ? !m_lastResult : m_lastResult);
+}
+
+bool SCA_DelaySensor::Evaluate(CValue* event)
+{
+ bool trigger = false;
+ bool result;
+
+ if (m_frameCount==-1) {
+ // this is needed to ensure ON trigger in case delay==0
+ // and avoid spurious OFF trigger when duration==0
+ m_lastResult = false;
+ m_frameCount = 0;
+ }
+
+ if (m_frameCount<m_delay) {
+ m_frameCount++;
+ result = false;
+ } else if (m_duration > 0) {
+ if (m_frameCount < m_delay+m_duration) {
+ m_frameCount++;
+ result = true;
+ } else {
+ result = false;
+ if (m_repeat)
+ m_frameCount = -1;
+ }
+ } else {
+ result = true;
+ if (m_repeat)
+ m_frameCount = -1;
+ }
+ if ((m_reset && m_level) || result != m_lastResult)
+ trigger = true;
+ m_reset = false;
+ m_lastResult = result;
+ return trigger;
+}
+
+/* ------------------------------------------------------------------------- */
+/* Python functions */
+/* ------------------------------------------------------------------------- */
+
+/* Integration hooks ------------------------------------------------------- */
+PyTypeObject SCA_DelaySensor::Type = {
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0,
+ "SCA_DelaySensor",
+ sizeof(SCA_DelaySensor),
+ 0,
+ PyDestructor,
+ 0,
+ __getattr,
+ __setattr,
+ 0, //&MyPyCompare,
+ __repr,
+ 0, //&cvalue_as_number,
+ 0,
+ 0,
+ 0,
+ 0
+};
+
+PyParentObject SCA_DelaySensor::Parents[] = {
+ &SCA_DelaySensor::Type,
+ &SCA_ISensor::Type,
+ &SCA_ILogicBrick::Type,
+ &CValue::Type,
+ NULL
+};
+
+PyMethodDef SCA_DelaySensor::Methods[] = {
+ /* setProperty */
+ {"setDelay", (PyCFunction) SCA_DelaySensor::sPySetDelay, METH_VARARGS, (PY_METHODCHAR)SetDelay_doc},
+ {"setDuration", (PyCFunction) SCA_DelaySensor::sPySetDuration, METH_VARARGS, (PY_METHODCHAR)SetDuration_doc},
+ {"setRepeat", (PyCFunction) SCA_DelaySensor::sPySetRepeat, METH_VARARGS, (PY_METHODCHAR)SetRepeat_doc},
+ /* getProperty */
+ {"getDelay", (PyCFunction) SCA_DelaySensor::sPyGetDelay, METH_NOARGS, (PY_METHODCHAR)GetDelay_doc},
+ {"getDuration", (PyCFunction) SCA_DelaySensor::sPyGetDuration, METH_NOARGS, (PY_METHODCHAR)GetDuration_doc},
+ {"getRepeat", (PyCFunction) SCA_DelaySensor::sPyGetRepeat, METH_NOARGS, (PY_METHODCHAR)GetRepeat_doc},
+ {NULL,NULL} //Sentinel
+};
+
+PyObject* SCA_DelaySensor::_getattr(const STR_String& attr) {
+ _getattr_up(SCA_ISensor);
+}
+
+const char SCA_DelaySensor::SetDelay_doc[] =
+"setDelay(delay)\n"
+"\t- delay: length of the initial OFF period as number of frame\n"
+"\t 0 for immediate trigger\n"
+"\tSet the initial delay before the positive trigger\n";
+PyObject* SCA_DelaySensor::PySetDelay(PyObject* self, PyObject* args, PyObject* kwds)
+{
+ int delay;
+
+ if(!PyArg_ParseTuple(args, "i", &delay)) {
+ return NULL;
+ }
+ if (delay < 0) {
+ PyErr_SetString(PyExc_ValueError, "Delay cannot be negative");
+ return NULL;
+ }
+ m_delay = delay;
+ Py_Return;
+}
+
+const char SCA_DelaySensor::SetDuration_doc[] =
+"setDuration(duration)\n"
+"\t- duration: length of the ON period in number of frame after the initial off period\n"
+"\t 0 for no ON period\n"
+"\tSet the duration of the ON pulse after initial delay.\n"
+"\tIf > 0, a negative trigger is fired at the end of the ON pulse.\n";
+PyObject* SCA_DelaySensor::PySetDuration(PyObject* self, PyObject* args, PyObject* kwds)
+{
+ int duration;
+
+ if(!PyArg_ParseTuple(args, "i", &duration)) {
+ return NULL;
+ }
+ if (duration < 0) {
+ PyErr_SetString(PyExc_ValueError, "Duration cannot be negative");
+ return NULL;
+ }
+ m_duration = duration;
+ Py_Return;
+}
+
+const char SCA_DelaySensor::SetRepeat_doc[] =
+"setRepeat(repeat)\n"
+"\t- repeat: 1 if the initial OFF-ON cycle should be repeated indefinately\n"
+"\t 0 if the initial OFF-ON cycle should run only once\n"
+"\tSet the sensor repeat mode\n";
+PyObject* SCA_DelaySensor::PySetRepeat(PyObject* self, PyObject* args, PyObject* kwds)
+{
+ int repeat;
+
+ if(!PyArg_ParseTuple(args, "i", &repeat)) {
+ return NULL;
+ }
+ m_repeat = (repeat != 0);
+ Py_Return;
+}
+
+const char SCA_DelaySensor::GetDelay_doc[] =
+"getDelay()\n"
+"\tReturn the delay parameter value\n";
+PyObject* SCA_DelaySensor::PyGetDelay(PyObject* self)
+{
+ return PyInt_FromLong(m_delay);
+}
+
+const char SCA_DelaySensor::GetDuration_doc[] =
+"getDuration()\n"
+"\tReturn the duration parameter value\n";
+PyObject* SCA_DelaySensor::PyGetDuration(PyObject* self)
+{
+ return PyInt_FromLong(m_duration);
+}
+
+const char SCA_DelaySensor::GetRepeat_doc[] =
+"getRepeat()\n"
+"\tReturn the repeat parameter value\n";
+PyObject* SCA_DelaySensor::PyGetRepeat(PyObject* self)
+{
+ return BoolToPyArg(m_repeat);
+}
+
+/* eof */
diff --git a/source/gameengine/GameLogic/SCA_DelaySensor.h b/source/gameengine/GameLogic/SCA_DelaySensor.h
new file mode 100644
index 00000000000..a997fabe3cd
--- /dev/null
+++ b/source/gameengine/GameLogic/SCA_DelaySensor.h
@@ -0,0 +1,77 @@
+/**
+ * SCA_DelaySensor.h
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __KX_DELAYSENSOR
+#define __KX_DELAYSENSOR
+#include "SCA_ISensor.h"
+
+class SCA_DelaySensor : public SCA_ISensor
+{
+ Py_Header;
+ bool m_lastResult;
+ bool m_repeat;
+ int m_delay;
+ int m_duration;
+ int m_frameCount;
+
+public:
+ SCA_DelaySensor(class SCA_EventManager* eventmgr,
+ SCA_IObject* gameobj,
+ int delay,
+ int duration,
+ bool repeat,
+ PyTypeObject* T =&Type);
+ virtual ~SCA_DelaySensor();
+ virtual CValue* GetReplica();
+ virtual bool Evaluate(CValue* event);
+ virtual bool IsPositiveTrigger();
+ virtual void Init();
+
+
+ /* --------------------------------------------------------------------- */
+ /* Python interface ---------------------------------------------------- */
+ /* --------------------------------------------------------------------- */
+
+ virtual PyObject* _getattr(const STR_String& attr);
+
+ /* setProperty */
+ KX_PYMETHOD_DOC(SCA_DelaySensor,SetDelay);
+ KX_PYMETHOD_DOC(SCA_DelaySensor,SetDuration);
+ KX_PYMETHOD_DOC(SCA_DelaySensor,SetRepeat);
+ /* getProperty */
+ KX_PYMETHOD_DOC_NOARGS(SCA_DelaySensor,GetDelay);
+ KX_PYMETHOD_DOC_NOARGS(SCA_DelaySensor,GetDuration);
+ KX_PYMETHOD_DOC_NOARGS(SCA_DelaySensor,GetRepeat);
+
+};
+
+#endif //__KX_ALWAYSSENSOR
+
diff --git a/source/gameengine/GameLogic/SCA_EventManager.cpp b/source/gameengine/GameLogic/SCA_EventManager.cpp
index 1ca88182ddc..e4fd0379597 100644
--- a/source/gameengine/GameLogic/SCA_EventManager.cpp
+++ b/source/gameengine/GameLogic/SCA_EventManager.cpp
@@ -45,17 +45,14 @@ SCA_EventManager::~SCA_EventManager()
{
}
-
+void SCA_EventManager::RegisterSensor(class SCA_ISensor* sensor)
+{
+ m_sensors.insert(sensor);
+}
void SCA_EventManager::RemoveSensor(class SCA_ISensor* sensor)
{
- std::vector<SCA_ISensor*>::iterator i =
- std::find(m_sensors.begin(), m_sensors.end(), sensor);
- if (!(i == m_sensors.end()))
- {
- std::swap(*i, m_sensors.back());
- m_sensors.pop_back();
- }
+ m_sensors.erase(sensor);
}
void SCA_EventManager::NextFrame(double curtime, double fixedtime)
@@ -72,7 +69,9 @@ void SCA_EventManager::EndFrame()
{
}
-
+void SCA_EventManager::UpdateFrame()
+{
+}
int SCA_EventManager::GetType()
{
diff --git a/source/gameengine/GameLogic/SCA_EventManager.h b/source/gameengine/GameLogic/SCA_EventManager.h
index 89731497f6f..9dbb5a6d24f 100644
--- a/source/gameengine/GameLogic/SCA_EventManager.h
+++ b/source/gameengine/GameLogic/SCA_EventManager.h
@@ -30,12 +30,14 @@
#define __KX_EVENTMANAGER
#include <vector>
+#include <set>
#include <algorithm>
class SCA_EventManager
{
protected:
- std::vector <class SCA_ISensor*> m_sensors;
+ // use a set to speed-up insertion/removal
+ std::set <class SCA_ISensor*> m_sensors;
public:
enum EVENT_MANAGER_TYPE {
@@ -49,7 +51,8 @@ public:
RAY_EVENTMGR,
RADAR_EVENTMGR,
NETWORK_EVENTMGR,
- JOY_EVENTMGR
+ JOY_EVENTMGR,
+ ACTUATOR_EVENTMGR
};
SCA_EventManager(EVENT_MANAGER_TYPE mgrtype);
@@ -58,8 +61,9 @@ public:
virtual void RemoveSensor(class SCA_ISensor* sensor);
virtual void NextFrame(double curtime, double fixedtime);
virtual void NextFrame();
+ virtual void UpdateFrame();
virtual void EndFrame();
- virtual void RegisterSensor(class SCA_ISensor* sensor)=0;
+ virtual void RegisterSensor(class SCA_ISensor* sensor);
int GetType();
protected:
diff --git a/source/gameengine/GameLogic/SCA_IActuator.cpp b/source/gameengine/GameLogic/SCA_IActuator.cpp
index 568d0eb4a89..eeca2d7b44c 100644
--- a/source/gameengine/GameLogic/SCA_IActuator.cpp
+++ b/source/gameengine/GameLogic/SCA_IActuator.cpp
@@ -36,6 +36,7 @@ using namespace std;
SCA_IActuator::SCA_IActuator(SCA_IObject* gameobj,
PyTypeObject* T) :
+ m_links(0),
SCA_ILogicBrick(gameobj,T)
{
// nothing to do
@@ -109,3 +110,12 @@ SCA_IActuator::~SCA_IActuator()
RemoveAllEvents();
}
+void SCA_IActuator::DecLink()
+{
+ m_links--;
+ if (m_links < 0)
+ {
+ printf("Warning: actuator %s has negative m_links: %d\n", m_name.Ptr(), m_links);
+ m_links = 0;
+ }
+}
diff --git a/source/gameengine/GameLogic/SCA_IActuator.h b/source/gameengine/GameLogic/SCA_IActuator.h
index bff32dcebaa..7ffb21b5490 100644
--- a/source/gameengine/GameLogic/SCA_IActuator.h
+++ b/source/gameengine/GameLogic/SCA_IActuator.h
@@ -34,8 +34,11 @@
class SCA_IActuator : public SCA_ILogicBrick
{
+ friend class SCA_LogicManager;
protected:
std::vector<CValue*> m_events;
+ int m_links; // number of active links to controllers
+ // when 0, the actuator is automatically stopped
void RemoveAllEvents();
public:
@@ -47,6 +50,15 @@ public:
PyTypeObject* T =&Type);
/**
+ * UnlinkObject(...)
+ * Certain actuator use gameobject pointers (like TractTo actuator)
+ * This function can be called when an object is removed to make
+ * sure that the actuator will not use it anymore.
+ */
+
+ virtual bool UnlinkObject(SCA_IObject* clientobj) { return false; }
+
+ /**
* Update(...)
* Update the actuator based upon the events received since
* the last call to Update, the current time and deltatime the
@@ -74,6 +86,11 @@ public:
*/
bool IsNegativeEvent() const;
virtual ~SCA_IActuator();
+
+ void ClrLink() { m_links=0; }
+ void IncLink() { m_links++; }
+ void DecLink();
+ bool IsNoLink() const { return !m_links; }
};
#endif //__KX_IACTUATOR
diff --git a/source/gameengine/GameLogic/SCA_IController.cpp b/source/gameengine/GameLogic/SCA_IController.cpp
index 5cb62678c6b..0bd20117f31 100644
--- a/source/gameengine/GameLogic/SCA_IController.cpp
+++ b/source/gameengine/GameLogic/SCA_IController.cpp
@@ -29,6 +29,7 @@
#include "SCA_IController.h"
#include "SCA_LogicManager.h"
#include "SCA_IActuator.h"
+#include "SCA_ISensor.h"
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -37,6 +38,7 @@
SCA_IController::SCA_IController(SCA_IObject* gameobj,
PyTypeObject* T)
:
+ m_statemask(0),
SCA_ILogicBrick(gameobj,T)
{
}
@@ -45,6 +47,7 @@ SCA_IController::SCA_IController(SCA_IObject* gameobj,
SCA_IController::~SCA_IController()
{
+ UnlinkAllActuators();
}
@@ -65,6 +68,14 @@ const std::vector<class SCA_IActuator*>& SCA_IController::GetLinkedActuators()
void SCA_IController::UnlinkAllSensors()
{
+ if (IsActive())
+ {
+ std::vector<class SCA_ISensor*>::iterator sensit;
+ for (sensit = m_linkedsensors.begin();!(sensit==m_linkedsensors.end());++sensit)
+ {
+ (*sensit)->DecLink();
+ }
+ }
m_linkedsensors.clear();
}
@@ -72,6 +83,14 @@ void SCA_IController::UnlinkAllSensors()
void SCA_IController::UnlinkAllActuators()
{
+ if (IsActive())
+ {
+ std::vector<class SCA_IActuator*>::iterator actit;
+ for (actit = m_linkedactuators.begin();!(actit==m_linkedactuators.end());++actit)
+ {
+ (*actit)->DecLink();
+ }
+ }
m_linkedactuators.clear();
}
@@ -95,26 +114,96 @@ void SCA_IController::Trigger(SCA_LogicManager* logicmgr)
void SCA_IController::LinkToActuator(SCA_IActuator* actua)
{
m_linkedactuators.push_back(actua);
+ if (IsActive())
+ {
+ actua->IncLink();
+ }
}
void SCA_IController::UnlinkActuator(class SCA_IActuator* actua)
{
std::vector<class SCA_IActuator*>::iterator actit;
- std::vector<class SCA_IActuator*>::iterator actfound = m_linkedactuators.end();
for (actit = m_linkedactuators.begin();!(actit==m_linkedactuators.end());++actit)
{
if ((*actit) == actua)
- actfound = actit;
+ {
+ break;
+ }
}
- if (!(actfound==m_linkedactuators.end()))
+ if (!(actit==m_linkedactuators.end()))
{
- m_linkedactuators.erase(actfound);
+ if (IsActive())
+ {
+ (*actit)->DecLink();
+ }
+ m_linkedactuators.erase(actit);
}
-
}
void SCA_IController::LinkToSensor(SCA_ISensor* sensor)
{
m_linkedsensors.push_back(sensor);
+ if (IsActive())
+ {
+ sensor->IncLink();
+ }
+}
+
+void SCA_IController::UnlinkSensor(class SCA_ISensor* sensor)
+{
+ std::vector<class SCA_ISensor*>::iterator sensit;
+ for (sensit = m_linkedsensors.begin();!(sensit==m_linkedsensors.end());++sensit)
+ {
+ if ((*sensit) == sensor)
+ {
+ break;
+ }
+
+ }
+ if (!(sensit==m_linkedsensors.end()))
+ {
+ if (IsActive())
+ {
+ (*sensit)->DecLink();
+ }
+ m_linkedsensors.erase(sensit);
+ }
}
+
+void SCA_IController::ApplyState(unsigned int state)
+{
+ std::vector<class SCA_IActuator*>::iterator actit;
+ std::vector<class SCA_ISensor*>::iterator sensit;
+
+ if (m_statemask & state)
+ {
+ if (!IsActive())
+ {
+ // reactive the controller, all the links to actuator are valid again
+ for (actit = m_linkedactuators.begin();!(actit==m_linkedactuators.end());++actit)
+ {
+ (*actit)->IncLink();
+ }
+ for (sensit = m_linkedsensors.begin();!(sensit==m_linkedsensors.end());++sensit)
+ {
+ (*sensit)->IncLink();
+ // remember that this controller just activated that sensor
+ (*sensit)->AddNewController(this);
+ }
+ SetActive(true);
+ }
+ } else if (IsActive())
+ {
+ for (actit = m_linkedactuators.begin();!(actit==m_linkedactuators.end());++actit)
+ {
+ (*actit)->DecLink();
+ }
+ for (sensit = m_linkedsensors.begin();!(sensit==m_linkedsensors.end());++sensit)
+ {
+ (*sensit)->DecLink();
+ }
+ SetActive(false);
+ }
+}
+
diff --git a/source/gameengine/GameLogic/SCA_IController.h b/source/gameengine/GameLogic/SCA_IController.h
index 79e956dec4e..f67c0942eb4 100644
--- a/source/gameengine/GameLogic/SCA_IController.h
+++ b/source/gameengine/GameLogic/SCA_IController.h
@@ -36,6 +36,7 @@ class SCA_IController : public SCA_ILogicBrick
protected:
std::vector<class SCA_ISensor*> m_linkedsensors;
std::vector<class SCA_IActuator*> m_linkedactuators;
+ unsigned int m_statemask;
public:
SCA_IController(SCA_IObject* gameobj,PyTypeObject* T);
virtual ~SCA_IController();
@@ -47,6 +48,9 @@ public:
void UnlinkAllSensors();
void UnlinkAllActuators();
void UnlinkActuator(class SCA_IActuator* actua);
+ void UnlinkSensor(class SCA_ISensor* sensor);
+ void SetState(unsigned int state) { m_statemask = state; }
+ void ApplyState(unsigned int state);
};
diff --git a/source/gameengine/GameLogic/SCA_ILogicBrick.cpp b/source/gameengine/GameLogic/SCA_ILogicBrick.cpp
index 8423d06dfcd..abd049e9d64 100644
--- a/source/gameengine/GameLogic/SCA_ILogicBrick.cpp
+++ b/source/gameengine/GameLogic/SCA_ILogicBrick.cpp
@@ -27,6 +27,7 @@
*/
#include "SCA_ILogicBrick.h"
+#include "PyObjectPlus.h"
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -82,7 +83,10 @@ void SCA_ILogicBrick::ReParent(SCA_IObject* parent)
m_gameobj = parent;
}
-
+void SCA_ILogicBrick::Relink(GEN_Map<GEN_HashedPtr, void*> *obj_map)
+{
+ // nothing to do
+}
CValue* SCA_ILogicBrick::Calc(VALUE_OPERATOR op, CValue *val)
{
@@ -242,8 +246,8 @@ PyParentObject SCA_ILogicBrick::Parents[] = {
PyMethodDef SCA_ILogicBrick::Methods[] = {
- {"getOwner", (PyCFunction) SCA_ILogicBrick::sPyGetOwner, METH_VARARGS},
- {"getExecutePriority", (PyCFunction) SCA_ILogicBrick::sPySetExecutePriority, METH_VARARGS},
+ {"getOwner", (PyCFunction) SCA_ILogicBrick::sPyGetOwner, METH_NOARGS},
+ {"getExecutePriority", (PyCFunction) SCA_ILogicBrick::sPySetExecutePriority, METH_NOARGS},
{"setExecutePriority", (PyCFunction) SCA_ILogicBrick::sPySetExecutePriority, METH_VARARGS},
{NULL,NULL} //Sentinel
};
@@ -258,9 +262,7 @@ SCA_ILogicBrick::_getattr(const STR_String& attr)
-PyObject* SCA_ILogicBrick::PyGetOwner(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* SCA_ILogicBrick::PyGetOwner(PyObject* self)
{
CValue* parent = GetParent();
if (parent)
@@ -270,8 +272,7 @@ PyObject* SCA_ILogicBrick::PyGetOwner(PyObject* self,
}
printf("ERROR: Python scriptblock without owner\n");
- Py_INCREF(Py_None);
- return Py_None;//Int_FromLong(IsPositiveTrigger());
+ Py_RETURN_NONE; //Int_FromLong(IsPositiveTrigger());
}
@@ -294,9 +295,7 @@ PyObject* SCA_ILogicBrick::PySetExecutePriority(PyObject* self,
-PyObject* SCA_ILogicBrick::PyGetExecutePriority(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* SCA_ILogicBrick::PyGetExecutePriority(PyObject* self)
{
return PyInt_FromLong(m_Execute_Ueber_Priority);
}
diff --git a/source/gameengine/GameLogic/SCA_ILogicBrick.h b/source/gameengine/GameLogic/SCA_ILogicBrick.h
index f359ee0911b..c28711ac0f6 100644
--- a/source/gameengine/GameLogic/SCA_ILogicBrick.h
+++ b/source/gameengine/GameLogic/SCA_ILogicBrick.h
@@ -32,6 +32,8 @@
#include "Value.h"
#include "SCA_IObject.h"
#include "BoolValue.h"
+#include "GEN_Map.h"
+#include "GEN_HashedPtr.h"
class SCA_ILogicBrick : public CValue
{
@@ -59,6 +61,7 @@ public:
SCA_IObject* GetParent();
virtual void ReParent(SCA_IObject* parent);
+ virtual void Relink(GEN_Map<GEN_HashedPtr, void*> *obj_map);
// act as a BoolValue (with value IsPositiveTrigger)
virtual CValue* Calc(VALUE_OPERATOR op, CValue *val);
@@ -82,9 +85,9 @@ public:
// python methods
- KX_PYMETHOD(SCA_ILogicBrick,GetOwner);
+ KX_PYMETHOD_NOARGS(SCA_ILogicBrick,GetOwner);
KX_PYMETHOD(SCA_ILogicBrick,SetExecutePriority);
- KX_PYMETHOD(SCA_ILogicBrick,GetExecutePriority);
+ KX_PYMETHOD_NOARGS(SCA_ILogicBrick,GetExecutePriority);
enum KX_BOOL_TYPE {
KX_BOOL_NODEF = 0,
diff --git a/source/gameengine/GameLogic/SCA_IObject.cpp b/source/gameengine/GameLogic/SCA_IObject.cpp
index 0d315a55f43..b0f8decee26 100644
--- a/source/gameengine/GameLogic/SCA_IObject.cpp
+++ b/source/gameengine/GameLogic/SCA_IObject.cpp
@@ -40,7 +40,7 @@
MT_Point3 SCA_IObject::m_sDummy=MT_Point3(0,0,0);
-SCA_IObject::SCA_IObject(PyTypeObject* T): CValue(T)
+SCA_IObject::SCA_IObject(PyTypeObject* T): m_initState(0), m_state(0), CValue(T)
{
m_suspended = false;
}
@@ -52,7 +52,9 @@ SCA_IObject::~SCA_IObject()
SCA_SensorList::iterator its;
for (its = m_sensors.begin(); !(its == m_sensors.end()); ++its)
{
- ((CValue*)(*its))->Release();
+ //Use Delete for sensor to ensure proper cleaning
+ (*its)->Delete();
+ //((CValue*)(*its))->Release();
}
SCA_ControllerList::iterator itc;
for (itc = m_controllers.begin(); !(itc == m_controllers.end()); ++itc)
@@ -60,6 +62,10 @@ SCA_IObject::~SCA_IObject()
((CValue*)(*itc))->Release();
}
SCA_ActuatorList::iterator ita;
+ for (ita = m_registeredActuators.begin(); !(ita==m_registeredActuators.end()); ++ita)
+ {
+ (*ita)->UnlinkObject(this);
+ }
for (ita = m_actuators.begin(); !(ita==m_actuators.end()); ++ita)
{
((CValue*)(*ita))->Release();
@@ -96,6 +102,7 @@ SCA_ActuatorList& SCA_IObject::GetActuators()
void SCA_IObject::AddSensor(SCA_ISensor* act)
{
+ act->AddRef();
m_sensors.push_back(act);
}
@@ -103,6 +110,7 @@ void SCA_IObject::AddSensor(SCA_ISensor* act)
void SCA_IObject::AddController(SCA_IController* act)
{
+ act->AddRef();
m_controllers.push_back(act);
}
@@ -110,10 +118,28 @@ void SCA_IObject::AddController(SCA_IController* act)
void SCA_IObject::AddActuator(SCA_IActuator* act)
{
+ act->AddRef();
m_actuators.push_back(act);
}
+void SCA_IObject::RegisterActuator(SCA_IActuator* act)
+{
+ // don't increase ref count, it would create dead lock
+ m_registeredActuators.push_back(act);
+}
+void SCA_IObject::UnregisterActuator(SCA_IActuator* act)
+{
+ SCA_ActuatorList::iterator ita;
+ for (ita = m_registeredActuators.begin(); ita != m_registeredActuators.end(); ita++)
+ {
+ if ((*ita) == act) {
+ (*ita) = m_registeredActuators.back();
+ m_registeredActuators.pop_back();
+ break;
+ }
+ }
+}
void SCA_IObject::SetIgnoreActivityCulling(bool b)
{
@@ -131,15 +157,17 @@ bool SCA_IObject::GetIgnoreActivityCulling()
void SCA_IObject::ReParentLogic()
{
- SCA_SensorList& oldsensors = GetSensors();
-
- int sen = 0;
- SCA_SensorList::iterator its;
- for (its = oldsensors.begin(); !(its==oldsensors.end()); ++its)
+ SCA_ActuatorList& oldactuators = GetActuators();
+ int act = 0;
+ SCA_ActuatorList::iterator ita;
+ for (ita = oldactuators.begin(); !(ita==oldactuators.end()); ++ita)
{
- SCA_ISensor* newsensor = (SCA_ISensor*)(*its)->GetReplica();
- newsensor->ReParent(this);
- oldsensors[sen++] = newsensor;
+ SCA_IActuator* newactuator = (SCA_IActuator*) (*ita)->GetReplica();
+ newactuator->ReParent(this);
+ // actuators are initially not connected to any controller
+ newactuator->SetActive(false);
+ newactuator->ClrLink();
+ oldactuators[act++] = newactuator;
}
SCA_ControllerList& oldcontrollers = GetControllers();
@@ -149,20 +177,26 @@ void SCA_IObject::ReParentLogic()
{
SCA_IController* newcontroller = (SCA_IController*)(*itc)->GetReplica();
newcontroller->ReParent(this);
+ newcontroller->SetActive(false);
oldcontrollers[con++]=newcontroller;
}
- SCA_ActuatorList& oldactuators = GetActuators();
-
- int act = 0;
- SCA_ActuatorList::iterator ita;
- for (ita = oldactuators.begin(); !(ita==oldactuators.end()); ++ita)
+ // convert sensors last so that actuators are already available for Actuator sensor
+ SCA_SensorList& oldsensors = GetSensors();
+ int sen = 0;
+ SCA_SensorList::iterator its;
+ for (its = oldsensors.begin(); !(its==oldsensors.end()); ++its)
{
- SCA_IActuator* newactuator = (SCA_IActuator*) (*ita)->GetReplica();
- newactuator->ReParent(this);
- newactuator->SetActive(false);
- oldactuators[act++] = newactuator;
+ SCA_ISensor* newsensor = (SCA_ISensor*)(*its)->GetReplica();
+ newsensor->ReParent(this);
+ newsensor->SetActive(false);
+ // sensors are initially not connected to any controller
+ newsensor->ClrLink();
+ oldsensors[sen++] = newsensor;
}
+
+ // a new object cannot be client of any actuator
+ m_registeredActuators.clear();
}
@@ -272,7 +306,7 @@ const MT_Point3& SCA_IObject::ConvertPythonPylist(PyObject* pylist)
}
#endif
-void SCA_IObject::Suspend(void)
+void SCA_IObject::Suspend()
{
if ((!m_ignore_activity_culling)
&& (!m_suspended)) {
@@ -301,6 +335,36 @@ void SCA_IObject::Resume(void)
}
}
+void SCA_IObject::SetState(unsigned int state)
+{
+ unsigned int tmpstate;
+ SCA_ControllerList::iterator contit;
+
+ // we will update the state in two steps:
+ // 1) set the new state bits that are 1
+ // 2) clr the new state bits that are 0
+ // This to ensure continuity if a sensor is attached to two states
+ // that are switching state: no need to deactive and reactive the sensor
+
+ tmpstate = m_state | state;
+ if (tmpstate != m_state)
+ {
+ // update the status of the controllers
+ for (contit = m_controllers.begin(); contit != m_controllers.end(); contit++)
+ {
+ (*contit)->ApplyState(tmpstate);
+ }
+ }
+ m_state = state;
+ if (m_state != tmpstate)
+ {
+ for (contit = m_controllers.begin(); contit != m_controllers.end(); contit++)
+ {
+ (*contit)->ApplyState(m_state);
+ }
+ }
+}
+
/* ------------------------------------------------------------------------- */
diff --git a/source/gameengine/GameLogic/SCA_IObject.h b/source/gameengine/GameLogic/SCA_IObject.h
index 8f3e25afa03..38a7ed29dca 100644
--- a/source/gameengine/GameLogic/SCA_IObject.h
+++ b/source/gameengine/GameLogic/SCA_IObject.h
@@ -55,6 +55,7 @@ protected:
SCA_SensorList m_sensors;
SCA_ControllerList m_controllers;
SCA_ActuatorList m_actuators;
+ SCA_ActuatorList m_registeredActuators; // actuators that use a pointer to this object
static class MT_Point3 m_sDummy;
/**
@@ -66,7 +67,17 @@ protected:
* Ignore updates?
*/
bool m_suspended;
-
+
+ /**
+ * init state of object (used when object is created)
+ */
+ unsigned int m_initState;
+
+ /**
+ * current state = bit mask of state that are active
+ */
+ unsigned int m_state;
+
public:
SCA_IObject(PyTypeObject* T=&Type);
@@ -79,6 +90,8 @@ public:
void AddSensor(SCA_ISensor* act);
void AddController(SCA_IController* act);
void AddActuator(SCA_IActuator* act);
+ void RegisterActuator(SCA_IActuator* act);
+ void UnregisterActuator(SCA_IActuator* act);
SCA_ISensor* FindSensor(const STR_String& sensorname);
SCA_IActuator* FindActuator(const STR_String& actuatorname);
@@ -108,7 +121,27 @@ public:
* Resume progress
*/
void Resume(void);
-
+
+ /**
+ * Set init state
+ */
+ void SetInitState(unsigned int initState) { m_initState = initState; }
+
+ /**
+ * initialize the state when object is created
+ */
+ void ResetState(void) { SetState(m_initState); }
+
+ /**
+ * Set the object state
+ */
+ void SetState(unsigned int state);
+
+ /**
+ * Get the object state
+ */
+ unsigned int GetState(void) { return m_state; }
+
// const class MT_Point3& ConvertPythonPylist(PyObject* pylist);
// here come the python forwarded methods
@@ -117,7 +150,7 @@ public:
virtual int GetGameObjectType() {return -1;}
typedef enum ObjectTypes {
- OBJ_ARMATURE=0
+ OBJ_ARMATURE=0,
}ObjectTypes;
};
diff --git a/source/gameengine/GameLogic/SCA_IScene.cpp b/source/gameengine/GameLogic/SCA_IScene.cpp
index 5e4e1cdcf92..9fbeb706910 100644
--- a/source/gameengine/GameLogic/SCA_IScene.cpp
+++ b/source/gameengine/GameLogic/SCA_IScene.cpp
@@ -27,25 +27,40 @@
*/
#include "SCA_IScene.h"
+#include "Value.h"
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
-SCA_IScene::SCA_IScene()
+SCA_DebugProp::SCA_DebugProp(): m_obj(NULL)
{
}
+SCA_DebugProp::~SCA_DebugProp()
+{
+ if (m_obj)
+ m_obj->Release();
+}
+SCA_IScene::SCA_IScene()
+{
+}
-SCA_IScene::~SCA_IScene()
+void SCA_IScene::RemoveAllDebugProperties()
{
- // release debugprop list
for (std::vector<SCA_DebugProp*>::iterator it = m_debugList.begin();
!(it==m_debugList.end());it++)
{
delete (*it);
}
+ m_debugList.clear();
+}
+
+
+SCA_IScene::~SCA_IScene()
+{
+ RemoveAllDebugProperties();
}
@@ -61,6 +76,7 @@ void SCA_IScene::AddDebugProperty(class CValue* debugprop,
{
SCA_DebugProp* dprop = new SCA_DebugProp();
dprop->m_obj = debugprop;
+ debugprop->AddRef();
dprop->m_name = name;
m_debugList.push_back(dprop);
}
diff --git a/source/gameengine/GameLogic/SCA_IScene.h b/source/gameengine/GameLogic/SCA_IScene.h
index 145d8a98512..d18778a37c2 100644
--- a/source/gameengine/GameLogic/SCA_IScene.h
+++ b/source/gameengine/GameLogic/SCA_IScene.h
@@ -37,6 +37,8 @@ struct SCA_DebugProp
{
class CValue* m_obj;
STR_String m_name;
+ SCA_DebugProp();
+ ~SCA_DebugProp();
};
class SCA_IScene
@@ -57,6 +59,7 @@ public:
std::vector<SCA_DebugProp*>& GetDebugProperties();
void AddDebugProperty(class CValue* debugprop,
const STR_String &name);
+ void RemoveAllDebugProperties();
};
#endif //__KX_ISCENE_H
diff --git a/source/gameengine/GameLogic/SCA_ISensor.cpp b/source/gameengine/GameLogic/SCA_ISensor.cpp
index 9fdee0c19da..b10ac676464 100644
--- a/source/gameengine/GameLogic/SCA_ISensor.cpp
+++ b/source/gameengine/GameLogic/SCA_ISensor.cpp
@@ -32,6 +32,8 @@
#include "SCA_ISensor.h"
#include "SCA_EventManager.h"
#include "SCA_LogicManager.h"
+// needed for IsTriggered()
+#include "SCA_PythonController.h"
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -41,7 +43,8 @@
void SCA_ISensor::ReParent(SCA_IObject* parent)
{
SCA_ILogicBrick::ReParent(parent);
- m_eventmgr->RegisterSensor(this);
+ // will be done when the sensor is activated
+ //m_eventmgr->RegisterSensor(this);
this->SetActive(false);
}
@@ -52,8 +55,11 @@ SCA_ISensor::SCA_ISensor(SCA_IObject* gameobj,
SCA_ILogicBrick(gameobj,T),
m_triggered(false)
{
+ m_links = 0;
m_suspended = false;
m_invert = false;
+ m_level = false;
+ m_reset = false;
m_pos_ticks = 0;
m_neg_ticks = 0;
m_pos_pulsemode = false;
@@ -94,6 +100,10 @@ void SCA_ISensor::SetInvert(bool inv) {
m_invert = inv;
}
+void SCA_ISensor::SetLevel(bool lvl) {
+ m_level = lvl;
+}
+
float SCA_ISensor::GetNumber() {
return IsPositiveTrigger();
@@ -111,6 +121,24 @@ void SCA_ISensor::Resume() {
m_suspended = false;
}
+void SCA_ISensor::Init() {
+ printf("Sensor %s has no init function, please report this bug to Blender.org\n", m_name.Ptr());
+}
+
+void SCA_ISensor::DecLink() {
+ m_links--;
+ if (m_links < 0)
+ {
+ printf("Warning: sensor %s has negative m_links: %d\n", m_name.Ptr(), m_links);
+ m_links = 0;
+ }
+ if (!m_links)
+ {
+ // sensor is detached from all controllers, remove it from manager
+ UnregisterToManager();
+ }
+}
+
/* python integration */
PyTypeObject SCA_ISensor::Type = {
@@ -140,23 +168,31 @@ PyParentObject SCA_ISensor::Parents[] = {
};
PyMethodDef SCA_ISensor::Methods[] = {
{"isPositive", (PyCFunction) SCA_ISensor::sPyIsPositive,
- METH_VARARGS, IsPositive_doc},
+ METH_NOARGS, (PY_METHODCHAR)IsPositive_doc},
+ {"isTriggered", (PyCFunction) SCA_ISensor::sPyIsTriggered,
+ METH_VARARGS, (PY_METHODCHAR)IsTriggered_doc},
{"getUsePosPulseMode", (PyCFunction) SCA_ISensor::sPyGetUsePosPulseMode,
- METH_VARARGS, GetUsePosPulseMode_doc},
+ METH_NOARGS, (PY_METHODCHAR)GetUsePosPulseMode_doc},
{"setUsePosPulseMode", (PyCFunction) SCA_ISensor::sPySetUsePosPulseMode,
- METH_VARARGS, SetUsePosPulseMode_doc},
+ METH_VARARGS, (PY_METHODCHAR)SetUsePosPulseMode_doc},
{"getFrequency", (PyCFunction) SCA_ISensor::sPyGetFrequency,
- METH_VARARGS, GetFrequency_doc},
+ METH_NOARGS, (PY_METHODCHAR)GetFrequency_doc},
{"setFrequency", (PyCFunction) SCA_ISensor::sPySetFrequency,
- METH_VARARGS, SetFrequency_doc},
+ METH_VARARGS, (PY_METHODCHAR)SetFrequency_doc},
{"getUseNegPulseMode", (PyCFunction) SCA_ISensor::sPyGetUseNegPulseMode,
- METH_VARARGS, GetUseNegPulseMode_doc},
+ METH_NOARGS, (PY_METHODCHAR)GetUseNegPulseMode_doc},
{"setUseNegPulseMode", (PyCFunction) SCA_ISensor::sPySetUseNegPulseMode,
- METH_VARARGS, SetUseNegPulseMode_doc},
+ METH_VARARGS, (PY_METHODCHAR)SetUseNegPulseMode_doc},
{"getInvert", (PyCFunction) SCA_ISensor::sPyGetInvert,
- METH_VARARGS, GetInvert_doc},
+ METH_NOARGS, (PY_METHODCHAR)GetInvert_doc},
{"setInvert", (PyCFunction) SCA_ISensor::sPySetInvert,
- METH_VARARGS, SetInvert_doc},
+ METH_VARARGS, (PY_METHODCHAR)SetInvert_doc},
+ {"getLevel", (PyCFunction) SCA_ISensor::sPyGetLevel,
+ METH_NOARGS, (PY_METHODCHAR)GetLevel_doc},
+ {"setLevel", (PyCFunction) SCA_ISensor::sPySetLevel,
+ METH_VARARGS, (PY_METHODCHAR)SetLevel_doc},
+ {"reset", (PyCFunction) SCA_ISensor::sPyReset,
+ METH_NOARGS, (PY_METHODCHAR)Reset_doc},
{NULL,NULL} //Sentinel
};
@@ -170,17 +206,29 @@ SCA_ISensor::_getattr(const STR_String& attr)
void SCA_ISensor::RegisterToManager()
{
+ // sensor is just activated, initialize it
+ Init();
+ m_newControllers.erase(m_newControllers.begin(), m_newControllers.end());
m_eventmgr->RegisterSensor(this);
}
+void SCA_ISensor::UnregisterToManager()
+{
+ m_eventmgr->RemoveSensor(this);
+}
+
void SCA_ISensor::Activate(class SCA_LogicManager* logicmgr, CValue* event)
{
// calculate if a __triggering__ is wanted
- if (!m_suspended) {
+ // don't evaluate a sensor that is not connected to any controller
+ if (m_links && !m_suspended) {
bool result = this->Evaluate(event);
if (result) {
logicmgr->AddActivatedSensor(this);
+ // reset these counters so that pulse are synchronized with transition
+ m_pos_ticks = 0;
+ m_neg_ticks = 0;
} else
{
/* First, the pulsing behaviour, if pulse mode is
@@ -209,26 +257,54 @@ void SCA_ISensor::Activate(class SCA_LogicManager* logicmgr, CValue* event)
}
}
}
+ if (!m_newControllers.empty())
+ {
+ if (!IsActive() && m_level)
+ {
+ // This level sensor is connected to at least one controller that was just made
+ // active but it did not generate an event yet, do it now to those controllers only
+ for (std::vector<SCA_IController*>::iterator ci=m_newControllers.begin();
+ ci != m_newControllers.end(); ci++)
+ {
+ logicmgr->AddTriggeredController(*ci, this);
+ }
+ }
+ // clear the list. Instead of using clear, which also release the memory,
+ // use erase, which keeps the memory available for next time.
+ m_newControllers.erase(m_newControllers.begin(), m_newControllers.end());
+ }
}
}
/* Python functions: */
-char SCA_ISensor::IsPositive_doc[] =
+const char SCA_ISensor::IsPositive_doc[] =
"isPositive()\n"
-"\tReturns whether the sensor is registered a positive event.\n";
-PyObject* SCA_ISensor::PyIsPositive(PyObject* self, PyObject* args, PyObject* kwds)
+"\tReturns whether the sensor is in an active state.\n";
+PyObject* SCA_ISensor::PyIsPositive(PyObject* self)
{
int retval = IsPositiveTrigger();
return PyInt_FromLong(retval);
}
+const char SCA_ISensor::IsTriggered_doc[] =
+"isTriggered()\n"
+"\tReturns whether the sensor has triggered the current controller.\n";
+PyObject* SCA_ISensor::PyIsTriggered(PyObject* self)
+{
+ // check with the current controller
+ int retval = 0;
+ if (SCA_PythonController::m_sCurrentController)
+ retval = SCA_PythonController::m_sCurrentController->IsTriggered(this);
+ return PyInt_FromLong(retval);
+}
+
/**
* getUsePulseMode: getter for the pulse mode (KX_TRUE = on)
*/
-char SCA_ISensor::GetUsePosPulseMode_doc[] =
+const char SCA_ISensor::GetUsePosPulseMode_doc[] =
"getUsePosPulseMode()\n"
"\tReturns whether positive pulse mode is active.\n";
-PyObject* SCA_ISensor::PyGetUsePosPulseMode(PyObject* self, PyObject* args, PyObject* kwds)
+PyObject* SCA_ISensor::PyGetUsePosPulseMode(PyObject* self)
{
return BoolToPyArg(m_pos_pulsemode);
}
@@ -236,7 +312,7 @@ PyObject* SCA_ISensor::PyGetUsePosPulseMode(PyObject* self, PyObject* args, PyOb
/**
* setUsePulseMode: setter for the pulse mode (KX_TRUE = on)
*/
-char SCA_ISensor::SetUsePosPulseMode_doc[] =
+const char SCA_ISensor::SetUsePosPulseMode_doc[] =
"setUsePosPulseMode(pulse?)\n"
"\t - pulse? : Pulse when a positive event occurs?\n"
"\t (KX_TRUE, KX_FALSE)\n"
@@ -252,10 +328,10 @@ PyObject* SCA_ISensor::PySetUsePosPulseMode(PyObject* self, PyObject* args, PyOb
/**
* getFrequency: getter for the pulse mode interval
*/
-char SCA_ISensor::GetFrequency_doc[] =
+const char SCA_ISensor::GetFrequency_doc[] =
"getFrequency()\n"
"\tReturns the frequency of the updates in pulse mode.\n" ;
-PyObject* SCA_ISensor::PyGetFrequency(PyObject* self, PyObject* args, PyObject* kwds)
+PyObject* SCA_ISensor::PyGetFrequency(PyObject* self)
{
return PyInt_FromLong(m_pulse_frequency);
}
@@ -263,7 +339,7 @@ PyObject* SCA_ISensor::PyGetFrequency(PyObject* self, PyObject* args, PyObject*
/**
* setFrequency: setter for the pulse mode (KX_TRUE = on)
*/
-char SCA_ISensor::SetFrequency_doc[] =
+const char SCA_ISensor::SetFrequency_doc[] =
"setFrequency(pulse_frequency)\n"
"\t- pulse_frequency: The frequency of the updates in pulse mode (integer)"
"\tSet the frequency of the updates in pulse mode.\n"
@@ -287,15 +363,15 @@ PyObject* SCA_ISensor::PySetFrequency(PyObject* self, PyObject* args, PyObject*
}
-char SCA_ISensor::GetInvert_doc[] =
+const char SCA_ISensor::GetInvert_doc[] =
"getInvert()\n"
"\tReturns whether or not pulses from this sensor are inverted.\n" ;
-PyObject* SCA_ISensor::PyGetInvert(PyObject* self, PyObject* args, PyObject* kwds)
+PyObject* SCA_ISensor::PyGetInvert(PyObject* self)
{
return BoolToPyArg(m_invert);
}
-char SCA_ISensor::SetInvert_doc[] =
+const char SCA_ISensor::SetInvert_doc[] =
"setInvert(invert?)\n"
"\t- invert?: Invert the event-values? (KX_TRUE, KX_FALSE)\n"
"\tSet whether to invert pulses.\n";
@@ -307,15 +383,39 @@ PyObject* SCA_ISensor::PySetInvert(PyObject* self, PyObject* args, PyObject* kwd
Py_Return;
}
-char SCA_ISensor::GetUseNegPulseMode_doc[] =
+const char SCA_ISensor::GetLevel_doc[] =
+"getLevel()\n"
+"\tReturns whether this sensor is a level detector or a edge detector.\n"
+"\tIt makes a difference only in case of logic state transition (state actuator).\n"
+"\tA level detector will immediately generate a pulse, negative or positive\n"
+"\tdepending on the sensor condition, as soon as the state is activated.\n"
+"\tA edge detector will wait for a state change before generating a pulse.\n";
+PyObject* SCA_ISensor::PyGetLevel(PyObject* self)
+{
+ return BoolToPyArg(m_level);
+}
+
+const char SCA_ISensor::SetLevel_doc[] =
+"setLevel(level?)\n"
+"\t- level?: Detect level instead of edge? (KX_TRUE, KX_FALSE)\n"
+"\tSet whether to detect level or edge transition when entering a state.\n";
+PyObject* SCA_ISensor::PySetLevel(PyObject* self, PyObject* args, PyObject* kwds)
+{
+ int pyarg = 0;
+ if(!PyArg_ParseTuple(args, "i", &pyarg)) { return NULL; }
+ m_level = PyArgToBool(pyarg);
+ Py_Return;
+}
+
+const char SCA_ISensor::GetUseNegPulseMode_doc[] =
"getUseNegPulseMode()\n"
"\tReturns whether negative pulse mode is active.\n";
-PyObject* SCA_ISensor::PyGetUseNegPulseMode(PyObject* self, PyObject* args, PyObject* kwds)
+PyObject* SCA_ISensor::PyGetUseNegPulseMode(PyObject* self)
{
return BoolToPyArg(m_neg_pulsemode);
}
-char SCA_ISensor::SetUseNegPulseMode_doc[] =
+const char SCA_ISensor::SetUseNegPulseMode_doc[] =
"setUseNegPulseMode(pulse?)\n"
"\t - pulse? : Pulse when a negative event occurs?\n"
"\t (KX_TRUE, KX_FALSE)\n"
@@ -328,4 +428,15 @@ PyObject* SCA_ISensor::PySetUseNegPulseMode(PyObject* self, PyObject* args, PyOb
Py_Return;
}
+const char SCA_ISensor::Reset_doc[] =
+"reset()\n"
+"\tReset sensor internal state, effect depends on the type of sensor and settings.\n"
+"\tThe sensor is put in its initial state as if it was just activated.\n";
+PyObject* SCA_ISensor::PyReset(PyObject* self)
+{
+ Init();
+ Py_Return;
+}
+
+
/* eof */
diff --git a/source/gameengine/GameLogic/SCA_ISensor.h b/source/gameengine/GameLogic/SCA_ISensor.h
index 000a4951e0f..d1872009291 100644
--- a/source/gameengine/GameLogic/SCA_ISensor.h
+++ b/source/gameengine/GameLogic/SCA_ISensor.h
@@ -34,6 +34,8 @@
#include "SCA_ILogicBrick.h"
+#include <vector>
+
/**
* Interface Class for all logic Sensors. Implements
* pulsemode,pulsefrequency */
@@ -61,12 +63,21 @@ class SCA_ISensor : public SCA_ILogicBrick
/** invert the output signal*/
bool m_invert;
+ /** detect level instead of edge*/
+ bool m_level;
+
+ /** sensor has been reset */
+ bool m_reset;
+
/** Sensor must ignore updates? */
bool m_suspended;
- /** Pass the activation on to the logic manager.*/
- void SignalActivation(class SCA_LogicManager* logicmgr);
-
+ /** number of connections to controller */
+ int m_links;
+
+ /** list of controllers that have just activated this sensor because of a state change */
+ std::vector<class SCA_IController*> m_newControllers;
+
public:
SCA_ISensor(SCA_IObject* gameobj,
class SCA_EventManager* eventmgr,
@@ -81,6 +92,7 @@ public:
void Activate(class SCA_LogicManager* logicmgr,CValue* event);
virtual bool Evaluate(CValue* event) = 0;
virtual bool IsPositiveTrigger();
+ virtual void Init();
virtual PyObject* _getattr(const STR_String& attr);
virtual CValue* GetReplica()=0;
@@ -94,10 +106,19 @@ public:
bool negmode,
int freq);
+ /** Release sensor
+ * For property sensor, it is used to release the pre-calculated expression
+ * so that self references are removed before the sensor itself is released
+ */
+ virtual void Delete() { Release(); }
/** Set inversion of pulses on or off. */
void SetInvert(bool inv);
+ /** set the level detection on or off */
+ void SetLevel(bool lvl);
+
+ virtual void RegisterToManager();
+ virtual void UnregisterToManager();
- void RegisterToManager();
virtual float GetNumber();
/** Stop sensing for a while. */
@@ -109,16 +130,30 @@ public:
/** Resume sensing. */
void Resume();
+ void AddNewController(class SCA_IController* controller)
+ { m_newControllers.push_back(controller); }
+ void ClrLink()
+ { m_links = 0; }
+ void IncLink()
+ { if (!m_links++) RegisterToManager(); }
+ void DecLink();
+ bool IsNoLink() const
+ { return !m_links; }
+
/* Python functions: */
- KX_PYMETHOD_DOC(SCA_ISensor,IsPositive);
- KX_PYMETHOD_DOC(SCA_ISensor,GetUsePosPulseMode);
+ KX_PYMETHOD_DOC_NOARGS(SCA_ISensor,IsPositive);
+ KX_PYMETHOD_DOC_NOARGS(SCA_ISensor,IsTriggered);
+ KX_PYMETHOD_DOC_NOARGS(SCA_ISensor,GetUsePosPulseMode);
KX_PYMETHOD_DOC(SCA_ISensor,SetUsePosPulseMode);
- KX_PYMETHOD_DOC(SCA_ISensor,GetFrequency);
+ KX_PYMETHOD_DOC_NOARGS(SCA_ISensor,GetFrequency);
KX_PYMETHOD_DOC(SCA_ISensor,SetFrequency);
- KX_PYMETHOD_DOC(SCA_ISensor,GetUseNegPulseMode);
+ KX_PYMETHOD_DOC_NOARGS(SCA_ISensor,GetUseNegPulseMode);
KX_PYMETHOD_DOC(SCA_ISensor,SetUseNegPulseMode);
- KX_PYMETHOD_DOC(SCA_ISensor,GetInvert);
+ KX_PYMETHOD_DOC_NOARGS(SCA_ISensor,GetInvert);
KX_PYMETHOD_DOC(SCA_ISensor,SetInvert);
+ KX_PYMETHOD_DOC_NOARGS(SCA_ISensor,GetLevel);
+ KX_PYMETHOD_DOC(SCA_ISensor,SetLevel);
+ KX_PYMETHOD_DOC_NOARGS(SCA_ISensor,Reset);
};
diff --git a/source/gameengine/GameLogic/SCA_JoystickManager.cpp b/source/gameengine/GameLogic/SCA_JoystickManager.cpp
index a095ad2a594..f3ce549a637 100644
--- a/source/gameengine/GameLogic/SCA_JoystickManager.cpp
+++ b/source/gameengine/GameLogic/SCA_JoystickManager.cpp
@@ -40,42 +40,49 @@ SCA_JoystickManager::SCA_JoystickManager(class SCA_LogicManager* logicmgr)
: SCA_EventManager(JOY_EVENTMGR),
m_logicmgr(logicmgr)
{
- m_joystick = new SCA_Joystick();
- m_joystick->CreateJoystickDevice();
+ int i;
+ for (i=0; i<JOYINDEX_MAX; i++) {
+ m_joystick[i] = SCA_Joystick::GetInstance( i );
+ }
}
SCA_JoystickManager::~SCA_JoystickManager()
{
- m_joystick->DestroyJoystickDevice();
- delete m_joystick;
+ int i;
+ for (i=0; i<JOYINDEX_MAX; i++) {
+ if(m_joystick[i])
+ m_joystick[i]->ReleaseInstance();
+ }
}
void SCA_JoystickManager::NextFrame(double curtime,double deltatime)
{
- for (unsigned int i = 0; i < m_sensors.size(); i++)
- {
- SCA_JoystickSensor* joysensor = (SCA_JoystickSensor*) m_sensors[i];
- if(!joysensor->IsSuspended())
+ if (m_sensors.size()==0) {
+ return;
+ }
+ else {
+ set<SCA_ISensor*>::iterator it;
+#ifndef DISABLE_SDL
+ SCA_Joystick::HandleEvents(); /* Handle all SDL Joystick events */
+#endif
+ for (it = m_sensors.begin(); it != m_sensors.end(); it++)
{
- m_joystick->HandleEvents();
- joysensor->Activate(m_logicmgr, NULL);
+ SCA_JoystickSensor* joysensor = (SCA_JoystickSensor*)(*it);
+ if(!joysensor->IsSuspended())
+ {
+ joysensor->Activate(m_logicmgr, NULL);
+ }
}
}
}
-void SCA_JoystickManager::RegisterSensor(SCA_ISensor* sensor)
-{
- m_sensors.push_back(sensor);
-}
-
-
-SCA_Joystick *SCA_JoystickManager::GetJoystickDevice()
+SCA_Joystick *SCA_JoystickManager::GetJoystickDevice( short int joyindex)
{
/*
*Return the instance of SCA_Joystick for use
*/
- return m_joystick;
+ return m_joystick[joyindex];
}
diff --git a/source/gameengine/GameLogic/SCA_JoystickManager.h b/source/gameengine/GameLogic/SCA_JoystickManager.h
index 3c4df64677e..d3a7ac95bea 100644
--- a/source/gameengine/GameLogic/SCA_JoystickManager.h
+++ b/source/gameengine/GameLogic/SCA_JoystickManager.h
@@ -40,13 +40,12 @@ class SCA_JoystickManager : public SCA_EventManager
/**
* SDL Joystick Class Instance
*/
- SCA_Joystick *m_joystick;
+ SCA_Joystick *m_joystick[JOYINDEX_MAX];
public:
SCA_JoystickManager(class SCA_LogicManager* logicmgr);
virtual ~SCA_JoystickManager();
virtual void NextFrame(double curtime,double deltatime);
- virtual void RegisterSensor(SCA_ISensor* sensor);
- SCA_Joystick* GetJoystickDevice(void);
+ SCA_Joystick* GetJoystickDevice(short int joyindex);
};
diff --git a/source/gameengine/GameLogic/SCA_JoystickSensor.cpp b/source/gameengine/GameLogic/SCA_JoystickSensor.cpp
index b0e7fee130d..8b96840b149 100644
--- a/source/gameengine/GameLogic/SCA_JoystickSensor.cpp
+++ b/source/gameengine/GameLogic/SCA_JoystickSensor.cpp
@@ -30,8 +30,11 @@
#include "SCA_EventManager.h"
#include "SCA_LogicManager.h"
+#include "PyObjectPlus.h"
+
#include <iostream>
+
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
@@ -39,34 +42,41 @@
SCA_JoystickSensor::SCA_JoystickSensor(class SCA_JoystickManager* eventmgr,
SCA_IObject* gameobj,
+ short int joyindex,
short int joymode,
int axis, int axisf,int prec,
- int button, int buttonf,
- int hat, int hatf,
+ int button,
+ int hat, int hatf, bool allevents,
PyTypeObject* T )
:SCA_ISensor(gameobj,eventmgr,T),
m_pJoystickMgr(eventmgr),
m_axis(axis),
m_axisf(axisf),
m_button(button),
- m_buttonf(buttonf),
m_hat(hat),
m_hatf(hatf),
m_precision(prec),
- m_joymode(joymode)
+ m_joymode(joymode),
+ m_joyindex(joyindex),
+ m_bAllEvents(allevents)
{
/*
std::cout << " axis " << m_axis << std::endl;
std::cout << " axis flag " << m_axisf << std::endl;
std::cout << " precision " << m_precision << std::endl;
std::cout << " button " << m_button << std::endl;
-std::cout << " button flag "<< m_buttonf << std::endl;
std::cout << " hat " << m_hat << std::endl;
std::cout << " hat flag " << m_hatf << std::endl;
*/
- m_istrig=0;
+ Init();
}
+void SCA_JoystickSensor::Init()
+{
+ m_istrig=(m_invert)?1:0;
+ m_istrig_prev=0;
+ m_reset = true;
+}
SCA_JoystickSensor::~SCA_JoystickSensor()
{
@@ -75,9 +85,10 @@ SCA_JoystickSensor::~SCA_JoystickSensor()
CValue* SCA_JoystickSensor::GetReplica()
{
- CValue* replica = new SCA_JoystickSensor(*this);
+ SCA_JoystickSensor* replica = new SCA_JoystickSensor(*this);
// this will copy properties and so on...
CValue::AddDataToReplica(replica);
+ replica->Init();
return replica;
}
@@ -93,9 +104,14 @@ bool SCA_JoystickSensor::IsPositiveTrigger()
bool SCA_JoystickSensor::Evaluate(CValue* event)
{
- SCA_Joystick *js = m_pJoystickMgr->GetJoystickDevice();
+ SCA_Joystick *js = m_pJoystickMgr->GetJoystickDevice(m_joyindex);
bool result = false;
+ bool reset = m_reset && m_level;
+ if(js==NULL) /* no joystick - dont do anything */
+ return false;
+
+ m_reset = false;
switch(m_joymode)
{
case KX_JOYSENSORMODE_AXIS:
@@ -107,10 +123,25 @@ bool SCA_JoystickSensor::Evaluate(CValue* event)
m_axisf == 3 == down
numberof== m_axis -- max 2
*/
+
+ if (!js->IsTrigAxis() && !reset) /* No events from SDL? - dont bother */
+ return false;
+
js->cSetPrecision(m_precision);
- if(m_axisf == 1){
+ if (m_bAllEvents) {
+ if(js->aAnyAxisIsPositive(m_axis)){
+ m_istrig = 1;
+ result = true;
+ }else{
+ if(m_istrig){
+ m_istrig = 0;
+ result = true;
+ }
+ }
+ }
+ else if(m_axisf == 1){
if(js->aUpAxisIsPositive(m_axis)){
- m_istrig =1;
+ m_istrig = 1;
result = true;
}else{
if(m_istrig){
@@ -119,7 +150,7 @@ bool SCA_JoystickSensor::Evaluate(CValue* event)
}
}
}
- if(m_axisf == 3){
+ else if(m_axisf == 3){
if(js->aDownAxisIsPositive(m_axis)){
m_istrig = 1;
result = true;
@@ -130,7 +161,7 @@ bool SCA_JoystickSensor::Evaluate(CValue* event)
}
}
}
- if(m_axisf == 2){
+ else if(m_axisf == 2){
if(js->aLeftAxisIsPositive(m_axis)){
m_istrig = 1;
result = true;
@@ -141,7 +172,7 @@ bool SCA_JoystickSensor::Evaluate(CValue* event)
}
}
}
- if(m_axisf == 0){
+ else if(m_axisf == 0){
if(js->aRightAxisIsPositive(m_axis)){
m_istrig = 1;
result = true;
@@ -157,32 +188,20 @@ bool SCA_JoystickSensor::Evaluate(CValue* event)
case KX_JOYSENSORMODE_BUTTON:
{
/* what is what!
- pressed = m_buttonf == 0
- released = m_buttonf == 1
m_button = the actual button in question
*/
- if(m_buttonf == 0){
- if(js->aButtonPressIsPositive(m_button)){
- m_istrig = 1;
+ if (!js->IsTrigButton() && !reset) /* No events from SDL? - dont bother */
+ return false;
+
+ if(( m_bAllEvents && js->aAnyButtonPressIsPositive()) || (!m_bAllEvents && js->aButtonPressIsPositive(m_button))) {
+ m_istrig = 1;
+ result = true;
+ }else {
+ if(m_istrig){
+ m_istrig = 0;
result = true;
- }else {
- if(m_istrig){
- m_istrig = 0;
- result = true;
- }
}
}
- if(m_buttonf == 1){
- if(js->aButtonReleaseIsPositive(m_button)){
- m_istrig = 1;
- result = true;
- }else {
- if(m_istrig){
- m_istrig = 0;
- result = true;
- }
- }
- }
break;
}
case KX_JOYSENSORMODE_HAT:
@@ -191,6 +210,10 @@ bool SCA_JoystickSensor::Evaluate(CValue* event)
numberof = m_hat -- max 2
direction= m_hatf -- max 12
*/
+
+ if (!js->IsTrigHat() && !reset) /* No events from SDL? - dont bother */
+ return false;
+
if(m_hat == 1){
if(js->aHatIsPositive(m_hatf)){
m_istrig = 1;
@@ -213,19 +236,6 @@ bool SCA_JoystickSensor::Evaluate(CValue* event)
}
}
}
- /*
- if(m_hat == 3){
- if(js->aHatIsPositive(m_hatf)){
- m_istrig = 1;
- result = true;
- }else{
- if(m_istrig){
- m_istrig = 0;
- result = true;
- }
- }
- }
- */
break;
}
/* test for ball anyone ?*/
@@ -233,9 +243,20 @@ bool SCA_JoystickSensor::Evaluate(CValue* event)
printf("Error invalid switch statement\n");
break;
}
- if(!js->IsTrig()){
- m_istrig = 0;
+
+ /* if not all events are enabled, only send a positive pulse when
+ * the button state changes */
+ if (!m_bAllEvents) {
+ if (m_istrig_prev == m_istrig) {
+ result = false;
+ } else {
+ m_istrig_prev = m_istrig;
+ }
}
+
+ if (reset)
+ result = true;
+
return result;
}
@@ -283,18 +304,22 @@ PyParentObject SCA_JoystickSensor::Parents[] = {
PyMethodDef SCA_JoystickSensor::Methods[] = {
- {"getAxis", (PyCFunction) SCA_JoystickSensor::sPyGetAxis, METH_NOARGS, GetAxis_doc},
- {"setAxis", (PyCFunction) SCA_JoystickSensor::sPySetAxis, METH_VARARGS, SetAxis_doc},
- {"getAxisValue", (PyCFunction) SCA_JoystickSensor::sPyGetRealAxis, METH_NOARGS, GetRealAxis_doc},
- {"getThreshold", (PyCFunction) SCA_JoystickSensor::sPyGetThreshold, METH_NOARGS, GetThreshold_doc},
- {"setThreshold", (PyCFunction) SCA_JoystickSensor::sPySetThreshold, METH_VARARGS, SetThreshold_doc},
- {"getButton", (PyCFunction) SCA_JoystickSensor::sPyGetButton, METH_NOARGS, GetButton_doc},
- {"setButton", (PyCFunction) SCA_JoystickSensor::sPySetButton, METH_VARARGS, SetButton_doc},
- {"getHat", (PyCFunction) SCA_JoystickSensor::sPyGetHat, METH_NOARGS, GetHat_doc},
- {"setHat", (PyCFunction) SCA_JoystickSensor::sPySetHat, METH_VARARGS, SetHat_doc},
- {"getNumAxes", (PyCFunction) SCA_JoystickSensor::sPyNumberOfAxes, METH_NOARGS, NumberOfAxes_doc},
- {"getNumButtons",(PyCFunction) SCA_JoystickSensor::sPyNumberOfButtons,METH_NOARGS, NumberOfButtons_doc},
- {"getNumHats", (PyCFunction) SCA_JoystickSensor::sPyNumberOfHats, METH_NOARGS, NumberOfHats_doc},
+ {"getIndex", (PyCFunction) SCA_JoystickSensor::sPyGetIndex, METH_NOARGS, (PY_METHODCHAR)GetIndex_doc},
+ {"setIndex", (PyCFunction) SCA_JoystickSensor::sPySetIndex, METH_O, (PY_METHODCHAR)SetIndex_doc},
+ {"getAxis", (PyCFunction) SCA_JoystickSensor::sPyGetAxis, METH_NOARGS, (PY_METHODCHAR)GetAxis_doc},
+ {"setAxis", (PyCFunction) SCA_JoystickSensor::sPySetAxis, METH_VARARGS, (PY_METHODCHAR)SetAxis_doc},
+ {"getAxisValue", (PyCFunction) SCA_JoystickSensor::sPyGetAxisValue, METH_NOARGS, (PY_METHODCHAR)GetAxisValue_doc},
+ {"getThreshold", (PyCFunction) SCA_JoystickSensor::sPyGetThreshold, METH_NOARGS, (PY_METHODCHAR)GetThreshold_doc},
+ {"setThreshold", (PyCFunction) SCA_JoystickSensor::sPySetThreshold, METH_VARARGS, (PY_METHODCHAR)SetThreshold_doc},
+ {"getButton", (PyCFunction) SCA_JoystickSensor::sPyGetButton, METH_NOARGS, (PY_METHODCHAR)GetButton_doc},
+ {"setButton", (PyCFunction) SCA_JoystickSensor::sPySetButton, METH_O, (PY_METHODCHAR)SetButton_doc},
+ {"getButtonValue",(PyCFunction) SCA_JoystickSensor::sPyGetButtonValue, METH_NOARGS,(PY_METHODCHAR)GetButtonValue_doc},
+ {"getHat", (PyCFunction) SCA_JoystickSensor::sPyGetHat, METH_NOARGS, (PY_METHODCHAR)GetHat_doc},
+ {"setHat", (PyCFunction) SCA_JoystickSensor::sPySetHat, METH_VARARGS, (PY_METHODCHAR)SetHat_doc},
+ {"getNumAxes", (PyCFunction) SCA_JoystickSensor::sPyNumberOfAxes, METH_NOARGS, (PY_METHODCHAR)NumberOfAxes_doc},
+ {"getNumButtons",(PyCFunction) SCA_JoystickSensor::sPyNumberOfButtons,METH_NOARGS, (PY_METHODCHAR)NumberOfButtons_doc},
+ {"getNumHats", (PyCFunction) SCA_JoystickSensor::sPyNumberOfHats, METH_NOARGS, (PY_METHODCHAR)NumberOfHats_doc},
+ {"isConnected", (PyCFunction) SCA_JoystickSensor::sPyConnected, METH_NOARGS, (PY_METHODCHAR)Connected_doc},
{NULL,NULL} //Sentinel
};
@@ -304,24 +329,44 @@ PyObject* SCA_JoystickSensor::_getattr(const STR_String& attr) {
}
+/* get index ---------------------------------------------------------- */
+const char SCA_JoystickSensor::GetIndex_doc[] =
+"getIndex\n"
+"\tReturns the joystick index to use.\n";
+PyObject* SCA_JoystickSensor::PyGetIndex( PyObject* self ) {
+ return PyInt_FromLong(m_joyindex);
+}
+
+
+/* set index ---------------------------------------------------------- */
+const char SCA_JoystickSensor::SetIndex_doc[] =
+"setIndex\n"
+"\tSets the joystick index to use.\n";
+PyObject* SCA_JoystickSensor::PySetIndex( PyObject* self, PyObject* value ) {
+ int index = PyInt_AsLong( value ); /* -1 on error, will raise an error in this case */
+ if (index < 0 || index >= JOYINDEX_MAX) {
+ PyErr_SetString(PyExc_ValueError, "joystick index out of range or not an int");
+ return NULL;
+ }
+
+ m_joyindex = index;
+ Py_RETURN_NONE;
+}
+
/* get axis ---------------------------------------------------------- */
-char SCA_JoystickSensor::GetAxis_doc[] =
+const char SCA_JoystickSensor::GetAxis_doc[] =
"getAxis\n"
-"\tReturns the current state of the axis.\n";
-PyObject* SCA_JoystickSensor::PyGetAxis( PyObject* self,
- PyObject* args,
- PyObject* kwds) {
+"\tReturns the current axis this sensor reacts to.\n";
+PyObject* SCA_JoystickSensor::PyGetAxis( PyObject* self) {
return Py_BuildValue("[ii]",m_axis, m_axisf);
}
/* set axis ---------------------------------------------------------- */
-char SCA_JoystickSensor::SetAxis_doc[] =
+const char SCA_JoystickSensor::SetAxis_doc[] =
"setAxis\n"
-"\tSets the current state of the axis.\n";
-PyObject* SCA_JoystickSensor::PySetAxis( PyObject* self,
- PyObject* args,
- PyObject* kwds) {
+"\tSets the current axis this sensor reacts to.\n";
+PyObject* SCA_JoystickSensor::PySetAxis( PyObject* self, PyObject* args ) {
int axis,axisflag;
if(!PyArg_ParseTuple(args, "ii", &axis, &axisflag)){
@@ -329,145 +374,145 @@ PyObject* SCA_JoystickSensor::PySetAxis( PyObject* self,
}
m_axis = axis;
m_axisf = axisflag;
- Py_Return;
+ Py_RETURN_NONE;
}
/* get axis value ----------------------------------------------------- */
-char SCA_JoystickSensor::GetRealAxis_doc[] =
+const char SCA_JoystickSensor::GetAxisValue_doc[] =
"getAxisValue\n"
-"\tReturns a list of the values for each axis .\n";
-PyObject* SCA_JoystickSensor::PyGetRealAxis( PyObject* self,
- PyObject* args,
- PyObject* kwds) {
- int a,b,c,d;
- SCA_Joystick *joy = m_pJoystickMgr->GetJoystickDevice();
- a = joy->GetAxis10();
- b = joy->GetAxis11();
- c = joy->GetAxis20();
- d = joy->GetAxis21();
- return Py_BuildValue("[iiii]",a,b,c,d);
+"\tReturns a list of the values for the current state of each axis.\n";
+PyObject* SCA_JoystickSensor::PyGetAxisValue( PyObject* self) {
+ SCA_Joystick *joy = m_pJoystickMgr->GetJoystickDevice(m_joyindex);
+ if(joy)
+ return Py_BuildValue("[iiii]", joy->GetAxis10(), joy->GetAxis11(), joy->GetAxis20(), joy->GetAxis21());
+ else
+ return Py_BuildValue("[iiii]", 0, 0, 0, 0);
}
/* get threshold ----------------------------------------------------- */
-char SCA_JoystickSensor::GetThreshold_doc[] =
+const char SCA_JoystickSensor::GetThreshold_doc[] =
"getThreshold\n"
"\tReturns the threshold of the axis.\n";
-PyObject* SCA_JoystickSensor::PyGetThreshold( PyObject* self,
- PyObject* args,
- PyObject* kwds) {
- return Py_BuildValue("i", m_precision);
+PyObject* SCA_JoystickSensor::PyGetThreshold( PyObject* self) {
+ return PyInt_FromLong(m_precision);
}
/* set threshold ----------------------------------------------------- */
-char SCA_JoystickSensor::SetThreshold_doc[] =
+const char SCA_JoystickSensor::SetThreshold_doc[] =
"setThreshold\n"
"\tSets the threshold of the axis.\n";
-PyObject* SCA_JoystickSensor::PySetThreshold( PyObject* self,
- PyObject* args,
- PyObject* kwds) {
+PyObject* SCA_JoystickSensor::PySetThreshold( PyObject* self, PyObject* args ) {
int thresh;
if(!PyArg_ParseTuple(args, "i", &thresh)){
return NULL;
}
m_precision = thresh;
- Py_Return;
+ Py_RETURN_NONE;
}
-
/* get button -------------------------------------------------------- */
-char SCA_JoystickSensor::GetButton_doc[] =
+const char SCA_JoystickSensor::GetButton_doc[] =
"getButton\n"
-"\tReturns the currently pressed button.\n";
-PyObject* SCA_JoystickSensor::PyGetButton( PyObject* self,
- PyObject* args,
- PyObject* kwds) {
- return Py_BuildValue("[ii]",m_button, m_buttonf);
+"\tReturns the current button this sensor is checking.\n";
+PyObject* SCA_JoystickSensor::PyGetButton( PyObject* self) {
+ return PyInt_FromLong(m_button);
}
-
/* set button -------------------------------------------------------- */
-char SCA_JoystickSensor::SetButton_doc[] =
+const char SCA_JoystickSensor::SetButton_doc[] =
"setButton\n"
"\tSets the button the sensor reacts to.\n";
-PyObject* SCA_JoystickSensor::PySetButton( PyObject* self,
- PyObject* args,
- PyObject* kwds) {
- int button,buttonflag;
- if(!PyArg_ParseTuple(args, "ii", &button, &buttonflag)){
+PyObject* SCA_JoystickSensor::PySetButton( PyObject* self, PyObject* value ) {
+ int button = PyInt_AsLong(value);
+ if(button==-1 && PyErr_Occurred()) {
+ PyErr_SetString(PyExc_ValueError, "expected an int");
return NULL;
}
m_button = button;
- m_buttonf = buttonflag;
- Py_Return;
+ Py_RETURN_NONE;
}
+/* get button value -------------------------------------------------- */
+const char SCA_JoystickSensor::GetButtonValue_doc[] =
+"getButtonValue\n"
+"\tReturns a list containing the indicies of the current pressed state of each button.\n";
+PyObject* SCA_JoystickSensor::PyGetButtonValue( PyObject* self) {
+ SCA_Joystick *joy = m_pJoystickMgr->GetJoystickDevice(m_joyindex);
+ PyObject *ls = PyList_New(0);
+ PyObject *value;
+ int i;
+
+ if(joy) {
+ for (i=0; i < joy->GetNumberOfButtons(); i++) {
+ if (joy->aButtonPressIsPositive(i)) {
+ value = PyInt_FromLong(i);
+ PyList_Append(ls, value);
+ Py_DECREF(value);
+ }
+ }
+ }
+ return ls;
+}
/* get hat ----------------------------------------------------------- */
-char SCA_JoystickSensor::GetHat_doc[] =
+const char SCA_JoystickSensor::GetHat_doc[] =
"getHat\n"
"\tReturns the current direction of the hat.\n";
-PyObject* SCA_JoystickSensor::PyGetHat( PyObject* self,
- PyObject* args,
- PyObject* kwds) {
+PyObject* SCA_JoystickSensor::PyGetHat( PyObject* self ) {
return Py_BuildValue("[ii]",m_hat, m_hatf);
}
/* set hat ----------------------------------------------------------- */
-char SCA_JoystickSensor::SetHat_doc[] =
+const char SCA_JoystickSensor::SetHat_doc[] =
"setHat\n"
"\tSets the hat the sensor reacts to.\n";
-PyObject* SCA_JoystickSensor::PySetHat( PyObject* self,
- PyObject* args,
- PyObject* kwds) {
+PyObject* SCA_JoystickSensor::PySetHat( PyObject* self, PyObject* args ) {
int hat,hatflag;
if(!PyArg_ParseTuple(args, "ii", &hat, &hatflag)){
return NULL;
}
m_hat = hat;
m_hatf = hatflag;
- Py_Return;
+ Py_RETURN_NONE;
}
/* get # of ----------------------------------------------------- */
-char SCA_JoystickSensor::NumberOfAxes_doc[] =
+const char SCA_JoystickSensor::NumberOfAxes_doc[] =
"getNumAxes\n"
"\tReturns the number of axes .\n";
-PyObject* SCA_JoystickSensor::PyNumberOfAxes( PyObject* self,
- PyObject* args,
- PyObject* kwds) {
- int num;
- SCA_Joystick *joy = m_pJoystickMgr->GetJoystickDevice();
- num = joy->GetNumberOfAxes();
- return Py_BuildValue("i",num);
+PyObject* SCA_JoystickSensor::PyNumberOfAxes( PyObject* self ) {
+ SCA_Joystick *joy = m_pJoystickMgr->GetJoystickDevice(m_joyindex);
+ // when the joystick is null their is 0 exis still. dumb but scripters should use isConnected()
+ return PyInt_FromLong( joy ? joy->GetNumberOfAxes() : 0 );
}
-char SCA_JoystickSensor::NumberOfButtons_doc[] =
+const char SCA_JoystickSensor::NumberOfButtons_doc[] =
"getNumButtons\n"
"\tReturns the number of buttons .\n";
-PyObject* SCA_JoystickSensor::PyNumberOfButtons( PyObject* self,
- PyObject* args,
- PyObject* kwds) {
- int num;
- SCA_Joystick *joy = m_pJoystickMgr->GetJoystickDevice();
- num = joy->GetNumberOfButtons();
- return Py_BuildValue("i",num);
+PyObject* SCA_JoystickSensor::PyNumberOfButtons( PyObject* self ) {
+ SCA_Joystick *joy = m_pJoystickMgr->GetJoystickDevice(m_joyindex);
+ return PyInt_FromLong( joy ? joy->GetNumberOfButtons() : 0 );
}
-char SCA_JoystickSensor::NumberOfHats_doc[] =
+const char SCA_JoystickSensor::NumberOfHats_doc[] =
"getNumHats\n"
"\tReturns the number of hats .\n";
-PyObject* SCA_JoystickSensor::PyNumberOfHats( PyObject* self,
- PyObject* args,
- PyObject* kwds) {
- int num;
- SCA_Joystick *joy = m_pJoystickMgr->GetJoystickDevice();
- num = joy->GetNumberOfHats();
- return Py_BuildValue("i",num);
+PyObject* SCA_JoystickSensor::PyNumberOfHats( PyObject* self ) {
+ SCA_Joystick *joy = m_pJoystickMgr->GetJoystickDevice(m_joyindex);
+ return PyInt_FromLong( joy ? joy->GetNumberOfHats() : 0 );
+}
+
+const char SCA_JoystickSensor::Connected_doc[] =
+"getConnected\n"
+"\tReturns True if a joystick is connected at this joysticks index.\n";
+PyObject* SCA_JoystickSensor::PyConnected( PyObject* self ) {
+ SCA_Joystick *joy = m_pJoystickMgr->GetJoystickDevice(m_joyindex);
+ return PyBool_FromLong( joy ? joy->Connected() : 0 );
}
diff --git a/source/gameengine/GameLogic/SCA_JoystickSensor.h b/source/gameengine/GameLogic/SCA_JoystickSensor.h
index 2fbe1edf1e7..d316ad1119c 100644
--- a/source/gameengine/GameLogic/SCA_JoystickSensor.h
+++ b/source/gameengine/GameLogic/SCA_JoystickSensor.h
@@ -69,9 +69,24 @@ class SCA_JoystickSensor :public SCA_ISensor
*/
bool m_istrig;
/**
+ * Last trigger state for this sensors joystick,
+ * Otherwise it will trigger all the time
+ * this is used to see if the trigger state changes.
+ */
+ bool m_istrig_prev;
+ /**
* The mode to determine axis,button or hat
*/
short int m_joymode;
+ /**
+ * Select which joystick to use
+ */
+ short int m_joyindex;
+
+ /**
+ * Detect all events for the currently selected type
+ */
+ bool m_bAllEvents;
enum KX_JOYSENSORMODE {
KX_JOYSENSORMODE_NODEF = 0,
@@ -85,39 +100,50 @@ class SCA_JoystickSensor :public SCA_ISensor
public:
SCA_JoystickSensor(class SCA_JoystickManager* eventmgr,
SCA_IObject* gameobj,
+ short int joyindex,
short int joymode,
int axis, int axisf,int prec,
- int button, int buttonf,
- int hat, int hatf,
+ int button,
+ int hat, int hatf, bool allevents,
PyTypeObject* T=&Type );
virtual ~SCA_JoystickSensor();
virtual CValue* GetReplica();
virtual bool Evaluate(CValue* event);
virtual bool IsPositiveTrigger();
+ virtual void Init();
+ short int GetJoyIndex(void){
+ return m_joyindex;
+ }
+
/* --------------------------------------------------------------------- */
/* Python interface ---------------------------------------------------- */
/* --------------------------------------------------------------------- */
virtual PyObject* _getattr(const STR_String& attr);
+ /* Joystick Index */
+ KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,GetIndex);
+ KX_PYMETHOD_DOC_O(SCA_JoystickSensor,SetIndex);
/* Axes*/
- KX_PYMETHOD_DOC(SCA_JoystickSensor,GetAxis);
- KX_PYMETHOD_DOC(SCA_JoystickSensor,SetAxis);
- KX_PYMETHOD_DOC(SCA_JoystickSensor,GetRealAxis);
- KX_PYMETHOD_DOC(SCA_JoystickSensor,GetThreshold);
- KX_PYMETHOD_DOC(SCA_JoystickSensor,SetThreshold);
+ KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,GetAxis);
+ KX_PYMETHOD_DOC_VARARGS(SCA_JoystickSensor,SetAxis);
+ KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,GetAxisValue);
+ KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,GetThreshold);
+ KX_PYMETHOD_DOC_VARARGS(SCA_JoystickSensor,SetThreshold);
/* Buttons */
- KX_PYMETHOD_DOC(SCA_JoystickSensor,GetButton);
- KX_PYMETHOD_DOC(SCA_JoystickSensor,SetButton);
+ KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,GetButton);
+ KX_PYMETHOD_DOC_O(SCA_JoystickSensor,SetButton);
+ KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,GetButtonValue);
/* Hats */
- KX_PYMETHOD_DOC(SCA_JoystickSensor,GetHat);
- KX_PYMETHOD_DOC(SCA_JoystickSensor,SetHat);
+ KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,GetHat);
+ KX_PYMETHOD_DOC_VARARGS(SCA_JoystickSensor,SetHat);
/* number of */
- KX_PYMETHOD_DOC(SCA_JoystickSensor,NumberOfAxes);
- KX_PYMETHOD_DOC(SCA_JoystickSensor,NumberOfButtons);
- KX_PYMETHOD_DOC(SCA_JoystickSensor,NumberOfHats);
+ KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,NumberOfAxes);
+ KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,NumberOfButtons);
+ KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,NumberOfHats);
+ KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,Connected);
};
diff --git a/source/gameengine/GameLogic/SCA_KeyboardManager.cpp b/source/gameengine/GameLogic/SCA_KeyboardManager.cpp
index 259b06134d7..6a96442b124 100644
--- a/source/gameengine/GameLogic/SCA_KeyboardManager.cpp
+++ b/source/gameengine/GameLogic/SCA_KeyboardManager.cpp
@@ -62,23 +62,14 @@ void SCA_KeyboardManager::NextFrame()
{
//const SCA_InputEvent& event = GetEventValue(SCA_IInputDevice::KX_EnumInputs inputcode)=0;
// cerr << "SCA_KeyboardManager::NextFrame"<< endl;
- for (unsigned int i=0;i<m_sensors.size();i++)
+ set<SCA_ISensor*>::iterator it;
+ for (it=m_sensors.begin(); it != m_sensors.end(); it++)
{
- SCA_KeyboardSensor* keysensor = (SCA_KeyboardSensor*)m_sensors[i];
- keysensor->Activate(m_logicmanager,NULL);
+ (*it)->Activate(m_logicmanager,NULL);
}
}
-
-
-void SCA_KeyboardManager::RegisterSensor(SCA_ISensor* keysensor)
-{
- m_sensors.push_back(keysensor);
-}
-
-
-
bool SCA_KeyboardManager::IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode)
{
return false;
diff --git a/source/gameengine/GameLogic/SCA_KeyboardManager.h b/source/gameengine/GameLogic/SCA_KeyboardManager.h
index b4a50f56025..8f3cc0ab715 100644
--- a/source/gameengine/GameLogic/SCA_KeyboardManager.h
+++ b/source/gameengine/GameLogic/SCA_KeyboardManager.h
@@ -55,7 +55,6 @@ public:
bool IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode);
virtual void NextFrame();
- virtual void RegisterSensor(class SCA_ISensor* sensor);
SCA_IInputDevice* GetInputDevice();
};
diff --git a/source/gameengine/GameLogic/SCA_KeyboardSensor.cpp b/source/gameengine/GameLogic/SCA_KeyboardSensor.cpp
index f7bec628991..fa39a13679f 100644
--- a/source/gameengine/GameLogic/SCA_KeyboardSensor.cpp
+++ b/source/gameengine/GameLogic/SCA_KeyboardSensor.cpp
@@ -62,7 +62,7 @@ SCA_KeyboardSensor::SCA_KeyboardSensor(SCA_KeyboardManager* keybdmgr,
if (hotkey == SCA_IInputDevice::KX_ESCKEY)
keybdmgr->GetInputDevice()->HookEscape();
// SetDrawColor(0xff0000ff);
- m_val=0;
+ Init();
}
@@ -71,14 +71,22 @@ SCA_KeyboardSensor::~SCA_KeyboardSensor()
{
}
-
+void SCA_KeyboardSensor::Init()
+{
+ // this function is used when the sensor is disconnected from all controllers
+ // by the state engine. It reinitializes the sensor as if it was just created.
+ // However, if the target key is pressed when the sensor is reactivated, it
+ // will not generated an event (see remark in Evaluate()).
+ m_val = (m_invert)?1:0;
+ m_reset = true;
+}
CValue* SCA_KeyboardSensor::GetReplica()
{
- CValue* replica = new SCA_KeyboardSensor(*this);
+ SCA_KeyboardSensor* replica = new SCA_KeyboardSensor(*this);
// this will copy properties and so on...
CValue::AddDataToReplica(replica);
-
+ replica->Init();
return replica;
}
@@ -113,8 +121,12 @@ bool SCA_KeyboardSensor::TriggerOnAllKeys()
bool SCA_KeyboardSensor::Evaluate(CValue* eventval)
{
bool result = false;
- SCA_IInputDevice* inputdev = m_pKeyboardMgr->GetInputDevice();
+ bool reset = m_reset && m_level;
+ bool qual = true;
+ bool qual_change = false;
+ short int m_val_orig = m_val;
+ SCA_IInputDevice* inputdev = m_pKeyboardMgr->GetInputDevice();
// cerr << "SCA_KeyboardSensor::Eval event, sensing for "<< m_hotkey << " at device " << inputdev << "\n";
/* See if we need to do logging: togPropState exists and is
@@ -127,24 +139,29 @@ bool SCA_KeyboardSensor::Evaluate(CValue* eventval)
LogKeystrokes();
}
-
+ m_reset = false;
/* Now see whether events must be bounced. */
if (m_bAllKeys)
{
bool justactivated = false;
bool justreleased = false;
+ bool active = false;
for (int i=SCA_IInputDevice::KX_BEGINKEY ; i< SCA_IInputDevice::KX_ENDKEY;i++)
{
const SCA_InputEvent & inevent = inputdev->GetEventValue((SCA_IInputDevice::KX_EnumInputs) i);
- if (inevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED)
- {
+ switch (inevent.m_status)
+ {
+ case SCA_InputEvent::KX_JUSTACTIVATED:
justactivated = true;
- }
- if (inevent.m_status == SCA_InputEvent::KX_JUSTRELEASED)
- {
+ break;
+ case SCA_InputEvent::KX_JUSTRELEASED:
justreleased = true;
+ break;
+ case SCA_InputEvent::KX_ACTIVE:
+ active = true;
+ break;
}
}
@@ -156,8 +173,27 @@ bool SCA_KeyboardSensor::Evaluate(CValue* eventval)
{
if (justreleased)
{
- m_val=0;
+ m_val=(active)?1:0;
result = true;
+ } else
+ {
+ if (active)
+ {
+ if (m_val == 0)
+ {
+ m_val = 1;
+ if (m_level) {
+ result = true;
+ }
+ }
+ } else
+ {
+ if (m_val == 1)
+ {
+ m_val = 0;
+ result = true;
+ }
+ }
}
}
@@ -170,9 +206,52 @@ bool SCA_KeyboardSensor::Evaluate(CValue* eventval)
(SCA_IInputDevice::KX_EnumInputs) m_hotkey);
// cerr << "======= SCA_KeyboardSensor::Evaluate:: status: " << inevent.m_status << endl;
-
+
+
+ /* Check qualifier keys
+ * - see if the qualifiers we request are pressed - 'qual' true/false
+ * - see if the qualifiers we request changed their state - 'qual_change' true/false
+ */
+ if (m_qual > 0) {
+ const SCA_InputEvent & qualevent = inputdev->GetEventValue((SCA_IInputDevice::KX_EnumInputs) m_qual);
+ switch(qualevent.m_status) {
+ case SCA_InputEvent::KX_NO_INPUTSTATUS:
+ qual = false;
+ break;
+ case SCA_InputEvent::KX_JUSTRELEASED:
+ qual_change = true;
+ qual = false;
+ break;
+ case SCA_InputEvent::KX_JUSTACTIVATED:
+ qual_change = true;
+ }
+ }
+ if (m_qual2 > 0 && qual==true) {
+ const SCA_InputEvent & qualevent = inputdev->GetEventValue((SCA_IInputDevice::KX_EnumInputs) m_qual2);
+ /* copy of above */
+ switch(qualevent.m_status) {
+ case SCA_InputEvent::KX_NO_INPUTSTATUS:
+ qual = false;
+ break;
+ case SCA_InputEvent::KX_JUSTRELEASED:
+ qual_change = true;
+ qual = false;
+ break;
+ case SCA_InputEvent::KX_JUSTACTIVATED:
+ qual_change = true;
+ }
+ }
+ /* done reading qualifiers */
+
if (inevent.m_status == SCA_InputEvent::KX_NO_INPUTSTATUS)
{
+ if (m_val == 1)
+ {
+ // this situation may occur after a scene suspend: the keyboard release
+ // event was not captured, produce now the event off
+ m_val = 0;
+ result = true;
+ }
} else
{
if (inevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED)
@@ -185,11 +264,52 @@ bool SCA_KeyboardSensor::Evaluate(CValue* eventval)
{
m_val = 0;
result = true;
+ } else
+ {
+ if (inevent.m_status == SCA_InputEvent::KX_ACTIVE)
+ {
+ if (m_val == 0)
+ {
+ m_val = 1;
+ if (m_level)
+ {
+ result = true;
+ }
+ }
+ }
}
}
}
+
+ /* Modify the key state based on qual(s)
+ * Tested carefuly. dont touch unless your really sure.
+ * note, this will only change the results if key modifiers are set.
+ *
+ * When all modifiers and keys are positive
+ * - pulse true
+ *
+ * When ANY of the modifiers or main key become inactive,
+ * - pulse false
+ */
+ if (qual==false) { /* one of the qualifiers are not pressed */
+ if (m_val_orig && qual_change) { /* we were originally enabled, but a qualifier changed */
+ result = true;
+ } else {
+ result = false;
+ }
+ m_val = 0; /* since one of the qualifiers is not on, set the state to false */
+ } else { /* we done have any qualifiers or they are all pressed */
+ if (m_val && qual_change) { /* the main key state is true and our qualifier just changed */
+ result = true;
+ }
+ }
+ /* done with key quals */
+
}
-
+
+ if (reset)
+ // force an event
+ result = true;
return result;
}
@@ -209,6 +329,7 @@ void SCA_KeyboardSensor::AddToTargetProp(int keyIndex)
newprop.SetLength(oldlength - 1);
CStringValue * newstringprop = new CStringValue(newprop, m_targetprop);
GetParent()->SetProperty(m_targetprop, newstringprop);
+ newstringprop->Release();
}
} else {
/* append */
@@ -216,6 +337,7 @@ void SCA_KeyboardSensor::AddToTargetProp(int keyIndex)
STR_String newprop = tprop->GetText() + pchar;
CStringValue * newstringprop = new CStringValue(newprop, m_targetprop);
GetParent()->SetProperty(m_targetprop, newstringprop);
+ newstringprop->Release();
}
} else {
if (!IsDelete(keyIndex)) {
@@ -224,6 +346,7 @@ void SCA_KeyboardSensor::AddToTargetProp(int keyIndex)
STR_String newprop = pchar;
CStringValue * newstringprop = new CStringValue(newprop, m_targetprop);
GetParent()->SetProperty(m_targetprop, newstringprop);
+ newstringprop->Release();
}
}
}
@@ -448,12 +571,12 @@ PyObject* SCA_KeyboardSensor::sPySetAllMode(PyObject* self,
PyObject* kwds)
{
// printf("sPyIsPositive\n");
- return ((SCA_KeyboardSensor*) self)->PyIsPositive(self, args, kwds);
+ return ((SCA_KeyboardSensor*) self)->PyIsPositive(self);
}
/** 1. GetKey : check which key this sensor looks at */
-char SCA_KeyboardSensor::GetKey_doc[] =
+const char SCA_KeyboardSensor::GetKey_doc[] =
"getKey()\n"
"\tReturn the code of the key this sensor is listening to.\n" ;
PyObject* SCA_KeyboardSensor::PyGetKey(PyObject* self, PyObject* args, PyObject* kwds)
@@ -462,7 +585,7 @@ PyObject* SCA_KeyboardSensor::PyGetKey(PyObject* self, PyObject* args, PyObject*
}
/** 2. SetKey: change the key to look at */
-char SCA_KeyboardSensor::SetKey_doc[] =
+const char SCA_KeyboardSensor::SetKey_doc[] =
"setKey(keycode)\n"
"\t- keycode: any code from GameKeys\n"
"\tSet the key this sensor should listen to.\n" ;
@@ -482,7 +605,7 @@ PyObject* SCA_KeyboardSensor::PySetKey(PyObject* self, PyObject* args, PyObject*
}
/** 3. GetHold1 : set the first bucky bit */
-char SCA_KeyboardSensor::GetHold1_doc[] =
+const char SCA_KeyboardSensor::GetHold1_doc[] =
"getHold1()\n"
"\tReturn the code of the first key modifier to the key this \n"
"\tsensor is listening to.\n" ;
@@ -492,7 +615,7 @@ PyObject* SCA_KeyboardSensor::PyGetHold1(PyObject* self, PyObject* args, PyObjec
}
/** 4. SetHold1: change the first bucky bit */
-char SCA_KeyboardSensor::SetHold1_doc[] =
+const char SCA_KeyboardSensor::SetHold1_doc[] =
"setHold1(keycode)\n"
"\t- keycode: any code from GameKeys\n"
"\tSet the first modifier to the key this sensor should listen to.\n" ;
@@ -512,7 +635,7 @@ PyObject* SCA_KeyboardSensor::PySetHold1(PyObject* self, PyObject* args, PyObjec
}
/** 5. GetHold2 : get the second bucky bit */
-char SCA_KeyboardSensor::GetHold2_doc[] =
+const char SCA_KeyboardSensor::GetHold2_doc[] =
"getHold2()\n"
"\tReturn the code of the second key modifier to the key this \n"
"\tsensor is listening to.\n" ;
@@ -522,7 +645,7 @@ PyObject* SCA_KeyboardSensor::PyGetHold2(PyObject* self, PyObject* args, PyObjec
}
/** 6. SetHold2: change the second bucky bit */
-char SCA_KeyboardSensor::SetHold2_doc[] =
+const char SCA_KeyboardSensor::SetHold2_doc[] =
"setHold2(keycode)\n"
"\t- keycode: any code from GameKeys\n"
"\tSet the first modifier to the key this sensor should listen to.\n" ;
@@ -542,7 +665,7 @@ PyObject* SCA_KeyboardSensor::PySetHold2(PyObject* self, PyObject* args, PyObjec
}
-char SCA_KeyboardSensor::GetPressedKeys_doc[] =
+const char SCA_KeyboardSensor::GetPressedKeys_doc[] =
"getPressedKeys()\n"
"\tGet a list of pressed keys that have either been pressed, or just released this frame.\n" ;
@@ -582,7 +705,7 @@ PyObject* SCA_KeyboardSensor::PyGetPressedKeys(PyObject* self, PyObject* args, P
-char SCA_KeyboardSensor::GetCurrentlyPressedKeys_doc[] =
+const char SCA_KeyboardSensor::GetCurrentlyPressedKeys_doc[] =
"getCurrentlyPressedKeys()\n"
"\tGet a list of keys that are currently pressed.\n" ;
@@ -653,17 +776,17 @@ PyParentObject SCA_KeyboardSensor::Parents[] = {
};
PyMethodDef SCA_KeyboardSensor::Methods[] = {
- {"getKey", (PyCFunction) SCA_KeyboardSensor::sPyGetKey, METH_VARARGS, GetKey_doc},
- {"setKey", (PyCFunction) SCA_KeyboardSensor::sPySetKey, METH_VARARGS, SetKey_doc},
- {"getHold1", (PyCFunction) SCA_KeyboardSensor::sPyGetHold1, METH_VARARGS, GetHold1_doc},
- {"setHold1", (PyCFunction) SCA_KeyboardSensor::sPySetHold1, METH_VARARGS, SetHold1_doc},
- {"getHold2", (PyCFunction) SCA_KeyboardSensor::sPyGetHold2, METH_VARARGS, GetHold2_doc},
- {"setHold2", (PyCFunction) SCA_KeyboardSensor::sPySetHold2, METH_VARARGS, SetHold2_doc},
-// {"getUseAllKeys", (PyCFunction) SCA_KeyboardSensor::sPyGetUseAllKeys, METH_VARARGS, GetUseAllKeys_doc},
-// {"setUseAllKeys", (PyCFunction) SCA_KeyboardSensor::sPySetUseAllKeys, METH_VARARGS, SetUseAllKeys_doc},
- {"getPressedKeys", (PyCFunction) SCA_KeyboardSensor::sPyGetPressedKeys, METH_VARARGS, GetPressedKeys_doc},
- {"getCurrentlyPressedKeys", (PyCFunction) SCA_KeyboardSensor::sPyGetCurrentlyPressedKeys, METH_VARARGS, GetCurrentlyPressedKeys_doc},
-// {"getKeyEvents", (PyCFunction) SCA_KeyboardSensor::sPyGetKeyEvents, METH_VARARGS, GetKeyEvents_doc},
+ {"getKey", (PyCFunction) SCA_KeyboardSensor::sPyGetKey, METH_VARARGS, (PY_METHODCHAR)GetKey_doc},
+ {"setKey", (PyCFunction) SCA_KeyboardSensor::sPySetKey, METH_VARARGS, (PY_METHODCHAR)SetKey_doc},
+ {"getHold1", (PyCFunction) SCA_KeyboardSensor::sPyGetHold1, METH_VARARGS, (PY_METHODCHAR)GetHold1_doc},
+ {"setHold1", (PyCFunction) SCA_KeyboardSensor::sPySetHold1, METH_VARARGS, (PY_METHODCHAR)SetHold1_doc},
+ {"getHold2", (PyCFunction) SCA_KeyboardSensor::sPyGetHold2, METH_VARARGS, (PY_METHODCHAR)GetHold2_doc},
+ {"setHold2", (PyCFunction) SCA_KeyboardSensor::sPySetHold2, METH_VARARGS, (PY_METHODCHAR)SetHold2_doc},
+// {"getUseAllKeys", (PyCFunction) SCA_KeyboardSensor::sPyGetUseAllKeys, METH_VARARGS, (PY_METHODCHAR)GetUseAllKeys_doc},
+// {"setUseAllKeys", (PyCFunction) SCA_KeyboardSensor::sPySetUseAllKeys, METH_VARARGS, (PY_METHODCHAR)SetUseAllKeys_doc},
+ {"getPressedKeys", (PyCFunction) SCA_KeyboardSensor::sPyGetPressedKeys, METH_VARARGS, (PY_METHODCHAR)GetPressedKeys_doc},
+ {"getCurrentlyPressedKeys", (PyCFunction) SCA_KeyboardSensor::sPyGetCurrentlyPressedKeys, METH_VARARGS, (PY_METHODCHAR)GetCurrentlyPressedKeys_doc},
+// {"getKeyEvents", (PyCFunction) SCA_KeyboardSensor::sPyGetKeyEvents, METH_VARARGS, (PY_METHODCHAR)GetKeyEvents_doc},
{NULL,NULL} //Sentinel
};
diff --git a/source/gameengine/GameLogic/SCA_KeyboardSensor.h b/source/gameengine/GameLogic/SCA_KeyboardSensor.h
index e87eddecd32..b86f6931d27 100644
--- a/source/gameengine/GameLogic/SCA_KeyboardSensor.h
+++ b/source/gameengine/GameLogic/SCA_KeyboardSensor.h
@@ -114,6 +114,8 @@ public:
PyTypeObject* T=&Type );
virtual ~SCA_KeyboardSensor();
virtual CValue* GetReplica();
+ virtual void Init();
+
short int GetHotkey();
virtual bool Evaluate(CValue* event);
diff --git a/source/gameengine/GameLogic/SCA_LogicManager.cpp b/source/gameengine/GameLogic/SCA_LogicManager.cpp
index 9c9c7dadc52..b584b37180f 100644
--- a/source/gameengine/GameLogic/SCA_LogicManager.cpp
+++ b/source/gameengine/GameLogic/SCA_LogicManager.cpp
@@ -33,6 +33,7 @@
#include "SCA_IController.h"
#include "SCA_IActuator.h"
#include "SCA_EventManager.h"
+#include "SCA_PythonController.h"
#include <set>
#ifdef HAVE_CONFIG_H
@@ -48,6 +49,10 @@ SCA_LogicManager::SCA_LogicManager()
SCA_LogicManager::~SCA_LogicManager()
{
+ /* AddRef() is not used when the objects are added to m_mapStringToGameObjects
+ so Release() should not be used either. The memory leak big is fixed
+ in BL_ConvertBlenderObjects()
+
int numgameobj = m_mapStringToGameObjects.size();
for (int i = 0; i < numgameobj; i++)
{
@@ -55,8 +60,9 @@ SCA_LogicManager::~SCA_LogicManager()
assert(gameobjptr);
if (gameobjptr)
(*gameobjptr)->Release();
-
+
}
+ */
/*for (int i=0;i<m_sensorcontrollermap.size();i++)
{
vector<SCA_IController*>* controllerarray = *(m_sensorcontrollermap[i]);
@@ -69,6 +75,8 @@ SCA_LogicManager::~SCA_LogicManager()
}
m_eventmanagers.clear();
m_sensorcontrollermapje.clear();
+ m_removedActuators.clear();
+ m_activeActuators.clear();
}
@@ -120,12 +128,17 @@ void SCA_LogicManager::RegisterGameMeshName(const STR_String& gamemeshname, void
-void SCA_LogicManager::RegisterGameObj(CValue* gameobj, void* blendobj)
+void SCA_LogicManager::RegisterGameObj(void* blendobj, CValue* gameobj)
{
- m_map_gameobj_to_blendobj.insert(CHashedPtr(gameobj), blendobj);
+ m_map_blendobj_to_gameobj.insert(CHashedPtr(blendobj), gameobj);
}
-
+void SCA_LogicManager::UnregisterGameObj(void* blendobj, CValue* gameobj)
+{
+ void **obp = m_map_blendobj_to_gameobj[CHashedPtr(blendobj)];
+ if (obp && (CValue*)(*obp) == gameobj)
+ m_map_blendobj_to_gameobj.remove(CHashedPtr(blendobj));
+}
CValue* SCA_LogicManager::GetGameObjectByName(const STR_String& gameobjname)
{
@@ -139,10 +152,10 @@ CValue* SCA_LogicManager::GetGameObjectByName(const STR_String& gameobjname)
}
-void* SCA_LogicManager::FindBlendObjByGameObj(CValue* gameobject)
+CValue* SCA_LogicManager::FindGameObjByBlendObj(void* blendobj)
{
- void **obp= m_map_gameobj_to_blendobj[CHashedPtr(gameobject)];
- return obp?*obp:NULL;
+ void **obp= m_map_blendobj_to_gameobj[CHashedPtr(blendobj)];
+ return obp?(CValue*)(*obp):NULL;
}
@@ -158,15 +171,25 @@ void* SCA_LogicManager::FindBlendObjByGameMeshName(const STR_String& gamemeshnam
void SCA_LogicManager::RemoveSensor(SCA_ISensor* sensor)
{
- m_sensorcontrollermapje.erase(sensor);
-
- for (vector<SCA_EventManager*>::const_iterator ie=m_eventmanagers.begin();
- !(ie==m_eventmanagers.end());ie++)
+ controllerlist contlist = m_sensorcontrollermapje[sensor];
+ for (controllerlist::const_iterator c= contlist.begin();!(c==contlist.end());c++)
{
- (*ie)->RemoveSensor(sensor);
+ (*c)->UnlinkSensor(sensor);
}
+ m_sensorcontrollermapje.erase(sensor);
+ sensor->UnregisterToManager();
}
+void SCA_LogicManager::RemoveController(SCA_IController* controller)
+{
+ controller->UnlinkAllSensors();
+ controller->UnlinkAllActuators();
+ std::map<SCA_ISensor*,controllerlist>::iterator sit;
+ for (sit = m_sensorcontrollermapje.begin();!(sit==m_sensorcontrollermapje.end());++sit)
+ {
+ (*sit).second.remove(controller);
+ }
+}
void SCA_LogicManager::RemoveDestroyedActuator(SCA_IActuator* actuator)
@@ -210,8 +233,6 @@ void SCA_LogicManager::BeginFrame(double curtime, double fixedtime)
// for this frame, look up for activated sensors, and build the collection of triggered controllers
// int numsensors = this->m_activatedsensors.size(); /*unused*/
- set<SmartControllerPtr> triggeredControllerSet;
-
for (vector<SCA_ISensor*>::const_iterator is=m_activatedsensors.begin();
!(is==m_activatedsensors.end());is++)
{
@@ -221,19 +242,29 @@ void SCA_LogicManager::BeginFrame(double curtime, double fixedtime)
!(c==contlist.end());c++)
{
SCA_IController* contr = *c;//controllerarray->at(c);
- triggeredControllerSet.insert(SmartControllerPtr(contr,0));
+ if (contr->IsActive())
+ {
+ m_triggeredControllerSet.insert(SmartControllerPtr(contr,0));
+ // So that the controller knows which sensor has activited it.
+ // Only needed for the python controller though.
+ if (contr->GetType() == &SCA_PythonController::Type)
+ {
+ SCA_PythonController* pythonController = (SCA_PythonController*)contr;
+ pythonController->AddTriggeredSensor(sensor);
+ }
+ }
}
//sensor->SetActive(false);
}
// int numtriggered = triggeredControllerSet.size(); /*unused*/
- for (set<SmartControllerPtr>::iterator tit=triggeredControllerSet.begin();
- !(tit==triggeredControllerSet.end());tit++)
+ for (set<SmartControllerPtr>::iterator tit=m_triggeredControllerSet.begin();
+ !(tit==m_triggeredControllerSet.end());tit++)
{
(*tit)->Trigger(this);
}
- triggeredControllerSet.clear();
+ m_triggeredControllerSet.clear();
}
@@ -248,6 +279,10 @@ void SCA_LogicManager::UpdateFrame(double curtime, bool frame)
}
m_removedActuators.clear();
+ // About to run actuators, but before update the sensors for those which depends on actuators
+ for (vector<SCA_EventManager*>::const_iterator ie=m_eventmanagers.begin(); !(ie==m_eventmanagers.end()); ie++)
+ (*ie)->UpdateFrame();
+
for (set<SmartActuatorPtr>::iterator ia = m_activeActuators.begin();!(ia==m_activeActuators.end());ia++)
{
//SCA_IActuator* actua = *ia;
@@ -258,6 +293,16 @@ void SCA_LogicManager::UpdateFrame(double curtime, bool frame)
(*ia)->SetActive(false);
//m_activeactuators.pop_back();
+ } else if ((*ia)->IsNoLink())
+ {
+ // This actuator has no more links but it still active
+ // make sure it will get a negative event on next frame to stop it
+ // Do this check after Update() rather than before to make sure
+ // that all the actuators that are activated at same time than a state
+ // actuator have a chance to execute.
+ CValue* event = new CBoolValue(false);
+ (*ia)->RemoveAllEvents();
+ (*ia)->AddEvent(event);
}
}
@@ -345,6 +390,17 @@ void SCA_LogicManager::AddActivatedSensor(SCA_ISensor* sensor)
}
}
+void SCA_LogicManager::AddTriggeredController(SCA_IController* controller, SCA_ISensor* sensor)
+{
+ m_triggeredControllerSet.insert(SmartControllerPtr(controller,0));
+ // so that the controller knows which sensor has activited it
+ // only needed for python controller
+ if (controller->GetType() == &SCA_PythonController::Type)
+ {
+ SCA_PythonController* pythonController = (SCA_PythonController*)controller;
+ pythonController->AddTriggeredSensor(sensor);
+ }
+}
void SCA_LogicManager::AddActiveActuator(SCA_IActuator* actua,CValue* event)
diff --git a/source/gameengine/GameLogic/SCA_LogicManager.h b/source/gameengine/GameLogic/SCA_LogicManager.h
index 39d8b865977..50383879d8f 100644
--- a/source/gameengine/GameLogic/SCA_LogicManager.h
+++ b/source/gameengine/GameLogic/SCA_LogicManager.h
@@ -99,6 +99,7 @@ class SCA_LogicManager
vector<class SCA_ISensor*> m_activatedsensors;
set<class SmartActuatorPtr> m_activeActuators;
+ set<class SmartControllerPtr> m_triggeredControllerSet;
map<SCA_ISensor*,controllerlist > m_sensorcontrollermapje;
@@ -109,7 +110,7 @@ class SCA_LogicManager
GEN_Map<STR_HashedString,void*> m_mapStringToActions;
GEN_Map<STR_HashedString,void*> m_map_gamemeshname_to_blendobj;
- GEN_Map<CHashedPtr,void*> m_map_gameobj_to_blendobj;
+ GEN_Map<CHashedPtr,void*> m_map_blendobj_to_gameobj;
vector<SmartActuatorPtr> m_removedActuators;
public:
@@ -127,6 +128,7 @@ public:
void EndFrame();
void AddActivatedSensor(SCA_ISensor* sensor);
void AddActiveActuator(SCA_IActuator* sensor,class CValue* event);
+ void AddTriggeredController(SCA_IController* controller, SCA_ISensor* sensor);
SCA_EventManager* FindEventManager(int eventmgrtype);
void RemoveGameObject(const STR_String& gameobjname);
@@ -152,8 +154,9 @@ public:
void RegisterGameMeshName(const STR_String& gamemeshname, void* blendobj);
void* FindBlendObjByGameMeshName(const STR_String& gamemeshname);
- void RegisterGameObj(CValue* gameobj, void* blendobj);
- void* FindBlendObjByGameObj(CValue* gameobj);
+ void RegisterGameObj(void* blendobj, CValue* gameobj);
+ void UnregisterGameObj(void* blendobj, CValue* gameobj);
+ CValue* FindGameObjByBlendObj(void* blendobj);
};
#endif //__KX_LOGICMANAGER
diff --git a/source/gameengine/GameLogic/SCA_MouseManager.cpp b/source/gameengine/GameLogic/SCA_MouseManager.cpp
index b4251d8ab53..ca875dad07c 100644
--- a/source/gameengine/GameLogic/SCA_MouseManager.cpp
+++ b/source/gameengine/GameLogic/SCA_MouseManager.cpp
@@ -75,9 +75,10 @@ void SCA_MouseManager::NextFrame()
{
if (m_mousedevice)
{
- for (unsigned int i = 0; i < m_sensors.size(); i++)
+ set<SCA_ISensor*>::iterator it;
+ for (it=m_sensors.begin(); it!=m_sensors.end(); it++)
{
- SCA_MouseSensor* mousesensor = (SCA_MouseSensor*) m_sensors[i];
+ SCA_MouseSensor* mousesensor = (SCA_MouseSensor*)(*it);
// (0,0) is the Upper Left corner in our local window
// coordinates
if (!mousesensor->IsSuspended())
@@ -98,15 +99,6 @@ void SCA_MouseManager::NextFrame()
}
}
-
-
-void SCA_MouseManager::RegisterSensor(SCA_ISensor* keysensor)
-{
- m_sensors.push_back(keysensor);
-}
-
-
-
bool SCA_MouseManager::IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode)
{
/* We should guard for non-mouse events maybe? A rather silly side */
diff --git a/source/gameengine/GameLogic/SCA_MouseManager.h b/source/gameengine/GameLogic/SCA_MouseManager.h
index bc8254486ad..efa4c639ce7 100644
--- a/source/gameengine/GameLogic/SCA_MouseManager.h
+++ b/source/gameengine/GameLogic/SCA_MouseManager.h
@@ -62,7 +62,6 @@ public:
*/
bool IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode);
virtual void NextFrame();
- virtual void RegisterSensor(class SCA_ISensor* sensor);
SCA_IInputDevice* GetInputDevice();
};
diff --git a/source/gameengine/GameLogic/SCA_MouseSensor.cpp b/source/gameengine/GameLogic/SCA_MouseSensor.cpp
index a91cf3e0439..d4952ce4777 100644
--- a/source/gameengine/GameLogic/SCA_MouseSensor.cpp
+++ b/source/gameengine/GameLogic/SCA_MouseSensor.cpp
@@ -58,7 +58,6 @@ SCA_MouseSensor::SCA_MouseSensor(SCA_MouseManager* eventmgr,
{
m_mousemode = mousemode;
m_triggermode = true;
- m_val = 0; /* stores the latest attribute */
switch (m_mousemode) {
case KX_MOUSESENSORMODE_LEFTBUTTON:
@@ -79,7 +78,13 @@ SCA_MouseSensor::SCA_MouseSensor(SCA_MouseManager* eventmgr,
default:
; /* ignore, no hotkey */
}
+ Init();
+}
+void SCA_MouseSensor::Init()
+{
+ m_val = (m_invert)?1:0; /* stores the latest attribute */
+ m_reset = true;
}
SCA_MouseSensor::~SCA_MouseSensor()
@@ -91,9 +96,10 @@ SCA_MouseSensor::~SCA_MouseSensor()
CValue* SCA_MouseSensor::GetReplica()
{
- CValue* replica = new SCA_MouseSensor(*this);
+ SCA_MouseSensor* replica = new SCA_MouseSensor(*this);
// this will copy properties and so on...
CValue::AddDataToReplica(replica);
+ replica->Init();
return replica;
}
@@ -128,6 +134,7 @@ SCA_IInputDevice::KX_EnumInputs SCA_MouseSensor::GetHotKey()
bool SCA_MouseSensor::Evaluate(CValue* event)
{
bool result = false;
+ bool reset = m_reset && m_level;
SCA_IInputDevice* mousedev = m_pMouseMgr->GetInputDevice();
@@ -139,7 +146,7 @@ bool SCA_MouseSensor::Evaluate(CValue* event)
/* both MOUSEX and MOUSEY. Treat all of these as key-presses. */
/* So, treat KX_MOUSESENSORMODE_POSITION as */
/* KX_MOUSESENSORMODE_POSITIONX || KX_MOUSESENSORMODE_POSITIONY */
-
+ m_reset = false;
switch (m_mousemode) {
case KX_MOUSESENSORMODE_LEFTBUTTON:
case KX_MOUSESENSORMODE_MIDDLEBUTTON:
@@ -158,6 +165,26 @@ bool SCA_MouseSensor::Evaluate(CValue* event)
{
m_val = 0;
result = true;
+ } else
+ {
+ if (event.m_status == SCA_InputEvent::KX_ACTIVE)
+ {
+ if (m_val == 0)
+ {
+ m_val = 1;
+ if (m_level)
+ {
+ result = true;
+ }
+ }
+ } else
+ {
+ if (m_val == 1)
+ {
+ m_val = 0;
+ result = true;
+ }
+ }
}
}
break;
@@ -183,6 +210,13 @@ bool SCA_MouseSensor::Evaluate(CValue* event)
{
m_val = 0;
result = true;
+ } else
+ {
+ if (m_val == 1)
+ {
+ m_val = 0;
+ result = true;
+ }
}
}
break;
@@ -191,6 +225,9 @@ bool SCA_MouseSensor::Evaluate(CValue* event)
; /* error */
}
+ if (reset)
+ // force an event
+ result = true;
return result;
}
@@ -246,8 +283,8 @@ PyParentObject SCA_MouseSensor::Parents[] = {
};
PyMethodDef SCA_MouseSensor::Methods[] = {
- {"getXPosition", (PyCFunction) SCA_MouseSensor::sPyGetXPosition, METH_VARARGS, GetXPosition_doc},
- {"getYPosition", (PyCFunction) SCA_MouseSensor::sPyGetYPosition, METH_VARARGS, GetYPosition_doc},
+ {"getXPosition", (PyCFunction) SCA_MouseSensor::sPyGetXPosition, METH_VARARGS, (PY_METHODCHAR)GetXPosition_doc},
+ {"getYPosition", (PyCFunction) SCA_MouseSensor::sPyGetYPosition, METH_VARARGS, (PY_METHODCHAR)GetYPosition_doc},
{NULL,NULL} //Sentinel
};
@@ -256,7 +293,7 @@ PyObject* SCA_MouseSensor::_getattr(const STR_String& attr) {
}
/* get x position ---------------------------------------------------------- */
-char SCA_MouseSensor::GetXPosition_doc[] =
+const char SCA_MouseSensor::GetXPosition_doc[] =
"getXPosition\n"
"\tReturns the x-coordinate of the mouse sensor, in frame coordinates.\n"
"\tThe lower-left corner is the origin. The coordinate is given in\n"
@@ -268,7 +305,7 @@ PyObject* SCA_MouseSensor::PyGetXPosition(PyObject* self,
}
/* get y position ---------------------------------------------------------- */
-char SCA_MouseSensor::GetYPosition_doc[] =
+const char SCA_MouseSensor::GetYPosition_doc[] =
"getYPosition\n"
"\tReturns the y-coordinate of the mouse sensor, in frame coordinates.\n"
"\tThe lower-left corner is the origin. The coordinate is given in\n"
diff --git a/source/gameengine/GameLogic/SCA_MouseSensor.h b/source/gameengine/GameLogic/SCA_MouseSensor.h
index 86c9d96a800..26a1c5e3fd2 100644
--- a/source/gameengine/GameLogic/SCA_MouseSensor.h
+++ b/source/gameengine/GameLogic/SCA_MouseSensor.h
@@ -96,7 +96,7 @@ class SCA_MouseSensor : public SCA_ISensor
virtual ~SCA_MouseSensor();
virtual CValue* GetReplica();
virtual bool Evaluate(CValue* event);
-
+ virtual void Init();
virtual bool IsPositiveTrigger();
short int GetModeKey();
SCA_IInputDevice::KX_EnumInputs GetHotKey();
diff --git a/source/gameengine/GameLogic/SCA_NANDController.cpp b/source/gameengine/GameLogic/SCA_NANDController.cpp
new file mode 100644
index 00000000000..5b869ee8298
--- /dev/null
+++ b/source/gameengine/GameLogic/SCA_NANDController.cpp
@@ -0,0 +1,144 @@
+/**
+ * 'Nand' together all inputs
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "SCA_NANDController.h"
+#include "SCA_ISensor.h"
+#include "SCA_LogicManager.h"
+#include "BoolValue.h"
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/* ------------------------------------------------------------------------- */
+/* Native functions */
+/* ------------------------------------------------------------------------- */
+
+SCA_NANDController::SCA_NANDController(SCA_IObject* gameobj,
+ PyTypeObject* T)
+ :
+ SCA_IController(gameobj,T)
+{
+}
+
+
+
+SCA_NANDController::~SCA_NANDController()
+{
+}
+
+
+
+void SCA_NANDController::Trigger(SCA_LogicManager* logicmgr)
+{
+
+ bool sensorresult = false;
+
+ for (vector<SCA_ISensor*>::const_iterator is=m_linkedsensors.begin();
+ !(is==m_linkedsensors.end());is++)
+ {
+ SCA_ISensor* sensor = *is;
+ if (!sensor->IsPositiveTrigger())
+ {
+ sensorresult = true;
+ break;
+ }
+ }
+
+ CValue* newevent = new CBoolValue(sensorresult);
+
+ for (vector<SCA_IActuator*>::const_iterator i=m_linkedactuators.begin();
+ !(i==m_linkedactuators.end());i++)
+ {
+ SCA_IActuator* actua = *i;//m_linkedactuators.at(i);
+ logicmgr->AddActiveActuator(actua,newevent);
+ }
+
+ // every actuator that needs the event, has a it's own reference to it now so
+ // release it (so to be clear: if there is no actuator, it's deleted right now)
+ newevent->Release();
+
+}
+
+
+
+CValue* SCA_NANDController::GetReplica()
+{
+ CValue* replica = new SCA_NANDController(*this);
+ // this will copy properties and so on...
+ CValue::AddDataToReplica(replica);
+
+ return replica;
+}
+
+
+
+/* ------------------------------------------------------------------------- */
+/* Python functions */
+/* ------------------------------------------------------------------------- */
+
+/* Integration hooks ------------------------------------------------------- */
+PyTypeObject SCA_NANDController::Type = {
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0,
+ "SCA_NANDController",
+ sizeof(SCA_NANDController),
+ 0,
+ PyDestructor,
+ 0,
+ __getattr,
+ __setattr,
+ 0, //&MyPyCompare,
+ __repr,
+ 0, //&cvalue_as_number,
+ 0,
+ 0,
+ 0,
+ 0
+};
+
+PyParentObject SCA_NANDController::Parents[] = {
+ &SCA_NANDController::Type,
+ &SCA_IController::Type,
+ &SCA_ILogicBrick::Type,
+ &CValue::Type,
+ NULL
+};
+
+PyMethodDef SCA_NANDController::Methods[] = {
+ {NULL,NULL} //Sentinel
+};
+
+PyObject* SCA_NANDController::_getattr(const STR_String& attr) {
+ _getattr_up(SCA_IController);
+}
+
+/* eof */
diff --git a/source/gameengine/GameLogic/SCA_NANDController.h b/source/gameengine/GameLogic/SCA_NANDController.h
new file mode 100644
index 00000000000..1193ff64f07
--- /dev/null
+++ b/source/gameengine/GameLogic/SCA_NANDController.h
@@ -0,0 +1,56 @@
+/**
+ * SCA_NANDController.h
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __KX_NANDCONTROLLER
+#define __KX_NANDCONTROLLER
+
+#include "SCA_IController.h"
+
+class SCA_NANDController : public SCA_IController
+{
+ Py_Header;
+ //virtual void Trigger(class SCA_LogicManager* logicmgr);
+public:
+ SCA_NANDController(SCA_IObject* gameobj,PyTypeObject* T=&Type);
+ virtual ~SCA_NANDController();
+ virtual CValue* GetReplica();
+ virtual void Trigger(SCA_LogicManager* logicmgr);
+
+ /* --------------------------------------------------------------------- */
+ /* Python interface ---------------------------------------------------- */
+ /* --------------------------------------------------------------------- */
+
+ virtual PyObject* _getattr(const STR_String& attr);
+
+};
+
+#endif //__KX_NANDCONTROLLER
+
diff --git a/source/gameengine/GameLogic/SCA_NORController.cpp b/source/gameengine/GameLogic/SCA_NORController.cpp
new file mode 100644
index 00000000000..2866dec0b74
--- /dev/null
+++ b/source/gameengine/GameLogic/SCA_NORController.cpp
@@ -0,0 +1,144 @@
+/**
+ * 'Nor' together all inputs
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "SCA_NORController.h"
+#include "SCA_ISensor.h"
+#include "SCA_LogicManager.h"
+#include "BoolValue.h"
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/* ------------------------------------------------------------------------- */
+/* Native functions */
+/* ------------------------------------------------------------------------- */
+
+SCA_NORController::SCA_NORController(SCA_IObject* gameobj,
+ PyTypeObject* T)
+ :
+ SCA_IController(gameobj,T)
+{
+}
+
+
+
+SCA_NORController::~SCA_NORController()
+{
+}
+
+
+
+void SCA_NORController::Trigger(SCA_LogicManager* logicmgr)
+{
+
+ bool sensorresult = true;
+
+ for (vector<SCA_ISensor*>::const_iterator is=m_linkedsensors.begin();
+ !(is==m_linkedsensors.end());is++)
+ {
+ SCA_ISensor* sensor = *is;
+ if (sensor->IsPositiveTrigger())
+ {
+ sensorresult = false;
+ break;
+ }
+ }
+
+ CValue* newevent = new CBoolValue(sensorresult);
+
+ for (vector<SCA_IActuator*>::const_iterator i=m_linkedactuators.begin();
+ !(i==m_linkedactuators.end());i++)
+ {
+ SCA_IActuator* actua = *i;//m_linkedactuators.at(i);
+ logicmgr->AddActiveActuator(actua,newevent);
+ }
+
+ // every actuator that needs the event, has a it's own reference to it now so
+ // release it (so to be clear: if there is no actuator, it's deleted right now)
+ newevent->Release();
+
+}
+
+
+
+CValue* SCA_NORController::GetReplica()
+{
+ CValue* replica = new SCA_NORController(*this);
+ // this will copy properties and so on...
+ CValue::AddDataToReplica(replica);
+
+ return replica;
+}
+
+
+
+/* ------------------------------------------------------------------------- */
+/* Python functions */
+/* ------------------------------------------------------------------------- */
+
+/* Integration hooks ------------------------------------------------------- */
+PyTypeObject SCA_NORController::Type = {
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0,
+ "SCA_NORController",
+ sizeof(SCA_NORController),
+ 0,
+ PyDestructor,
+ 0,
+ __getattr,
+ __setattr,
+ 0, //&MyPyCompare,
+ __repr,
+ 0, //&cvalue_as_number,
+ 0,
+ 0,
+ 0,
+ 0
+};
+
+PyParentObject SCA_NORController::Parents[] = {
+ &SCA_NORController::Type,
+ &SCA_IController::Type,
+ &SCA_ILogicBrick::Type,
+ &CValue::Type,
+ NULL
+};
+
+PyMethodDef SCA_NORController::Methods[] = {
+ {NULL,NULL} //Sentinel
+};
+
+PyObject* SCA_NORController::_getattr(const STR_String& attr) {
+ _getattr_up(SCA_IController);
+}
+
+/* eof */
diff --git a/source/gameengine/GameLogic/SCA_NORController.h b/source/gameengine/GameLogic/SCA_NORController.h
new file mode 100644
index 00000000000..aab59e3d46c
--- /dev/null
+++ b/source/gameengine/GameLogic/SCA_NORController.h
@@ -0,0 +1,56 @@
+/**
+ * SCA_NORController.h
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __KX_NORCONTROLLER
+#define __KX_NORCONTROLLER
+
+#include "SCA_IController.h"
+
+class SCA_NORController : public SCA_IController
+{
+ Py_Header;
+ //virtual void Trigger(class SCA_LogicManager* logicmgr);
+public:
+ SCA_NORController(SCA_IObject* gameobj,PyTypeObject* T=&Type);
+ virtual ~SCA_NORController();
+ virtual CValue* GetReplica();
+ virtual void Trigger(SCA_LogicManager* logicmgr);
+
+ /* --------------------------------------------------------------------- */
+ /* Python interface ---------------------------------------------------- */
+ /* --------------------------------------------------------------------- */
+
+ virtual PyObject* _getattr(const STR_String& attr);
+
+};
+
+#endif //__KX_NORCONTROLLER
+
diff --git a/source/gameengine/GameLogic/SCA_PropertyActuator.cpp b/source/gameengine/GameLogic/SCA_PropertyActuator.cpp
index 1ee32e64b6c..3b541e87f02 100644
--- a/source/gameengine/GameLogic/SCA_PropertyActuator.cpp
+++ b/source/gameengine/GameLogic/SCA_PropertyActuator.cpp
@@ -42,17 +42,23 @@
/* Native functions */
/* ------------------------------------------------------------------------- */
-SCA_PropertyActuator::SCA_PropertyActuator(SCA_IObject* gameobj,CValue* sourceObj,const STR_String& propname,const STR_String& expr,int acttype,PyTypeObject* T )
+SCA_PropertyActuator::SCA_PropertyActuator(SCA_IObject* gameobj,SCA_IObject* sourceObj,const STR_String& propname,const STR_String& expr,int acttype,PyTypeObject* T )
: SCA_IActuator(gameobj,T),
m_type(acttype),
m_propname(propname),
m_exprtxt(expr),
m_sourceObj(sourceObj)
{
+ // protect ourselves against someone else deleting the source object
+ // don't protect against ourselves: it would create a dead lock
+ if (m_sourceObj)
+ m_sourceObj->RegisterActuator(this);
}
SCA_PropertyActuator::~SCA_PropertyActuator()
{
+ if (m_sourceObj)
+ m_sourceObj->UnregisterActuator(this);
}
bool SCA_PropertyActuator::Update()
@@ -87,12 +93,11 @@ bool SCA_PropertyActuator::Update()
if (oldprop)
{
oldprop->SetValue(newval);
- newval->Release();
} else
{
propowner->SetProperty(m_propname,newval);
}
-
+ newval->Release();
break;
}
case KX_ACT_PROP_ADD:
@@ -120,9 +125,11 @@ bool SCA_PropertyActuator::Update()
CValue* copyprop = m_sourceObj->GetProperty(m_exprtxt);
if (copyprop)
{
+ CValue *val = copyprop->GetReplica();
GetParent()->SetProperty(
m_propname,
- copyprop->GetReplica());
+ val);
+ val->Release();
}
}
@@ -173,7 +180,36 @@ GetReplica() {
};
+void SCA_PropertyActuator::ProcessReplica()
+{
+ // no need to check for self reference like in the constructor:
+ // the replica will always have a different parent
+ if (m_sourceObj)
+ m_sourceObj->RegisterActuator(this);
+ SCA_IActuator::ProcessReplica();
+}
+bool SCA_PropertyActuator::UnlinkObject(SCA_IObject* clientobj)
+{
+ if (clientobj == m_sourceObj)
+ {
+ // this object is being deleted, we cannot continue to track it.
+ m_sourceObj = NULL;
+ return true;
+ }
+ return false;
+}
+
+void SCA_PropertyActuator::Relink(GEN_Map<GEN_HashedPtr, void*> *obj_map)
+{
+ void **h_obj = (*obj_map)[m_sourceObj];
+ if (h_obj) {
+ if (m_sourceObj)
+ m_sourceObj->UnregisterActuator(this);
+ m_sourceObj = (SCA_IObject*)(*h_obj);
+ m_sourceObj->RegisterActuator(this);
+ }
+}
/* ------------------------------------------------------------------------- */
@@ -209,10 +245,10 @@ PyParentObject SCA_PropertyActuator::Parents[] = {
};
PyMethodDef SCA_PropertyActuator::Methods[] = {
- {"setProperty", (PyCFunction) SCA_PropertyActuator::sPySetProperty, METH_VARARGS, SetProperty_doc},
- {"getProperty", (PyCFunction) SCA_PropertyActuator::sPyGetProperty, METH_VARARGS, GetProperty_doc},
- {"setValue", (PyCFunction) SCA_PropertyActuator::sPySetValue, METH_VARARGS, SetValue_doc},
- {"getValue", (PyCFunction) SCA_PropertyActuator::sPyGetValue, METH_VARARGS, GetValue_doc},
+ {"setProperty", (PyCFunction) SCA_PropertyActuator::sPySetProperty, METH_VARARGS, (PY_METHODCHAR)SetProperty_doc},
+ {"getProperty", (PyCFunction) SCA_PropertyActuator::sPyGetProperty, METH_VARARGS, (PY_METHODCHAR)GetProperty_doc},
+ {"setValue", (PyCFunction) SCA_PropertyActuator::sPySetValue, METH_VARARGS, (PY_METHODCHAR)SetValue_doc},
+ {"getValue", (PyCFunction) SCA_PropertyActuator::sPyGetValue, METH_VARARGS, (PY_METHODCHAR)GetValue_doc},
{NULL,NULL} //Sentinel
};
@@ -221,7 +257,7 @@ PyObject* SCA_PropertyActuator::_getattr(const STR_String& attr) {
}
/* 1. setProperty */
-char SCA_PropertyActuator::SetProperty_doc[] =
+const char SCA_PropertyActuator::SetProperty_doc[] =
"setProperty(name)\n"
"\t- name: string\n"
"\tSet the property on which to operate. If there is no property\n"
@@ -236,17 +272,18 @@ PyObject* SCA_PropertyActuator::PySetProperty(PyObject* self, PyObject* args, Py
CValue* prop = GetParent()->FindIdentifier(nameArg);
- if (prop) {
+ if (!prop->IsError()) {
m_propname = nameArg;
} else {
; /* not found ... */
}
+ prop->Release();
Py_Return;
}
/* 2. getProperty */
-char SCA_PropertyActuator::GetProperty_doc[] =
+const char SCA_PropertyActuator::GetProperty_doc[] =
"getProperty(name)\n"
"\tReturn the property on which the actuator operates.\n";
PyObject* SCA_PropertyActuator::PyGetProperty(PyObject* self, PyObject* args, PyObject* kwds)
@@ -255,7 +292,7 @@ PyObject* SCA_PropertyActuator::PyGetProperty(PyObject* self, PyObject* args, Py
}
/* 3. setValue */
-char SCA_PropertyActuator::SetValue_doc[] =
+const char SCA_PropertyActuator::SetValue_doc[] =
"setValue(value)\n"
"\t- value: string\n"
"\tSet the value with which the actuator operates. If the value\n"
@@ -274,7 +311,7 @@ PyObject* SCA_PropertyActuator::PySetValue(PyObject* self, PyObject* args, PyObj
}
/* 4. getValue */
-char SCA_PropertyActuator::GetValue_doc[] =
+const char SCA_PropertyActuator::GetValue_doc[] =
"getValue()\n"
"\tReturns the value with which the actuator operates.\n";
PyObject* SCA_PropertyActuator::PyGetValue(PyObject* self, PyObject* args, PyObject* kwds)
diff --git a/source/gameengine/GameLogic/SCA_PropertyActuator.h b/source/gameengine/GameLogic/SCA_PropertyActuator.h
index 05a7cfbc501..1e435684572 100644
--- a/source/gameengine/GameLogic/SCA_PropertyActuator.h
+++ b/source/gameengine/GameLogic/SCA_PropertyActuator.h
@@ -52,7 +52,7 @@ class SCA_PropertyActuator : public SCA_IActuator
int m_type;
STR_String m_propname;
STR_String m_exprtxt;
- CValue* m_sourceObj; // for copy property actuator
+ SCA_IObject* m_sourceObj; // for copy property actuator
public:
@@ -60,7 +60,7 @@ public:
SCA_PropertyActuator(
SCA_IObject* gameobj,
- CValue* sourceObj,
+ SCA_IObject* sourceObj,
const STR_String& propname,
const STR_String& expr,
int acttype,
@@ -74,6 +74,10 @@ public:
GetReplica(
);
+ virtual void ProcessReplica();
+ virtual bool UnlinkObject(SCA_IObject* clientobj);
+ virtual void Relink(GEN_Map<GEN_HashedPtr, void*> *obj_map);
+
virtual bool
Update();
diff --git a/source/gameengine/GameLogic/SCA_PropertyEventManager.cpp b/source/gameengine/GameLogic/SCA_PropertyEventManager.cpp
index fc56d101728..e5e3f9cced5 100644
--- a/source/gameengine/GameLogic/SCA_PropertyEventManager.cpp
+++ b/source/gameengine/GameLogic/SCA_PropertyEventManager.cpp
@@ -47,19 +47,10 @@ SCA_PropertyEventManager::~SCA_PropertyEventManager()
}
-
-
-void SCA_PropertyEventManager::RegisterSensor(SCA_ISensor* sensor)
-{
- m_sensors.push_back(sensor);
-}
-
-
-
void SCA_PropertyEventManager::NextFrame()
{
// check for changed properties
- for (vector<SCA_ISensor*>::const_iterator it = m_sensors.begin();!(it==m_sensors.end());it++)
+ for (set<SCA_ISensor*>::const_iterator it = m_sensors.begin();!(it==m_sensors.end());it++)
{
(*it)->Activate(m_logicmgr,NULL);
}
diff --git a/source/gameengine/GameLogic/SCA_PropertyEventManager.h b/source/gameengine/GameLogic/SCA_PropertyEventManager.h
index aaa303a52c8..f166065b198 100644
--- a/source/gameengine/GameLogic/SCA_PropertyEventManager.h
+++ b/source/gameengine/GameLogic/SCA_PropertyEventManager.h
@@ -43,7 +43,6 @@ public:
SCA_PropertyEventManager(class SCA_LogicManager* logicmgr);
virtual ~SCA_PropertyEventManager();
virtual void NextFrame();
- virtual void RegisterSensor(SCA_ISensor* sensor);
//SCA_LogicManager* GetLogicManager() { return m_logicmgr;}
};
diff --git a/source/gameengine/GameLogic/SCA_PropertySensor.cpp b/source/gameengine/GameLogic/SCA_PropertySensor.cpp
index 21ec6d39c08..64e3d49c6cb 100644
--- a/source/gameengine/GameLogic/SCA_PropertySensor.cpp
+++ b/source/gameengine/GameLogic/SCA_PropertySensor.cpp
@@ -54,47 +54,65 @@ SCA_PropertySensor::SCA_PropertySensor(SCA_EventManager* eventmgr,
m_checkpropval(propval),
m_checkpropmaxval(propmaxval),
m_checkpropname(propname),
- m_lastresult(false),
m_range_expr(NULL)
{
- m_recentresult=false;
//CParser pars;
//pars.SetContext(this->AddRef());
//CValue* resultval = m_rightexpr->Calculate();
CValue* orgprop = GetParent()->FindIdentifier(m_checkpropname);
- if (orgprop)
+ if (!orgprop->IsError())
{
m_previoustext = orgprop->GetText();
- orgprop->Release();
}
+ orgprop->Release();
if (m_checktype==KX_PROPSENSOR_INTERVAL)
{
PrecalculateRangeExpression();
}
+ Init();
+}
+void SCA_PropertySensor::Init()
+{
+ m_recentresult = false;
+ m_lastresult = m_invert?true:false;
+ m_reset = true;
}
void SCA_PropertySensor::PrecalculateRangeExpression()
{
CParser pars;
+ //The context is needed to retrieve the property at runtime but it creates
+ //loop of references
pars.SetContext(this->AddRef());
STR_String checkstr = "(" + m_checkpropval + " <= "
+ m_checkpropname + ") && ( "
+ m_checkpropname + " <= "
- + m_checkpropmaxval;
+ + m_checkpropmaxval + ")";
m_range_expr = pars.ProcessText(checkstr);
}
-
+// Forced deletion of precalculated range expression to break reference loop
+// Use this function when you know that you won't use the sensor anymore
+void SCA_PropertySensor::Delete()
+{
+ if (m_range_expr)
+ {
+ m_range_expr->Release();
+ m_range_expr = NULL;
+ }
+ Release();
+}
CValue* SCA_PropertySensor::GetReplica()
{
SCA_PropertySensor* replica = new SCA_PropertySensor(*this);
// m_range_expr must be recalculated on replica!
CValue::AddDataToReplica(replica);
+ replica->Init();
replica->m_range_expr = NULL;
if (replica->m_checktype==KX_PROPSENSOR_INTERVAL)
@@ -137,14 +155,15 @@ SCA_PropertySensor::~SCA_PropertySensor()
bool SCA_PropertySensor::Evaluate(CValue* event)
{
bool result = CheckPropertyCondition();
+ bool reset = m_reset && m_level;
+ m_reset = false;
if (m_lastresult!=result)
{
m_lastresult = result;
return true;
}
-
- return false;
+ return (reset) ? true : false;
}
@@ -161,7 +180,7 @@ bool SCA_PropertySensor::CheckPropertyCondition()
case KX_PROPSENSOR_EQUAL:
{
CValue* orgprop = GetParent()->FindIdentifier(m_checkpropname);
- if (orgprop)
+ if (!orgprop->IsError())
{
STR_String testprop = orgprop->GetText();
// Force strings to upper case, to avoid confusion in
@@ -174,9 +193,8 @@ bool SCA_PropertySensor::CheckPropertyCondition()
} else {
result = (orgprop->GetText() == m_checkpropval);
}
- orgprop->Release();
-
}
+ orgprop->Release();
if (reverse)
result = !result;
@@ -241,15 +259,15 @@ bool SCA_PropertySensor::CheckPropertyCondition()
{
CValue* orgprop = GetParent()->FindIdentifier(m_checkpropname);
- if (orgprop)
+ if (!orgprop->IsError())
{
if (m_previoustext != orgprop->GetText())
{
m_previoustext = orgprop->GetText();
result = true;
}
- orgprop->Release();
}
+ orgprop->Release();
//cout << " \nSens:Prop:changed!"; /* need implementation here!!! */
break;
@@ -315,12 +333,12 @@ PyParentObject SCA_PropertySensor::Parents[] = {
};
PyMethodDef SCA_PropertySensor::Methods[] = {
- {"getType", (PyCFunction) SCA_PropertySensor::sPyGetType, METH_VARARGS, GetType_doc},
- {"setType", (PyCFunction) SCA_PropertySensor::sPySetType, METH_VARARGS, SetType_doc},
- {"getProperty", (PyCFunction) SCA_PropertySensor::sPyGetProperty, METH_VARARGS, GetProperty_doc},
- {"setProperty", (PyCFunction) SCA_PropertySensor::sPySetProperty, METH_VARARGS, SetProperty_doc},
- {"getValue", (PyCFunction) SCA_PropertySensor::sPyGetValue, METH_VARARGS, GetValue_doc},
- {"setValue", (PyCFunction) SCA_PropertySensor::sPySetValue, METH_VARARGS, SetValue_doc},
+ {"getType", (PyCFunction) SCA_PropertySensor::sPyGetType, METH_VARARGS, (PY_METHODCHAR)GetType_doc},
+ {"setType", (PyCFunction) SCA_PropertySensor::sPySetType, METH_VARARGS, (PY_METHODCHAR)SetType_doc},
+ {"getProperty", (PyCFunction) SCA_PropertySensor::sPyGetProperty, METH_VARARGS, (PY_METHODCHAR)GetProperty_doc},
+ {"setProperty", (PyCFunction) SCA_PropertySensor::sPySetProperty, METH_VARARGS, (PY_METHODCHAR)SetProperty_doc},
+ {"getValue", (PyCFunction) SCA_PropertySensor::sPyGetValue, METH_VARARGS, (PY_METHODCHAR)GetValue_doc},
+ {"setValue", (PyCFunction) SCA_PropertySensor::sPySetValue, METH_VARARGS, (PY_METHODCHAR)SetValue_doc},
{NULL,NULL} //Sentinel
};
@@ -329,7 +347,7 @@ PyObject* SCA_PropertySensor::_getattr(const STR_String& attr) {
}
/* 1. getType */
-char SCA_PropertySensor::GetType_doc[] =
+const char SCA_PropertySensor::GetType_doc[] =
"getType()\n"
"\tReturns the type of check this sensor performs.\n";
PyObject* SCA_PropertySensor::PyGetType(PyObject* self, PyObject* args, PyObject* kwds)
@@ -338,7 +356,7 @@ PyObject* SCA_PropertySensor::PyGetType(PyObject* self, PyObject* args, PyObject
}
/* 2. setType */
-char SCA_PropertySensor::SetType_doc[] =
+const char SCA_PropertySensor::SetType_doc[] =
"setType(type)\n"
"\t- type: KX_PROPSENSOR_EQUAL, KX_PROPSENSOR_NOTEQUAL,\n"
"\t KX_PROPSENSOR_INTERVAL, KX_PROPSENSOR_CHANGED,\n"
@@ -361,7 +379,7 @@ PyObject* SCA_PropertySensor::PySetType(PyObject* self, PyObject* args, PyObject
}
/* 3. getProperty */
-char SCA_PropertySensor::GetProperty_doc[] =
+const char SCA_PropertySensor::GetProperty_doc[] =
"getProperty()\n"
"\tReturn the property with which the sensor operates.\n";
PyObject* SCA_PropertySensor::PyGetProperty(PyObject* self, PyObject* args, PyObject* kwds)
@@ -370,7 +388,7 @@ PyObject* SCA_PropertySensor::PyGetProperty(PyObject* self, PyObject* args, PyOb
}
/* 4. setProperty */
-char SCA_PropertySensor::SetProperty_doc[] =
+const char SCA_PropertySensor::SetProperty_doc[] =
"setProperty(name)\n"
"\t- name: string\n"
"\tSets the property with which to operate. If there is no property\n"
@@ -385,17 +403,18 @@ PyObject* SCA_PropertySensor::PySetProperty(PyObject* self, PyObject* args, PyOb
return NULL;
}
- if (FindIdentifier(STR_String(propNameArg))) {
+ CValue *prop = FindIdentifier(STR_String(propNameArg));
+ if (!prop->IsError()) {
m_checkpropname = propNameArg;
} else {
; /* error: bad property name */
}
-
+ prop->Release();
Py_Return;
}
/* 5. getValue */
-char SCA_PropertySensor::GetValue_doc[] =
+const char SCA_PropertySensor::GetValue_doc[] =
"getValue()\n"
"\tReturns the value with which the sensor operates.\n";
PyObject* SCA_PropertySensor::PyGetValue(PyObject* self, PyObject* args, PyObject* kwds)
@@ -404,7 +423,7 @@ PyObject* SCA_PropertySensor::PyGetValue(PyObject* self, PyObject* args, PyObjec
}
/* 6. setValue */
-char SCA_PropertySensor::SetValue_doc[] =
+const char SCA_PropertySensor::SetValue_doc[] =
"setValue(value)\n"
"\t- value: string\n"
"\tSet the value with which the sensor operates. If the value\n"
diff --git a/source/gameengine/GameLogic/SCA_PropertySensor.h b/source/gameengine/GameLogic/SCA_PropertySensor.h
index e1e27684ecc..6871cb3afdc 100644
--- a/source/gameengine/GameLogic/SCA_PropertySensor.h
+++ b/source/gameengine/GameLogic/SCA_PropertySensor.h
@@ -74,8 +74,10 @@ public:
KX_PROPSENSOR_TYPE checktype,
PyTypeObject* T=&Type );
+ virtual void Delete();
virtual ~SCA_PropertySensor();
virtual CValue* GetReplica();
+ virtual void Init();
void PrecalculateRangeExpression();
bool CheckPropertyCondition();
diff --git a/source/gameengine/GameLogic/SCA_PythonController.cpp b/source/gameengine/GameLogic/SCA_PythonController.cpp
index 44cdc0a7de5..c354ab39747 100644
--- a/source/gameengine/GameLogic/SCA_PythonController.cpp
+++ b/source/gameengine/GameLogic/SCA_PythonController.cpp
@@ -33,8 +33,11 @@
#include "SCA_LogicManager.h"
#include "SCA_ISensor.h"
#include "SCA_IActuator.h"
+#include "PyObjectPlus.h"
#include "compile.h"
#include "eval.h"
+#include <algorithm>
+
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -116,7 +119,7 @@ CValue* SCA_PythonController::GetReplica()
void SCA_PythonController::SetScriptText(const STR_String& text)
{
- m_scriptText = "import GameLogic\n" + text;
+ m_scriptText = text;
m_bModified = true;
}
@@ -139,28 +142,33 @@ void SCA_PythonController::SetDictionary(PyObject* pythondictionary)
m_pythondictionary = PyDict_Copy(pythondictionary); /* new reference */
}
+int SCA_PythonController::IsTriggered(class SCA_ISensor* sensor)
+{
+ if (std::find(m_triggeredSensors.begin(), m_triggeredSensors.end(), sensor) !=
+ m_triggeredSensors.end())
+ return 1;
+ return 0;
+}
+
#if 0
-static char* sPyGetCurrentController__doc__;
+static const char* sPyGetCurrentController__doc__;
#endif
-PyObject* SCA_PythonController::sPyGetCurrentController(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* SCA_PythonController::sPyGetCurrentController(PyObject* self)
{
m_sCurrentController->AddRef();
return m_sCurrentController;
}
#if 0
-static char* sPyAddActiveActuator__doc__;
+static const char* sPyAddActiveActuator__doc__;
#endif
PyObject* SCA_PythonController::sPyAddActiveActuator(
PyObject* self,
- PyObject* args,
- PyObject* kwds)
+ PyObject* args)
{
PyObject* ob1;
@@ -187,14 +195,13 @@ PyObject* SCA_PythonController::sPyAddActiveActuator(
m_sCurrentLogicManager->AddActiveActuator((SCA_IActuator*)act,boolval);
boolval->Release();
}
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
-char* SCA_PythonController::sPyGetCurrentController__doc__ = "getCurrentController()";
-char* SCA_PythonController::sPyAddActiveActuator__doc__= "addActiveActuator(actuator,bool)";
-char SCA_PythonController::GetActuators_doc[] = "getActuator";
+const char* SCA_PythonController::sPyGetCurrentController__doc__ = "getCurrentController()";
+const char* SCA_PythonController::sPyAddActiveActuator__doc__= "addActiveActuator(actuator,bool)";
+const char SCA_PythonController::GetActuators_doc[] = "getActuator";
PyTypeObject SCA_PythonController::Type = {
PyObject_HEAD_INIT(&PyType_Type)
@@ -222,16 +229,13 @@ PyParentObject SCA_PythonController::Parents[] = {
NULL
};
PyMethodDef SCA_PythonController::Methods[] = {
- {"getActuators", (PyCFunction) SCA_PythonController::sPyGetActuators,
- METH_VARARGS, SCA_PythonController::GetActuators_doc},
- {"getActuator", (PyCFunction) SCA_PythonController::sPyGetActuator,
- METH_VARARGS, SCA_PythonController::GetActuator_doc},
- {"getSensors", (PyCFunction) SCA_PythonController::sPyGetSensors,
- METH_VARARGS, SCA_PythonController::GetSensors_doc},
- {"getSensor", (PyCFunction) SCA_PythonController::sPyGetSensor,
- METH_VARARGS, SCA_PythonController::GetSensor_doc},
- {"getScript", (PyCFunction) SCA_PythonController::sPyGetScript, METH_VARARGS},
- {"setScript", (PyCFunction) SCA_PythonController::sPySetScript, METH_VARARGS},
+ {"getActuators", (PyCFunction) SCA_PythonController::sPyGetActuators, METH_NOARGS, (PY_METHODCHAR)SCA_PythonController::GetActuators_doc},
+ {"getActuator", (PyCFunction) SCA_PythonController::sPyGetActuator, METH_O, (PY_METHODCHAR)SCA_PythonController::GetActuator_doc},
+ {"getSensors", (PyCFunction) SCA_PythonController::sPyGetSensors, METH_NOARGS, (PY_METHODCHAR)SCA_PythonController::GetSensors_doc},
+ {"getSensor", (PyCFunction) SCA_PythonController::sPyGetSensor, METH_O, (PY_METHODCHAR)SCA_PythonController::GetSensor_doc},
+ {"getScript", (PyCFunction) SCA_PythonController::sPyGetScript, METH_NOARGS},
+ {"setScript", (PyCFunction) SCA_PythonController::sPySetScript, METH_O},
+ {"getState", (PyCFunction) SCA_PythonController::sPyGetState, METH_NOARGS},
{NULL,NULL} //Sentinel
};
@@ -255,9 +259,17 @@ void SCA_PythonController::Trigger(SCA_LogicManager* logicmgr)
{
// didn't compile, so instead of compile, complain
// something is wrong, tell the user what went wrong
- printf("PYTHON SCRIPT ERROR:\n");
+ printf("Python compile error from controller \"%s\": \n", GetName().Ptr());
//PyRun_SimpleString(m_scriptText.Ptr());
PyErr_Print();
+
+ /* Added in 2.48a, the last_traceback can reference Objects for example, increasing
+ * their user count. Not to mention holding references to wrapped data.
+ * This is especially bad when the PyObject for the wrapped data is free'd, after blender
+ * has alredy dealocated the pointer */
+ PySys_SetObject( "last_traceback", Py_None);
+ PyErr_Clear(); /* just to be sure */
+
return;
}
m_bModified=false;
@@ -280,43 +292,36 @@ void SCA_PythonController::Trigger(SCA_LogicManager* logicmgr)
* break it by hand, then DECREF (which in this case
* should always ensure excdict is cleared).
*/
-/* PyObject *excdict= myPyDict_Copy(m_pythondictionary);
- struct _object* resultobj = PyEval_EvalCode((PyCodeObject*)m_bytecode,
- excdict,
- excdict
- );
- PyDict_Clear(excdict);
- Py_DECREF(excdict);*/
-
-#if 1
PyObject *excdict= PyDict_Copy(m_pythondictionary);
PyObject* resultobj = PyEval_EvalCode((PyCodeObject*)m_bytecode,
- excdict,
- excdict
- );
- PyDict_Clear(excdict);
- Py_DECREF(excdict);
-#else
-
- PyObject* resultobj = PyEval_EvalCode((PyCodeObject*)m_bytecode,
- m_pythondictionary,
- m_pythondictionary
- );
-
-#endif
+ excdict, excdict);
if (resultobj)
{
Py_DECREF(resultobj);
- } else
+ }
+ else
{
// something is wrong, tell the user what went wrong
- printf("PYTHON SCRIPT ERROR:\n");
+ printf("Python script error from controller \"%s\": \n", GetName().Ptr());
PyErr_Print();
+
+ /* Added in 2.48a, the last_traceback can reference Objects for example, increasing
+ * their user count. Not to mention holding references to wrapped data.
+ * This is especially bad when the PyObject for the wrapped data is free'd, after blender
+ * has alredy dealocated the pointer */
+ PySys_SetObject( "last_traceback", Py_None);
+ PyErr_Clear(); /* just to be sure */
+
//PyRun_SimpleString(m_scriptText.Ptr());
}
+ // clear after PyErrPrint - seems it can be using
+ // something in this dictionary and crash?
+ PyDict_Clear(excdict);
+ Py_DECREF(excdict);
+ m_triggeredSensors.erase(m_triggeredSensors.begin(), m_triggeredSensors.end());
m_sCurrentController = NULL;
}
@@ -329,30 +334,26 @@ PyObject* SCA_PythonController::_getattr(const STR_String& attr)
-PyObject* SCA_PythonController::PyGetActuators(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* SCA_PythonController::PyGetActuators(PyObject* self)
{
PyObject* resultlist = PyList_New(m_linkedactuators.size());
for (unsigned int index=0;index<m_linkedactuators.size();index++)
{
- PyList_SetItem(resultlist,index,m_linkedactuators[index]->AddRef());
+ PyList_SET_ITEM(resultlist,index,m_linkedactuators[index]->AddRef());
}
return resultlist;
}
-char SCA_PythonController::GetSensor_doc[] =
+const char SCA_PythonController::GetSensor_doc[] =
"GetSensor (char sensorname) return linked sensor that is named [sensorname]\n";
PyObject*
-SCA_PythonController::PyGetSensor(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+SCA_PythonController::PyGetSensor(PyObject* self, PyObject* value)
{
- char *scriptArg;
-
- if (!PyArg_ParseTuple(args, "s", &scriptArg)) {
+ char *scriptArg = PyString_AsString(value);
+ if (scriptArg==NULL) {
+ PyErr_SetString(PyExc_TypeError, "expected a string (sensor name)");
return NULL;
}
@@ -365,24 +366,24 @@ SCA_PythonController::PyGetSensor(PyObject* self,
return sensor->AddRef();
}
}
-
- PyErr_SetString(PyExc_AttributeError, "Unable to find requested sensor");
+
+ char emsg[96];
+ PyOS_snprintf( emsg, sizeof( emsg ), "Unable to find requested sensor \"%s\"", scriptArg );
+ PyErr_SetString(PyExc_AttributeError, emsg);
return NULL;
}
-char SCA_PythonController::GetActuator_doc[] =
+const char SCA_PythonController::GetActuator_doc[] =
"GetActuator (char sensorname) return linked actuator that is named [actuatorname]\n";
PyObject*
-SCA_PythonController::PyGetActuator(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+SCA_PythonController::PyGetActuator(PyObject* self, PyObject* value)
{
- char *scriptArg;
-
- if (!PyArg_ParseTuple(args, "s", &scriptArg)) {
+ char *scriptArg = PyString_AsString(value);
+ if (scriptArg==NULL) {
+ PyErr_SetString(PyExc_TypeError, "expected a string (actuator name)");
return NULL;
}
@@ -395,42 +396,39 @@ SCA_PythonController::PyGetActuator(PyObject* self,
return actua->AddRef();
}
}
-
- PyErr_SetString(PyExc_AttributeError, "Unable to find requested actuator");
+
+ char emsg[96];
+ PyOS_snprintf( emsg, sizeof( emsg ), "Unable to find requested actuator \"%s\"", scriptArg );
+ PyErr_SetString(PyExc_AttributeError, emsg);
return NULL;
}
-char SCA_PythonController::GetSensors_doc[] = "getSensors returns a list of all attached sensors";
+const char SCA_PythonController::GetSensors_doc[] = "getSensors returns a list of all attached sensors";
PyObject*
-SCA_PythonController::PyGetSensors(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+SCA_PythonController::PyGetSensors(PyObject* self)
{
PyObject* resultlist = PyList_New(m_linkedsensors.size());
for (unsigned int index=0;index<m_linkedsensors.size();index++)
{
- PyList_SetItem(resultlist,index,m_linkedsensors[index]->AddRef());
+ PyList_SET_ITEM(resultlist,index,m_linkedsensors[index]->AddRef());
}
return resultlist;
}
/* 1. getScript */
-PyObject* SCA_PythonController::PyGetScript(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* SCA_PythonController::PyGetScript(PyObject* self)
{
return PyString_FromString(m_scriptText);
}
/* 2. setScript */
-PyObject* SCA_PythonController::PySetScript(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* SCA_PythonController::PySetScript(PyObject* self, PyObject* value)
{
- char *scriptArg;
- if (!PyArg_ParseTuple(args, "s", &scriptArg)) {
+ char *scriptArg = PyString_AsString(value);
+ if (scriptArg==NULL) {
+ PyErr_SetString(PyExc_TypeError, "expected a string (script name)");
return NULL;
}
@@ -439,7 +437,13 @@ PyObject* SCA_PythonController::PySetScript(PyObject* self,
this->SetScriptText(scriptArg);
- Py_Return;
+ Py_RETURN_NONE;
+}
+
+/* 1. getScript */
+PyObject* SCA_PythonController::PyGetState(PyObject* self)
+{
+ return PyInt_FromLong(m_statemask);
}
/* eof */
diff --git a/source/gameengine/GameLogic/SCA_PythonController.h b/source/gameengine/GameLogic/SCA_PythonController.h
index 63975234da9..d9b2e242bea 100644
--- a/source/gameengine/GameLogic/SCA_PythonController.h
+++ b/source/gameengine/GameLogic/SCA_PythonController.h
@@ -36,6 +36,8 @@
#include "SCA_LogicManager.h"
#include "BoolValue.h"
+#include <vector>
+
class SCA_IObject;
class SCA_PythonController : public SCA_IController
{
@@ -47,6 +49,7 @@ class SCA_PythonController : public SCA_IController
STR_String m_scriptText;
STR_String m_scriptName;
PyObject* m_pythondictionary;
+ std::vector<class SCA_ISensor*> m_triggeredSensors;
public:
static SCA_PythonController* m_sCurrentController; // protected !!!
@@ -64,23 +67,24 @@ class SCA_PythonController : public SCA_IController
void SetScriptText(const STR_String& text);
void SetScriptName(const STR_String& name);
void SetDictionary(PyObject* pythondictionary);
+ void AddTriggeredSensor(class SCA_ISensor* sensor)
+ { m_triggeredSensors.push_back(sensor); }
+ int IsTriggered(class SCA_ISensor* sensor);
- static char* sPyGetCurrentController__doc__;
- static PyObject* sPyGetCurrentController(PyObject* self,
- PyObject* args,
- PyObject* kwds);
- static char* sPyAddActiveActuator__doc__;
+ static const char* sPyGetCurrentController__doc__;
+ static PyObject* sPyGetCurrentController(PyObject* self);
+ static const char* sPyAddActiveActuator__doc__;
static PyObject* sPyAddActiveActuator(PyObject* self,
- PyObject* args,
- PyObject* kwds);
+ PyObject* args);
virtual PyObject* _getattr(const STR_String& attr);
- KX_PYMETHOD_DOC(SCA_PythonController,GetSensors);
- KX_PYMETHOD_DOC(SCA_PythonController,GetSensor);
- KX_PYMETHOD_DOC(SCA_PythonController,GetActuator);
- KX_PYMETHOD_DOC(SCA_PythonController,GetActuators);
- KX_PYMETHOD(SCA_PythonController,SetScript);
- KX_PYMETHOD(SCA_PythonController,GetScript);
+ KX_PYMETHOD_DOC_NOARGS(SCA_PythonController,GetSensors);
+ KX_PYMETHOD_DOC_NOARGS(SCA_PythonController,GetActuators);
+ KX_PYMETHOD_DOC_O(SCA_PythonController,GetSensor);
+ KX_PYMETHOD_DOC_O(SCA_PythonController,GetActuator);
+ KX_PYMETHOD_O(SCA_PythonController,SetScript);
+ KX_PYMETHOD_NOARGS(SCA_PythonController,GetScript);
+ KX_PYMETHOD_NOARGS(SCA_PythonController,GetState);
};
diff --git a/source/gameengine/GameLogic/SCA_RandomActuator.cpp b/source/gameengine/GameLogic/SCA_RandomActuator.cpp
index 60570f7c19c..7b50a483cd8 100644
--- a/source/gameengine/GameLogic/SCA_RandomActuator.cpp
+++ b/source/gameengine/GameLogic/SCA_RandomActuator.cpp
@@ -58,6 +58,7 @@ SCA_RandomActuator::SCA_RandomActuator(SCA_IObject *gameobj,
m_parameter2(para2),
m_distribution(mode)
{
+ // m_base is never deleted, probably a memory leak!
m_base = new SCA_RandomNumberGenerator(seed);
m_counter = 0;
enforceConstraints();
@@ -75,6 +76,7 @@ SCA_RandomActuator::~SCA_RandomActuator()
CValue* SCA_RandomActuator::GetReplica()
{
SCA_RandomActuator* replica = new SCA_RandomActuator(*this);
+ // replication just copy the m_base pointer => common random generator
replica->ProcessReplica();
CValue::AddDataToReplica(replica);
@@ -337,23 +339,23 @@ PyParentObject SCA_RandomActuator::Parents[] = {
};
PyMethodDef SCA_RandomActuator::Methods[] = {
- {"setSeed", (PyCFunction) SCA_RandomActuator::sPySetSeed, METH_VARARGS, SetSeed_doc},
- {"getSeed", (PyCFunction) SCA_RandomActuator::sPyGetSeed, METH_VARARGS, GetSeed_doc},
- {"getPara1", (PyCFunction) SCA_RandomActuator::sPyGetPara1, METH_VARARGS, GetPara1_doc},
- {"getPara2", (PyCFunction) SCA_RandomActuator::sPyGetPara2, METH_VARARGS, GetPara2_doc},
- {"getDistribution", (PyCFunction) SCA_RandomActuator::sPyGetDistribution, METH_VARARGS, GetDistribution_doc},
- {"setProperty", (PyCFunction) SCA_RandomActuator::sPySetProperty, METH_VARARGS, SetProperty_doc},
- {"getProperty", (PyCFunction) SCA_RandomActuator::sPyGetProperty, METH_VARARGS, GetProperty_doc},
- {"setBoolConst", (PyCFunction) SCA_RandomActuator::sPySetBoolConst, METH_VARARGS, SetBoolConst_doc},
- {"setBoolUniform", (PyCFunction) SCA_RandomActuator::sPySetBoolUniform, METH_VARARGS, SetBoolUniform_doc},
- {"setBoolBernouilli",(PyCFunction) SCA_RandomActuator::sPySetBoolBernouilli, METH_VARARGS, SetBoolBernouilli_doc},
- {"setIntConst", (PyCFunction) SCA_RandomActuator::sPySetIntConst, METH_VARARGS, SetIntConst_doc},
- {"setIntUniform", (PyCFunction) SCA_RandomActuator::sPySetIntUniform, METH_VARARGS, SetIntUniform_doc},
- {"setIntPoisson", (PyCFunction) SCA_RandomActuator::sPySetIntPoisson, METH_VARARGS, SetIntPoisson_doc},
- {"setFloatConst", (PyCFunction) SCA_RandomActuator::sPySetFloatConst, METH_VARARGS, SetFloatConst_doc},
- {"setFloatUniform", (PyCFunction) SCA_RandomActuator::sPySetFloatUniform, METH_VARARGS, SetFloatUniform_doc},
- {"setFloatNormal", (PyCFunction) SCA_RandomActuator::sPySetFloatNormal, METH_VARARGS, SetFloatNormal_doc},
- {"setFloatNegativeExponential", (PyCFunction) SCA_RandomActuator::sPySetFloatNegativeExponential, METH_VARARGS, SetFloatNegativeExponential_doc},
+ {"setSeed", (PyCFunction) SCA_RandomActuator::sPySetSeed, METH_VARARGS, (PY_METHODCHAR)SetSeed_doc},
+ {"getSeed", (PyCFunction) SCA_RandomActuator::sPyGetSeed, METH_VARARGS, (PY_METHODCHAR)GetSeed_doc},
+ {"getPara1", (PyCFunction) SCA_RandomActuator::sPyGetPara1, METH_VARARGS, (PY_METHODCHAR)GetPara1_doc},
+ {"getPara2", (PyCFunction) SCA_RandomActuator::sPyGetPara2, METH_VARARGS, (PY_METHODCHAR)GetPara2_doc},
+ {"getDistribution", (PyCFunction) SCA_RandomActuator::sPyGetDistribution, METH_VARARGS, (PY_METHODCHAR)GetDistribution_doc},
+ {"setProperty", (PyCFunction) SCA_RandomActuator::sPySetProperty, METH_VARARGS, (PY_METHODCHAR)SetProperty_doc},
+ {"getProperty", (PyCFunction) SCA_RandomActuator::sPyGetProperty, METH_VARARGS, (PY_METHODCHAR)GetProperty_doc},
+ {"setBoolConst", (PyCFunction) SCA_RandomActuator::sPySetBoolConst, METH_VARARGS, (PY_METHODCHAR)SetBoolConst_doc},
+ {"setBoolUniform", (PyCFunction) SCA_RandomActuator::sPySetBoolUniform, METH_VARARGS, (PY_METHODCHAR)SetBoolUniform_doc},
+ {"setBoolBernouilli",(PyCFunction) SCA_RandomActuator::sPySetBoolBernouilli, METH_VARARGS, (PY_METHODCHAR)SetBoolBernouilli_doc},
+ {"setIntConst", (PyCFunction) SCA_RandomActuator::sPySetIntConst, METH_VARARGS, (PY_METHODCHAR)SetIntConst_doc},
+ {"setIntUniform", (PyCFunction) SCA_RandomActuator::sPySetIntUniform, METH_VARARGS, (PY_METHODCHAR)SetIntUniform_doc},
+ {"setIntPoisson", (PyCFunction) SCA_RandomActuator::sPySetIntPoisson, METH_VARARGS, (PY_METHODCHAR)SetIntPoisson_doc},
+ {"setFloatConst", (PyCFunction) SCA_RandomActuator::sPySetFloatConst, METH_VARARGS, (PY_METHODCHAR)SetFloatConst_doc},
+ {"setFloatUniform", (PyCFunction) SCA_RandomActuator::sPySetFloatUniform, METH_VARARGS, (PY_METHODCHAR)SetFloatUniform_doc},
+ {"setFloatNormal", (PyCFunction) SCA_RandomActuator::sPySetFloatNormal, METH_VARARGS, (PY_METHODCHAR)SetFloatNormal_doc},
+ {"setFloatNegativeExponential", (PyCFunction) SCA_RandomActuator::sPySetFloatNegativeExponential, METH_VARARGS, (PY_METHODCHAR)SetFloatNegativeExponential_doc},
{NULL,NULL} //Sentinel
};
@@ -362,7 +364,7 @@ PyObject* SCA_RandomActuator::_getattr(const STR_String& attr) {
}
/* 1. setSeed */
-char SCA_RandomActuator::SetSeed_doc[] =
+const char SCA_RandomActuator::SetSeed_doc[] =
"setSeed(seed)\n"
"\t- seed: integer\n"
"\tSet the initial seed of the generator. Equal seeds produce\n"
@@ -379,7 +381,7 @@ PyObject* SCA_RandomActuator::PySetSeed(PyObject* self, PyObject* args, PyObject
Py_Return;
}
/* 2. getSeed */
-char SCA_RandomActuator::GetSeed_doc[] =
+const char SCA_RandomActuator::GetSeed_doc[] =
"getSeed()\n"
"\tReturns the initial seed of the generator. Equal seeds produce\n"
"\tequal series.\n";
@@ -388,7 +390,7 @@ PyObject* SCA_RandomActuator::PyGetSeed(PyObject* self, PyObject* args, PyObject
}
/* 4. getPara1 */
-char SCA_RandomActuator::GetPara1_doc[] =
+const char SCA_RandomActuator::GetPara1_doc[] =
"getPara1()\n"
"\tReturns the first parameter of the active distribution. Refer\n"
"\tto the documentation of the generator types for the meaning\n"
@@ -398,7 +400,7 @@ PyObject* SCA_RandomActuator::PyGetPara1(PyObject* self, PyObject* args, PyObjec
}
/* 6. getPara2 */
-char SCA_RandomActuator::GetPara2_doc[] =
+const char SCA_RandomActuator::GetPara2_doc[] =
"getPara2()\n"
"\tReturns the first parameter of the active distribution. Refer\n"
"\tto the documentation of the generator types for the meaning\n"
@@ -408,7 +410,7 @@ PyObject* SCA_RandomActuator::PyGetPara2(PyObject* self, PyObject* args, PyObjec
}
/* 8. getDistribution */
-char SCA_RandomActuator::GetDistribution_doc[] =
+const char SCA_RandomActuator::GetDistribution_doc[] =
"getDistribution()\n"
"\tReturns the type of the active distribution.\n";
PyObject* SCA_RandomActuator::PyGetDistribution(PyObject* self, PyObject* args, PyObject* kwds) {
@@ -416,7 +418,7 @@ PyObject* SCA_RandomActuator::PyGetDistribution(PyObject* self, PyObject* args,
}
/* 9. setProperty */
-char SCA_RandomActuator::SetProperty_doc[] =
+const char SCA_RandomActuator::SetProperty_doc[] =
"setProperty(name)\n"
"\t- name: string\n"
"\tSet the property to which the random value is assigned. If the \n"
@@ -429,17 +431,17 @@ PyObject* SCA_RandomActuator::PySetProperty(PyObject* self, PyObject* args, PyOb
CValue* prop = GetParent()->FindIdentifier(nameArg);
- if (prop) {
+ if (!prop->IsError()) {
m_propname = nameArg;
- prop->Release();
} else {
; /* not found ... */
}
+ prop->Release();
Py_Return;
}
/* 10. getProperty */
-char SCA_RandomActuator::GetProperty_doc[] =
+const char SCA_RandomActuator::GetProperty_doc[] =
"getProperty(name)\n"
"\tReturn the property to which the random value is assigned. If the \n"
"\tgenerator and property types do not match, the assignment is ignored.\n";
@@ -448,7 +450,7 @@ PyObject* SCA_RandomActuator::PyGetProperty(PyObject* self, PyObject* args, PyOb
}
/* 11. setBoolConst */
-char SCA_RandomActuator::SetBoolConst_doc[] =
+const char SCA_RandomActuator::SetBoolConst_doc[] =
"setBoolConst(value)\n"
"\t- value: 0 or 1\n"
"\tSet this generator to produce a constant boolean value.\n";
@@ -468,7 +470,7 @@ PyObject* SCA_RandomActuator::PySetBoolConst(PyObject* self,
Py_Return;
}
/* 12. setBoolUniform, */
-char SCA_RandomActuator::SetBoolUniform_doc[] =
+const char SCA_RandomActuator::SetBoolUniform_doc[] =
"setBoolUniform()\n"
"\tSet this generator to produce true and false, each with 50%% chance of occuring\n";
PyObject* SCA_RandomActuator::PySetBoolUniform(PyObject* self,
@@ -480,7 +482,7 @@ PyObject* SCA_RandomActuator::PySetBoolUniform(PyObject* self,
Py_Return;
}
/* 13. setBoolBernouilli, */
-char SCA_RandomActuator::SetBoolBernouilli_doc[] =
+const char SCA_RandomActuator::SetBoolBernouilli_doc[] =
"setBoolBernouilli(value)\n"
"\t- value: a float between 0 and 1\n"
"\tReturn false value * 100%% of the time.\n";
@@ -498,7 +500,7 @@ PyObject* SCA_RandomActuator::PySetBoolBernouilli(PyObject* self,
Py_Return;
}
/* 14. setIntConst,*/
-char SCA_RandomActuator::SetIntConst_doc[] =
+const char SCA_RandomActuator::SetIntConst_doc[] =
"setIntConst(value)\n"
"\t- value: integer\n"
"\tAlways return value\n";
@@ -516,7 +518,7 @@ PyObject* SCA_RandomActuator::PySetIntConst(PyObject* self,
Py_Return;
}
/* 15. setIntUniform,*/
-char SCA_RandomActuator::SetIntUniform_doc[] =
+const char SCA_RandomActuator::SetIntUniform_doc[] =
"setIntUniform(lower_bound, upper_bound)\n"
"\t- lower_bound: integer\n"
"\t- upper_bound: integer\n"
@@ -537,7 +539,7 @@ PyObject* SCA_RandomActuator::PySetIntUniform(PyObject* self,
Py_Return;
}
/* 16. setIntPoisson, */
-char SCA_RandomActuator::SetIntPoisson_doc[] =
+const char SCA_RandomActuator::SetIntPoisson_doc[] =
"setIntPoisson(value)\n"
"\t- value: float\n"
"\tReturn a Poisson-distributed number. This performs a series\n"
@@ -557,7 +559,7 @@ PyObject* SCA_RandomActuator::PySetIntPoisson(PyObject* self,
Py_Return;
}
/* 17. setFloatConst,*/
-char SCA_RandomActuator::SetFloatConst_doc[] =
+const char SCA_RandomActuator::SetFloatConst_doc[] =
"setFloatConst(value)\n"
"\t- value: float\n"
"\tAlways return value\n";
@@ -575,7 +577,7 @@ PyObject* SCA_RandomActuator::PySetFloatConst(PyObject* self,
Py_Return;
}
/* 18. setFloatUniform, */
-char SCA_RandomActuator::SetFloatUniform_doc[] =
+const char SCA_RandomActuator::SetFloatUniform_doc[] =
"setFloatUniform(lower_bound, upper_bound)\n"
"\t- lower_bound: float\n"
"\t- upper_bound: float\n"
@@ -596,7 +598,7 @@ PyObject* SCA_RandomActuator::PySetFloatUniform(PyObject* self,
Py_Return;
}
/* 19. setFloatNormal, */
-char SCA_RandomActuator::SetFloatNormal_doc[] =
+const char SCA_RandomActuator::SetFloatNormal_doc[] =
"setFloatNormal(mean, standard_deviation)\n"
"\t- mean: float\n"
"\t- standard_deviation: float\n"
@@ -617,7 +619,7 @@ PyObject* SCA_RandomActuator::PySetFloatNormal(PyObject* self,
Py_Return;
}
/* 20. setFloatNegativeExponential, */
-char SCA_RandomActuator::SetFloatNegativeExponential_doc[] =
+const char SCA_RandomActuator::SetFloatNegativeExponential_doc[] =
"setFloatNegativeExponential(half_life)\n"
"\t- half_life: float\n"
"\tReturn negative-exponentially distributed numbers. The half-life 'time'\n"
diff --git a/source/gameengine/GameLogic/SCA_RandomEventManager.cpp b/source/gameengine/GameLogic/SCA_RandomEventManager.cpp
index 02020a52a17..156478d866d 100644
--- a/source/gameengine/GameLogic/SCA_RandomEventManager.cpp
+++ b/source/gameengine/GameLogic/SCA_RandomEventManager.cpp
@@ -50,16 +50,9 @@ SCA_RandomEventManager::SCA_RandomEventManager(class SCA_LogicManager* logicmgr)
void SCA_RandomEventManager::NextFrame()
{
- for (vector<class SCA_ISensor*>::const_iterator i= m_sensors.begin();!(i==m_sensors.end());i++)
+ for (set<class SCA_ISensor*>::const_iterator i= m_sensors.begin();!(i==m_sensors.end());i++)
{
- SCA_ISensor *sensor = *i;
- sensor->Activate(m_logicmgr, NULL);
+ (*i)->Activate(m_logicmgr, NULL);
}
}
-
-
-void SCA_RandomEventManager::RegisterSensor(SCA_ISensor* sensor)
-{
- m_sensors.push_back(sensor);
-};
diff --git a/source/gameengine/GameLogic/SCA_RandomEventManager.h b/source/gameengine/GameLogic/SCA_RandomEventManager.h
index 8c75ef665fa..79138c23c62 100644
--- a/source/gameengine/GameLogic/SCA_RandomEventManager.h
+++ b/source/gameengine/GameLogic/SCA_RandomEventManager.h
@@ -45,7 +45,6 @@ public:
SCA_RandomEventManager(class SCA_LogicManager* logicmgr);
virtual void NextFrame();
- virtual void RegisterSensor(SCA_ISensor* sensor);
};
#endif //__KX_RANDOMEVENTMGR
diff --git a/source/gameengine/GameLogic/SCA_RandomSensor.cpp b/source/gameengine/GameLogic/SCA_RandomSensor.cpp
index 540a5865537..202fd6382e6 100644
--- a/source/gameengine/GameLogic/SCA_RandomSensor.cpp
+++ b/source/gameengine/GameLogic/SCA_RandomSensor.cpp
@@ -50,12 +50,9 @@ SCA_RandomSensor::SCA_RandomSensor(SCA_EventManager* eventmgr,
PyTypeObject* T)
: SCA_ISensor(gameobj,eventmgr, T)
{
- m_iteration = 0;
- m_lastdraw = false;
-
+ // m_basegenerator is never deleted => memory leak
m_basegenerator = new SCA_RandomNumberGenerator(startseed);
- m_currentDraw = m_basegenerator->Draw();
- RegisterToManager();
+ Init();
}
@@ -65,11 +62,19 @@ SCA_RandomSensor::~SCA_RandomSensor()
/* Nothing to be done here. */
}
+void SCA_RandomSensor::Init()
+{
+ m_iteration = 0;
+ m_interval = 0;
+ m_lastdraw = false;
+ m_currentDraw = m_basegenerator->Draw();
+}
CValue* SCA_RandomSensor::GetReplica()
{
CValue* replica = new SCA_RandomSensor(*this);
+ // replication copies m_basegenerator pointer => share same generator
// this will copy properties and so on...
CValue::AddDataToReplica(replica);
@@ -95,20 +100,25 @@ bool SCA_RandomSensor::Evaluate(CValue* event)
/* this is a reasonable way of generating bools. Check Knuth. */
/* Furthermore, we only draw each <delay>-eth frame. */
- bool drawResult = false;
-
- if (m_iteration > 31) {
- m_currentDraw = m_basegenerator->Draw();
- drawResult = (m_currentDraw & 0x1) == 0;
- m_iteration = 1;
- } else {
- drawResult = ((m_currentDraw >> m_iteration) & 0x1) == 0;
- m_iteration++;
+ bool evaluateResult = false;
+
+ if (++m_interval > m_pulse_frequency) {
+ bool drawResult = false;
+ m_interval = 0;
+ if (m_iteration > 31) {
+ m_currentDraw = m_basegenerator->Draw();
+ drawResult = (m_currentDraw & 0x1) == 0;
+ m_iteration = 1;
+ } else {
+ drawResult = ((m_currentDraw >> m_iteration) & 0x1) == 0;
+ m_iteration++;
+ }
+ evaluateResult = drawResult != m_lastdraw;
+ m_lastdraw = drawResult;
}
/* now pass this result to some controller */
- m_lastdraw = drawResult;
- return drawResult;
+ return evaluateResult;
}
/* ------------------------------------------------------------------------- */
@@ -144,9 +154,9 @@ PyParentObject SCA_RandomSensor::Parents[] = {
};
PyMethodDef SCA_RandomSensor::Methods[] = {
- {"setSeed", (PyCFunction) SCA_RandomSensor::sPySetSeed, METH_VARARGS, SetSeed_doc},
- {"getSeed", (PyCFunction) SCA_RandomSensor::sPyGetSeed, METH_VARARGS, GetSeed_doc},
- {"getLastDraw", (PyCFunction) SCA_RandomSensor::sPyGetLastDraw, METH_VARARGS, GetLastDraw_doc},
+ {"setSeed", (PyCFunction) SCA_RandomSensor::sPySetSeed, METH_VARARGS, (PY_METHODCHAR)SetSeed_doc},
+ {"getSeed", (PyCFunction) SCA_RandomSensor::sPyGetSeed, METH_VARARGS, (PY_METHODCHAR)GetSeed_doc},
+ {"getLastDraw", (PyCFunction) SCA_RandomSensor::sPyGetLastDraw, METH_VARARGS, (PY_METHODCHAR)GetLastDraw_doc},
{NULL,NULL} //Sentinel
};
@@ -155,7 +165,7 @@ PyObject* SCA_RandomSensor::_getattr(const STR_String& attr) {
}
/* 1. setSeed */
-char SCA_RandomSensor::SetSeed_doc[] =
+const char SCA_RandomSensor::SetSeed_doc[] =
"setSeed(seed)\n"
"\t- seed: integer\n"
"\tSet the initial seed of the generator. Equal seeds produce\n"
@@ -173,7 +183,7 @@ PyObject* SCA_RandomSensor::PySetSeed(PyObject* self, PyObject* args, PyObject*
}
/* 2. getSeed */
-char SCA_RandomSensor::GetSeed_doc[] =
+const char SCA_RandomSensor::GetSeed_doc[] =
"getSeed()\n"
"\tReturns the initial seed of the generator. Equal seeds produce\n"
"\tequal series.\n";
@@ -182,7 +192,7 @@ PyObject* SCA_RandomSensor::PyGetSeed(PyObject* self, PyObject* args, PyObject*
}
/* 3. getLastDraw */
-char SCA_RandomSensor::GetLastDraw_doc[] =
+const char SCA_RandomSensor::GetLastDraw_doc[] =
"getLastDraw()\n"
"\tReturn the last value that was drawn.\n";
PyObject* SCA_RandomSensor::PyGetLastDraw(PyObject* self, PyObject* args, PyObject* kwds) {
diff --git a/source/gameengine/GameLogic/SCA_RandomSensor.h b/source/gameengine/GameLogic/SCA_RandomSensor.h
index 729df9b2a62..d29bfb6837a 100644
--- a/source/gameengine/GameLogic/SCA_RandomSensor.h
+++ b/source/gameengine/GameLogic/SCA_RandomSensor.h
@@ -42,6 +42,7 @@ class SCA_RandomSensor : public SCA_ISensor
unsigned int m_currentDraw;
int m_iteration;
+ int m_interval;
SCA_RandomNumberGenerator *m_basegenerator;
bool m_lastdraw;
public:
@@ -53,6 +54,7 @@ public:
virtual CValue* GetReplica();
virtual bool Evaluate(CValue* event);
virtual bool IsPositiveTrigger();
+ virtual void Init();
/* --------------------------------------------------------------------- */
/* Python interface ---------------------------------------------------- */
diff --git a/source/gameengine/GameLogic/SCA_TimeEventManager.cpp b/source/gameengine/GameLogic/SCA_TimeEventManager.cpp
index 643f1247a52..b7fadd3d62c 100644
--- a/source/gameengine/GameLogic/SCA_TimeEventManager.cpp
+++ b/source/gameengine/GameLogic/SCA_TimeEventManager.cpp
@@ -65,6 +65,11 @@ void SCA_TimeEventManager::RegisterSensor(SCA_ISensor* sensor)
// not yet
}
+void SCA_TimeEventManager::RemoveSensor(SCA_ISensor* sensor)
+{
+ // empty
+}
+
void SCA_TimeEventManager::NextFrame(double curtime, double fixedtime)
diff --git a/source/gameengine/GameLogic/SCA_TimeEventManager.h b/source/gameengine/GameLogic/SCA_TimeEventManager.h
index 2fd39661a2d..bd57e12eb44 100644
--- a/source/gameengine/GameLogic/SCA_TimeEventManager.h
+++ b/source/gameengine/GameLogic/SCA_TimeEventManager.h
@@ -45,6 +45,7 @@ public:
virtual void NextFrame(double curtime, double fixedtime);
virtual void RegisterSensor(class SCA_ISensor* sensor);
+ virtual void RemoveSensor(class SCA_ISensor* sensor);
void AddTimeProperty(CValue* timeval);
void RemoveTimeProperty(CValue* timeval);
};
diff --git a/source/gameengine/GameLogic/SCA_XNORController.cpp b/source/gameengine/GameLogic/SCA_XNORController.cpp
new file mode 100644
index 00000000000..3ef7c07fe0a
--- /dev/null
+++ b/source/gameengine/GameLogic/SCA_XNORController.cpp
@@ -0,0 +1,148 @@
+/**
+ * 'Xnor' together all inputs
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "SCA_XNORController.h"
+#include "SCA_ISensor.h"
+#include "SCA_LogicManager.h"
+#include "BoolValue.h"
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/* ------------------------------------------------------------------------- */
+/* Native functions */
+/* ------------------------------------------------------------------------- */
+
+SCA_XNORController::SCA_XNORController(SCA_IObject* gameobj,
+ PyTypeObject* T)
+ :
+ SCA_IController(gameobj,T)
+{
+}
+
+
+
+SCA_XNORController::~SCA_XNORController()
+{
+}
+
+
+
+void SCA_XNORController::Trigger(SCA_LogicManager* logicmgr)
+{
+
+ bool sensorresult = true;
+
+ for (vector<SCA_ISensor*>::const_iterator is=m_linkedsensors.begin();
+ !(is==m_linkedsensors.end());is++)
+ {
+ SCA_ISensor* sensor = *is;
+ if (sensor->IsPositiveTrigger())
+ {
+ if (sensorresult == false)
+ {
+ sensorresult = true;
+ break;
+ }
+ sensorresult = false;
+ }
+ }
+
+ CValue* newevent = new CBoolValue(sensorresult);
+
+ for (vector<SCA_IActuator*>::const_iterator i=m_linkedactuators.begin();
+ !(i==m_linkedactuators.end());i++)
+ {
+ SCA_IActuator* actua = *i;//m_linkedactuators.at(i);
+ logicmgr->AddActiveActuator(actua,newevent);
+ }
+
+ // every actuator that needs the event, has a it's own reference to it now so
+ // release it (so to be clear: if there is no actuator, it's deleted right now)
+ newevent->Release();
+
+}
+
+
+
+CValue* SCA_XNORController::GetReplica()
+{
+ CValue* replica = new SCA_XNORController(*this);
+ // this will copy properties and so on...
+ CValue::AddDataToReplica(replica);
+
+ return replica;
+}
+
+
+
+/* ------------------------------------------------------------------------- */
+/* Python functions */
+/* ------------------------------------------------------------------------- */
+
+/* Integration hooks ------------------------------------------------------- */
+PyTypeObject SCA_XNORController::Type = {
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0,
+ "SCA_XNORController",
+ sizeof(SCA_XNORController),
+ 0,
+ PyDestructor,
+ 0,
+ __getattr,
+ __setattr,
+ 0, //&MyPyCompare,
+ __repr,
+ 0, //&cvalue_as_number,
+ 0,
+ 0,
+ 0,
+ 0
+};
+
+PyParentObject SCA_XNORController::Parents[] = {
+ &SCA_XNORController::Type,
+ &SCA_IController::Type,
+ &SCA_ILogicBrick::Type,
+ &CValue::Type,
+ NULL
+};
+
+PyMethodDef SCA_XNORController::Methods[] = {
+ {NULL,NULL} //Sentinel
+};
+
+PyObject* SCA_XNORController::_getattr(const STR_String& attr) {
+ _getattr_up(SCA_IController);
+}
+
+/* eof */
diff --git a/source/gameengine/GameLogic/SCA_XNORController.h b/source/gameengine/GameLogic/SCA_XNORController.h
new file mode 100644
index 00000000000..4b1eaee95d8
--- /dev/null
+++ b/source/gameengine/GameLogic/SCA_XNORController.h
@@ -0,0 +1,56 @@
+/**
+ * SCA_XNORController.h
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __KX_XNORCONTROLLER
+#define __KX_XNORCONTROLLER
+
+#include "SCA_IController.h"
+
+class SCA_XNORController : public SCA_IController
+{
+ Py_Header;
+ //virtual void Trigger(class SCA_LogicManager* logicmgr);
+public:
+ SCA_XNORController(SCA_IObject* gameobj,PyTypeObject* T=&Type);
+ virtual ~SCA_XNORController();
+ virtual CValue* GetReplica();
+ virtual void Trigger(SCA_LogicManager* logicmgr);
+
+ /* --------------------------------------------------------------------- */
+ /* Python interface ---------------------------------------------------- */
+ /* --------------------------------------------------------------------- */
+
+ virtual PyObject* _getattr(const STR_String& attr);
+
+};
+
+#endif //__KX_XNORCONTROLLER
+
diff --git a/source/gameengine/GameLogic/SCA_XORController.cpp b/source/gameengine/GameLogic/SCA_XORController.cpp
new file mode 100644
index 00000000000..6499c62f5f2
--- /dev/null
+++ b/source/gameengine/GameLogic/SCA_XORController.cpp
@@ -0,0 +1,148 @@
+/**
+ * 'Xor' together all inputs
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "SCA_XORController.h"
+#include "SCA_ISensor.h"
+#include "SCA_LogicManager.h"
+#include "BoolValue.h"
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/* ------------------------------------------------------------------------- */
+/* Native functions */
+/* ------------------------------------------------------------------------- */
+
+SCA_XORController::SCA_XORController(SCA_IObject* gameobj,
+ PyTypeObject* T)
+ :
+ SCA_IController(gameobj,T)
+{
+}
+
+
+
+SCA_XORController::~SCA_XORController()
+{
+}
+
+
+
+void SCA_XORController::Trigger(SCA_LogicManager* logicmgr)
+{
+
+ bool sensorresult = false;
+
+ for (vector<SCA_ISensor*>::const_iterator is=m_linkedsensors.begin();
+ !(is==m_linkedsensors.end());is++)
+ {
+ SCA_ISensor* sensor = *is;
+ if (sensor->IsPositiveTrigger())
+ {
+ if (sensorresult == true)
+ {
+ sensorresult = false;
+ break;
+ }
+ sensorresult = true;
+ }
+ }
+
+ CValue* newevent = new CBoolValue(sensorresult);
+
+ for (vector<SCA_IActuator*>::const_iterator i=m_linkedactuators.begin();
+ !(i==m_linkedactuators.end());i++)
+ {
+ SCA_IActuator* actua = *i;//m_linkedactuators.at(i);
+ logicmgr->AddActiveActuator(actua,newevent);
+ }
+
+ // every actuator that needs the event, has a it's own reference to it now so
+ // release it (so to be clear: if there is no actuator, it's deleted right now)
+ newevent->Release();
+
+}
+
+
+
+CValue* SCA_XORController::GetReplica()
+{
+ CValue* replica = new SCA_XORController(*this);
+ // this will copy properties and so on...
+ CValue::AddDataToReplica(replica);
+
+ return replica;
+}
+
+
+
+/* ------------------------------------------------------------------------- */
+/* Python functions */
+/* ------------------------------------------------------------------------- */
+
+/* Integration hooks ------------------------------------------------------- */
+PyTypeObject SCA_XORController::Type = {
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0,
+ "SCA_XORController",
+ sizeof(SCA_XORController),
+ 0,
+ PyDestructor,
+ 0,
+ __getattr,
+ __setattr,
+ 0, //&MyPyCompare,
+ __repr,
+ 0, //&cvalue_as_number,
+ 0,
+ 0,
+ 0,
+ 0
+};
+
+PyParentObject SCA_XORController::Parents[] = {
+ &SCA_XORController::Type,
+ &SCA_IController::Type,
+ &SCA_ILogicBrick::Type,
+ &CValue::Type,
+ NULL
+};
+
+PyMethodDef SCA_XORController::Methods[] = {
+ {NULL,NULL} //Sentinel
+};
+
+PyObject* SCA_XORController::_getattr(const STR_String& attr) {
+ _getattr_up(SCA_IController);
+}
+
+/* eof */
diff --git a/source/gameengine/GameLogic/SCA_XORController.h b/source/gameengine/GameLogic/SCA_XORController.h
new file mode 100644
index 00000000000..f50cd33c125
--- /dev/null
+++ b/source/gameengine/GameLogic/SCA_XORController.h
@@ -0,0 +1,56 @@
+/**
+ * SCA_XORController.h
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __KX_XORCONTROLLER
+#define __KX_XORCONTROLLER
+
+#include "SCA_IController.h"
+
+class SCA_XORController : public SCA_IController
+{
+ Py_Header;
+ //virtual void Trigger(class SCA_LogicManager* logicmgr);
+public:
+ SCA_XORController(SCA_IObject* gameobj,PyTypeObject* T=&Type);
+ virtual ~SCA_XORController();
+ virtual CValue* GetReplica();
+ virtual void Trigger(SCA_LogicManager* logicmgr);
+
+ /* --------------------------------------------------------------------- */
+ /* Python interface ---------------------------------------------------- */
+ /* --------------------------------------------------------------------- */
+
+ virtual PyObject* _getattr(const STR_String& attr);
+
+};
+
+#endif //__KX_XORCONTROLLER
+
diff --git a/source/gameengine/GameLogic/SConscript b/source/gameengine/GameLogic/SConscript
index 38064733b73..ee0e638af60 100644
--- a/source/gameengine/GameLogic/SConscript
+++ b/source/gameengine/GameLogic/SConscript
@@ -5,8 +5,16 @@ sources = env.Glob('*.cpp') + env.Glob('Joystick/*.cpp')
incs = '. #/source/kernel/gen_system #/intern/string'
incs += ' #/source/gameengine/Expressions #/intern/moto/include'
+incs += ' #/source/gameengine/Rasterizer'
incs += ' ' + env['BF_PYTHON_INC']
-incs += ' ' + env['BF_SDL_INC']
-env.BlenderLib ( 'bf_logic', sources, Split(incs), [], libtype=['game','player'], priority=[30, 100] )
+
+defs = ''
+
+if env['WITH_BF_SDL']:
+ incs += ' ' + env['BF_SDL_INC']
+else:
+ defs += ' DISABLE_SDL'
+
+env.BlenderLib ( 'bf_logic', sources, Split(incs), Split(defs), libtype=['game','player'], priority=[30, 100] )
diff --git a/source/gameengine/GamePlayer/CMakeLists.txt b/source/gameengine/GamePlayer/CMakeLists.txt
index ff1040bfb40..fc5912155cf 100644
--- a/source/gameengine/GamePlayer/CMakeLists.txt
+++ b/source/gameengine/GamePlayer/CMakeLists.txt
@@ -25,3 +25,7 @@
# ***** END GPL LICENSE BLOCK *****
SUBDIRS(common ghost)
+
+IF(WITH_WEBPLUGIN)
+ SUBDIRS(xembed)
+ENDIF(WITH_WEBPLUGIN)
diff --git a/source/gameengine/GamePlayer/Makefile b/source/gameengine/GamePlayer/Makefile
index 747a82fc333..c4f78f23117 100644
--- a/source/gameengine/GamePlayer/Makefile
+++ b/source/gameengine/GamePlayer/Makefile
@@ -34,7 +34,7 @@ SOURCEDIR = source/gameengine/GamePlayer
DIR = $(OCGDIR)/gameengine/GamePlayer
DIRS = common ghost
-ifneq ($(NAN_NO_PLUGIN),true)
+ifeq ($(WITH_BF_WEBPLUGIN),true)
ifeq ($(OS),$(findstring $(OS), "freebsd irix windows"))
ifneq ($(FREE_WINDOWS),true)
DIRS += netscape
diff --git a/source/gameengine/GamePlayer/SConscript b/source/gameengine/GamePlayer/SConscript
index df6d26e5d16..0b140bba8e7 100644
--- a/source/gameengine/GamePlayer/SConscript
+++ b/source/gameengine/GamePlayer/SConscript
@@ -1,3 +1,3 @@
#!/usr/bin/python
SConscript(['common/SConscript',
- 'ghost/SConscript'])
+ 'ghost/SConscript'])
diff --git a/source/gameengine/GamePlayer/common/CMakeLists.txt b/source/gameengine/GamePlayer/common/CMakeLists.txt
index 29cdcd640f5..0c6c4179e2d 100644
--- a/source/gameengine/GamePlayer/common/CMakeLists.txt
+++ b/source/gameengine/GamePlayer/common/CMakeLists.txt
@@ -30,7 +30,6 @@ SET(SRC
GPC_Engine.cpp
GPC_KeyboardDevice.cpp
GPC_MouseDevice.cpp
- GPC_PolygonMaterial.cpp
GPC_RawImage.cpp
GPC_RawLoadDotBlendArray.cpp
GPC_RawLogoArrays.cpp
@@ -69,6 +68,8 @@ SET(INC
../../../../source/gameengine/GamePlayer/ghost
../../../../source/blender/misc
../../../../source/blender/blenloader
+ ../../../../source/blender/gpu
+ ../../../../extern/glew/include
${PYTHON_INC}
${SOLID_INC}
${PNG_INC}
diff --git a/source/gameengine/GamePlayer/common/GPC_Canvas.h b/source/gameengine/GamePlayer/common/GPC_Canvas.h
index bd66c865988..87719041f65 100644
--- a/source/gameengine/GamePlayer/common/GPC_Canvas.h
+++ b/source/gameengine/GamePlayer/common/GPC_Canvas.h
@@ -33,18 +33,12 @@
#include "RAS_ICanvas.h"
#include "RAS_Rect.h"
-#if defined(WIN32) || defined(__APPLE__)
- #ifdef WIN32
- #pragma warning (disable:4786) // suppress stl-MSVC debug info warning
- #include <windows.h>
- #include <GL/gl.h>
- #else // WIN32
- // __APPLE__ is defined
- #include <AGL/gl.h>
- #endif // WIN32
-#else //defined(WIN32) || defined(__APPLE__)
- #include <GL/gl.h>
-#endif //defined(WIN32) || defined(__APPLE__)
+#ifdef WIN32
+ #pragma warning (disable:4786) // suppress stl-MSVC debug info warning
+ #include <windows.h>
+#endif // WIN32
+
+#include "GL/glew.h"
#include <map>
@@ -136,6 +130,12 @@ public:
) {
return m_displayarea;
};
+
+ RAS_Rect &
+ GetWindowArea(
+ ) {
+ return m_displayarea;
+ }
void
BeginFrame(
diff --git a/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.cpp b/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.cpp
index c5064c86b5a..474df9276a7 100644
--- a/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.cpp
+++ b/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.cpp
@@ -29,6 +29,8 @@
#include "GPC_KeyboardDevice.h"
+#include <cstdlib>
+
/**
* NextFrame toggles currentTable with previousTable,
* and copies relevant event information from previous to current table
diff --git a/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.h b/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.h
index aa2bfefb603..891589dd118 100644
--- a/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.h
+++ b/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.h
@@ -55,9 +55,9 @@ protected:
* System dependent keyboard codes are stored as ints.
*/
std::map<int, KX_EnumInputs> m_reverseKeyTranslateTable;
- bool m_hookesc;
public:
+ bool m_hookesc;
GPC_KeyboardDevice()
: m_hookesc(false)
{
diff --git a/source/gameengine/GamePlayer/common/GPC_PolygonMaterial.cpp b/source/gameengine/GamePlayer/common/GPC_PolygonMaterial.cpp
index 46fe24d8b87..b1e2b5af0e6 100644
--- a/source/gameengine/GamePlayer/common/GPC_PolygonMaterial.cpp
+++ b/source/gameengine/GamePlayer/common/GPC_PolygonMaterial.cpp
@@ -31,23 +31,7 @@
#include <config.h>
#endif
-#ifdef WIN32
-#include <windows.h>
-#endif // WIN32
-#ifdef __APPLE__
-#define GL_GLEXT_LEGACY 1
-#include <OpenGL/gl.h>
-#include <OpenGL/glu.h>
-#else
-#include <GL/gl.h>
-#if defined(__sun__) && !defined(__sparc__)
-#include <mesa/glu.h>
-#else
-#include <GL/glu.h>
-#endif
-#endif
-
-
+#include "GL/glew.h"
#include "GPC_PolygonMaterial.h"
#include "MT_Vector3.h"
@@ -88,7 +72,6 @@ static int fDoMipMap = 1;
static int fLinearMipMap=1;
static int fAlphamode= -1;
-using namespace bgl;
/* (n&(n-1)) zeros the least significant bit of n */
static int is_pow2(int num) {
return ((num)&(num-1))==0;
@@ -154,16 +137,23 @@ int set_tpage(MTFace *tface)
fAlphamode= tface->transp;
if(fAlphamode) {
- glEnable(GL_BLEND);
-
if(fAlphamode==TF_ADD) {
+ glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
+ glDisable ( GL_ALPHA_TEST );
/* glBlendEquationEXT(GL_FUNC_ADD_EXT); */
}
else if(fAlphamode==TF_ALPHA) {
+ glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ glDisable ( GL_ALPHA_TEST );
/* glBlendEquationEXT(GL_FUNC_ADD_EXT); */
}
+ else if (fAlphamode==TF_CLIP){
+ glDisable(GL_BLEND);
+ glEnable ( GL_ALPHA_TEST );
+ glAlphaFunc(GL_GREATER, 0.5f);
+ }
/* else { */
/* glBlendFunc(GL_ONE, GL_ONE); */
/* glBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT); */
diff --git a/source/gameengine/GamePlayer/common/GPC_RawImage.cpp b/source/gameengine/GamePlayer/common/GPC_RawImage.cpp
index a9cfb0a9366..e6e97cbdfd3 100644
--- a/source/gameengine/GamePlayer/common/GPC_RawImage.cpp
+++ b/source/gameengine/GamePlayer/common/GPC_RawImage.cpp
@@ -45,7 +45,7 @@ GPC_RawImage::GPC_RawImage()
bool GPC_RawImage::Load(
- char *srcName,
+ const char *srcName,
int destWidth, int destHeight,
TImageAlignment alignment, int offsetX, int offsetY)
{
diff --git a/source/gameengine/GamePlayer/common/GPC_RawImage.h b/source/gameengine/GamePlayer/common/GPC_RawImage.h
index 17c00d2fcc3..49a3043bffc 100644
--- a/source/gameengine/GamePlayer/common/GPC_RawImage.h
+++ b/source/gameengine/GamePlayer/common/GPC_RawImage.h
@@ -61,7 +61,7 @@ public:
* @param offsetX Amount of horzontal offset applied to the resource image.
* @param offsetY Amount of vertical offset applied to the resource image.
*/
- virtual bool Load(char *srcName,
+ virtual bool Load(const char *srcName,
int destWidth, int destHeight,
TImageAlignment alignment = alignTopLeft,
int offsetX = 0, int offsetY = 0);
diff --git a/source/gameengine/GamePlayer/common/GPC_RenderTools.cpp b/source/gameengine/GamePlayer/common/GPC_RenderTools.cpp
index 5912a8a10fc..78d8eaf2aa3 100644
--- a/source/gameengine/GamePlayer/common/GPC_RenderTools.cpp
+++ b/source/gameengine/GamePlayer/common/GPC_RenderTools.cpp
@@ -27,22 +27,7 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#include <assert.h>
-
-#ifdef WIN32
-#pragma warning (disable : 4786)
-#include <windows.h>
-#endif
-
-#ifdef __APPLE__
-#define GL_GLEXT_LEGACY 1
-#include <OpenGL/gl.h>
-#else
-#include <GL/gl.h>
-#endif
-#include <iostream>
-
-#include "GPC_RenderTools.h"
+#include "GL/glew.h"
#include "RAS_IRenderTools.h"
#include "RAS_IRasterizer.h"
@@ -50,122 +35,248 @@
#include "RAS_ICanvas.h"
#include "RAS_GLExtensionManager.h"
-// next two includes/dependencies come from the shadow feature
-// it needs the gameobject and the sumo physics scene for a raycast
#include "KX_GameObject.h"
-
-#include "GPC_PolygonMaterial.h"
#include "KX_PolygonMaterial.h"
-#include "Value.h"
+#include "KX_BlenderMaterial.h"
+#include "KX_RayCast.h"
+#include "KX_IPhysicsController.h"
+
+#include "PHY_IPhysicsEnvironment.h"
-//#include "KX_BlenderGL.h" // for text printing
-//#include "KX_BlenderClientObject.h"
#include "STR_String.h"
-#include "RAS_BucketManager.h" // for polymaterial (needed for textprinting)
-
-
-// Blender includes
-/* This list includes only data type definitions */
-#include "DNA_object_types.h"
-#include "DNA_material_types.h"
-#include "DNA_image_types.h"
-#include "DNA_lamp_types.h"
-#include "DNA_group_types.h"
-#include "DNA_scene_types.h"
-#include "DNA_camera_types.h"
-#include "DNA_property_types.h"
-#include "DNA_text_types.h"
-#include "DNA_sensor_types.h"
-#include "DNA_controller_types.h"
-#include "DNA_actuator_types.h"
-#include "DNA_mesh_types.h"
-#include "DNA_meshdata_types.h"
-#include "DNA_view3d_types.h"
-#include "DNA_world_types.h"
-
-#include "BKE_global.h"
-#include "BKE_image.h"
-#include "BKE_bmfont.h"
+
+#include "GPU_draw.h"
+
+#include "BKE_bmfont.h" // for text printing
#include "BKE_bmfont_types.h"
-#include "BKE_main.h"
-#include "IMB_imbuf_types.h"
-// End of Blender includes
+#include "GPC_RenderTools.h"
-#include "KX_Scene.h"
-#include "KX_RayCast.h"
-#include "KX_IPhysicsController.h"
-#include "PHY_IPhysicsEnvironment.h"
-#include "KX_BlenderMaterial.h"
+unsigned int GPC_RenderTools::m_numgllights;
GPC_RenderTools::GPC_RenderTools()
{
m_font = BMF_GetFont(BMF_kHelvetica10);
+
glGetIntegerv(GL_MAX_LIGHTS, (GLint*) &m_numgllights);
if (m_numgllights < 8)
m_numgllights = 8;
}
-
GPC_RenderTools::~GPC_RenderTools()
{
}
+void GPC_RenderTools::BeginFrame(RAS_IRasterizer* rasty)
+{
+ m_clientobject = NULL;
+ m_lastlightlayer = -1;
+ m_lastlighting = false;
+ DisableOpenGLLights();
+}
void GPC_RenderTools::EndFrame(RAS_IRasterizer* rasty)
{
}
+/* ProcessLighting performs lighting on objects. the layer is a bitfield that
+ * contains layer information. There are 20 'official' layers in blender. A
+ * light is applied on an object only when they are in the same layer. OpenGL
+ * has a maximum of 8 lights (simultaneous), so 20 * 8 lights are possible in
+ * a scene. */
-void GPC_RenderTools::BeginFrame(RAS_IRasterizer* rasty)
+void GPC_RenderTools::ProcessLighting(int layer, const MT_Transform& viewmat)
{
- m_clientobject=NULL;
- m_modified=true;
- DisableOpenGLLights();
+ if(m_lastlightlayer == layer)
+ return;
-}
+ m_lastlightlayer = layer;
-int GPC_RenderTools::ProcessLighting(int layer)
-{
- int result = false;
+ bool enable = false;
- if (layer < 0)
- {
- DisableOpenGLLights();
- result = false;
- } else
+ if (layer >= 0)
{
if (m_clientobject)
- {
- if (applyLights(layer))
- {
- EnableOpenGLLights();
- result = true;
- } else
- {
- DisableOpenGLLights();
- result = false;
- }
+ {
+ if (layer == RAS_LIGHT_OBJECT_LAYER)
+ layer = static_cast<KX_GameObject*>(m_clientobject)->GetLayer();
+
+ enable = applyLights(layer, viewmat);
}
}
- return result;
+
+ if(enable)
+ EnableOpenGLLights();
+ else
+ DisableOpenGLLights();
}
void GPC_RenderTools::EnableOpenGLLights()
{
+ if(m_lastlighting == true)
+ return;
+
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
- glColorMaterial(GL_FRONT_AND_BACK,GL_DIFFUSE);
- if (bgl::QueryExtension(bgl::_GL_EXT_separate_specular_color) || bgl::QueryVersion(1, 2))
+
+ glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
+ glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, true);
+ if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2)
glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
+
+ m_lastlighting = true;
+}
+
+void GPC_RenderTools::DisableOpenGLLights()
+{
+ if(m_lastlighting == false)
+ return;
+
+ glDisable(GL_LIGHTING);
+ glDisable(GL_COLOR_MATERIAL);
+
+ m_lastlighting = false;
+}
+
+
+void GPC_RenderTools::SetClientObject(RAS_IRasterizer *rasty, void* obj)
+{
+ if (m_clientobject != obj)
+ {
+ bool ccw = (obj == NULL || !((KX_GameObject*)obj)->IsNegativeScaling());
+ rasty->SetFrontFace(ccw);
+
+ m_clientobject = obj;
+ }
+}
+
+bool GPC_RenderTools::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data)
+{
+ double* const oglmatrix = (double* const) data;
+ MT_Point3 resultpoint(result->m_hitPoint);
+ MT_Vector3 resultnormal(result->m_hitNormal);
+ MT_Vector3 left(oglmatrix[0],oglmatrix[1],oglmatrix[2]);
+ MT_Vector3 dir = -(left.cross(resultnormal)).safe_normalized();
+ left = (dir.cross(resultnormal)).safe_normalized();
+ // for the up vector, we take the 'resultnormal' returned by the physics
+
+ double maat[16]={
+ left[0], left[1], left[2], 0,
+ dir[0], dir[1], dir[2], 0,
+ resultnormal[0],resultnormal[1],resultnormal[2], 0,
+ 0, 0, 0, 1};
+ glTranslated(resultpoint[0],resultpoint[1],resultpoint[2]);
+ //glMultMatrixd(oglmatrix);
+ glMultMatrixd(maat);
+ return true;
+}
+
+void GPC_RenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmatrix,int objectdrawmode )
+{
+ /* FIXME:
+ blender: intern/moto/include/MT_Vector3.inl:42: MT_Vector3 operator/(const
+ MT_Vector3&, double): Assertion `!MT_fuzzyZero(s)' failed.
+
+ Program received signal SIGABRT, Aborted.
+ [Switching to Thread 16384 (LWP 1519)]
+ 0x40477571 in kill () from /lib/libc.so.6
+ (gdb) bt
+ #7 0x08334368 in MT_Vector3::normalized() const ()
+ #8 0x0833e6ec in GPC_RenderTools::applyTransform(RAS_IRasterizer*, double*, int) ()
+ */
+
+ if (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED ||
+ objectdrawmode & RAS_IPolyMaterial::BILLBOARD_AXISALIGNED)
+ {
+ // rotate the billboard/halo
+ //page 360/361 3D Game Engine Design, David Eberly for a discussion
+ // on screen aligned and axis aligned billboards
+ // assumed is that the preprocessor transformed all billboard polygons
+ // so that their normal points into the positive x direction (1.0 , 0.0 , 0.0)
+ // when new parenting for objects is done, this rotation
+ // will be moved into the object
+
+ MT_Point3 objpos (oglmatrix[12],oglmatrix[13],oglmatrix[14]);
+ MT_Point3 campos = rasty->GetCameraPosition();
+ MT_Vector3 dir = (campos - objpos).safe_normalized();
+ MT_Vector3 up(0,0,1.0);
+
+ KX_GameObject* gameobj = (KX_GameObject*) this->m_clientobject;
+ // get scaling of halo object
+ MT_Vector3 size = gameobj->GetSGNode()->GetLocalScale();
+
+ bool screenaligned = (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED)!=0;//false; //either screen or axisaligned
+ if (screenaligned)
+ {
+ up = (up - up.dot(dir) * dir).safe_normalized();
+ } else
+ {
+ dir = (dir - up.dot(dir)*up).safe_normalized();
+ }
+
+ MT_Vector3 left = dir.normalized();
+ dir = (left.cross(up)).normalized();
+
+ // we have calculated the row vectors, now we keep
+ // local scaling into account:
+
+ left *= size[0];
+ dir *= size[1];
+ up *= size[2];
+ double maat[16]={
+ left[0], left[1],left[2], 0,
+ dir[0], dir[1],dir[2],0,
+ up[0],up[1],up[2],0,
+ 0,0,0,1};
+ glTranslated(objpos[0],objpos[1],objpos[2]);
+ glMultMatrixd(maat);
+
+ } else
+ {
+ if (objectdrawmode & RAS_IPolyMaterial::SHADOW)
+ {
+ // shadow must be cast to the ground, physics system needed here!
+ MT_Point3 frompoint(oglmatrix[12],oglmatrix[13],oglmatrix[14]);
+ KX_GameObject *gameobj = (KX_GameObject*) this->m_clientobject;
+ MT_Vector3 direction = MT_Vector3(0,0,-1);
+
+ direction.normalize();
+ direction *= 100000;
+
+ MT_Point3 topoint = frompoint + direction;
+
+ KX_Scene* kxscene = (KX_Scene*) m_auxilaryClientInfo;
+ PHY_IPhysicsEnvironment* physics_environment = kxscene->GetPhysicsEnvironment();
+ KX_IPhysicsController* physics_controller = gameobj->GetPhysicsController();
+
+ KX_GameObject *parent = gameobj->GetParent();
+ if (!physics_controller && parent)
+ physics_controller = parent->GetPhysicsController();
+ if (parent)
+ parent->Release();
+
+ KX_RayCast::Callback<GPC_RenderTools> callback(this, physics_controller, oglmatrix);
+ if (!KX_RayCast::RayTest(physics_environment, frompoint, topoint, callback))
+ {
+ // couldn't find something to cast the shadow on...
+ glMultMatrixd(oglmatrix);
+ }
+ } else
+ {
+
+ // 'normal' object
+ glMultMatrixd(oglmatrix);
+ }
+ }
}
-void GPC_RenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode,
- const char* text,
- int xco,
- int yco,
- int width,
- int height)
+
+void GPC_RenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode,
+ const char* text,
+ int xco,
+ int yco,
+ int width,
+ int height)
{
STR_String tmpstr(text);
int lines;
@@ -238,21 +349,19 @@ void GPC_RenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode,
glDisable(GL_LIGHTING);
}
-/**
- * Copied from KX_BlenderRenderTools.cpp in KX_blenderhook
- * Renders text into a (series of) polygon(s), using a texture font,
- * Each character consists of one polygon (one quad or two triangles)
- */
+/* Render Text renders text into a (series of) polygon, using a texture font,
+ * Each character consists of one polygon (one quad or two triangles) */
+
void GPC_RenderTools::RenderText(
int mode,
RAS_IPolyMaterial* polymat,
- float v1[3], float v2[3], float v3[3], float v4[3])
+ float v1[3], float v2[3], float v3[3], float v4[3], int glattrib)
{
STR_String mytext = ((CValue*)m_clientobject)->GetPropertyText("Text");
const unsigned int flag = polymat->GetFlag();
struct MTFace* tface = 0;
- unsigned int* col = 0;
+ unsigned int *col = 0;
if(flag & RAS_BLENDERMAT) {
KX_BlenderMaterial *bl_mat = static_cast<KX_BlenderMaterial*>(polymat);
@@ -263,110 +372,29 @@ void GPC_RenderTools::RenderText(
tface = blenderpoly->GetMTFace();
col = blenderpoly->GetMCol();
}
-
- BL_RenderText(mode, mytext, mytext.Length(), tface, col, v1, v2, v3, v4);
+
+ GPU_render_text(tface, mode, mytext, mytext.Length(), col, v1, v2, v3, v4, glattrib);
}
-
-/**
- * Copied from KX_BlenderGL.cpp in KX_blenderhook
- */
-void GPC_RenderTools::BL_RenderText(
- int mode,
- const char* textstr,
- int textlen,
- struct MTFace* tface,
- unsigned int* col,
- float v1[3],float v2[3],float v3[3],float v4[3])
+void GPC_RenderTools::PushMatrix()
{
- struct Image* ima;
-
- if (mode & TF_BMFONT) {
- //char string[MAX_PROPSTRING];
-// float tmat[4][4];
- int characters, index, character;
- float centerx, centery, sizex, sizey, transx, transy, movex, movey, advance;
-
-// bProperty *prop;
-
- // string = "Frank van Beek";
-
- characters = textlen;
-
- ima = (struct Image*) tface->tpage;
- if (ima == NULL) {
- characters = 0;
- }
-
- if(!col) glColor3f(1.0f, 1.0f, 1.0f);
-
- glPushMatrix();
- for (index = 0; index < characters; index++) {
- // lets calculate offset stuff
- character = textstr[index];
-
- // space starts at offset 1
- // character = character - ' ' + 1;
-
- matrixGlyph((ImBuf *)ima->ibufs.first, character, & centerx, &centery, &sizex, &sizey, &transx, &transy, &movex, &movey, &advance);
-
- glBegin(GL_POLYGON);
- // printf(" %c %f %f %f %f\n", character, tface->uv[0][0], tface->uv[0][1], );
- // glTexCoord2f((tface->uv[0][0] - centerx) * sizex + transx, (tface->uv[0][1] - centery) * sizey + transy);
- glTexCoord2f((tface->uv[0][0] - centerx) * sizex + transx, (tface->uv[0][1] - centery) * sizey + transy);
-
- if(col) BL_spack(col[0]);
- // glVertex3fv(v1);
- glVertex3f(sizex * v1[0] + movex, sizey * v1[1] + movey, v1[2]);
-
- glTexCoord2f((tface->uv[1][0] - centerx) * sizex + transx, (tface->uv[1][1] - centery) * sizey + transy);
- if(col) BL_spack(col[1]);
- // glVertex3fv(v2);
- glVertex3f(sizex * v2[0] + movex, sizey * v2[1] + movey, v2[2]);
-
- glTexCoord2f((tface->uv[2][0] - centerx) * sizex + transx, (tface->uv[2][1] - centery) * sizey + transy);
- if(col) BL_spack(col[2]);
- // glVertex3fv(v3);
- glVertex3f(sizex * v3[0] + movex, sizey * v3[1] + movey, v3[2]);
-
- if(v4) {
- // glTexCoord2f((tface->uv[3][0] - centerx) * sizex + transx, 1.0 - (1.0 - tface->uv[3][1]) * sizey - transy);
- glTexCoord2f((tface->uv[3][0] - centerx) * sizex + transx, (tface->uv[3][1] - centery) * sizey + transy);
- if(col) BL_spack(col[3]);
- // glVertex3fv(v4);
- glVertex3f(sizex * v4[0] + movex, sizey * v4[1] + movey, v4[2]);
- }
- glEnd();
-
- glTranslatef(advance, 0.0, 0.0);
- }
- glPopMatrix();
-
- }
+ glPushMatrix();
}
-
-RAS_IPolyMaterial* GPC_RenderTools::CreateBlenderPolyMaterial(
- const STR_String &texname,
- bool ba,const STR_String& matname,int tile,int tilexrep,int tileyrep,int mode,bool transparant, bool zsort,
- int lightlayer,bool bIsTriangle,void* clientobject,void* tface)
+void GPC_RenderTools::PopMatrix()
{
- assert(!"Deprecated");
-/* return new GPC_PolygonMaterial(texname, ba,matname,tile,tilexrep,tileyrep,
- mode,transparant,zsort,lightlayer,bIsTriangle,clientobject,tface);
- */
- return NULL;
+ glPopMatrix();
}
-int GPC_RenderTools::applyLights(int objectlayer)
+int GPC_RenderTools::applyLights(int objectlayer, const MT_Transform& viewmat)
{
-// taken from blender source, incompatibility between Blender Object / GameObject
-
- int count;
+ // taken from blender source, incompatibility between Blender Object / GameObject
+ float glviewmat[16];
+ unsigned int count;
float vec[4];
-
+
vec[3]= 1.0;
for(count=0; count<m_numgllights; count++)
@@ -375,23 +403,20 @@ int GPC_RenderTools::applyLights(int objectlayer)
//std::vector<struct RAS_LightObject*> m_lights;
std::vector<struct RAS_LightObject*>::iterator lit = m_lights.begin();
+ viewmat.getValue(glviewmat);
+ glPushMatrix();
+ glLoadMatrixf(glviewmat);
for (lit = m_lights.begin(), count = 0; !(lit==m_lights.end()) && count < m_numgllights; ++lit)
{
RAS_LightObject* lightdata = (*lit);
if (lightdata->m_layer & objectlayer)
{
-
- glPushMatrix();
- glLoadMatrixf(m_viewmat);
-
-
vec[0] = (*(lightdata->m_worldmatrix))(0,3);
vec[1] = (*(lightdata->m_worldmatrix))(1,3);
vec[2] = (*(lightdata->m_worldmatrix))(2,3);
vec[3] = 1;
-
if(lightdata->m_type==RAS_LightObject::LIGHT_SUN) {
vec[0] = (*(lightdata->m_worldmatrix))(0,2);
@@ -447,126 +472,16 @@ int GPC_RenderTools::applyLights(int objectlayer)
}
glLightfv((GLenum)(GL_LIGHT0+count), GL_SPECULAR, vec);
glEnable((GLenum)(GL_LIGHT0+count));
-
- count++;
- glPopMatrix();
+ count++;
}
}
+ glPopMatrix();
return count;
}
-bool GPC_RenderTools::RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data)
-{
- double* const oglmatrix = (double* const) data;
- MT_Point3 resultpoint(hit_point);
- MT_Vector3 resultnormal(hit_normal);
- MT_Vector3 left(oglmatrix[0],oglmatrix[1],oglmatrix[2]);
- MT_Vector3 dir = -(left.cross(resultnormal)).safe_normalized();
- left = (dir.cross(resultnormal)).safe_normalized();
- // for the up vector, we take the 'resultnormal' returned by the physics
-
- double maat[16]={
- left[0], left[1], left[2], 0,
- dir[0], dir[1], dir[2], 0,
- resultnormal[0],resultnormal[1],resultnormal[2], 0,
- 0, 0, 0, 1};
- glTranslated(resultpoint[0],resultpoint[1],resultpoint[2]);
- //glMultMatrixd(oglmatrix);
- glMultMatrixd(maat);
- return true;
-}
-
-void GPC_RenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmatrix,int objectdrawmode )
-{
- if (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED ||
- objectdrawmode & RAS_IPolyMaterial::BILLBOARD_AXISALIGNED)
- {
- // rotate the billboard/halo
- //page 360/361 3D Game Engine Design, David Eberly for a discussion
- // on screen aligned and axis aligned billboards
- // assumed is that the preprocessor transformed all billboard polygons
- // so that their normal points into the positive x direction (1.0 , 0.0 , 0.0)
- // when new parenting for objects is done, this rotation
- // will be moved into the object
-
- MT_Point3 objpos (oglmatrix[12],oglmatrix[13],oglmatrix[14]);
- MT_Point3 campos = rasty->GetCameraPosition();
- MT_Vector3 dir = (campos - objpos).safe_normalized();
- MT_Vector3 up(0,0,1.0);
-
- KX_GameObject* gameobj = (KX_GameObject*) this->m_clientobject;
- // get scaling of halo object
- MT_Vector3 size = gameobj->GetSGNode()->GetLocalScale();
-
- bool screenaligned = (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED)!=0;//false; //either screen or axisaligned
- if (screenaligned)
- {
- up = (up - up.dot(dir) * dir).safe_normalized();
- } else
- {
- dir = (dir - up.dot(dir)*up).safe_normalized();
- }
-
- MT_Vector3 left = dir.normalized();
- dir = (left.cross(up)).normalized();
-
- // we have calculated the row vectors, now we keep
- // local scaling into account:
-
- left *= size[0];
- dir *= size[1];
- up *= size[2];
- double maat[16]={
- left[0], left[1],left[2], 0,
- dir[0], dir[1],dir[2],0,
- up[0],up[1],up[2],0,
- 0,0,0,1};
- glTranslated(objpos[0],objpos[1],objpos[2]);
- glMultMatrixd(maat);
-
- } else
- {
- if (objectdrawmode & RAS_IPolyMaterial::SHADOW)
- {
- // shadow must be cast to the ground, physics system needed here!
- MT_Point3 frompoint(oglmatrix[12],oglmatrix[13],oglmatrix[14]);
- KX_GameObject *gameobj = (KX_GameObject*) this->m_clientobject;
- MT_Vector3 direction = MT_Vector3(0,0,-1);
-
- direction.normalize();
- direction *= 100000;
-
- MT_Point3 topoint = frompoint + direction;
-
- KX_Scene* kxscene = (KX_Scene*) m_auxilaryClientInfo;
- PHY_IPhysicsEnvironment* physics_environment = kxscene->GetPhysicsEnvironment();
- KX_IPhysicsController* physics_controller = gameobj->GetPhysicsController();
-
- KX_GameObject *parent = gameobj->GetParent();
- if (!physics_controller && parent)
- physics_controller = parent->GetPhysicsController();
- if (parent)
- parent->Release();
-
- MT_Point3 resultpoint;
- MT_Vector3 resultnormal;
- if (!KX_RayCast::RayTest(physics_controller, physics_environment, frompoint, topoint, resultpoint, resultnormal, KX_RayCast::Callback<GPC_RenderTools>(this, oglmatrix)))
- {
- // couldn't find something to cast the shadow on...
- glMultMatrixd(oglmatrix);
- }
- } else
- {
-
- // 'normal' object
- glMultMatrixd(oglmatrix);
- }
- }
-}
-
void GPC_RenderTools::MotionBlur(RAS_IRasterizer* rasterizer)
{
int state = rasterizer->GetMotionBlurState();
@@ -590,4 +505,13 @@ void GPC_RenderTools::MotionBlur(RAS_IRasterizer* rasterizer)
}
}
-unsigned int GPC_RenderTools::m_numgllights;
+void GPC_RenderTools::Update2DFilter(vector<STR_String>& propNames, void* gameObj, RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode, int pass, STR_String& text)
+{
+ m_filtermanager.EnableFilter(propNames, gameObj, filtermode, pass, text);
+}
+
+void GPC_RenderTools::Render2DFilters(RAS_ICanvas* canvas)
+{
+ m_filtermanager.RenderFilters(canvas);
+}
+
diff --git a/source/gameengine/GamePlayer/common/GPC_RenderTools.h b/source/gameengine/GamePlayer/common/GPC_RenderTools.h
index f62aafff7c2..382956e73ea 100644
--- a/source/gameengine/GamePlayer/common/GPC_RenderTools.h
+++ b/source/gameengine/GamePlayer/common/GPC_RenderTools.h
@@ -30,146 +30,79 @@
#ifndef __GPC_RENDERTOOLS_H
#define __GPC_RENDERTOOLS_H
-#if defined(WIN32) || defined(__APPLE__)
- #ifdef WIN32
- #include <windows.h>
- #include <GL/gl.h>
- #else // WIN32
- // __APPLE__ is defined
- #include <AGL/gl.h>
- #endif // WIN32
-#else //defined(WIN32) || defined(__APPLE__)
- #include <GL/gl.h>
-#endif //defined(WIN32) || defined(__APPLE__)
-
+#ifdef WIN32
+// don't show stl-warnings
+#pragma warning (disable:4786)
+#include <windows.h>
+#endif // WIN32
#include "RAS_IRenderTools.h"
#include "BMF_Api.h"
struct KX_ClientObjectInfo;
+class KX_RayCast;
+/* BlenderRenderTools are a set of tools to apply 2D/3D graphics effects, which
+ * are not part of the (polygon) Rasterizer. Effects like 2D text, 3D (polygon)
+ * text, lighting.
+ *
+ * Most of this code is duplicated in KX_BlenderRenderTools, so this should be
+ * moved to some common location to avoid duplication. */
class GPC_RenderTools : public RAS_IRenderTools
{
+ int m_lastlightlayer;
+ bool m_lastlighting;
+ static unsigned int m_numgllights;
+
+ BMF_Font* m_font;
+
public:
- GPC_RenderTools();
- virtual ~GPC_RenderTools();
-
- virtual void EndFrame(RAS_IRasterizer* rasty);
- virtual void BeginFrame(RAS_IRasterizer* rasty);
-
- void DisableOpenGLLights()
- {
- glDisable(GL_LIGHTING);
- glDisable(GL_COLOR_MATERIAL);
- }
-
- void EnableOpenGLLights();
-
- int ProcessLighting(int layer);
-
- void Perspective(int a, int width, int height, float mat[4][4], float viewmat[4][4])
- {
- if(a== 0)
- {
- glMatrixMode(GL_PROJECTION);
- glMatrixMode(GL_MODELVIEW);
- glLoadIdentity();
- }
- else
- {
- if(a== 1)
- {
- glMatrixMode(GL_PROJECTION);
- glMatrixMode(GL_MODELVIEW);
- }
- }
- }
-
- /**
- * @attention mode is ignored here
- */
- virtual void RenderText2D(
- RAS_TEXT_RENDER_MODE mode,
- const char* text,
- int xco,
- int yco,
- int width,
- int height);
-
- /**
- * Renders text into a (series of) polygon(s), using a texture font,
- * Each character consists of one polygon (one quad or two triangles)
- */
- virtual void RenderText(
- int mode,
- RAS_IPolyMaterial* polymat,
- float v1[3],
- float v2[3],
- float v3[3],
- float v4[3]);
-
- void Render(RAS_IRasterizer* rasty,double* oglmatrix,int objectdrawmode)
- {
- glPopMatrix();
- glPushMatrix();
- glMultMatrixd(oglmatrix);
- }
-
- void applyTransform(RAS_IRasterizer* rasty, double* oglmatrix, int objectdrawmode);
-
- virtual void PushMatrix()
- {
- glPushMatrix();
- }
-
- virtual void PopMatrix()
- {
- glPopMatrix();
- }
-
- virtual class RAS_IPolyMaterial* CreateBlenderPolyMaterial(
- const STR_String &texname,
- bool ba,
- const STR_String& matname,
- int tile,
- int tilexrep,int tileyrep,
- int mode,
- bool transparant,
- bool zsort,
- int lightlayer,
- bool bIsTriangle,
- void* clientobject,
- void* tface);
-
- int applyLights(int objectlayer);
-
- bool RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data);
+ GPC_RenderTools();
+ virtual ~GPC_RenderTools();
+
+ void EndFrame(RAS_IRasterizer* rasty);
+ void BeginFrame(RAS_IRasterizer* rasty);
+
+ void EnableOpenGLLights();
+ void DisableOpenGLLights();
+ void ProcessLighting(int layer, const MT_Transform& viewmat);
+
+ /* @attention mode is ignored here */
+ void RenderText2D(RAS_TEXT_RENDER_MODE mode,
+ const char* text,
+ int xco,
+ int yco,
+ int width,
+ int height);
+ void RenderText(int mode,
+ class RAS_IPolyMaterial* polymat,
+ float v1[3],
+ float v2[3],
+ float v3[3],
+ float v4[3],
+ int glattrib);
+
+ void applyTransform(RAS_IRasterizer* rasty, double* oglmatrix, int objectdrawmode);
+ int applyLights(int objectlayer, const MT_Transform& viewmat);
+
+ void PushMatrix();
+ void PopMatrix();
+
+ bool RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data);
+ bool NeedRayCast(KX_ClientObjectInfo* client) { return true; }
virtual void MotionBlur(RAS_IRasterizer* rasterizer);
-protected:
- /**
- * Copied from KX_BlenderGL.cpp in KX_blenderhook
- */
- void BL_RenderText(
- int mode,
- const char* textstr,
- int textlen,
- struct MTFace* tface,
- unsigned int* col,
- float v1[3],float v2[3],float v3[3],float v4[3]);
- void BL_spack(unsigned int ucol)
- {
- char *cp = (char *)&ucol;
- glColor3ub(cp[3], cp[2], cp[1]);
- }
+ virtual void Update2DFilter(vector<STR_String>& propNames, void* gameObj, RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode, int pass, STR_String& text);
- BMF_Font* m_font;
- static unsigned int m_numgllights;
+ virtual void Render2DFilters(RAS_ICanvas* canvas);
+
+ virtual void SetClientObject(RAS_IRasterizer *rasty, void* obj);
};
#endif // __GPC_RENDERTOOLS_H
+
diff --git a/source/gameengine/GamePlayer/common/Makefile b/source/gameengine/GamePlayer/common/Makefile
index b4800878704..6a12e659be6 100644
--- a/source/gameengine/GamePlayer/common/Makefile
+++ b/source/gameengine/GamePlayer/common/Makefile
@@ -35,6 +35,7 @@ include nan_compile.mk
CCFLAGS += $(LEVEL_1_CPP_WARNINGS)
+CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(OPENGL_HEADERS)
CPPFLAGS += -I../../../blender/blenkernel
@@ -42,6 +43,7 @@ CPPFLAGS += -I../../../blender/blenloader
CPPFLAGS += -I../../../blender/blenlib
CPPFLAGS += -I../../../blender/imbuf
CPPFLAGS += -I../../../blender/makesdna
+CPPFLAGS += -I../../../blender/gpu
CPPFLAGS += -I../../../kernel/gen_system
CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include
@@ -60,6 +62,7 @@ CPPFLAGS += -I../../../gameengine/Converter
CPPFLAGS += -I../../../gameengine/Expressions
CPPFLAGS += -I../../../gameengine/GameLogic
CPPFLAGS += -I../../../gameengine/Converter
+CPPFLAGS += -I../../../gameengine/BlenderRoutines
CPPFLAGS += -I../../../gameengine/Ketsji
CPPFLAGS += -I../../../gameengine/Ketsji/KXNetwork
CPPFLAGS += -I../../../gameengine/Network
diff --git a/source/gameengine/GamePlayer/common/SConscript b/source/gameengine/GamePlayer/common/SConscript
index b6e373b4f92..30f20a670d3 100644
--- a/source/gameengine/GamePlayer/common/SConscript
+++ b/source/gameengine/GamePlayer/common/SConscript
@@ -4,60 +4,62 @@ Import ('env')
source_files = ['bmfont.cpp',
- 'GPC_Canvas.cpp',
- 'GPC_Engine.cpp',
- 'GPC_KeyboardDevice.cpp',
- 'GPC_MouseDevice.cpp',
- 'GPC_PolygonMaterial.cpp',
- 'GPC_RawImage.cpp',
- 'GPC_RawLoadDotBlendArray.cpp',
- 'GPC_RawLogoArrays.cpp',
- 'GPC_RenderTools.cpp',
- 'GPC_System.cpp']
+ 'GPC_Canvas.cpp',
+ 'GPC_Engine.cpp',
+ 'GPC_KeyboardDevice.cpp',
+ 'GPC_MouseDevice.cpp',
+ 'GPC_RawImage.cpp',
+ 'GPC_RawLoadDotBlendArray.cpp',
+ 'GPC_RawLogoArrays.cpp',
+ 'GPC_RenderTools.cpp',
+ 'GPC_System.cpp']
incs = ['.',
- '#intern/string',
- '#intern/ghost',
- '#intern/guardedalloc',
- '#intern/bmfont',
- '#intern/moto/include',
- '#intern/SoundSystem',
- '#source/gameengine/Rasterizer/RAS_OpenGLRasterizer',
- '#source/kernel/gen_system',
- '#source/kernel/gen_messaging',
- '#source/gameengine/Converter',
- '#source/blender/imbuf',
- '#source/gameengine/Ketsji',
- '#source/blender/blenlib',
- '#source/blender/blenkernel',
- '#source/blender',
- '#source/blender/editors/include',
- '#source/blender/makesdna',
- '#source/gameengine/Rasterizer',
- '#source/gameengine/GameLogic',
- '#source/gameengine/Expressions',
- '#source/gameengine/Network',
- '#source/gameengine/SceneGraph',
- '#source/gameengine/Physics/common',
- '#source/gameengine/Physics/Sumo',
- '#source/gameengine/Physics/Sumo/Fuzzics/include',
- '#source/gameengine/Network/LoopBackNetwork',
- '#source/gameengine/GamePlayer/ghost',
- '#source/blender/misc',
- '#source/blender/blenloader']
-
+ '#intern/string',
+ '#intern/ghost',
+ '#intern/guardedalloc',
+ '#intern/bmfont',
+ '#intern/moto/include',
+ '#intern/SoundSystem',
+ '#source/gameengine/Rasterizer/RAS_OpenGLRasterizer',
+ '#source/kernel/gen_system',
+ '#source/kernel/gen_messaging',
+ '#source/gameengine/Converter',
+ '#source/blender/imbuf',
+ '#source/gameengine/Ketsji',
+ '#source/blender/blenlib',
+ '#source/blender/blenkernel',
+ '#source/blender',
+ '#source/blender/include',
+ '#source/blender/makesdna',
+ '#source/gameengine/BlenderRoutines',
+ '#source/gameengine/Rasterizer',
+ '#source/gameengine/GameLogic',
+ '#source/gameengine/Expressions',
+ '#source/gameengine/Network',
+ '#source/gameengine/SceneGraph',
+ '#source/gameengine/Physics/common',
+ '#source/gameengine/Physics/Sumo',
+ '#source/gameengine/Physics/Sumo/Fuzzics/include',
+ '#source/gameengine/Network/LoopBackNetwork',
+ '#source/gameengine/GamePlayer/ghost',
+ '#source/blender/misc',
+ '#source/blender/blenloader',
+ '#source/blender/gpu',
+ '#extern/glew/include']
+
#This is all plugin stuff!
#if sys.platform=='win32':
# source_files += ['windows/GPW_Canvas.cpp',
-# 'windows/GPW_Engine.cpp',
-# 'windows/GPW_KeyboardDevice.cpp',
-# 'windows/GPW_System.cpp']
+# 'windows/GPW_Engine.cpp',
+# 'windows/GPW_KeyboardDevice.cpp',
+# 'windows/GPW_System.cpp']
# gp_common_env.Append ( CPPPATH = ['windows'])
#elif sys.platform=='linux2' or sys.platform=='linux-i386':
# source_files += ['unix/GPU_Canvas.cpp',
-# 'unix/GPU_Engine.cpp',
-# 'unix/GPU_KeyboardDevice.cpp',
-# 'unix/GPU_System.cpp']
+# 'unix/GPU_Engine.cpp',
+# 'unix/GPU_KeyboardDevice.cpp',
+# 'unix/GPU_System.cpp']
# gp_common_env.Append ( CPPPATH = ['unix'])
incs += Split(env['BF_PYTHON_INC'])
@@ -67,6 +69,6 @@ incs += Split(env['BF_ZLIB_INC'])
cflags=[]
if env['OURPLATFORM']=='win32-vc':
- cflags = ['/GR']
+ cflags = ['/GR']
env.BlenderLib (libname='gp_common', sources=source_files, includes=incs, defines = [], libtype='player', priority=5, compileflags=cflags)
diff --git a/source/gameengine/GamePlayer/common/unix/GPU_PolygonMaterial.h b/source/gameengine/GamePlayer/common/unix/GPU_PolygonMaterial.h
index fee729a84ac..e5ed7f39811 100644
--- a/source/gameengine/GamePlayer/common/unix/GPU_PolygonMaterial.h
+++ b/source/gameengine/GamePlayer/common/unix/GPU_PolygonMaterial.h
@@ -37,9 +37,9 @@ class GPU_PolygonMaterial : public BP_PolygonMaterial
public:
GPUPolygonMaterial(const STR_String& texname, bool ba,const STR_String& matname,
int tile, int tileXrep, int tileYrep, int mode, int transparant,
- int lightlayer,bool bIsTriangle,void* clientobject,void* tpage) :
+ int lightlayer,,void* tpage) :
BP_PolygonMaterial(texname, ba,matname, tile, tileXrep, tileYrep,
- mode, transparant, lightlayer, bIsTriangle, clientobject),
+ mode, transparant, lightlayer),
m_tface(tpage)
{
}
diff --git a/source/gameengine/GamePlayer/common/windows/GPW_Canvas.h b/source/gameengine/GamePlayer/common/windows/GPW_Canvas.h
index bb1abd71505..bf8cb720811 100644
--- a/source/gameengine/GamePlayer/common/windows/GPW_Canvas.h
+++ b/source/gameengine/GamePlayer/common/windows/GPW_Canvas.h
@@ -36,7 +36,7 @@
#include <iostream>
#include <windows.h>
-#include <gl/gl.h>
+//#include <gl/gl.h>
#include "GPC_Canvas.h"
diff --git a/source/gameengine/GamePlayer/ghost/CMakeLists.txt b/source/gameengine/GamePlayer/ghost/CMakeLists.txt
index 3d17cd2cfdd..5e0ca93ac06 100644
--- a/source/gameengine/GamePlayer/ghost/CMakeLists.txt
+++ b/source/gameengine/GamePlayer/ghost/CMakeLists.txt
@@ -64,7 +64,9 @@ SET(INC
../../../../source/gameengine/GamePlayer/common
../../../../source/blender/misc
../../../../source/blender/blenloader
+ ../../../../source/blender/gpu
../../../../extern/solid
+ ../../../../extern/glew/include
${PYTHON_INC}
)
diff --git a/source/gameengine/GamePlayer/ghost/GPG_Application.cpp b/source/gameengine/GamePlayer/ghost/GPG_Application.cpp
index 020798d5f24..aa5e5835cdc 100644
--- a/source/gameengine/GamePlayer/ghost/GPG_Application.cpp
+++ b/source/gameengine/GamePlayer/ghost/GPG_Application.cpp
@@ -37,23 +37,14 @@
#include <windows.h>
#endif
-#ifdef __APPLE__
-#define GL_GLEXT_LEGACY 1
-#include <OpenGL/gl.h>
-#include <OpenGL/glu.h>
-#else
-#include <GL/gl.h>
-#if defined(__sun__) && !defined(__sparc__)
-#include <mesa/glu.h>
-#else
-#include <GL/glu.h>
-#endif
-#endif
+#include "GL/glew.h"
+#include "GPU_extensions.h"
#include "GPG_Application.h"
#include <iostream>
#include <MT_assert.h>
+#include <stdlib.h>
/**********************************
* Begin Blender include block
@@ -66,6 +57,8 @@ extern "C"
#include "BLO_readfile.h"
#include "BKE_global.h"
#include "BKE_main.h"
+#include "IMB_imbuf.h"
+#include "DNA_scene_types.h"
#ifdef __cplusplus
}
#endif // __cplusplus
@@ -107,15 +100,15 @@ extern "C"
#include "GHOST_IWindow.h"
#include "GHOST_Rect.h"
-
static void frameTimerProc(GHOST_ITimerTask* task, GHOST_TUns64 time);
static GHOST_ISystem* fSystem = 0;
static const int kTimerFreq = 10;
-GPG_Application::GPG_Application(GHOST_ISystem* system, struct Main* maggie, STR_String startSceneName)
- : m_startSceneName(startSceneName),
- m_maggie(maggie),
+GPG_Application::GPG_Application(GHOST_ISystem* system)
+ : m_startSceneName(""),
+ m_startScene(0),
+ m_maggie(0),
m_exitRequested(0),
m_system(system),
m_mainWindow(0),
@@ -123,6 +116,7 @@ GPG_Application::GPG_Application(GHOST_ISystem* system, struct Main* maggie, STR
m_cursor(GHOST_kStandardCursorFirstCursor),
m_engineInitialized(0),
m_engineRunning(0),
+ m_isEmbedded(false),
m_ketsjiengine(0),
m_kxsystem(0),
m_keyboard(0),
@@ -133,7 +127,10 @@ GPG_Application::GPG_Application(GHOST_ISystem* system, struct Main* maggie, STR
m_sceneconverter(0),
m_networkdevice(0),
m_audiodevice(0),
- m_blendermat(0)
+ m_blendermat(0),
+ m_blenderglslmat(0),
+ m_pyGlobalDictString(0),
+ m_pyGlobalDictString_Length(0)
{
fSystem = system;
}
@@ -142,21 +139,28 @@ GPG_Application::GPG_Application(GHOST_ISystem* system, struct Main* maggie, STR
GPG_Application::~GPG_Application(void)
{
+ if(m_pyGlobalDictString) {
+ delete [] m_pyGlobalDictString;
+ m_pyGlobalDictString = 0;
+ m_pyGlobalDictString_Length = 0;
+ }
+
exitEngine();
fSystem->disposeWindow(m_mainWindow);
}
-bool GPG_Application::SetGameEngineData(struct Main* maggie, STR_String startSceneName)
+bool GPG_Application::SetGameEngineData(struct Main* maggie, Scene *scene)
{
bool result = false;
- if (maggie != NULL && startSceneName != "")
+ if (maggie != NULL && scene != NULL)
{
- G.scene = (Scene*)maggie->scene.first;
+ G.scene = scene;
m_maggie = maggie;
- m_startSceneName = startSceneName;
+ m_startSceneName = scene->id.name+2;
+ m_startScene = scene;
result = true;
}
@@ -328,6 +332,26 @@ bool GPG_Application::startWindow(STR_String& title,
return success;
}
+bool GPG_Application::startEmbeddedWindow(STR_String& title,
+ const GHOST_TEmbedderWindowID parentWindow,
+ const bool stereoVisual,
+ const int stereoMode) {
+
+ m_mainWindow = fSystem->createWindow(title, 0, 0, 0, 0, GHOST_kWindowStateNormal,
+ GHOST_kDrawingContextTypeOpenGL, stereoVisual, parentWindow);
+
+ if (!m_mainWindow) {
+ printf("error: could not create main window\n");
+ exit(-1);
+ }
+ m_isEmbedded = true;
+
+ bool success = initEngine(m_mainWindow, stereoMode);
+ if (success) {
+ success = startEngine();
+ }
+ return success;
+}
bool GPG_Application::startFullScreen(
@@ -486,7 +510,8 @@ bool GPG_Application::initEngine(GHOST_IWindow* window, const int stereoMode)
{
if (!m_engineInitialized)
{
- bgl::InitExtensions(1);
+ GPU_extensions_init();
+ bgl::InitExtensions(true);
// get and set the preferences
SYS_SystemHandle syshandle = SYS_GetSystem();
@@ -504,25 +529,16 @@ bool GPG_Application::initEngine(GHOST_IWindow* window, const int stereoMode)
bool fixed_framerate= (SYS_GetCommandLineInt(syshandle, "fixed_framerate", fixedFr) != 0);
bool frameRate = (SYS_GetCommandLineInt(syshandle, "show_framerate", 0) != 0);
- bool useVertexArrays = SYS_GetCommandLineInt(syshandle,"vertexarrays",1) != 0;
- bool useLists = (SYS_GetCommandLineInt(syshandle, "displaylists", G.fileflags & G_FILE_DIAPLAY_LISTS) != 0);
-#ifdef GL_ARB_multitexture
- int gameflag =(G.fileflags & G_FILE_GAME_MAT);
- // ----------------------------------
- if(bgl::RAS_EXT_support._ARB_multitexture && bgl::QueryVersion(1, 1)) {
- m_blendermat = (SYS_GetCommandLineInt(syshandle, "blender_material", gameflag) != 0);
- int unitmax=0;
- glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, (GLint*)&unitmax);
- bgl::max_texture_units = MAXTEX>unitmax?unitmax:MAXTEX;
- //std::cout << "using(" << bgl::max_texture_units << ") of(" << unitmax << ") texture units." << std::endl;
- } else {
- bgl::max_texture_units = 0;
- }
-#else
- m_blendermat=0;
-#endif//GL_ARB_multitexture
- // ----------------------------------
-
+ bool useLists = (SYS_GetCommandLineInt(syshandle, "displaylists", G.fileflags & G_FILE_DISPLAY_LISTS) != 0);
+
+ if(GLEW_ARB_multitexture && GLEW_VERSION_1_1)
+ m_blendermat = (SYS_GetCommandLineInt(syshandle, "blender_material", 1) != 0);
+
+ if(GPU_extensions_minimum_support())
+ m_blenderglslmat = (SYS_GetCommandLineInt(syshandle, "blender_glsl_material", 1) != 0);
+ else if(G.fileflags & G_FILE_GAME_MAT_GLSL)
+ m_blendermat = false;
+
// create the canvas, rasterizer and rendertools
m_canvas = new GPG_Canvas(window);
if (!m_canvas)
@@ -533,12 +549,17 @@ bool GPG_Application::initEngine(GHOST_IWindow* window, const int stereoMode)
if (!m_rendertools)
goto initFailed;
- if(useLists)
- m_rasterizer = new RAS_ListRasterizer(m_canvas);
- else if (useVertexArrays && bgl::QueryVersion(1, 1))
+ if(useLists) {
+ if(GLEW_VERSION_1_1)
+ m_rasterizer = new RAS_ListRasterizer(m_canvas, true);
+ else
+ m_rasterizer = new RAS_ListRasterizer(m_canvas);
+ }
+ else if (GLEW_VERSION_1_1)
m_rasterizer = new RAS_VAOpenGLRasterizer(m_canvas);
else
m_rasterizer = new RAS_OpenGLRasterizer(m_canvas);
+
m_rasterizer->SetStereoMode((RAS_IRasterizer::StereoMode) stereoMode);
if (!m_rasterizer)
goto initFailed;
@@ -640,31 +661,37 @@ bool GPG_Application::startEngine(void)
{
STR_String startscenename = m_startSceneName.Ptr();
m_ketsjiengine->SetSceneConverter(m_sceneconverter);
-
+
// if (always_use_expand_framing)
// sceneconverter->SetAlwaysUseExpandFraming(true);
- if(m_blendermat)
+ if(m_blendermat && (G.fileflags & G_FILE_GAME_MAT))
m_sceneconverter->SetMaterials(true);
+ if(m_blenderglslmat && (G.fileflags & G_FILE_GAME_MAT_GLSL))
+ m_sceneconverter->SetGLSLMaterials(true);
KX_Scene* startscene = new KX_Scene(m_keyboard,
m_mouse,
m_networkdevice,
m_audiodevice,
- startscenename);
+ startscenename,
+ m_startScene);
// some python things
PyObject* dictionaryobject = initGamePlayerPythonScripting("Ketsji", psl_Lowest);
m_ketsjiengine->SetPythonDictionary(dictionaryobject);
initRasterizer(m_rasterizer, m_canvas);
- PyObject *gameLogic = initGameLogic(startscene);
+ PyObject *gameLogic = initGameLogic(m_ketsjiengine, startscene);
+ PyDict_SetItemString(dictionaryobject, "GameLogic", gameLogic); // Same as importing the module
initGameKeys();
initPythonConstraintBinding();
+ initMathutils();
+ initVideoTexture();
-
-
-
-
+ // Set the GameLogic.globalDict from marshal'd data, so we can
+ // load new blend files and keep data in GameLogic.globalDict
+ loadGamePythonConfig(m_pyGlobalDictString, m_pyGlobalDictString_Length);
+
m_sceneconverter->ConvertScene(
startscenename,
startscene,
@@ -682,6 +709,11 @@ bool GPG_Application::startEngine(void)
m_ketsjiengine->StartEngine(true);
m_engineRunning = true;
+ // Set the animation playback rate for ipo's and actions
+ // the framerate below should patch with FPS macro defined in blendef.h
+ // Could be in StartEngine set the framerate, we need the scene to do this
+ m_ketsjiengine->SetAnimFrameRate( (((double) G.scene->r.frs_sec) / G.scene->r.frs_sec_base) );
+
}
if (!m_engineRunning)
@@ -695,6 +727,16 @@ bool GPG_Application::startEngine(void)
void GPG_Application::stopEngine()
{
+ // GameLogic.globalDict gets converted into a buffer, and sorted in
+ // m_pyGlobalDictString so we can restore after python has stopped
+ // and started between .blend file loads.
+ if(m_pyGlobalDictString) {
+ delete [] m_pyGlobalDictString;
+ m_pyGlobalDictString = 0;
+ }
+
+ m_pyGlobalDictString_Length = saveGamePythonConfig(&m_pyGlobalDictString);
+
// when exiting the mainloop
exitGamePythonScripting();
m_ketsjiengine->StopEngine();
@@ -761,6 +803,12 @@ void GPG_Application::exitEngine()
m_canvas = 0;
}
+ libtiff_exit();
+#ifdef WITH_QUICKTIME
+ quicktime_exit();
+#endif
+ GPU_extensions_exit();
+
m_exitRequested = 0;
m_engineInitialized = false;
}
@@ -838,11 +886,12 @@ bool GPG_Application::handleKey(GHOST_IEvent* event, bool isDown)
{
GHOST_TEventDataPtr eventData = ((GHOST_IEvent*)event)->getData();
GHOST_TEventKeyData* keyData = static_cast<GHOST_TEventKeyData*>(eventData);
- if (fSystem->getFullScreen()) {
- if (keyData->key == GHOST_kKeyEsc) {
+ //no need for this test
+ //if (fSystem->getFullScreen()) {
+ if (keyData->key == GHOST_kKeyEsc && !m_keyboard->m_hookesc && !m_isEmbedded) {
m_exitRequested = KX_EXIT_REQUEST_OUTSIDE;
}
- }
+ //}
m_keyboard->ConvertEvent(keyData->key, isDown);
handled = true;
}
diff --git a/source/gameengine/GamePlayer/ghost/GPG_Application.h b/source/gameengine/GamePlayer/ghost/GPG_Application.h
index 024ca1dbf32..38408f919b4 100644
--- a/source/gameengine/GamePlayer/ghost/GPG_Application.h
+++ b/source/gameengine/GamePlayer/ghost/GPG_Application.h
@@ -50,17 +50,19 @@ class GPG_Canvas;
class GPG_KeyboardDevice;
class GPG_System;
struct Main;
+struct Scene;
class GPG_Application : public GHOST_IEventConsumer
{
public:
- GPG_Application(GHOST_ISystem* system, struct Main* maggie, STR_String startSceneName);
+ GPG_Application(GHOST_ISystem* system);
~GPG_Application(void);
- bool SetGameEngineData(struct Main* maggie,STR_String startSceneName);
+ bool SetGameEngineData(struct Main* maggie, struct Scene* scene);
bool startWindow(STR_String& title, int windowLeft, int windowTop, int windowWidth, int windowHeight,
const bool stereoVisual, const int stereoMode);
bool startFullScreen(int width, int height, int bpp, int frequency, const bool stereoVisual, const int stereoMode);
+ bool startEmbeddedWindow(STR_String& title, const GHOST_TEmbedderWindowID parent_window, const bool stereoVisual, const int stereoMode);
#ifdef WIN32
bool startScreenSaverFullScreen(int width, int height, int bpp, int frequency, const bool stereoVisual, const int stereoMode);
bool startScreenSaverPreview(HWND parentWindow, const bool stereoVisual, const int stereoMode);
@@ -100,6 +102,7 @@ protected:
/* The game data */
STR_String m_startSceneName;
+ struct Scene* m_startScene;
struct Main* m_maggie;
/* Exit state. */
@@ -118,6 +121,8 @@ protected:
bool m_engineInitialized;
/** Engine state. */
bool m_engineRunning;
+ /** Running on embedded window */
+ bool m_isEmbedded;
/** the gameengine itself */
KX_KetsjiEngine* m_ketsjiengine;
@@ -141,6 +146,13 @@ protected:
SND_IAudioDevice* m_audiodevice;
bool m_blendermat;
-
+ bool m_blenderglslmat;
+
+ /*
+ * GameLogic.globalDict as a string so that loading new blend files can use the same dict.
+ * Do this because python starts/stops when loading blend files.
+ */
+ char* m_pyGlobalDictString;
+ int m_pyGlobalDictString_Length;
};
diff --git a/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp b/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp
index 5226ca02662..0bf0317d8f2 100644
--- a/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp
+++ b/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp
@@ -44,6 +44,7 @@
#endif // __APPLE__
#include "GEN_messaging.h"
#include "KX_KetsjiEngine.h"
+#include "KX_PythonInit.h"
/**********************************
* Begin Blender include block
@@ -52,25 +53,31 @@
extern "C"
{
#endif // __cplusplus
+#include "MEM_guardedalloc.h"
+#include "BKE_blender.h"
#include "BKE_global.h"
#include "BKE_icons.h"
+#include "BKE_node.h"
#include "BLI_blenlib.h"
#include "DNA_scene_types.h"
#include "BLO_readfile.h"
#include "BLO_readblenfile.h"
+#include "IMB_imbuf.h"
int GHOST_HACK_getFirstFile(char buf[]);
#ifdef __cplusplus
}
#endif // __cplusplus
+
+#include "GPU_draw.h"
+
/**********************************
* End Blender include block
**********************************/
#include "SYS_System.h"
#include "GPG_Application.h"
-#include "GPC_PolygonMaterial.h"
#include "GHOST_ISystem.h"
#include "RAS_IRasterizer.h"
@@ -146,9 +153,9 @@ static BOOL scr_saver_init(int argc, char **argv)
#endif /* WIN32 */
-void usage(char* program)
+void usage(const char* program)
{
- char * consoleoption;
+ const char * consoleoption;
#ifdef _WIN32
consoleoption = "-c ";
#else
@@ -176,9 +183,13 @@ void usage(char* program)
printf(" anaglyph (Red-Blue glasses)\n");
printf(" vinterlace (Vertical interlace for autostereo display)\n");
printf(" depending on the type of stereo you want\n");
+#ifndef _WIN32
+ printf(" -i: parent windows ID \n");
+#endif
#ifdef _WIN32
printf(" -c: keep console window open\n");
#endif
+ printf(" -d: turn debugging on\n");
printf(" -g: game engine options:\n");
printf(" Name Default Description\n");
printf(" ----------------------------------------\n");
@@ -187,14 +198,14 @@ void usage(char* program)
printf(" show_framerate 0 Show the frame rate\n");
printf(" show_properties 0 Show debug properties\n");
printf(" show_profile 0 Show profiling information\n");
- printf(" vertexarrays 1 Enable vertex arrays\n");
printf(" blender_material 0 Enable material settings\n");
printf("\n");
printf("example: %s -p 10 10 320 200 -g noaudio c:\\loadtest.blend\n", program);
- printf("example: %s -g vertexarrays = 0 c:\\loadtest.blend\n", program);
+ printf("example: %s -g show_framerate = 0 c:\\loadtest.blend\n", program);
}
-char *get_filename(int argc, char **argv) {
+static void get_filename(int argc, char **argv, char *filename)
+{
#ifdef __APPLE__
/* On Mac we park the game file (called game.blend) in the application bundle.
* The executable is located in the bundle as well.
@@ -202,22 +213,18 @@ char *get_filename(int argc, char **argv) {
*/
int srclen = ::strlen(argv[0]);
int len = 0;
- char *filename = NULL;
+ char *gamefile = NULL;
+ filename[0] = '\0';
+
if (argc > 1) {
if (BLI_exists(argv[argc-1])) {
- len = ::strlen(argv[argc-1]);
- filename = new char [len + 1];
- ::strcpy(filename, argv[argc-1]);
- return(filename);
+ BLI_strncpy(filename, argv[argc-1], FILE_MAXDIR + FILE_MAXFILE);
}
if (::strncmp(argv[argc-1], "-psn_", 5)==0) {
static char firstfilebuf[512];
if (GHOST_HACK_getFirstFile(firstfilebuf)) {
- len = ::strlen(firstfilebuf);
- filename = new char [len + 1];
- ::strcpy(filename, firstfilebuf);
- return(filename);
+ BLI_strncpy(filename, firstfilebuf, FILE_MAXDIR + FILE_MAXFILE);
}
}
}
@@ -225,23 +232,26 @@ char *get_filename(int argc, char **argv) {
srclen -= ::strlen("MacOS/blenderplayer");
if (srclen > 0) {
len = srclen + ::strlen("Resources/game.blend");
- filename = new char [len + 1];
- ::strcpy(filename, argv[0]);
- ::strcpy(filename + srclen, "Resources/game.blend");
+ gamefile = new char [len + 1];
+ ::strcpy(gamefile, argv[0]);
+ ::strcpy(gamefile + srclen, "Resources/game.blend");
//::printf("looking for file: %s\n", filename);
- if (BLI_exists(filename)) {
- return (filename);
- }
+ if (BLI_exists(gamefile))
+ BLI_strncpy(filename, gamefile, FILE_MAXDIR + FILE_MAXFILE);
+
+ delete gamefile;
}
- return(NULL);
#else
- return (argc>1)?argv[argc-1]:NULL;
+ filename[0] = '\0';
+
+ if(argc > 1)
+ BLI_strncpy(filename, argv[argc-1], FILE_MAXDIR + FILE_MAXFILE);
#endif // !_APPLE
}
-static BlendFileData *load_game_data(char *progname, char *filename = NULL) {
+static BlendFileData *load_game_data(char *progname, char *filename = NULL, char *relativename = NULL) {
BlendReadError error;
BlendFileData *bfd = NULL;
@@ -283,7 +293,7 @@ int main(int argc, char** argv)
bool fullScreenParFound = false;
bool windowParFound = false;
bool closeConsole = true;
- RAS_IRasterizer::StereoMode stereomode;
+ RAS_IRasterizer::StereoMode stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO;
bool stereoWindow = false;
bool stereoParFound = false;
int windowLeft = 100;
@@ -294,14 +304,16 @@ int main(int argc, char** argv)
GHOST_TUns32 fullScreenHeight= 0;
int fullScreenBpp = 32;
int fullScreenFrequency = 60;
+ GHOST_TEmbedderWindowID parentWindow = 0;
+
+
#ifdef __linux__
#ifdef __alpha__
signal (SIGFPE, SIG_IGN);
#endif /* __alpha__ */
#endif /* __linux__ */
BLI_where_am_i(bprogname, argv[0]);
-
#ifdef __APPLE__
// Can't use Carbon right now because of double defined type ID (In Carbon.h and DNA_ID.h, sigh)
/*
@@ -323,8 +335,18 @@ int main(int argc, char** argv)
::DisposeNibReference(nibRef);
*/
#endif // __APPLE__
+
+ init_nodesystem();
+ initglobals();
+
GEN_init_messaging_system();
+
+#ifdef WITH_QUICKTIME
+ quicktime_init();
+#endif
+
+ libtiff_init();
// Parse command line options
#ifndef NDEBUG
@@ -403,6 +425,12 @@ int main(int argc, char** argv)
}
}
break;
+
+ case 'd':
+ i++;
+ G.f |= G_DEBUG; /* std output printf's */
+ MEM_set_memory_debug();
+ break;
case 'p':
// Parse window position and size options
@@ -455,6 +483,16 @@ int main(int argc, char** argv)
usage(argv[0]);
return 0;
break;
+#ifndef _WIN32
+ case 'i':
+ i++;
+ if ( (i + 1) < argc )
+ parentWindow = atoi(argv[i++]);
+#ifndef NDEBUG
+ printf("XWindows ID = %d\n", parentWindow);
+#endif //NDEBUG
+
+#endif // _WIN32
case 'c':
i++;
closeConsole = false;
@@ -525,21 +563,19 @@ int main(int argc, char** argv)
return 0;
}
- if (!stereoParFound) stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO;
-
#ifdef WIN32
if (scr_saver_mode != SCREEN_SAVER_MODE_CONFIGURATION)
#endif
{
#ifdef __APPLE__
//SYS_WriteCommandLineInt(syshandle, "show_framerate", 1);
- SYS_WriteCommandLineInt(syshandle, "nomipmap", 1);
+ //SYS_WriteCommandLineInt(syshandle, "nomipmap", 1);
//fullScreen = false; // Can't use full screen
#endif
if (SYS_GetCommandLineInt(syshandle, "nomipmap", 0))
{
- GPC_PolygonMaterial::SetMipMappingEnabled(0);
+ GPU_set_mipmap(0);
}
// Create the system
@@ -561,32 +597,46 @@ int main(int argc, char** argv)
{
int exitcode = KX_EXIT_REQUEST_NO_REQUEST;
STR_String exitstring = "";
- GPG_Application app(system, NULL, exitstring);
+ GPG_Application app(system);
bool firstTimeRunning = true;
+ char filename[FILE_MAXDIR + FILE_MAXFILE];
+ char pathname[FILE_MAXDIR + FILE_MAXFILE];
+ char *titlename;
+
+ get_filename(argc, argv, filename);
+ if(filename[0])
+ BLI_convertstringcwd(filename);
do
{
// Read the Blender file
- char *filename = get_filename(argc, argv);
- char *titlename;
- char pathname[160];
BlendFileData *bfd;
// if we got an exitcode 3 (KX_EXIT_REQUEST_START_OTHER_GAME) load a different file
if (exitcode == KX_EXIT_REQUEST_START_OTHER_GAME)
{
- char basedpath[160];
+ char basedpath[240];
- // base the actuator filename with respect
- // to the original file working directory
+ // base the actuator filename relative to the last file
strcpy(basedpath, exitstring.Ptr());
- BLI_convertstringcode(basedpath, pathname, 0);
+ BLI_convertstringcode(basedpath, pathname);
bfd = load_game_data(basedpath);
+
+ if (!bfd)
+ {
+ // just add "//" in front of it
+ char temppath[242];
+ strcpy(temppath, "//");
+ strcat(temppath, basedpath);
+
+ BLI_convertstringcode(temppath, pathname);
+ bfd = load_game_data(temppath);
+ }
}
else
{
- bfd = load_game_data(argv[0], filename);
+ bfd = load_game_data(bprogname, filename[0]? filename: NULL);
}
//::printf("game data loaded from %s\n", filename);
@@ -608,9 +658,10 @@ int main(int argc, char** argv)
#endif // WIN32
Main *maggie = bfd->main;
Scene *scene = bfd->curscene;
- strcpy (pathname, maggie->name);
- char *startscenename = scene->id.name + 2;
- G.fileflags = bfd->fileflags;
+ G.main = maggie;
+
+ if (firstTimeRunning)
+ G.fileflags = bfd->fileflags;
//Seg Fault; icon.c gIcons == 0
BKE_icons_init(1);
@@ -647,12 +698,16 @@ int main(int argc, char** argv)
}
// GPG_Application app (system, maggie, startscenename);
- app.SetGameEngineData(maggie, startscenename);
+ app.SetGameEngineData(maggie, scene);
+ BLI_strncpy(pathname, maggie->name, sizeof(pathname));
+ BLI_strncpy(G.sce, maggie->name, sizeof(G.sce));
+
if (firstTimeRunning)
{
+ setGamePythonPath(G.sce);
firstTimeRunning = false;
-
+
if (fullScreen)
{
#ifdef WIN32
@@ -710,7 +765,10 @@ int main(int argc, char** argv)
else
#endif
{
- app.startWindow(title, windowLeft, windowTop, windowWidth, windowHeight,
+ if (parentWindow != 0)
+ app.startEmbeddedWindow(title, parentWindow, stereoWindow, stereomode);
+ else
+ app.startWindow(title, windowLeft, windowTop, windowWidth, windowHeight,
stereoWindow, stereomode);
}
}
@@ -737,13 +795,8 @@ int main(int argc, char** argv)
}
}
app.StopGameEngine();
+
BLO_blendfiledata_free(bfd);
-
-#ifdef __APPLE__
- if (filename) {
- delete [] filename;
- }
-#endif // __APPLE__
}
} while (exitcode == KX_EXIT_REQUEST_RESTART_GAME || exitcode == KX_EXIT_REQUEST_START_OTHER_GAME);
}
@@ -759,6 +812,8 @@ int main(int argc, char** argv)
}
}
+ free_nodesystem();
+
return error ? -1 : 0;
}
diff --git a/source/gameengine/GamePlayer/ghost/Makefile b/source/gameengine/GamePlayer/ghost/Makefile
index fd070c006f5..52e219db8f2 100644
--- a/source/gameengine/GamePlayer/ghost/Makefile
+++ b/source/gameengine/GamePlayer/ghost/Makefile
@@ -36,10 +36,12 @@ include nan_compile.mk
CCFLAGS += $(LEVEL_1_CPP_WARNINGS)
# OpenGL header files
+CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(OPENGL_HEADERS)
CPPFLAGS += -I$(NAN_STRING)/include
CPPFLAGS += -I$(NAN_BMFONT)/include
CPPFLAGS += -I$(NAN_SOUNDSYSTEM)/include
+CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include
CPPFLAGS += -I../../GamePlayer/common
@@ -68,6 +70,9 @@ CPPFLAGS += -I../../../blender/blenloader
CPPFLAGS += -I../../../blender/imbuf
CPPFLAGS += -I../../../blender/makesdna
CPPFLAGS += -I../../../blender/readblenfile
+CPPFLAGS += -I../../../blender/gpu
+
+CPPFLAGS += -I../../../gameengine/BlenderRoutines
# kernel? GEN? stuff
CPPFLAGS += -I../../../kernel/gen_system
@@ -77,4 +82,3 @@ CPPFLAGS += -I$(NAN_STRING)/include
CPPFLAGS += -I$(NAN_GHOST)/include
CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION)
-
diff --git a/source/gameengine/GamePlayer/ghost/SConscript b/source/gameengine/GamePlayer/ghost/SConscript
index f704f02c513..a7ee2d51d14 100644
--- a/source/gameengine/GamePlayer/ghost/SConscript
+++ b/source/gameengine/GamePlayer/ghost/SConscript
@@ -3,47 +3,51 @@ import sys
Import ('env')
source_files = ['GPG_Application.cpp',
- 'GPG_Canvas.cpp',
- 'GPG_ghost.cpp',
- 'GPG_KeyboardDevice.cpp',
- 'GPG_System.cpp']
+ 'GPG_Canvas.cpp',
+ 'GPG_ghost.cpp',
+ 'GPG_KeyboardDevice.cpp',
+ 'GPG_System.cpp']
incs = ['.',
- '#intern/string',
- '#intern/ghost',
- '#intern/guardedalloc',
- '#intern/bmfont',
- '#intern/moto/include',
- '#intern/SoundSystem',
- '#source/gameengine/Rasterizer/RAS_OpenGLRasterizer',
- '#source/kernel/gen_system',
- '#source/kernel/gen_messaging',
- '#source/gameengine/Converter',
- '#source/blender/imbuf',
- '#source/gameengine/Ketsji',
- '#source/blender/blenlib',
- '#source/blender/blenkernel',
- '#source/blender/readblenfile',
- '#source/blender',
- '#source/blender/editors/include',
- '#source/blender/makesdna',
- '#source/gameengine/Rasterizer',
- '#source/gameengine/GameLogic',
- '#source/gameengine/Expressions',
- '#source/gameengine/Network',
- '#source/gameengine/SceneGraph',
- '#source/gameengine/Physics/common',
- '#source/gameengine/Physics/Sumo',
- '#source/gameengine/Physics/Sumo/Fuzzics/include',
- '#source/gameengine/Network/LoopBackNetwork',
- '#source/gameengine/GamePlayer/common',
- '#source/blender/misc',
- '#source/blender/blenloader']
+ '#intern/string',
+ '#intern/ghost',
+ '#intern/guardedalloc',
+ '#intern/bmfont',
+ '#intern/moto/include',
+ '#intern/SoundSystem',
+ '#source/gameengine/Rasterizer/RAS_OpenGLRasterizer',
+ '#source/kernel/gen_system',
+ '#source/kernel/gen_messaging',
+ '#source/gameengine/Converter',
+ '#source/blender/imbuf',
+ '#source/gameengine/Ketsji',
+ '#source/blender/blenlib',
+ '#source/blender/blenkernel',
+ '#source/blender/readblenfile',
+ '#source/blender',
+ '#source/blender/include',
+ '#source/blender/makesdna',
+ '#source/gameengine/BlenderRoutines',
+ '#source/gameengine/Rasterizer',
+ '#source/gameengine/GameLogic',
+ '#source/gameengine/Expressions',
+ '#source/gameengine/Network',
+ '#source/gameengine/SceneGraph',
+ '#source/gameengine/Physics/common',
+ '#source/gameengine/Physics/Sumo',
+ '#source/gameengine/Physics/Sumo/Fuzzics/include',
+ '#source/gameengine/Network/LoopBackNetwork',
+ '#source/gameengine/GamePlayer/common',
+ '#source/blender/misc',
+ '#source/blender/blenloader',
+ '#source/blender/gpu',
+ '#extern/glew/include']
incs += Split(env['BF_PYTHON_INC'])
incs += Split(env['BF_SOLID_INC'])
cflags = []
if env['OURPLATFORM']=='win32-vc':
- cflags = ['/GR']
+ cflags = ['/GR']
+
env.BlenderLib (libname='gp_ghost', sources=source_files, includes = incs, defines = [], libtype='player',priority=5, compileflags=cflags)
diff --git a/source/gameengine/Ketsji/BL_BlenderShader.cpp b/source/gameengine/Ketsji/BL_BlenderShader.cpp
new file mode 100644
index 00000000000..8ec463be6ff
--- /dev/null
+++ b/source/gameengine/Ketsji/BL_BlenderShader.cpp
@@ -0,0 +1,170 @@
+
+#include "DNA_customdata_types.h"
+#include "DNA_material_types.h"
+#include "DNA_scene_types.h"
+
+#include "BKE_global.h"
+#include "BKE_main.h"
+
+#include "BL_BlenderShader.h"
+#include "BL_Material.h"
+
+#include "GPU_extensions.h"
+#include "GPU_material.h"
+
+#include "RAS_BucketManager.h"
+#include "RAS_MeshObject.h"
+#include "RAS_IRasterizer.h"
+
+BL_BlenderShader::BL_BlenderShader(KX_Scene *scene, struct Material *ma, int lightlayer)
+:
+ mScene(scene),
+ mMat(ma),
+ mLightLayer(lightlayer)
+{
+ mBlenderScene = scene->GetBlenderScene();
+ mBlendMode = GPU_BLEND_SOLID;
+
+ if(mMat)
+ GPU_material_from_blender(mBlenderScene, mMat);
+}
+
+BL_BlenderShader::~BL_BlenderShader()
+{
+ if(mMat && GPU_material_from_blender(mBlenderScene, mMat))
+ GPU_material_unbind(GPU_material_from_blender(mBlenderScene, mMat));
+}
+
+bool BL_BlenderShader::Ok()
+{
+ return VerifyShader();
+}
+
+bool BL_BlenderShader::VerifyShader()
+{
+ if(mMat)
+ return (GPU_material_from_blender(mBlenderScene, mMat) != 0);
+ else
+ return false;
+}
+
+void BL_BlenderShader::SetProg(bool enable, double time)
+{
+ if(VerifyShader()) {
+ if(enable)
+ GPU_material_bind(GPU_material_from_blender(mBlenderScene, mMat), mLightLayer, ~0, time);
+ else
+ GPU_material_unbind(GPU_material_from_blender(mBlenderScene, mMat));
+ }
+}
+
+int BL_BlenderShader::GetAttribNum()
+{
+ GPUVertexAttribs attribs;
+ int i, enabled = 0;
+
+ if(!VerifyShader())
+ return enabled;
+
+ GPU_material_vertex_attributes(GPU_material_from_blender(mBlenderScene, mMat), &attribs);
+
+ for(i = 0; i < attribs.totlayer; i++)
+ if(attribs.layer[i].glindex+1 > enabled)
+ enabled= attribs.layer[i].glindex+1;
+
+ if(enabled > BL_MAX_ATTRIB)
+ enabled = BL_MAX_ATTRIB;
+
+ return enabled;
+}
+
+void BL_BlenderShader::SetAttribs(RAS_IRasterizer* ras, const BL_Material *mat)
+{
+ GPUVertexAttribs attribs;
+ GPUMaterial *gpumat;
+ int i, attrib_num;
+
+ ras->SetAttribNum(0);
+
+ if(!VerifyShader())
+ return;
+
+ gpumat = GPU_material_from_blender(mBlenderScene, mMat);
+
+ if(ras->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED) {
+ GPU_material_vertex_attributes(gpumat, &attribs);
+ attrib_num = GetAttribNum();
+
+ ras->SetTexCoordNum(0);
+ ras->SetAttribNum(attrib_num);
+ for(i=0; i<attrib_num; i++)
+ ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_DISABLE, i);
+
+ for(i = 0; i < attribs.totlayer; i++) {
+ if(attribs.layer[i].glindex > attrib_num)
+ continue;
+
+ if(attribs.layer[i].type == CD_MTFACE) {
+ if(!mat->uvName.IsEmpty() && strcmp(mat->uvName.ReadPtr(), attribs.layer[i].name) == 0)
+ ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_UV1, attribs.layer[i].glindex);
+ else if(!mat->uv2Name.IsEmpty() && strcmp(mat->uv2Name.ReadPtr(), attribs.layer[i].name) == 0)
+ ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_UV2, attribs.layer[i].glindex);
+ else
+ ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_UV1, attribs.layer[i].glindex);
+ }
+ else if(attribs.layer[i].type == CD_TANGENT)
+ ras->SetAttrib(RAS_IRasterizer::RAS_TEXTANGENT, attribs.layer[i].glindex);
+ else if(attribs.layer[i].type == CD_ORCO)
+ ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_ORCO, attribs.layer[i].glindex);
+ else if(attribs.layer[i].type == CD_NORMAL)
+ ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_NORM, attribs.layer[i].glindex);
+ else if(attribs.layer[i].type == CD_MCOL)
+ ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_VCOL, attribs.layer[i].glindex);
+ else
+ ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_DISABLE, attribs.layer[i].glindex);
+ }
+ }
+}
+
+void BL_BlenderShader::Update(const RAS_MeshSlot & ms, RAS_IRasterizer* rasty )
+{
+ float obmat[4][4], viewmat[4][4], viewinvmat[4][4], obcol[4];
+ GPUMaterial *gpumat;
+
+ gpumat = GPU_material_from_blender(mBlenderScene, mMat);
+
+ if(!gpumat || !GPU_material_bound(gpumat))
+ return;
+
+ MT_Matrix4x4 model;
+ model.setValue(ms.m_OpenGLMatrix);
+ const MT_Matrix4x4& view = rasty->GetViewMatrix();
+ const MT_Matrix4x4& viewinv = rasty->GetViewInvMatrix();
+
+ // note: getValue gives back column major as needed by OpenGL
+ model.getValue((float*)obmat);
+ view.getValue((float*)viewmat);
+ viewinv.getValue((float*)viewinvmat);
+
+ if(ms.m_bObjectColor)
+ ms.m_RGBAcolor.getValue((float*)obcol);
+ else
+ obcol[0]= obcol[1]= obcol[2]= obcol[3]= 1.0f;
+
+ GPU_material_bind_uniforms(gpumat, obmat, viewmat, viewinvmat, obcol);
+
+ mBlendMode = GPU_material_blend_mode(gpumat, obcol);
+}
+
+int BL_BlenderShader::GetBlendMode()
+{
+ return mBlendMode;
+}
+
+bool BL_BlenderShader::Equals(BL_BlenderShader *blshader)
+{
+ /* to avoid unneeded state switches */
+ return (blshader && mMat == blshader->mMat && mLightLayer == blshader->mLightLayer);
+}
+
+// eof
diff --git a/source/gameengine/Ketsji/BL_BlenderShader.h b/source/gameengine/Ketsji/BL_BlenderShader.h
new file mode 100644
index 00000000000..5c1f59f94ad
--- /dev/null
+++ b/source/gameengine/Ketsji/BL_BlenderShader.h
@@ -0,0 +1,53 @@
+
+#ifndef __BL_GPUSHADER_H__
+#define __BL_GPUSHADER_H__
+
+#include "GPU_material.h"
+
+#include "MT_Matrix4x4.h"
+#include "MT_Matrix3x3.h"
+#include "MT_Tuple2.h"
+#include "MT_Tuple3.h"
+#include "MT_Tuple4.h"
+
+#include "RAS_IPolygonMaterial.h"
+
+#include "KX_Scene.h"
+
+struct Material;
+struct Scene;
+class BL_Material;
+
+#define BL_MAX_ATTRIB 16
+
+/**
+ * BL_BlenderShader
+ * Blender GPU shader material
+ */
+class BL_BlenderShader
+{
+private:
+ KX_Scene *mScene;
+ struct Scene *mBlenderScene;
+ struct Material *mMat;
+ int mLightLayer;
+ int mBlendMode;
+
+ bool VerifyShader();
+
+public:
+ BL_BlenderShader(KX_Scene *scene, struct Material *ma, int lightlayer);
+ virtual ~BL_BlenderShader();
+
+ bool Ok();
+ void SetProg(bool enable, double time=0.0);
+
+ int GetAttribNum();
+ void SetAttribs(class RAS_IRasterizer* ras, const BL_Material *mat);
+ void Update(const class RAS_MeshSlot & ms, class RAS_IRasterizer* rasty);
+ int GetBlendMode();
+
+ bool Equals(BL_BlenderShader *blshader);
+};
+
+#endif//__BL_GPUSHADER_H__
diff --git a/source/gameengine/Ketsji/BL_Material.cpp b/source/gameengine/Ketsji/BL_Material.cpp
index 7ed2da590a9..7e3d6984f19 100644
--- a/source/gameengine/Ketsji/BL_Material.cpp
+++ b/source/gameengine/Ketsji/BL_Material.cpp
@@ -34,6 +34,7 @@ BL_Material::BL_Material()
rgb[3] = 0;
IdMode = 0;
ras_mode = 0;
+ glslmat = 0;
tile = 0;
matname = "NoMaterial";
matcolor[0] = 0.5f;
@@ -104,7 +105,8 @@ void BL_Material::GetConversionRGB(unsigned int *nrgb) {
*nrgb = rgb[3];
}
-void BL_Material::SetConversionUV(MT_Point2 *nuv) {
+void BL_Material::SetConversionUV(const STR_String& name, MT_Point2 *nuv) {
+ uvName = name;
uv[0] = *nuv++;
uv[1] = *nuv++;
uv[2] = *nuv++;
@@ -117,7 +119,8 @@ void BL_Material::GetConversionUV(MT_Point2 *nuv){
*nuv++ = uv[2];
*nuv = uv[3];
}
-void BL_Material::SetConversionUV2(MT_Point2 *nuv) {
+void BL_Material::SetConversionUV2(const STR_String& name, MT_Point2 *nuv) {
+ uv2Name = name;
uv2[0] = *nuv++;
uv2[1] = *nuv++;
uv2[2] = *nuv++;
diff --git a/source/gameengine/Ketsji/BL_Material.h b/source/gameengine/Ketsji/BL_Material.h
index 8be91316237..0eaa234566c 100644
--- a/source/gameengine/Ketsji/BL_Material.h
+++ b/source/gameengine/Ketsji/BL_Material.h
@@ -18,9 +18,9 @@ struct EnvMap;
this will default to users available units
to build with more available, just increment this value
although the more you add the slower the search time will be.
- we will go for three, which should be enough
+ we will go for eight, which should be enough
*/
-#define MAXTEX 3//match in RAS_TexVert & RAS_OpenGLRasterizer
+#define MAXTEX 8 //match in RAS_TexVert & RAS_OpenGLRasterizer
// different mapping modes
class BL_Mapping
@@ -47,6 +47,7 @@ public:
int IdMode;
unsigned int ras_mode;
+ bool glslmat;
STR_String texname[MAXTEX];
unsigned int flag[MAXTEX];
@@ -82,13 +83,16 @@ public:
MT_Point2 uv[4];
MT_Point2 uv2[4];
+ STR_String uvName;
+ STR_String uv2Name;
+
void SetConversionRGB(unsigned int *rgb);
void GetConversionRGB(unsigned int *rgb);
- void SetConversionUV(MT_Point2 *uv);
+ void SetConversionUV(const STR_String& name, MT_Point2 *uv);
void GetConversionUV(MT_Point2 *uv);
- void SetConversionUV2(MT_Point2 *uv);
+ void SetConversionUV2(const STR_String& name, MT_Point2 *uv);
void GetConversionUV2(MT_Point2 *uv);
void SetSharedMaterial(bool v);
@@ -125,8 +129,7 @@ enum BL_flag
TEXALPHA=8, // use alpha combiner functions
TEXNEG=16, // negate blending
HASIPO=32,
- USENEGALPHA=64,
- ALPHA_TEST=128
+ USENEGALPHA=64
};
// BL_Material::ras_mode
@@ -135,8 +138,8 @@ enum BL_ras_mode
POLY_VIS=1,
COLLIDER=2,
ZSORT=4,
- TRANSP=8,
- TRIANGLE=16,
+ ALPHA=8,
+ // TRIANGLE=16,
USE_LIGHT=32,
WIRE=64
};
diff --git a/source/gameengine/Ketsji/BL_Shader.cpp b/source/gameengine/Ketsji/BL_Shader.cpp
index 3b74b74727a..80892764089 100644
--- a/source/gameengine/Ketsji/BL_Shader.cpp
+++ b/source/gameengine/Ketsji/BL_Shader.cpp
@@ -1,20 +1,5 @@
-
-#ifdef WIN32
-#include <windows.h>
-#endif // WIN32
-#ifdef __APPLE__
-#define GL_GLEXT_LEGACY 1
-#include <OpenGL/gl.h>
-#include <OpenGL/glu.h>
-#else
-#include <GL/gl.h>
-#if defined(__sun__) && !defined(__sparc__)
-#include <mesa/glu.h>
-#else
-#include <GL/glu.h>
-#endif
-#endif
+#include "GL/glew.h"
#include <iostream>
#include "BL_Shader.h"
@@ -30,7 +15,6 @@
#include "RAS_MeshObject.h"
#include "RAS_IRasterizer.h"
-//using namespace bgl;
#define spit(x) std::cout << x << std::endl;
#define SORT_UNIFORMS 1
@@ -45,7 +29,7 @@ BL_Uniform::BL_Uniform(int data_size)
mDataLen(data_size)
{
#ifdef SORT_UNIFORMS
- MT_assert(mDataLen <= UNIFORM_MAX_LEN);
+ MT_assert((int)mDataLen <= UNIFORM_MAX_LEN);
mData = (void*)MEM_mallocN(mDataLen, "shader-uniform-alloc");
#endif
}
@@ -62,7 +46,6 @@ BL_Uniform::~BL_Uniform()
void BL_Uniform::Apply(class BL_Shader *shader)
{
-#ifdef GL_ARB_shader_objects
#ifdef SORT_UNIFORMS
MT_assert(mType > UNI_NONE && mType < UNI_MAX && mData);
@@ -73,48 +56,47 @@ void BL_Uniform::Apply(class BL_Shader *shader)
{
case UNI_FLOAT: {
float *f = (float*)mData;
- bgl::blUniform1fARB(mLoc,(GLfloat)*f);
+ glUniform1fARB(mLoc,(GLfloat)*f);
}break;
case UNI_INT: {
int *f = (int*)mData;
- bgl::blUniform1iARB(mLoc, (GLint)*f);
+ glUniform1iARB(mLoc, (GLint)*f);
}break;
case UNI_FLOAT2: {
float *f = (float*)mData;
- bgl::blUniform2fvARB(mLoc,1, (GLfloat*)f);
+ glUniform2fvARB(mLoc,1, (GLfloat*)f);
}break;
case UNI_FLOAT3: {
float *f = (float*)mData;
- bgl::blUniform3fvARB(mLoc,1,(GLfloat*)f);
+ glUniform3fvARB(mLoc,1,(GLfloat*)f);
}break;
case UNI_FLOAT4: {
float *f = (float*)mData;
- bgl::blUniform4fvARB(mLoc,1,(GLfloat*)f);
+ glUniform4fvARB(mLoc,1,(GLfloat*)f);
}break;
case UNI_INT2: {
int *f = (int*)mData;
- bgl::blUniform2ivARB(mLoc,1,(GLint*)f);
+ glUniform2ivARB(mLoc,1,(GLint*)f);
}break;
case UNI_INT3: {
int *f = (int*)mData;
- bgl::blUniform3ivARB(mLoc,1,(GLint*)f);
+ glUniform3ivARB(mLoc,1,(GLint*)f);
}break;
case UNI_INT4: {
int *f = (int*)mData;
- bgl::blUniform4ivARB(mLoc,1,(GLint*)f);
+ glUniform4ivARB(mLoc,1,(GLint*)f);
}break;
case UNI_MAT4: {
float *f = (float*)mData;
- bgl::blUniformMatrix4fvARB(mLoc, 1, mTranspose?GL_TRUE:GL_FALSE,(GLfloat*)f);
+ glUniformMatrix4fvARB(mLoc, 1, mTranspose?GL_TRUE:GL_FALSE,(GLfloat*)f);
}break;
case UNI_MAT3: {
float *f = (float*)mData;
- bgl::blUniformMatrix3fvARB(mLoc, 1, mTranspose?GL_TRUE:GL_FALSE,(GLfloat*)f);
+ glUniformMatrix3fvARB(mLoc, 1, mTranspose?GL_TRUE:GL_FALSE,(GLfloat*)f);
}break;
}
mDirty = false;
#endif
-#endif
}
void BL_Uniform::SetData(int location, int type,bool transpose)
@@ -143,17 +125,14 @@ BL_Shader::BL_Shader(PyTypeObject *T)
mError(0),
mDirty(true)
{
- // if !RAS_EXT_support._ARB_shader_objects this class will not be used
+ // if !GLEW_ARB_shader_objects this class will not be used
//for (int i=0; i<MAXTEX; i++) {
// mSampler[i] = BL_Sampler();
//}
}
-using namespace bgl;
-
BL_Shader::~BL_Shader()
{
-#ifdef GL_ARB_shader_objects
//for (int i=0; i<MAXTEX; i++){
// if(mSampler[i].mOwn) {
// if(mSampler[i].mTexture)
@@ -163,14 +142,13 @@ BL_Shader::~BL_Shader()
ClearUniforms();
if( mShader ) {
- bgl::blDeleteObjectARB(mShader);
+ glDeleteObjectARB(mShader);
mShader = 0;
}
vertProg = 0;
fragProg = 0;
mOk = 0;
- bgl::blUseProgramObjectARB(0);
-#endif//GL_ARB_shader_objects
+ glUseProgramObjectARB(0);
}
void BL_Shader::ClearUniforms()
@@ -265,8 +243,6 @@ void BL_Shader::UnloadShader()
bool BL_Shader::LinkProgram()
{
-#ifdef GL_ARB_shader_objects
-
int vertlen = 0, fraglen=0, proglen=0;
int vertstatus=0, fragstatus=0, progstatus=0;
unsigned int tmpVert=0, tmpFrag=0, tmpProg=0;
@@ -280,25 +256,25 @@ bool BL_Shader::LinkProgram()
spit("Invalid GLSL sources");
return false;
}
- if( !RAS_EXT_support._ARB_fragment_shader) {
+ if( !GLEW_ARB_fragment_shader) {
spit("Fragment shaders not supported");
return false;
}
- if( !RAS_EXT_support._ARB_vertex_shader) {
+ if( !GLEW_ARB_vertex_shader) {
spit("Vertex shaders not supported");
return false;
}
// -- vertex shader ------------------
- tmpVert = bgl::blCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
- bgl::blShaderSourceARB(tmpVert, 1, (const char**)&vertProg, 0);
- bgl::blCompileShaderARB(tmpVert);
- bgl::blGetObjectParameterivARB(tmpVert, GL_OBJECT_INFO_LOG_LENGTH_ARB,(GLint*) &vertlen);
+ tmpVert = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
+ glShaderSourceARB(tmpVert, 1, (const char**)&vertProg, 0);
+ glCompileShaderARB(tmpVert);
+ glGetObjectParameterivARB(tmpVert, GL_OBJECT_INFO_LOG_LENGTH_ARB,(GLint*) &vertlen);
// print info if any
if( vertlen > 0 && vertlen < MAX_LOG_LEN){
logInf = (char*)MEM_mallocN(vertlen, "vert-log");
- bgl::blGetInfoLogARB(tmpVert, vertlen, (GLsizei*)&char_len, logInf);
+ glGetInfoLogARB(tmpVert, vertlen, (GLsizei*)&char_len, logInf);
if(char_len >0) {
spit("---- Vertex Shader Error ----");
spit(logInf);
@@ -307,20 +283,20 @@ bool BL_Shader::LinkProgram()
logInf=0;
}
// check for compile errors
- bgl::blGetObjectParameterivARB(tmpVert, GL_OBJECT_COMPILE_STATUS_ARB,(GLint*)&vertstatus);
+ glGetObjectParameterivARB(tmpVert, GL_OBJECT_COMPILE_STATUS_ARB,(GLint*)&vertstatus);
if(!vertstatus) {
spit("---- Vertex shader failed to compile ----");
goto programError;
}
// -- fragment shader ----------------
- tmpFrag = bgl::blCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
- bgl::blShaderSourceARB(tmpFrag, 1,(const char**)&fragProg, 0);
- bgl::blCompileShaderARB(tmpFrag);
- bgl::blGetObjectParameterivARB(tmpFrag, GL_OBJECT_INFO_LOG_LENGTH_ARB, (GLint*) &fraglen);
+ tmpFrag = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
+ glShaderSourceARB(tmpFrag, 1,(const char**)&fragProg, 0);
+ glCompileShaderARB(tmpFrag);
+ glGetObjectParameterivARB(tmpFrag, GL_OBJECT_INFO_LOG_LENGTH_ARB, (GLint*) &fraglen);
if(fraglen >0 && fraglen < MAX_LOG_LEN){
logInf = (char*)MEM_mallocN(fraglen, "frag-log");
- bgl::blGetInfoLogARB(tmpFrag, fraglen,(GLsizei*) &char_len, logInf);
+ glGetInfoLogARB(tmpFrag, fraglen,(GLsizei*) &char_len, logInf);
if(char_len >0) {
spit("---- Fragment Shader Error ----");
spit(logInf);
@@ -329,7 +305,7 @@ bool BL_Shader::LinkProgram()
logInf=0;
}
- bgl::blGetObjectParameterivARB(tmpFrag, GL_OBJECT_COMPILE_STATUS_ARB, (GLint*) &fragstatus);
+ glGetObjectParameterivARB(tmpFrag, GL_OBJECT_COMPILE_STATUS_ARB, (GLint*) &fragstatus);
if(!fragstatus){
spit("---- Fragment shader failed to compile ----");
goto programError;
@@ -338,17 +314,17 @@ bool BL_Shader::LinkProgram()
// -- program ------------------------
// set compiled vert/frag shader & link
- tmpProg = bgl::blCreateProgramObjectARB();
- bgl::blAttachObjectARB(tmpProg, tmpVert);
- bgl::blAttachObjectARB(tmpProg, tmpFrag);
- bgl::blLinkProgramARB(tmpProg);
- bgl::blGetObjectParameterivARB(tmpProg, GL_OBJECT_INFO_LOG_LENGTH_ARB, (GLint*) &proglen);
- bgl::blGetObjectParameterivARB(tmpProg, GL_OBJECT_LINK_STATUS_ARB, (GLint*) &progstatus);
+ tmpProg = glCreateProgramObjectARB();
+ glAttachObjectARB(tmpProg, tmpVert);
+ glAttachObjectARB(tmpProg, tmpFrag);
+ glLinkProgramARB(tmpProg);
+ glGetObjectParameterivARB(tmpProg, GL_OBJECT_INFO_LOG_LENGTH_ARB, (GLint*) &proglen);
+ glGetObjectParameterivARB(tmpProg, GL_OBJECT_LINK_STATUS_ARB, (GLint*) &progstatus);
if(proglen > 0 && proglen < MAX_LOG_LEN) {
logInf = (char*)MEM_mallocN(proglen, "prog-log");
- bgl::blGetInfoLogARB(tmpProg, proglen, (GLsizei*)&char_len, logInf);
+ glGetInfoLogARB(tmpProg, proglen, (GLsizei*)&char_len, logInf);
if(char_len >0) {
spit("---- GLSL Program ----");
spit(logInf);
@@ -364,24 +340,24 @@ bool BL_Shader::LinkProgram()
// set
mShader = tmpProg;
- bgl::blDeleteObjectARB(tmpVert);
- bgl::blDeleteObjectARB(tmpFrag);
+ glDeleteObjectARB(tmpVert);
+ glDeleteObjectARB(tmpFrag);
mOk = 1;
mError = 0;
return true;
programError:
if(tmpVert) {
- bgl::blDeleteObjectARB(tmpVert);
+ glDeleteObjectARB(tmpVert);
tmpVert=0;
}
if(tmpFrag) {
- bgl::blDeleteObjectARB(tmpFrag);
+ glDeleteObjectARB(tmpFrag);
tmpFrag=0;
}
if(tmpProg) {
- bgl::blDeleteObjectARB(tmpProg);
+ glDeleteObjectARB(tmpProg);
tmpProg=0;
}
@@ -389,9 +365,6 @@ programError:
mUse = 0;
mError = 1;
return false;
-#else
- return false;
-#endif//GL_ARB_shader_objects
}
const char *BL_Shader::GetVertPtr()
@@ -427,15 +400,13 @@ unsigned int BL_Shader::GetProg()
void BL_Shader::SetSampler(int loc, int unit)
{
-#ifdef GL_ARB_shader_objects
- if( RAS_EXT_support._ARB_fragment_shader &&
- RAS_EXT_support._ARB_vertex_shader &&
- RAS_EXT_support._ARB_shader_objects
+ if( GLEW_ARB_fragment_shader &&
+ GLEW_ARB_vertex_shader &&
+ GLEW_ARB_shader_objects
)
{
- bgl::blUniform1iARB(loc, unit);
+ glUniform1iARB(loc, unit);
}
-#endif
}
//
//void BL_Shader::InitializeSampler(int unit, BL_Texture* texture)
@@ -448,37 +419,33 @@ void BL_Shader::SetSampler(int loc, int unit)
void BL_Shader::SetProg(bool enable)
{
-#ifdef GL_ARB_shader_objects
- if( RAS_EXT_support._ARB_fragment_shader &&
- RAS_EXT_support._ARB_vertex_shader &&
- RAS_EXT_support._ARB_shader_objects
+ if( GLEW_ARB_fragment_shader &&
+ GLEW_ARB_vertex_shader &&
+ GLEW_ARB_shader_objects
)
{
if( mShader != 0 && mOk && enable) {
- bgl::blUseProgramObjectARB(mShader);
+ glUseProgramObjectARB(mShader);
}
else {
- bgl::blUseProgramObjectARB(0);
+ glUseProgramObjectARB(0);
}
}
-#endif
}
-void BL_Shader::Update( const KX_MeshSlot & ms, RAS_IRasterizer* rasty )
+void BL_Shader::Update( const RAS_MeshSlot & ms, RAS_IRasterizer* rasty )
{
-#ifdef GL_ARB_shader_objects
if(!Ok() || !mPreDef.size())
return;
- if( RAS_EXT_support._ARB_fragment_shader &&
- RAS_EXT_support._ARB_vertex_shader &&
- RAS_EXT_support._ARB_shader_objects
+ if( GLEW_ARB_fragment_shader &&
+ GLEW_ARB_vertex_shader &&
+ GLEW_ARB_shader_objects
)
{
MT_Matrix4x4 model;
model.setValue(ms.m_OpenGLMatrix);
- MT_Matrix4x4 view;
- rasty->GetViewMatrix(view);
+ const MT_Matrix4x4& view = rasty->GetViewMatrix();
if(mAttr==SHD_TANGENT)
ms.m_mesh->SetMeshModified(true);
@@ -557,13 +524,15 @@ void BL_Shader::Update( const KX_MeshSlot & ms, RAS_IRasterizer* rasty )
}
case VIEWMATRIX_INVERSE:
{
- view.invert();
+ MT_Matrix4x4 viewinv = view;
+ viewinv.invert();
SetUniform(uni->mLoc, view);
break;
}
case VIEWMATRIX_INVERSETRANSPOSE:
{
- view.invert();
+ MT_Matrix4x4 viewinv = view;
+ viewinv.invert();
SetUniform(uni->mLoc, view, true);
break;
}
@@ -577,210 +546,186 @@ void BL_Shader::Update( const KX_MeshSlot & ms, RAS_IRasterizer* rasty )
}
}
}
-#endif
}
int BL_Shader::GetAttribLocation(const STR_String& name)
{
-#ifdef GL_ARB_shader_objects
- if( RAS_EXT_support._ARB_fragment_shader &&
- RAS_EXT_support._ARB_vertex_shader &&
- RAS_EXT_support._ARB_shader_objects
+ if( GLEW_ARB_fragment_shader &&
+ GLEW_ARB_vertex_shader &&
+ GLEW_ARB_shader_objects
)
{
- return bgl::blGetAttribLocationARB(mShader, name.ReadPtr());
+ return glGetAttribLocationARB(mShader, name.ReadPtr());
}
-#endif
+
return -1;
}
void BL_Shader::BindAttribute(const STR_String& attr, int loc)
{
-#ifdef GL_ARB_shader_objects
- if( RAS_EXT_support._ARB_fragment_shader &&
- RAS_EXT_support._ARB_vertex_shader &&
- RAS_EXT_support._ARB_shader_objects
+ if( GLEW_ARB_fragment_shader &&
+ GLEW_ARB_vertex_shader &&
+ GLEW_ARB_shader_objects
)
{
- bgl::blBindAttribLocationARB(mShader, loc, attr.ReadPtr());
+ glBindAttribLocationARB(mShader, loc, attr.ReadPtr());
}
-#endif
}
int BL_Shader::GetUniformLocation(const STR_String& name)
{
-#ifdef GL_ARB_shader_objects
- if( RAS_EXT_support._ARB_fragment_shader &&
- RAS_EXT_support._ARB_vertex_shader &&
- RAS_EXT_support._ARB_shader_objects
+ if( GLEW_ARB_fragment_shader &&
+ GLEW_ARB_vertex_shader &&
+ GLEW_ARB_shader_objects
)
{
MT_assert(mShader!=0);
- int location = bgl::blGetUniformLocationARB(mShader, name.ReadPtr());
+ int location = glGetUniformLocationARB(mShader, name.ReadPtr());
if(location == -1)
spit("Invalid uniform value: " << name.ReadPtr() << ".");
return location;
}
-#endif
+
return -1;
}
void BL_Shader::SetUniform(int uniform, const MT_Tuple2& vec)
{
-#ifdef GL_ARB_shader_objects
- if( RAS_EXT_support._ARB_fragment_shader &&
- RAS_EXT_support._ARB_vertex_shader &&
- RAS_EXT_support._ARB_shader_objects
+ if( GLEW_ARB_fragment_shader &&
+ GLEW_ARB_vertex_shader &&
+ GLEW_ARB_shader_objects
)
{
float value[2];
vec.getValue(value);
- bgl::blUniform2fvARB(uniform, 1, value);
+ glUniform2fvARB(uniform, 1, value);
}
-#endif
}
void BL_Shader::SetUniform(int uniform, const MT_Tuple3& vec)
{
-#ifdef GL_ARB_shader_objects
- if( RAS_EXT_support._ARB_fragment_shader &&
- RAS_EXT_support._ARB_vertex_shader &&
- RAS_EXT_support._ARB_shader_objects
+ if( GLEW_ARB_fragment_shader &&
+ GLEW_ARB_vertex_shader &&
+ GLEW_ARB_shader_objects
)
{
float value[3];
vec.getValue(value);
- bgl::blUniform3fvARB(uniform, 1, value);
+ glUniform3fvARB(uniform, 1, value);
}
-#endif
}
void BL_Shader::SetUniform(int uniform, const MT_Tuple4& vec)
{
-#ifdef GL_ARB_shader_objects
- if( RAS_EXT_support._ARB_fragment_shader &&
- RAS_EXT_support._ARB_vertex_shader &&
- RAS_EXT_support._ARB_shader_objects
+ if( GLEW_ARB_fragment_shader &&
+ GLEW_ARB_vertex_shader &&
+ GLEW_ARB_shader_objects
)
{
float value[4];
vec.getValue(value);
- bgl::blUniform4fvARB(uniform, 1, value);
+ glUniform4fvARB(uniform, 1, value);
}
-#endif
}
void BL_Shader::SetUniform(int uniform, const unsigned int& val)
{
-#ifdef GL_ARB_shader_objects
- if( RAS_EXT_support._ARB_fragment_shader &&
- RAS_EXT_support._ARB_vertex_shader &&
- RAS_EXT_support._ARB_shader_objects
+ if( GLEW_ARB_fragment_shader &&
+ GLEW_ARB_vertex_shader &&
+ GLEW_ARB_shader_objects
)
{
- bgl::blUniform1iARB(uniform, val);
+ glUniform1iARB(uniform, val);
}
-#endif
}
void BL_Shader::SetUniform(int uniform, const int val)
{
-#ifdef GL_ARB_shader_objects
- if( RAS_EXT_support._ARB_fragment_shader &&
- RAS_EXT_support._ARB_vertex_shader &&
- RAS_EXT_support._ARB_shader_objects
+ if( GLEW_ARB_fragment_shader &&
+ GLEW_ARB_vertex_shader &&
+ GLEW_ARB_shader_objects
)
{
- bgl::blUniform1iARB(uniform, val);
+ glUniform1iARB(uniform, val);
}
-#endif
}
void BL_Shader::SetUniform(int uniform, const float& val)
{
-#ifdef GL_ARB_shader_objects
- if( RAS_EXT_support._ARB_fragment_shader &&
- RAS_EXT_support._ARB_vertex_shader &&
- RAS_EXT_support._ARB_shader_objects
+ if( GLEW_ARB_fragment_shader &&
+ GLEW_ARB_vertex_shader &&
+ GLEW_ARB_shader_objects
)
{
- bgl::blUniform1fARB(uniform, val);
+ glUniform1fARB(uniform, val);
}
-#endif
}
void BL_Shader::SetUniform(int uniform, const MT_Matrix4x4& vec, bool transpose)
{
-#ifdef GL_ARB_shader_objects
- if( RAS_EXT_support._ARB_fragment_shader &&
- RAS_EXT_support._ARB_vertex_shader &&
- RAS_EXT_support._ARB_shader_objects
+ if( GLEW_ARB_fragment_shader &&
+ GLEW_ARB_vertex_shader &&
+ GLEW_ARB_shader_objects
)
{
float value[16];
+ // note: getValue gives back column major as needed by OpenGL
vec.getValue(value);
- bgl::blUniformMatrix4fvARB(uniform, 1, transpose?GL_TRUE:GL_FALSE, value);
+ glUniformMatrix4fvARB(uniform, 1, transpose?GL_TRUE:GL_FALSE, value);
}
-#endif
}
void BL_Shader::SetUniform(int uniform, const MT_Matrix3x3& vec, bool transpose)
{
-#ifdef GL_ARB_shader_objects
- if( RAS_EXT_support._ARB_fragment_shader &&
- RAS_EXT_support._ARB_vertex_shader &&
- RAS_EXT_support._ARB_shader_objects
+ if( GLEW_ARB_fragment_shader &&
+ GLEW_ARB_vertex_shader &&
+ GLEW_ARB_shader_objects
)
{
float value[9];
value[0] = (float)vec[0][0]; value[1] = (float)vec[1][0]; value[2] = (float)vec[2][0];
value[3] = (float)vec[0][1]; value[4] = (float)vec[1][1]; value[5] = (float)vec[2][1];
value[6] = (float)vec[0][2]; value[7] = (float)vec[1][2]; value[7] = (float)vec[2][2];
- bgl::blUniformMatrix3fvARB(uniform, 1, transpose?GL_TRUE:GL_FALSE, value);
+ glUniformMatrix3fvARB(uniform, 1, transpose?GL_TRUE:GL_FALSE, value);
}
-#endif
}
void BL_Shader::SetUniform(int uniform, const float* val, int len)
{
-#ifdef GL_ARB_shader_objects
- if( RAS_EXT_support._ARB_fragment_shader &&
- RAS_EXT_support._ARB_vertex_shader &&
- RAS_EXT_support._ARB_shader_objects
+ if( GLEW_ARB_fragment_shader &&
+ GLEW_ARB_vertex_shader &&
+ GLEW_ARB_shader_objects
)
{
if(len == 2)
- bgl::blUniform2fvARB(uniform, 1,(GLfloat*)val);
+ glUniform2fvARB(uniform, 1,(GLfloat*)val);
else if (len == 3)
- bgl::blUniform3fvARB(uniform, 1,(GLfloat*)val);
+ glUniform3fvARB(uniform, 1,(GLfloat*)val);
else if (len == 4)
- bgl::blUniform4fvARB(uniform, 1,(GLfloat*)val);
+ glUniform4fvARB(uniform, 1,(GLfloat*)val);
else
MT_assert(0);
}
-#endif
}
void BL_Shader::SetUniform(int uniform, const int* val, int len)
{
-#ifdef GL_ARB_shader_objects
- if( RAS_EXT_support._ARB_fragment_shader &&
- RAS_EXT_support._ARB_vertex_shader &&
- RAS_EXT_support._ARB_shader_objects
+ if( GLEW_ARB_fragment_shader &&
+ GLEW_ARB_vertex_shader &&
+ GLEW_ARB_shader_objects
)
{
if(len == 2)
- bgl::blUniform2ivARB(uniform, 1, (GLint*)val);
+ glUniform2ivARB(uniform, 1, (GLint*)val);
else if (len == 3)
- bgl::blUniform3ivARB(uniform, 1, (GLint*)val);
+ glUniform3ivARB(uniform, 1, (GLint*)val);
else if (len == 4)
- bgl::blUniform4ivARB(uniform, 1, (GLint*)val);
+ glUniform4ivARB(uniform, 1, (GLint*)val);
else
MT_assert(0);
}
-#endif
}
@@ -848,7 +793,6 @@ PyParentObject BL_Shader::Parents[] = {
KX_PYMETHODDEF_DOC( BL_Shader, setSource," setSource(vertexProgram, fragmentProgram)" )
{
-#ifdef GL_ARB_shader_objects
if(mShader !=0 && mOk )
{
// already set...
@@ -861,7 +805,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setSource," setSource(vertexProgram, fragmentProg
vertProg = v;
fragProg = f;
if( LinkProgram() ) {
- bgl::blUseProgramObjectARB( mShader );
+ glUseProgramObjectARB( mShader );
mUse = apply!=0;
Py_Return;
}
@@ -871,23 +815,18 @@ KX_PYMETHODDEF_DOC( BL_Shader, setSource," setSource(vertexProgram, fragmentProg
Py_Return;
}
return NULL;
-#else
- Py_Return;
-#endif
}
KX_PYMETHODDEF_DOC( BL_Shader, delSource, "delSource( )" )
{
-#ifdef GL_ARB_shader_objects
ClearUniforms();
- bgl::blUseProgramObjectARB(0);
+ glUseProgramObjectARB(0);
- bgl::blDeleteObjectARB(mShader);
+ glDeleteObjectARB(mShader);
mShader = 0;
mOk = 0;
mUse = 0;
-#endif
Py_Return;
}
@@ -908,25 +847,23 @@ KX_PYMETHODDEF_DOC( BL_Shader, getFragmentProg ,"getFragmentProg( )" )
KX_PYMETHODDEF_DOC( BL_Shader, validate, "validate()")
{
-#ifdef GL_ARB_shader_objects
if(mError) {
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
if(mShader==0) {
PyErr_Format(PyExc_TypeError, "invalid shader object");
return NULL;
}
int stat = 0;
- bgl::blValidateProgramARB(mShader);
- bgl::blGetObjectParameterivARB(mShader, GL_OBJECT_VALIDATE_STATUS_ARB,(GLint*) &stat);
+ glValidateProgramARB(mShader);
+ glGetObjectParameterivARB(mShader, GL_OBJECT_VALIDATE_STATUS_ARB,(GLint*) &stat);
if(stat > 0 && stat < MAX_LOG_LEN) {
int char_len=0;
char *logInf = (char*)MEM_mallocN(stat, "validate-log");
- bgl::blGetInfoLogARB(mShader, stat,(GLsizei*) &char_len, logInf);
+ glGetInfoLogARB(mShader, stat,(GLsizei*) &char_len, logInf);
if(char_len >0) {
spit("---- GLSL Validation ----");
spit(logInf);
@@ -934,7 +871,6 @@ KX_PYMETHODDEF_DOC( BL_Shader, validate, "validate()")
MEM_freeN(logInf);
logInf=0;
}
-#endif//GL_ARB_shader_objects
Py_Return;
}
@@ -942,11 +878,10 @@ KX_PYMETHODDEF_DOC( BL_Shader, validate, "validate()")
KX_PYMETHODDEF_DOC( BL_Shader, setSampler, "setSampler(name, index)" )
{
if(mError) {
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
- char *uniform="";
+ const char *uniform="";
int index=-1;
if(PyArg_ParseTuple(args, "si", &uniform, &index))
{
@@ -965,7 +900,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setSampler, "setSampler(name, index)" )
//else
// spit("Invalid texture sample index: " << index);
}
- Py_Return;
+ Py_RETURN_NONE;
}
return NULL;
}
@@ -984,11 +919,10 @@ KX_PYMETHODDEF_DOC( BL_Shader, setNumberOfPasses, "setNumberOfPasses( max-pass )
KX_PYMETHODDEF_DOC( BL_Shader, setUniform1f, "setUniform1f(name, fx)" )
{
if(mError) {
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
- char *uniform="";
+ const char *uniform="";
float value=0;
if(PyArg_ParseTuple(args, "sf", &uniform, &value ))
{
@@ -1010,10 +944,9 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform1f, "setUniform1f(name, fx)" )
KX_PYMETHODDEF_DOC( BL_Shader, setUniform2f , "setUniform2f(name, fx, fy)")
{
if(mError) {
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
- char *uniform="";
+ const char *uniform="";
float array[2]={ 0,0 };
if(PyArg_ParseTuple(args, "sff", &uniform, &array[0],&array[1] ))
{
@@ -1035,10 +968,9 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform2f , "setUniform2f(name, fx, fy)")
KX_PYMETHODDEF_DOC( BL_Shader, setUniform3f, "setUniform3f(name, fx,fy,fz) ")
{
if(mError) {
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
- char *uniform="";
+ const char *uniform="";
float array[3]={0,0,0};
if(PyArg_ParseTuple(args, "sfff", &uniform, &array[0],&array[1],&array[2]))
{
@@ -1061,10 +993,9 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform3f, "setUniform3f(name, fx,fy,fz) ")
KX_PYMETHODDEF_DOC( BL_Shader, setUniform4f, "setUniform4f(name, fx,fy,fz, fw) ")
{
if(mError) {
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
- char *uniform="";
+ const char *uniform="";
float array[4]={0,0,0,0};
if(PyArg_ParseTuple(args, "sffff", &uniform, &array[0],&array[1],&array[2], &array[3]))
{
@@ -1086,10 +1017,9 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform4f, "setUniform4f(name, fx,fy,fz, fw) "
KX_PYMETHODDEF_DOC( BL_Shader, setUniform1i, "setUniform1i(name, ix)" )
{
if(mError) {
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
- char *uniform="";
+ const char *uniform="";
int value=0;
if(PyArg_ParseTuple(args, "si", &uniform, &value ))
{
@@ -1111,10 +1041,9 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform1i, "setUniform1i(name, ix)" )
KX_PYMETHODDEF_DOC( BL_Shader, setUniform2i , "setUniform2i(name, ix, iy)")
{
if(mError) {
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
- char *uniform="";
+ const char *uniform="";
int array[2]={ 0,0 };
if(PyArg_ParseTuple(args, "sii", &uniform, &array[0],&array[1] ))
{
@@ -1136,11 +1065,10 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform2i , "setUniform2i(name, ix, iy)")
KX_PYMETHODDEF_DOC( BL_Shader, setUniform3i, "setUniform3i(name, ix,iy,iz) ")
{
if(mError) {
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
- char *uniform="";
+ const char *uniform="";
int array[3]={0,0,0};
if(PyArg_ParseTuple(args, "siii", &uniform, &array[0],&array[1],&array[2]))
{
@@ -1161,10 +1089,9 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform3i, "setUniform3i(name, ix,iy,iz) ")
KX_PYMETHODDEF_DOC( BL_Shader, setUniform4i, "setUniform4i(name, ix,iy,iz, iw) ")
{
if(mError) {
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
- char *uniform="";
+ const char *uniform="";
int array[4]={0,0,0, 0};
if(PyArg_ParseTuple(args, "siiii", &uniform, &array[0],&array[1],&array[2], &array[3] ))
{
@@ -1185,10 +1112,9 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform4i, "setUniform4i(name, ix,iy,iz, iw) "
KX_PYMETHODDEF_DOC( BL_Shader, setUniformfv , "setUniformfv( float (list2 or list3 or list4) )")
{
if(mError) {
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
- char*uniform = "";
+ const char *uniform = "";
PyObject *listPtr =0;
float array_data[4] = {0.f,0.f,0.f,0.f};
@@ -1255,10 +1181,9 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniformfv , "setUniformfv( float (list2 or lis
KX_PYMETHODDEF_DOC( BL_Shader, setUniformiv, "setUniformiv( int (list2 or list3 or list4) )")
{
if(mError) {
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
- char*uniform = "";
+ const char *uniform = "";
PyObject *listPtr =0;
int array_data[4] = {0,0,0,0};
@@ -1328,8 +1253,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniformMatrix4,
"setUniformMatrix4(uniform-name, mat-4x4, transpose(row-major=true, col-major=false)" )
{
if(mError) {
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
float matr[16] = {
@@ -1339,7 +1263,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniformMatrix4,
0,0,0,1
};
- char *uniform="";
+ const char *uniform="";
PyObject *matrix=0;
int transp=1; // MT_ is row major so transpose by default....
if(PyArg_ParseTuple(args, "sO|i",&uniform, &matrix,&transp))
@@ -1371,8 +1295,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniformMatrix3,
"setUniformMatrix3(uniform-name, list[3x3], transpose(row-major=true, col-major=false)" )
{
if(mError) {
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
float matr[9] = {
@@ -1381,7 +1304,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniformMatrix3,
0,0,1,
};
- char *uniform="";
+ const char *uniform="";
PyObject *matrix=0;
int transp=1; // MT_ is row major so transpose by default....
if(PyArg_ParseTuple(args, "sO|i",&uniform, &matrix,&transp))
@@ -1411,10 +1334,8 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniformMatrix3,
KX_PYMETHODDEF_DOC( BL_Shader, setAttrib, "setAttrib(enum)" )
{
-#ifdef GL_ARB_shader_objects
if(mError) {
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
int attr=0;
if(PyArg_ParseTuple(args, "i", &attr )) {
@@ -1423,23 +1344,21 @@ KX_PYMETHODDEF_DOC( BL_Shader, setAttrib, "setAttrib(enum)" )
return NULL;
}
mAttr=SHD_TANGENT;
- bgl::blUseProgramObjectARB(mShader);
- bgl::blBindAttribLocationARB(mShader, mAttr, "Tangent");
+ glUseProgramObjectARB(mShader);
+ glBindAttribLocationARB(mShader, mAttr, "Tangent");
Py_Return;
}
return NULL;
-#endif
}
KX_PYMETHODDEF_DOC( BL_Shader, setUniformDef, "setUniformDef(name, enum)" )
{
if(mError) {
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
- char *uniform="";
+ const char *uniform="";
int nloc=0;
if(PyArg_ParseTuple(args, "si",&uniform, &nloc))
{
diff --git a/source/gameengine/Ketsji/BL_Shader.h b/source/gameengine/Ketsji/BL_Shader.h
index 8f303454087..18ca8f8b4f8 100644
--- a/source/gameengine/Ketsji/BL_Shader.h
+++ b/source/gameengine/Ketsji/BL_Shader.h
@@ -102,8 +102,8 @@ private:
bool mUse; // ...
//BL_Sampler mSampler[MAXTEX]; // Number of samplers
int mAttr; // Tangent attribute
- char* vertProg; // Vertex program string
- char* fragProg; // Fragment program string
+ const char* vertProg; // Vertex program string
+ const char* fragProg; // Fragment program string
bool mError; // ...
bool mDirty; //
@@ -177,7 +177,7 @@ public:
void UnloadShader();
// Update predefined uniforms each render call
- void Update(const class KX_MeshSlot & ms, class RAS_IRasterizer* rasty);
+ void Update(const class RAS_MeshSlot & ms, class RAS_IRasterizer* rasty);
//// Set sampler units (copied)
//void InitializeSampler(int unit, BL_Texture* texture );
diff --git a/source/gameengine/Ketsji/BL_Texture.cpp b/source/gameengine/Ketsji/BL_Texture.cpp
index 53e1af46e4e..f0ef84032f7 100644
--- a/source/gameengine/Ketsji/BL_Texture.cpp
+++ b/source/gameengine/Ketsji/BL_Texture.cpp
@@ -1,22 +1,10 @@
// ------------------------------------
-#ifdef WIN32
-#include <windows.h>
-#endif // WIN32
-#ifdef __APPLE__
-#define GL_GLEXT_LEGACY 1
-#include <OpenGL/gl.h>
-#include <OpenGL/glu.h>
-#else
-#include <GL/gl.h>
-#if defined(__sun__) && !defined(__sparc__)
-#include <mesa/glu.h>
-#else
-#include <GL/glu.h>
-#endif
-#endif
+
+#include "GL/glew.h"
#include <iostream>
#include <map>
+#include <stdlib.h>
#include "BL_Material.h"
#include "BL_Texture.h"
@@ -29,15 +17,11 @@
#include "BLI_blenlib.h"
#include "RAS_OpenGLRasterizer/RAS_GLExtensionManager.h"
-#include "RAS_OpenGLRasterizer/ARB_multitexture.h"
#include "RAS_ICanvas.h"
#include "RAS_Rect.h"
#include "KX_GameObject.h"
-
-using namespace bgl;
-
#define spit(x) std::cout << x << std::endl;
#include "MEM_guardedalloc.h"
@@ -219,9 +203,7 @@ void BL_Texture::InitNonPow2Tex(unsigned int *pix,int x,int y,bool mipmap)
bool BL_Texture::InitCubeMap(int unit, EnvMap *cubemap)
{
-#ifdef GL_ARB_texture_cube_map
-
- if (!RAS_EXT_support._ARB_texture_cube_map)
+ if (!GLEW_ARB_texture_cube_map)
{
spit("cubemaps not supported");
mOk = false;
@@ -311,9 +293,8 @@ bool BL_Texture::InitCubeMap(int unit, EnvMap *cubemap)
glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
- #ifdef GL_VERSION_1_2
- glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE );
- #endif
+ if(GLEW_VERSION_1_2)
+ glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE );
if (needs_split)
my_free_envmapdata(cubemap);
@@ -325,13 +306,6 @@ bool BL_Texture::InitCubeMap(int unit, EnvMap *cubemap)
mOk = IsValid();
return mOk;
-
-#else
-
- mOk = false;
- return mOk;
-
-#endif//GL_ARB_texture_cube_map
}
bool BL_Texture::IsValid()
@@ -360,51 +334,41 @@ unsigned int BL_Texture::GetTextureType() const
int BL_Texture::GetMaxUnits()
{
GLint unit=0;
-#ifdef GL_ARB_multitexture
- if(RAS_EXT_support._ARB_multitexture) {
+
+ if(GLEW_ARB_multitexture) {
glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &unit);
return (MAXTEX>=unit?unit:MAXTEX);
}
-#endif
+
return 0;
}
void BL_Texture::ActivateFirst()
{
-#ifdef GL_ARB_multitexture
- if(RAS_EXT_support._ARB_multitexture)
- bgl::blActiveTextureARB(GL_TEXTURE0_ARB);
-#endif
+ if(GLEW_ARB_multitexture)
+ glActiveTextureARB(GL_TEXTURE0_ARB);
}
void BL_Texture::ActivateUnit(int unit)
{
-#ifdef GL_ARB_multitexture
- if(RAS_EXT_support._ARB_multitexture)
+ if(GLEW_ARB_multitexture)
if(unit <= MAXTEX)
- bgl::blActiveTextureARB(GL_TEXTURE0_ARB+unit);
-#endif
+ glActiveTextureARB(GL_TEXTURE0_ARB+unit);
}
void BL_Texture::DisableUnit()
{
-#ifdef GL_ARB_multitexture
- if(RAS_EXT_support._ARB_multitexture)
- bgl::blActiveTextureARB(GL_TEXTURE0_ARB+mUnit);
-
-#endif
-
+ if(GLEW_ARB_multitexture)
+ glActiveTextureARB(GL_TEXTURE0_ARB+mUnit);
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
- #ifdef GL_ARB_texture_cube_map
- if(RAS_EXT_support._ARB_texture_cube_map && glIsEnabled(GL_TEXTURE_CUBE_MAP_ARB))
+ if(GLEW_ARB_texture_cube_map && glIsEnabled(GL_TEXTURE_CUBE_MAP_ARB))
glDisable(GL_TEXTURE_CUBE_MAP_ARB);
else
- #endif
{
if (glIsEnabled(GL_TEXTURE_2D))
glDisable(GL_TEXTURE_2D);
@@ -420,11 +384,9 @@ void BL_Texture::DisableUnit()
void BL_Texture::DisableAllTextures()
{
-#ifdef GL_ARB_multitexture
- glDisable(GL_BLEND);
for(int i=0; i<MAXTEX; i++) {
- if(RAS_EXT_support._ARB_multitexture)
- bgl::blActiveTextureARB(GL_TEXTURE0_ARB+i);
+ if(GLEW_ARB_multitexture)
+ glActiveTextureARB(GL_TEXTURE0_ARB+i);
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
@@ -436,38 +398,29 @@ void BL_Texture::DisableAllTextures()
glDisable(GL_TEXTURE_GEN_Q);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
}
- if(RAS_EXT_support._ARB_multitexture)
- bgl::blActiveTextureARB(GL_TEXTURE0_ARB);
-#endif
+ if(GLEW_ARB_multitexture)
+ glActiveTextureARB(GL_TEXTURE0_ARB);
}
void BL_Texture::ActivateTexture()
{
-#ifdef GL_ARB_multitexture
- if(RAS_EXT_support._ARB_multitexture)
- bgl::blActiveTextureARB(GL_TEXTURE0_ARB+mUnit);
+ if(GLEW_ARB_multitexture)
+ glActiveTextureARB(GL_TEXTURE0_ARB+mUnit);
-#ifdef GL_ARB_texture_cube_map
- if (mType == GL_TEXTURE_CUBE_MAP_ARB && RAS_EXT_support._ARB_texture_cube_map)
+ if (mType == GL_TEXTURE_CUBE_MAP_ARB && GLEW_ARB_texture_cube_map)
{
glBindTexture( GL_TEXTURE_CUBE_MAP_ARB, mTexture );
glEnable(GL_TEXTURE_CUBE_MAP_ARB);
}
- else
-#endif
- {
-
- #ifdef GL_ARB_texture_cube_map
- if(RAS_EXT_support._ARB_texture_cube_map )
+ else {
+ if(GLEW_ARB_texture_cube_map )
glDisable(GL_TEXTURE_CUBE_MAP_ARB);
- #endif
glBindTexture( GL_TEXTURE_2D, mTexture );
glEnable(GL_TEXTURE_2D);
}
-#endif
}
void BL_Texture::SetMapping(int mode)
@@ -481,9 +434,8 @@ void BL_Texture::SetMapping(int mode)
return;
}
-#ifdef GL_ARB_texture_cube_map
if( mType == GL_TEXTURE_CUBE_MAP_ARB &&
- RAS_EXT_support._ARB_texture_cube_map &&
+ GLEW_ARB_texture_cube_map &&
mode &USEREFL)
{
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB );
@@ -497,7 +449,6 @@ void BL_Texture::SetMapping(int mode)
return;
}
else
-#endif
{
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP );
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP );
@@ -512,11 +463,7 @@ void BL_Texture::SetMapping(int mode)
void BL_Texture::setTexEnv(BL_Material *mat, bool modulate)
{
-#ifndef GL_ARB_texture_env_combine
- glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
- return;
-#else
- if(modulate || !RAS_EXT_support._ARB_texture_env_combine){
+ if(modulate || !GLEW_ARB_texture_env_combine){
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
return;
}
@@ -650,7 +597,6 @@ void BL_Texture::setTexEnv(BL_Material *mat, bool modulate)
glTexEnvf( GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1.0);
glEndList();
-#endif //!GL_ARB_texture_env_combine
}
int BL_Texture::GetPow2(int n)
diff --git a/source/gameengine/Ketsji/BL_Texture.h b/source/gameengine/Ketsji/BL_Texture.h
index 0d0c7a277f2..830ffceb0f7 100644
--- a/source/gameengine/Ketsji/BL_Texture.h
+++ b/source/gameengine/Ketsji/BL_Texture.h
@@ -59,6 +59,14 @@ public:
void SetMapping(int mode);
void DisableUnit();
void setTexEnv(BL_Material *mat, bool modulate=false);
+ unsigned int swapTexture (unsigned int newTex) {
+ // swap texture codes
+ unsigned int tmp = mTexture;
+ mTexture = newTex;
+ // return original texture code
+ return tmp;
+ }
+
};
#endif//__BL_TEXTURE_H__
diff --git a/source/gameengine/Ketsji/CMakeLists.txt b/source/gameengine/Ketsji/CMakeLists.txt
index a10b07ff491..d054894589f 100644
--- a/source/gameengine/Ketsji/CMakeLists.txt
+++ b/source/gameengine/Ketsji/CMakeLists.txt
@@ -26,6 +26,19 @@
FILE(GLOB SRC *.cpp)
+#XXX disabled for 2.5 because of missing python
+#SET(SRC
+# ${SRC}
+# ../../../source/blender/python/api2_2x/Mathutils.c
+# ../../../source/blender/python/api2_2x/constant.c
+# ../../../source/blender/python/api2_2x/euler.c
+# ../../../source/blender/python/api2_2x/gen_utils.c
+# ../../../source/blender/python/api2_2x/matrix.c
+# ../../../source/blender/python/api2_2x/point.c
+# ../../../source/blender/python/api2_2x/quat.c
+# ../../../source/blender/python/api2_2x/vector.c
+#)
+
SET(INC
.
../../../source/kernel/gen_system
@@ -39,7 +52,8 @@ SET(INC
../../../intern/moto/include
../../../source/gameengine/Ketsji
../../../source/blender/blenlib
- ../../../source/blender/blenkernel
+ ../../../source/blender/blenkernel
+ ../../../source/blender/python/api2_2x
../../../source/blender
../../../source/blender/include
../../../source/blender/makesdna
@@ -57,8 +71,10 @@ SET(INC
../../../intern/SoundSystem
../../../source/blender/misc
../../../source/blender/blenloader
+ ../../../source/blender/gpu
../../../extern/bullet2/src
../../../extern/solid
+ ../../../extern/glew/include
${PYTHON_INC}
${SDL_INC}
)
diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.cpp b/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.cpp
index 7b5b7fdf78c..eee8e9f6827 100644
--- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.cpp
+++ b/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.cpp
@@ -55,28 +55,13 @@ KX_NetworkEventManager::~KX_NetworkEventManager()
//printf("KX_NetworkEventManager destructor\n");
}
-void KX_NetworkEventManager::RegisterSensor(class SCA_ISensor* sensor)
-{
- //printf("KX_NetworkEventManager RegisterSensor\n");
- m_sensors.push_back(sensor);
-}
-
-void KX_NetworkEventManager::RemoveSensor(class SCA_ISensor* sensor)
-{
- //printf("KX_NetworkEventManager RemoveSensor\n");
- // Network specific RemoveSensor stuff goes here
-
- // parent
- SCA_EventManager::RemoveSensor(sensor);
-}
-
void KX_NetworkEventManager::NextFrame()
{
// printf("KX_NetworkEventManager::proceed %.2f - %.2f\n", curtime, deltatime);
// each frame, the logicmanager will call the network
// eventmanager to look for network events, and process it's
// 'network' sensors
- vector<class SCA_ISensor*>::iterator it;
+ set<class SCA_ISensor*>::iterator it;
for (it = m_sensors.begin(); !(it==m_sensors.end()); it++) {
// printf("KX_NetworkEventManager::proceed sensor %.2f\n", curtime);
diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.h b/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.h
index 0b097ba2ef6..ae88f1d4987 100644
--- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.h
+++ b/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.h
@@ -42,9 +42,6 @@ public:
class NG_NetworkDeviceInterface *ndi);
virtual ~KX_NetworkEventManager ();
- virtual void RegisterSensor(class SCA_ISensor* sensor);
- virtual void RemoveSensor(class SCA_ISensor* sensor);
-
virtual void NextFrame();
virtual void EndFrame();
diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.cpp b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.cpp
index 3ade810c394..85921ae75ca 100644
--- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.cpp
+++ b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.cpp
@@ -158,6 +158,9 @@ PyObject* KX_NetworkMessageActuator::PySetToPropName(
if (PyArg_ParseTuple(args, "s", &ToPropName)) {
m_toPropName = ToPropName;
}
+ else {
+ return NULL;
+ }
Py_Return;
}
@@ -173,7 +176,10 @@ PyObject* KX_NetworkMessageActuator::PySetSubject(
if (PyArg_ParseTuple(args, "s", &Subject)) {
m_subject = Subject;
}
-
+ else {
+ return NULL;
+ }
+
Py_Return;
}
@@ -188,6 +194,9 @@ PyObject* KX_NetworkMessageActuator::PySetBodyType(
if (PyArg_ParseTuple(args, "i", &BodyType)) {
m_bodyType = BodyType;
}
+ else {
+ return NULL;
+ }
Py_Return;
}
@@ -203,6 +212,9 @@ PyObject* KX_NetworkMessageActuator::PySetBody(
if (PyArg_ParseTuple(args, "s", &Body)) {
m_body = Body;
}
+ else {
+ return NULL;
+ }
Py_Return;
}
diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp
index c9fa920a426..8956df9c96b 100644
--- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp
+++ b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp
@@ -58,10 +58,15 @@ KX_NetworkMessageSensor::KX_NetworkMessageSensor(
m_NetworkScene(NetworkScene),
m_subject(subject),
m_frame_message_count (0),
- m_IsUp(false),
m_BodyList(NULL),
m_SubjectList(NULL)
{
+ Init();
+}
+
+void KX_NetworkMessageSensor::Init()
+{
+ m_IsUp = false;
}
KX_NetworkMessageSensor::~KX_NetworkMessageSensor()
@@ -139,7 +144,11 @@ bool KX_NetworkMessageSensor::Evaluate(CValue* event)
result = (WasUp != m_IsUp);
- // Return true if the message received state has changed.
+ // Return always true if a message was received otherwise we can loose messages
+ if (m_IsUp)
+ return true;
+ // Is it usefull to return also true when the first frame without a message??
+ // This will cause a fast on/off cycle that seems useless!
return result;
}
@@ -187,20 +196,20 @@ PyParentObject KX_NetworkMessageSensor::Parents[] = {
PyMethodDef KX_NetworkMessageSensor::Methods[] = {
{"setSubjectFilterText", (PyCFunction)
- KX_NetworkMessageSensor::sPySetSubjectFilterText, METH_VARARGS,
- SetSubjectFilterText_doc},
+ KX_NetworkMessageSensor::sPySetSubjectFilterText, METH_O,
+ (PY_METHODCHAR)SetSubjectFilterText_doc},
{"getFrameMessageCount", (PyCFunction)
- KX_NetworkMessageSensor::sPyGetFrameMessageCount, METH_VARARGS,
- GetFrameMessageCount_doc},
+ KX_NetworkMessageSensor::sPyGetFrameMessageCount, METH_NOARGS,
+ (PY_METHODCHAR)GetFrameMessageCount_doc},
{"getBodies", (PyCFunction)
- KX_NetworkMessageSensor::sPyGetBodies, METH_VARARGS,
- GetBodies_doc},
+ KX_NetworkMessageSensor::sPyGetBodies, METH_NOARGS,
+ (PY_METHODCHAR)GetBodies_doc},
{"getSubject", (PyCFunction)
- KX_NetworkMessageSensor::sPyGetSubject, METH_VARARGS,
- GetSubject_doc},
+ KX_NetworkMessageSensor::sPyGetSubject, METH_NOARGS,
+ (PY_METHODCHAR)GetSubject_doc},
{"getSubjects", (PyCFunction)
- KX_NetworkMessageSensor::sPyGetSubjects, METH_VARARGS,
- GetSubjects_doc},
+ KX_NetworkMessageSensor::sPyGetSubjects, METH_NOARGS,
+ (PY_METHODCHAR)GetSubjects_doc},
{NULL,NULL} //Sentinel
};
@@ -209,85 +218,66 @@ PyObject* KX_NetworkMessageSensor::_getattr(const STR_String& attr) {
}
// 1. Set the message subject that this sensor listens for
-char KX_NetworkMessageSensor::SetSubjectFilterText_doc[] =
+const char KX_NetworkMessageSensor::SetSubjectFilterText_doc[] =
"\tsetSubjectFilterText(value)\n"
"\tChange the message subject text that this sensor is listening to.\n";
-PyObject* KX_NetworkMessageSensor::PySetSubjectFilterText(
- PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_NetworkMessageSensor::PySetSubjectFilterText( PyObject* self, PyObject* value)
{
- char* Subject;
-
- if (PyArg_ParseTuple(args, "s", &Subject))
- {
- m_subject = Subject;
+ char* Subject = PyString_AsString(value);
+ if (Subject==NULL) {
+ PyErr_SetString(PyExc_TypeError, "expected a string message");
+ return NULL;
}
-
- Py_Return;
+
+ m_subject = Subject;
+ Py_RETURN_NONE;
}
// 2. Get the number of messages received since the last frame
-char KX_NetworkMessageSensor::GetFrameMessageCount_doc[] =
+const char KX_NetworkMessageSensor::GetFrameMessageCount_doc[] =
"\tgetFrameMessageCount()\n"
"\tGet the number of messages received since the last frame.\n";
-PyObject* KX_NetworkMessageSensor::PyGetFrameMessageCount(
- PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_NetworkMessageSensor::PyGetFrameMessageCount( PyObject* )
{
return PyInt_FromLong(long(m_frame_message_count));
}
// 3. Get the message bodies
-char KX_NetworkMessageSensor::GetBodies_doc[] =
+const char KX_NetworkMessageSensor::GetBodies_doc[] =
"\tgetBodies()\n"
"\tGet the list of message bodies.\n";
-PyObject* KX_NetworkMessageSensor::PyGetBodies(
- PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_NetworkMessageSensor::PyGetBodies( PyObject* )
{
if (m_BodyList) {
return ((PyObject*) m_BodyList->AddRef());
+ } else {
+ return ((PyObject*) new CListValue());
}
-
- Py_Return;
}
// 4. Get the message subject: field of the message sensor
-char KX_NetworkMessageSensor::GetSubject_doc[] =
+const char KX_NetworkMessageSensor::GetSubject_doc[] =
"\tgetSubject()\n"
"\tGet the subject: field of the message sensor.\n";
-PyObject* KX_NetworkMessageSensor::PyGetSubject(
- PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_NetworkMessageSensor::PyGetSubject( PyObject* )
{
- if (m_subject) {
- return PyString_FromString(m_subject);
- }
-
- Py_Return;
+ return PyString_FromString(m_subject ? m_subject : "");
}
// 5. Get the message subjects
-char KX_NetworkMessageSensor::GetSubjects_doc[] =
+const char KX_NetworkMessageSensor::GetSubjects_doc[] =
"\tgetSubjects()\n"
"\tGet list of message subjects.\n";
-PyObject* KX_NetworkMessageSensor::PyGetSubjects(
- PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_NetworkMessageSensor::PyGetSubjects( PyObject* )
{
if (m_SubjectList) {
- return ((PyObject*) m_SubjectList->AddRef());
- }
-
- Py_Return;
+ return ((PyObject*) m_SubjectList->AddRef());
+ } else {
+ return ((PyObject*) new CListValue());
+ }
}
diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h
index d051b715aab..8cdfd6cdb5a 100644
--- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h
+++ b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h
@@ -65,6 +65,7 @@ public:
virtual CValue* GetReplica();
virtual bool Evaluate(CValue* event);
virtual bool IsPositiveTrigger();
+ virtual void Init();
void EndFrame();
/* ------------------------------------------------------------- */
@@ -73,11 +74,11 @@ public:
virtual PyObject* _getattr(const STR_String& attr);
- KX_PYMETHOD_DOC(KX_NetworkMessageSensor, SetSubjectFilterText);
- KX_PYMETHOD_DOC(KX_NetworkMessageSensor, GetFrameMessageCount);
- KX_PYMETHOD_DOC(KX_NetworkMessageSensor, GetBodies);
- KX_PYMETHOD_DOC(KX_NetworkMessageSensor, GetSubject);
- KX_PYMETHOD_DOC(KX_NetworkMessageSensor, GetSubjects);
+ KX_PYMETHOD_DOC_O(KX_NetworkMessageSensor, SetSubjectFilterText);
+ KX_PYMETHOD_DOC_NOARGS(KX_NetworkMessageSensor, GetFrameMessageCount);
+ KX_PYMETHOD_DOC_NOARGS(KX_NetworkMessageSensor, GetBodies);
+ KX_PYMETHOD_DOC_NOARGS(KX_NetworkMessageSensor, GetSubject);
+ KX_PYMETHOD_DOC_NOARGS(KX_NetworkMessageSensor, GetSubjects);
};
diff --git a/source/gameengine/Ketsji/KX_BlenderMaterial.cpp b/source/gameengine/Ketsji/KX_BlenderMaterial.cpp
index bbf5640f8e0..f92200780d5 100644
--- a/source/gameengine/Ketsji/KX_BlenderMaterial.cpp
+++ b/source/gameengine/Ketsji/KX_BlenderMaterial.cpp
@@ -6,21 +6,7 @@
#include <config.h>
#endif
-#ifdef WIN32
-#include <windows.h>
-#endif // WIN32
-#ifdef __APPLE__
-#define GL_GLEXT_LEGACY 1
-#include <OpenGL/gl.h>
-#include <OpenGL/glu.h>
-#else
-#include <GL/gl.h>
-#if defined(__sun__) && !defined(__sparc__)
-#include <mesa/glu.h>
-#else
-#include <GL/glu.h>
-#endif
-#endif
+#include "GL/glew.h"
#include "KX_BlenderMaterial.h"
#include "BL_Material.h"
@@ -33,14 +19,12 @@
#include "MT_Vector4.h"
#include "MT_Matrix4x4.h"
+#include "RAS_BucketManager.h"
#include "RAS_MeshObject.h"
#include "RAS_IRasterizer.h"
#include "RAS_OpenGLRasterizer/RAS_GLExtensionManager.h"
-#include "RAS_OpenGLRasterizer/ARB_multitexture.h"
-extern "C" {
-//XXX #include "BDR_drawmesh.h"
-}
+#include "GPU_draw.h"
#include "STR_HashedString.h"
@@ -51,9 +35,11 @@ extern "C" {
#include "DNA_meshdata_types.h"
#include "BKE_mesh.h"
// ------------------------------------
-using namespace bgl;
#define spit(x) std::cout << x << std::endl;
+BL_Shader *KX_BlenderMaterial::mLastShader = NULL;
+BL_BlenderShader *KX_BlenderMaterial::mLastBlenderShader = NULL;
+
//static PyObject *gTextureDict = 0;
KX_BlenderMaterial::KX_BlenderMaterial(
@@ -61,7 +47,6 @@ KX_BlenderMaterial::KX_BlenderMaterial(
BL_Material *data,
bool skin,
int lightlayer,
- void *clientobject,
PyTypeObject *T
)
: PyObjectPlus(T),
@@ -72,35 +57,33 @@ KX_BlenderMaterial::KX_BlenderMaterial(
data->tilexrep[0],
data->tileyrep[0],
data->mode,
- ((data->ras_mode &TRANSP)!=0),
+ data->transp,
+ ((data->ras_mode &ALPHA)!=0),
((data->ras_mode &ZSORT)!=0),
- lightlayer,
- ((data->ras_mode &TRIANGLE)!=0),
- clientobject
+ lightlayer
),
mMaterial(data),
mShader(0),
+ mBlenderShader(0),
mScene(scene),
mUserDefBlend(0),
mModified(0),
+ mConstructed(false),
mPass(0)
{
// --------------------------------
// RAS_IPolyMaterial variables...
- m_flag |=RAS_BLENDERMAT;
- m_flag |=(mMaterial->IdMode>=ONETEX)?RAS_MULTITEX:0;
- m_flag |=(mMaterial->ras_mode & USE_LIGHT)!=0?RAS_MULTILIGHT:0;
- m_flag |=(mMaterial->ras_mode &ALPHA_TEST)!=0?RAS_FORCEALPHA:0;
+ m_flag |= RAS_BLENDERMAT;
+ m_flag |= (mMaterial->IdMode>=ONETEX)? RAS_MULTITEX: 0;
+ m_flag |= ((mMaterial->ras_mode & USE_LIGHT)!=0)? RAS_MULTILIGHT: 0;
+ m_flag |= (mMaterial->glslmat)? RAS_BLENDERGLSL: 0;
// figure max
int enabled = mMaterial->num_enabled;
int max = BL_Texture::GetMaxUnits();
mMaterial->num_enabled = enabled>=max?max:enabled;
- // base class
- m_enabled = mMaterial->num_enabled;
-
// test the sum of the various modes for equality
// so we can ether accept or reject this material
// as being equal, this is rather important to
@@ -111,14 +94,16 @@ KX_BlenderMaterial::KX_BlenderMaterial(
mMaterial->blend_mode[i]
);
}
- m_multimode += mMaterial->IdMode+mMaterial->ras_mode;
+ m_multimode += mMaterial->IdMode+ (mMaterial->ras_mode & ~(COLLIDER|USE_LIGHT));
}
KX_BlenderMaterial::~KX_BlenderMaterial()
{
// cleanup work
- OnExit();
+ if (mConstructed)
+ // clean only if material was actually used
+ OnExit();
}
@@ -137,41 +122,77 @@ unsigned int* KX_BlenderMaterial::GetMCol(void) const
void KX_BlenderMaterial::OnConstruction()
{
+ if (mConstructed)
+ // when material are reused between objects
+ return;
+
+ if(mMaterial->glslmat)
+ SetBlenderGLSLShader();
+
// for each unique material...
int i;
for(i=0; i<mMaterial->num_enabled; i++) {
if( mMaterial->mapping[i].mapping & USEENV ) {
- if(!RAS_EXT_support._ARB_texture_cube_map) {
+ if(!GLEW_ARB_texture_cube_map) {
spit("CubeMap textures not supported");
continue;
}
if(!mTextures[i].InitCubeMap(i, mMaterial->cubemap[i] ) )
spit("unable to initialize image("<<i<<") in "<<
- mMaterial->matname<< ", image will not be available");
+ mMaterial->matname<< ", image will not be available");
}
else {
if( mMaterial->img[i] ) {
if( ! mTextures[i].InitFromImage(i, mMaterial->img[i], (mMaterial->flag[i] &MIPMAP)!=0 ))
spit("unable to initialize image("<<i<<") in "<<
- mMaterial->matname<< ", image will not be available");
+ mMaterial->matname<< ", image will not be available");
}
}
}
+
mBlendFunc[0] =0;
mBlendFunc[1] =0;
+ mConstructed = true;
+}
+
+void KX_BlenderMaterial::EndFrame()
+{
+ if(mLastBlenderShader) {
+ mLastBlenderShader->SetProg(false);
+ mLastBlenderShader = NULL;
+ }
+
+ if(mLastShader) {
+ mLastShader->SetProg(false);
+ mLastShader = NULL;
+ }
}
void KX_BlenderMaterial::OnExit()
{
if( mShader ) {
- //note, the shader here is allocated, per unique material
- //and this function is called per face
- mShader->SetProg(0);
+ //note, the shader here is allocated, per unique material
+ //and this function is called per face
+ if(mShader == mLastShader) {
+ mShader->SetProg(false);
+ mLastShader = NULL;
+ }
+
delete mShader;
mShader = 0;
}
+ if( mBlenderShader ) {
+ if(mBlenderShader == mLastBlenderShader) {
+ mBlenderShader->SetProg(false);
+ mLastBlenderShader = NULL;
+ }
+
+ delete mBlenderShader;
+ mBlenderShader = 0;
+ }
+
BL_Texture::ActivateFirst();
for(int i=0; i<mMaterial->num_enabled; i++) {
BL_Texture::ActivateUnit(i);
@@ -180,24 +201,30 @@ void KX_BlenderMaterial::OnExit()
}
if( mMaterial->tface )
- ; //XXX set_tpage(mMaterial->tface);
+ GPU_set_tpage(mMaterial->tface);
}
void KX_BlenderMaterial::setShaderData( bool enable, RAS_IRasterizer *ras)
{
- MT_assert(RAS_EXT_support._ARB_shader_objects && mShader);
+ MT_assert(GLEW_ARB_shader_objects && mShader);
int i;
if( !enable || !mShader->Ok() ) {
// frame cleanup.
- mShader->SetProg(false);
+ if(mShader == mLastShader) {
+ mShader->SetProg(false);
+ mLastShader = NULL;
+ }
+
+ ras->SetBlendingMode(TF_SOLID);
BL_Texture::DisableAllTextures();
return;
}
BL_Texture::DisableAllTextures();
mShader->SetProg(true);
+ mLastShader = mShader;
BL_Texture::ActivateFirst();
@@ -211,29 +238,60 @@ void KX_BlenderMaterial::setShaderData( bool enable, RAS_IRasterizer *ras)
}
if(!mUserDefBlend) {
- setDefaultBlending();
+ ras->SetBlendingMode(mMaterial->transp);
}
else {
+ ras->SetBlendingMode(TF_SOLID);
+ ras->SetBlendingMode(-1); // indicates custom mode
+
// tested to be valid enums
glEnable(GL_BLEND);
glBlendFunc(mBlendFunc[0], mBlendFunc[1]);
}
}
+void KX_BlenderMaterial::setBlenderShaderData( bool enable, RAS_IRasterizer *ras)
+{
+ if( !enable || !mBlenderShader->Ok() ) {
+ ras->SetBlendingMode(TF_SOLID);
+
+ // frame cleanup.
+ if(mLastBlenderShader) {
+ mLastBlenderShader->SetProg(false);
+ mLastBlenderShader= NULL;
+ }
+ else
+ BL_Texture::DisableAllTextures();
+
+ return;
+ }
+
+ if(!mBlenderShader->Equals(mLastBlenderShader)) {
+ ras->SetBlendingMode(mMaterial->transp);
+
+ if(mLastBlenderShader)
+ mLastBlenderShader->SetProg(false);
+ else
+ BL_Texture::DisableAllTextures();
+
+ mBlenderShader->SetProg(true, ras->GetTime());
+ mLastBlenderShader= mBlenderShader;
+ }
+}
void KX_BlenderMaterial::setTexData( bool enable, RAS_IRasterizer *ras)
{
- if(RAS_EXT_support._ARB_shader_objects && mShader)
- mShader->SetProg(false);
-
BL_Texture::DisableAllTextures();
- if( !enable )
+
+ if( !enable ) {
+ ras->SetBlendingMode(TF_SOLID);
return;
+ }
BL_Texture::ActivateFirst();
if( mMaterial->IdMode == DEFAULT_BLENDER ) {
- setDefaultBlending();
+ ras->SetBlendingMode(mMaterial->transp);
return;
}
@@ -243,7 +301,7 @@ void KX_BlenderMaterial::setTexData( bool enable, RAS_IRasterizer *ras)
mTextures[0].ActivateTexture();
mTextures[0].setTexEnv(0, true);
mTextures[0].SetMapping(mMaterial->mapping[0].mapping);
- setDefaultBlending();
+ ras->SetBlendingMode(mMaterial->transp);
}
return;
}
@@ -266,9 +324,12 @@ void KX_BlenderMaterial::setTexData( bool enable, RAS_IRasterizer *ras)
}
if(!mUserDefBlend) {
- setDefaultBlending();
+ ras->SetBlendingMode(mMaterial->transp);
}
else {
+ ras->SetBlendingMode(TF_SOLID);
+ ras->SetBlendingMode(-1); // indicates custom mode
+
glEnable(GL_BLEND);
glBlendFunc(mBlendFunc[0], mBlendFunc[1]);
}
@@ -284,29 +345,31 @@ KX_BlenderMaterial::ActivatShaders(
// reset...
if(tmp->mMaterial->IsShared())
cachingInfo =0;
-
+
+ if(mLastBlenderShader) {
+ mLastBlenderShader->SetProg(false);
+ mLastBlenderShader= NULL;
+ }
+
if (GetCachingInfo() != cachingInfo) {
if (!cachingInfo)
- tmp->setShaderData( false, rasty);
+ tmp->setShaderData(false, rasty);
cachingInfo = GetCachingInfo();
- if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED ) {
- tmp->setShaderData( true, rasty);
- rasty->EnableTextures(true);
- }
- else {
- tmp->setShaderData( false, rasty);
- rasty->EnableTextures(false);
- }
+ if(rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED)
+ tmp->setShaderData(true, rasty);
+ else
+ tmp->setShaderData(false, rasty);
if(mMaterial->mode & RAS_IRasterizer::KX_TWOSIDE)
rasty->SetCullFace(false);
else
rasty->SetCullFace(true);
- if (((mMaterial->ras_mode &WIRE)!=0) || mMaterial->mode & RAS_IRasterizer::KX_LINES)
+ if (((mMaterial->ras_mode &WIRE)!=0) || (mMaterial->mode & RAS_IRasterizer::KX_LINES) ||
+ (rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME))
{
if((mMaterial->ras_mode &WIRE)!=0)
rasty->SetCullFace(false);
@@ -321,33 +384,84 @@ KX_BlenderMaterial::ActivatShaders(
}
void
+KX_BlenderMaterial::ActivateBlenderShaders(
+ RAS_IRasterizer* rasty,
+ TCachingInfo& cachingInfo)const
+{
+ KX_BlenderMaterial *tmp = const_cast<KX_BlenderMaterial*>(this);
+
+ if(mLastShader) {
+ mLastShader->SetProg(false);
+ mLastShader= NULL;
+ }
+
+ if (GetCachingInfo() != cachingInfo) {
+ if (!cachingInfo)
+ tmp->setBlenderShaderData(false, rasty);
+
+ cachingInfo = GetCachingInfo();
+
+ if(rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED)
+ tmp->setBlenderShaderData(true, rasty);
+ else
+ tmp->setBlenderShaderData(false, rasty);
+
+ if(mMaterial->mode & RAS_IRasterizer::KX_TWOSIDE)
+ rasty->SetCullFace(false);
+ else
+ rasty->SetCullFace(true);
+
+ if (((mMaterial->ras_mode & WIRE)!=0) || (mMaterial->mode & RAS_IRasterizer::KX_LINES) ||
+ (rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME))
+ {
+ if((mMaterial->ras_mode &WIRE)!=0)
+ rasty->SetCullFace(false);
+ rasty->SetLines(true);
+ }
+ else
+ rasty->SetLines(false);
+
+ ActivatGLMaterials(rasty);
+ mBlenderShader->SetAttribs(rasty, mMaterial);
+ }
+}
+
+void
KX_BlenderMaterial::ActivateMat(
RAS_IRasterizer* rasty,
TCachingInfo& cachingInfo
)const
{
KX_BlenderMaterial *tmp = const_cast<KX_BlenderMaterial*>(this);
+
+ if(mLastShader) {
+ mLastShader->SetProg(false);
+ mLastShader= NULL;
+ }
+
+ if(mLastBlenderShader) {
+ mLastBlenderShader->SetProg(false);
+ mLastBlenderShader= NULL;
+ }
+
if (GetCachingInfo() != cachingInfo) {
if (!cachingInfo)
tmp->setTexData( false,rasty );
cachingInfo = GetCachingInfo();
- if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED) {
+ if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED)
tmp->setTexData( true,rasty );
- rasty->EnableTextures(true);
- }
- else{
+ else
tmp->setTexData( false,rasty);
- rasty->EnableTextures(false);
- }
if(mMaterial->mode & RAS_IRasterizer::KX_TWOSIDE)
rasty->SetCullFace(false);
else
rasty->SetCullFace(true);
- if (((mMaterial->ras_mode &WIRE)!=0) || mMaterial->mode & RAS_IRasterizer::KX_LINES)
+ if (((mMaterial->ras_mode &WIRE)!=0) || (mMaterial->mode & RAS_IRasterizer::KX_LINES) ||
+ (rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME))
{
if((mMaterial->ras_mode &WIRE)!=0)
rasty->SetCullFace(false);
@@ -356,77 +470,113 @@ KX_BlenderMaterial::ActivateMat(
else
rasty->SetLines(false);
}
+
ActivatGLMaterials(rasty);
ActivateTexGen(rasty);
}
-
bool
KX_BlenderMaterial::Activate(
RAS_IRasterizer* rasty,
TCachingInfo& cachingInfo
)const
{
- bool dopass = false;
- if( RAS_EXT_support._ARB_shader_objects && ( mShader && mShader->Ok() ) ) {
- if( (mPass++) < mShader->getNumPass() ) {
+ if(GLEW_ARB_shader_objects && (mShader && mShader->Ok())) {
+ if((mPass++) < mShader->getNumPass() ) {
ActivatShaders(rasty, cachingInfo);
- dopass = true;
- return dopass;
+ return true;
+ }
+ else {
+ if(mShader == mLastShader) {
+ mShader->SetProg(false);
+ mLastShader = NULL;
+ }
+ mPass = 0;
+ return false;
+ }
+ }
+ else if( GLEW_ARB_shader_objects && (mBlenderShader && mBlenderShader->Ok() ) ) {
+ if(mPass++ == 0) {
+ ActivateBlenderShaders(rasty, cachingInfo);
+ return true;
}
else {
- mShader->SetProg(false);
mPass = 0;
- dopass = false;
- return dopass;
+ return false;
}
}
else {
- switch (mPass++)
- {
- case 0:
- ActivateMat(rasty, cachingInfo);
- dopass = true;
- break;
- default:
- mPass = 0;
- dopass = false;
- break;
+ if(mPass++ == 0) {
+ ActivateMat(rasty, cachingInfo);
+ return true;
+ }
+ else {
+ mPass = 0;
+ return false;
}
}
- return dopass;
}
-void KX_BlenderMaterial::ActivateMeshSlot(const KX_MeshSlot & ms, RAS_IRasterizer* rasty) const
+bool KX_BlenderMaterial::UsesLighting(RAS_IRasterizer *rasty) const
{
- if(mShader && RAS_EXT_support._ARB_shader_objects)
+ if(!RAS_IPolyMaterial::UsesLighting(rasty))
+ return false;
+
+ if(mShader && mShader->Ok())
+ return true;
+ else if(mBlenderShader && mBlenderShader->Ok())
+ return false;
+ else
+ return true;
+}
+
+void KX_BlenderMaterial::ActivateMeshSlot(const RAS_MeshSlot & ms, RAS_IRasterizer* rasty) const
+{
+ if(mShader && GLEW_ARB_shader_objects) {
mShader->Update(ms, rasty);
+ }
+ else if(mBlenderShader && GLEW_ARB_shader_objects) {
+ int blendmode;
+
+ mBlenderShader->Update(ms, rasty);
+
+ /* we do blend modes here, because they can change per object
+ * with the same material due to obcolor/obalpha */
+ blendmode = mBlenderShader->GetBlendMode();
+ if((blendmode == TF_SOLID || blendmode == TF_ALPHA) && mMaterial->transp != TF_SOLID)
+ blendmode = mMaterial->transp;
+
+ rasty->SetBlendingMode(blendmode);
+ }
}
void KX_BlenderMaterial::ActivatGLMaterials( RAS_IRasterizer* rasty )const
{
- rasty->SetSpecularity(
- mMaterial->speccolor[0]*mMaterial->spec_f,
- mMaterial->speccolor[1]*mMaterial->spec_f,
- mMaterial->speccolor[2]*mMaterial->spec_f,
- mMaterial->spec_f
- );
+ if(mShader || !mBlenderShader) {
+ rasty->SetSpecularity(
+ mMaterial->speccolor[0]*mMaterial->spec_f,
+ mMaterial->speccolor[1]*mMaterial->spec_f,
+ mMaterial->speccolor[2]*mMaterial->spec_f,
+ mMaterial->spec_f
+ );
- rasty->SetShinyness( mMaterial->hard );
+ rasty->SetShinyness( mMaterial->hard );
- rasty->SetDiffuse(
- mMaterial->matcolor[0]*mMaterial->ref+mMaterial->emit,
- mMaterial->matcolor[1]*mMaterial->ref+mMaterial->emit,
- mMaterial->matcolor[2]*mMaterial->ref+mMaterial->emit,
- 1.0f);
+ rasty->SetDiffuse(
+ mMaterial->matcolor[0]*mMaterial->ref+mMaterial->emit,
+ mMaterial->matcolor[1]*mMaterial->ref+mMaterial->emit,
+ mMaterial->matcolor[2]*mMaterial->ref+mMaterial->emit,
+ 1.0f);
- rasty->SetEmissive(
- mMaterial->matcolor[0]*mMaterial->emit,
- mMaterial->matcolor[1]*mMaterial->emit,
- mMaterial->matcolor[2]*mMaterial->emit,
- 1.0 );
+ rasty->SetEmissive(
+ mMaterial->matcolor[0]*mMaterial->emit,
+ mMaterial->matcolor[1]*mMaterial->emit,
+ mMaterial->matcolor[2]*mMaterial->emit,
+ 1.0 );
+
+ rasty->SetAmbient(mMaterial->amb);
+ }
- rasty->SetAmbient(mMaterial->amb);
if (mMaterial->material)
rasty->SetPolygonOffset(-mMaterial->material->zoffs, 0.0);
}
@@ -434,52 +584,43 @@ void KX_BlenderMaterial::ActivatGLMaterials( RAS_IRasterizer* rasty )const
void KX_BlenderMaterial::ActivateTexGen(RAS_IRasterizer *ras) const
{
- if(mShader && RAS_EXT_support._ARB_shader_objects)
- if(mShader->GetAttribute() == BL_Shader::SHD_TANGENT)
- ras->SetAttrib(RAS_IRasterizer::RAS_TEXTANGENT);
+ if(ras->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED) {
+ ras->SetAttribNum(0);
+ if(mShader && GLEW_ARB_shader_objects) {
+ if(mShader->GetAttribute() == BL_Shader::SHD_TANGENT) {
+ ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_DISABLE, 0);
+ ras->SetAttrib(RAS_IRasterizer::RAS_TEXTANGENT, 1);
+ ras->SetAttribNum(2);
+ }
+ }
- for(int i=0; i<mMaterial->num_enabled; i++) {
- int mode = mMaterial->mapping[i].mapping;
+ ras->SetTexCoordNum(mMaterial->num_enabled);
- if (mode &USECUSTOMUV)
- {
- STR_String str = mMaterial->mapping[i].uvCoName;
- if (!str.IsEmpty())
- ras->SetTexCoords(RAS_IRasterizer::RAS_TEXCO_UV2, i);
- continue;
- }
+ for(int i=0; i<mMaterial->num_enabled; i++) {
+ int mode = mMaterial->mapping[i].mapping;
- if( mode &(USEREFL|USEOBJ))
- ras->SetTexCoords(RAS_IRasterizer::RAS_TEXCO_GEN, i);
- else if(mode &USEORCO)
- ras->SetTexCoords(RAS_IRasterizer::RAS_TEXCO_ORCO, i);
- else if(mode &USENORM)
- ras->SetTexCoords(RAS_IRasterizer::RAS_TEXCO_NORM, i);
- else if(mode &USEUV)
- ras->SetTexCoords(RAS_IRasterizer::RAS_TEXCO_UV1, i);
- else if(mode &USETANG)
- ras->SetTexCoords(RAS_IRasterizer::RAS_TEXTANGENT, i);
- else
- ras->SetTexCoords(RAS_IRasterizer::RAS_TEXCO_DISABLE, i);
- }
-}
+ if (mode &USECUSTOMUV)
+ {
+ STR_String str = mMaterial->mapping[i].uvCoName;
+ if (!str.IsEmpty())
+ ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_UV2, i);
+ continue;
+ }
-bool KX_BlenderMaterial::setDefaultBlending()
-{
- if( mMaterial->transp &TF_ADD) {
- glEnable(GL_BLEND);
- glBlendFunc(GL_ONE, GL_ONE);
- return true;
- }
-
- if( mMaterial->transp & TF_ALPHA ) {
- glEnable(GL_BLEND);
- glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
- return true;
+ if( mode &(USEREFL|USEOBJ))
+ ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_GEN, i);
+ else if(mode &USEORCO)
+ ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_ORCO, i);
+ else if(mode &USENORM)
+ ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_NORM, i);
+ else if(mode &USEUV)
+ ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_UV1, i);
+ else if(mode &USETANG)
+ ras->SetTexCoord(RAS_IRasterizer::RAS_TEXTANGENT, i);
+ else
+ ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_DISABLE, i);
+ }
}
-
- glDisable(GL_BLEND);
- return false;
}
void KX_BlenderMaterial::setTexMatrixData(int i)
@@ -487,8 +628,7 @@ void KX_BlenderMaterial::setTexMatrixData(int i)
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
-#ifdef GL_ARB_texture_cube_map
- if( RAS_EXT_support._ARB_texture_cube_map &&
+ if( GLEW_ARB_texture_cube_map &&
mTextures[i].GetTextureType() == GL_TEXTURE_CUBE_MAP_ARB &&
mMaterial->mapping[i].mapping & USEREFL) {
glScalef(
@@ -498,7 +638,6 @@ void KX_BlenderMaterial::setTexMatrixData(int i)
);
}
else
-#endif
{
glScalef(
mMaterial->mapping[i].scale[0],
@@ -556,8 +695,7 @@ void KX_BlenderMaterial::setObjectMatrixData(int i, RAS_IRasterizer *ras)
glEnable(GL_TEXTURE_GEN_T);
glEnable(GL_TEXTURE_GEN_R);
- MT_Matrix4x4 mvmat;
- ras->GetViewMatrix(mvmat);
+ const MT_Matrix4x4& mvmat = ras->GetViewMatrix();
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
@@ -647,28 +785,23 @@ int KX_BlenderMaterial::_setattr(const STR_String& attr, PyObject *pyvalue)
KX_PYMETHODDEF_DOC( KX_BlenderMaterial, getShader , "getShader()")
{
-#ifdef GL_ARB_fragment_shader
- if( !RAS_EXT_support._ARB_fragment_shader) {
+ if( !GLEW_ARB_fragment_shader) {
if(!mModified)
spit("Fragment shaders not supported");
mModified = true;
Py_Return;
}
-#endif
-#ifdef GL_ARB_vertex_shader
- if( !RAS_EXT_support._ARB_vertex_shader) {
+ if( !GLEW_ARB_vertex_shader) {
if(!mModified)
spit("Vertex shaders not supported");
mModified = true;
Py_Return;
}
-#endif
-#ifdef GL_ARB_shader_objects
- if(!RAS_EXT_support._ARB_shader_objects) {
+ if(!GLEW_ARB_shader_objects) {
if(!mModified)
spit("GLSL not supported");
mModified = true;
@@ -684,7 +817,9 @@ KX_PYMETHODDEF_DOC( KX_BlenderMaterial, getShader , "getShader()")
}
if(mShader && !mShader->GetError()) {
+ m_flag &= ~RAS_BLENDERGLSL;
mMaterial->SetSharedMaterial(true);
+ mScene->GetBucketManager()->ReleaseDisplayLists(this);
Py_INCREF(mShader);
return mShader;
}else
@@ -707,13 +842,20 @@ KX_PYMETHODDEF_DOC( KX_BlenderMaterial, getShader , "getShader()")
}
PyErr_Format(PyExc_ValueError, "GLSL Error");
return NULL;
-
-#else
- Py_Return;
-#endif//GL_ARB_shader_objects
}
+void KX_BlenderMaterial::SetBlenderGLSLShader(void)
+{
+ if(!mBlenderShader)
+ mBlenderShader = new BL_BlenderShader(mScene, mMaterial->material, m_lightlayer);
+
+ if(!mBlenderShader->Ok()) {
+ delete mBlenderShader;
+ mBlenderShader = 0;
+ }
+}
+
KX_PYMETHODDEF_DOC( KX_BlenderMaterial, getMaterialIndex, "getMaterialIndex()")
{
return PyInt_FromLong( mMaterial->material_index );
diff --git a/source/gameengine/Ketsji/KX_BlenderMaterial.h b/source/gameengine/Ketsji/KX_BlenderMaterial.h
index 2b1264154d0..6e5db1b56c1 100644
--- a/source/gameengine/Ketsji/KX_BlenderMaterial.h
+++ b/source/gameengine/Ketsji/KX_BlenderMaterial.h
@@ -8,6 +8,7 @@
#include "BL_Material.h"
#include "BL_Texture.h"
#include "BL_Shader.h"
+#include "BL_BlenderShader.h"
#include "PyObjectPlus.h"
@@ -27,7 +28,6 @@ public:
BL_Material* mat,
bool skin,
int lightlayer,
- void* clientobject,
PyTypeObject* T=&Type
);
@@ -46,7 +46,7 @@ public:
virtual
void ActivateMeshSlot(
- const KX_MeshSlot & ms,
+ const RAS_MeshSlot & ms,
RAS_IRasterizer* rasty
) const;
@@ -60,9 +60,19 @@ public:
TCachingInfo& cachingInfo
)const;
+ void ActivateBlenderShaders(
+ RAS_IRasterizer* rasty,
+ TCachingInfo& cachingInfo
+ )const;
MTFace* GetMTFace(void) const;
unsigned int* GetMCol(void) const;
+ BL_Texture * getTex (unsigned int idx) {
+ return (idx < MAXTEX) ? mTextures + idx : NULL;
+ }
+ Image * getImage (unsigned int idx) {
+ return (idx < MAXTEX && mMaterial) ? mMaterial->img[idx] : NULL;
+ }
// for ipos
void UpdateIPO(
@@ -85,24 +95,32 @@ public:
// --------------------------------
// pre calculate to avoid pops/lag at startup
virtual void OnConstruction( );
+
+ static void EndFrame();
+
private:
- BL_Material* mMaterial;
- BL_Shader* mShader;
+ BL_Material* mMaterial;
+ BL_Shader* mShader;
+ BL_BlenderShader* mBlenderShader;
KX_Scene* mScene;
BL_Texture mTextures[MAXTEX]; // texture array
bool mUserDefBlend;
unsigned int mBlendFunc[2];
bool mModified;
+ bool mConstructed; // if false, don't clean on exit
+
+ void SetBlenderGLSLShader();
void ActivatGLMaterials( RAS_IRasterizer* rasty )const;
void ActivateTexGen( RAS_IRasterizer *ras ) const;
+ bool UsesLighting(RAS_IRasterizer *rasty) const;
// message centers
void setTexData( bool enable,RAS_IRasterizer *ras);
+ void setBlenderShaderData( bool enable, RAS_IRasterizer *ras);
void setShaderData( bool enable, RAS_IRasterizer *ras);
- bool setDefaultBlending();
void setObjectMatrixData(int i, RAS_IRasterizer *ras);
void setTexMatrixData(int i);
@@ -111,6 +129,10 @@ private:
// cleanup stuff
void OnExit();
+ // shader chacing
+ static BL_BlenderShader *mLastBlenderShader;
+ static BL_Shader *mLastShader;
+
mutable int mPass;
};
diff --git a/source/gameengine/Ketsji/KX_BulletPhysicsController.cpp b/source/gameengine/Ketsji/KX_BulletPhysicsController.cpp
index aa5d1f1cec1..bf838e60210 100644
--- a/source/gameengine/Ketsji/KX_BulletPhysicsController.cpp
+++ b/source/gameengine/Ketsji/KX_BulletPhysicsController.cpp
@@ -13,18 +13,32 @@
#include "KX_ClientObjectInfo.h"
#include "PHY_IPhysicsEnvironment.h"
+#include "CcdPhysicsEnvironment.h"
+#include "BulletSoftBody/btSoftBody.h"
KX_BulletPhysicsController::KX_BulletPhysicsController (const CcdConstructionInfo& ci, bool dyna)
: KX_IPhysicsController(dyna,(PHY_IPhysicsController*)this),
-CcdPhysicsController(ci)
+CcdPhysicsController(ci),
+m_savedCollisionFlags(0)
{
}
KX_BulletPhysicsController::~KX_BulletPhysicsController ()
{
-
+ // The game object has a direct link to
+ if (m_pObject)
+ {
+ // If we cheat in SetObject, we must also cheat here otherwise the
+ // object will still things it has a physical controller
+ // Note that it requires that m_pObject is reset in case the object is deleted
+ // before the controller (usual case, see KX_Scene::RemoveNodeDestructObjec)
+ // The non usual case is when the object is not deleted because its reference is hanging
+ // in a AddObject actuator but the node is deleted. This case is covered here.
+ KX_GameObject* gameobj = (KX_GameObject*) m_pObject->GetSGClientObject();
+ gameobj->SetPhysicsController(NULL,false);
+ }
}
void KX_BulletPhysicsController::resolveCombinedVelocities(float linvelX,float linvelY,float linvelZ,float angVelX,float angVelY,float angVelZ)
@@ -58,6 +72,7 @@ void KX_BulletPhysicsController::SetObject (SG_IObject* object)
}
+
void KX_BulletPhysicsController::setMargin (float collisionMargin)
{
CcdPhysicsController::SetMargin(collisionMargin);
@@ -90,10 +105,17 @@ MT_Vector3 KX_BulletPhysicsController::GetLinearVelocity()
CcdPhysicsController::GetLinearVelocity(angVel[0],angVel[1],angVel[2]);//rcruiz
return MT_Vector3(angVel[0],angVel[1],angVel[2]);
}
+MT_Vector3 KX_BulletPhysicsController::GetAngularVelocity()
+{
+ float angVel[3];
+ //CcdPhysicsController::GetAngularVelocity(angVel[0],angVel[1],angVel[2]);
+ CcdPhysicsController::GetAngularVelocity(angVel[0],angVel[1],angVel[2]);//rcruiz
+ return MT_Vector3(angVel[0],angVel[1],angVel[2]);
+}
MT_Vector3 KX_BulletPhysicsController::GetVelocity(const MT_Point3& pos)
{
float linVel[3];
- CcdPhysicsController::GetLinearVelocity(linVel[0],linVel[1],linVel[2]);
+ CcdPhysicsController::GetVelocity(pos[0], pos[1], pos[2], linVel[0],linVel[1],linVel[2]);
return MT_Vector3(linVel[0],linVel[1],linVel[2]);
}
@@ -112,9 +134,10 @@ void KX_BulletPhysicsController::getOrientation(MT_Quaternion& orn)
CcdPhysicsController::getOrientation(myorn[0],myorn[1],myorn[2],myorn[3]);
orn = MT_Quaternion(myorn[0],myorn[1],myorn[2],myorn[3]);
}
-void KX_BulletPhysicsController::setOrientation(const MT_Quaternion& orn)
+void KX_BulletPhysicsController::setOrientation(const MT_Matrix3x3& orn)
{
- CcdPhysicsController::setOrientation(orn.x(),orn.y(),orn.z(),orn.w());
+ btMatrix3x3 btmat(orn[0][0], orn[0][1], orn[0][2], orn[1][0], orn[1][1], orn[1][2], orn[2][0], orn[2][1], orn[2][2]);
+ CcdPhysicsController::setWorldOrientation(btmat);
}
void KX_BulletPhysicsController::setPosition(const MT_Point3& pos)
{
@@ -126,13 +149,23 @@ void KX_BulletPhysicsController::setScaling(const MT_Vector3& scaling)
}
MT_Scalar KX_BulletPhysicsController::GetMass()
{
-
- MT_Scalar invmass = GetRigidBody()->getInvMass();
+ if (GetSoftBody())
+ return GetSoftBody()->getTotalMass();
+
+ MT_Scalar invmass = 0.f;
+ if (GetRigidBody())
+ invmass = GetRigidBody()->getInvMass();
if (invmass)
return 1.f/invmass;
return 0.f;
}
+
+MT_Scalar KX_BulletPhysicsController::GetRadius()
+{
+ return MT_Scalar(CcdPhysicsController::GetRadius());
+}
+
MT_Vector3 KX_BulletPhysicsController::getReactionForce()
{
assert(0);
@@ -142,14 +175,37 @@ void KX_BulletPhysicsController::setRigidBody(bool rigid)
{
}
-void KX_BulletPhysicsController::SuspendDynamics()
+void KX_BulletPhysicsController::SuspendDynamics(bool ghost)
{
- GetRigidBody()->setActivationState(DISABLE_SIMULATION);
-
+ btRigidBody *body = GetRigidBody();
+ if (body && body->getActivationState() != DISABLE_SIMULATION)
+ {
+ btBroadphaseProxy* handle = body->getBroadphaseHandle();
+ m_savedCollisionFlags = body->getCollisionFlags();
+ m_savedMass = GetMass();
+ m_savedCollisionFilterGroup = handle->m_collisionFilterGroup;
+ m_savedCollisionFilterMask = handle->m_collisionFilterMask;
+ body->setActivationState(DISABLE_SIMULATION);
+ GetPhysicsEnvironment()->updateCcdPhysicsController(this,
+ 0.0,
+ btCollisionObject::CF_STATIC_OBJECT|((ghost)?btCollisionObject::CF_NO_CONTACT_RESPONSE:(m_savedCollisionFlags&btCollisionObject::CF_NO_CONTACT_RESPONSE)),
+ btBroadphaseProxy::StaticFilter,
+ btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);
+ }
}
+
void KX_BulletPhysicsController::RestoreDynamics()
{
- GetRigidBody()->forceActivationState(ACTIVE_TAG);
+ btRigidBody *body = GetRigidBody();
+ if (body && body->getActivationState() == DISABLE_SIMULATION)
+ {
+ GetPhysicsEnvironment()->updateCcdPhysicsController(this,
+ m_savedMass,
+ m_savedCollisionFlags,
+ m_savedCollisionFilterGroup,
+ m_savedCollisionFilterMask);
+ GetRigidBody()->forceActivationState(ACTIVE_TAG);
+ }
}
SG_Controller* KX_BulletPhysicsController::GetReplica(class SG_Node* destnode)
@@ -161,6 +217,9 @@ SG_Controller* KX_BulletPhysicsController::GetReplica(class SG_Node* destnode)
//parentcontroller is here be able to avoid collisions between parent/child
PHY_IPhysicsController* parentctrl = NULL;
+ KX_BulletPhysicsController* parentKxCtrl = NULL;
+ CcdPhysicsController* ccdParent = NULL;
+
if (destnode != destnode->GetRootSGParent())
{
@@ -180,12 +239,15 @@ SG_Controller* KX_BulletPhysicsController::GetReplica(class SG_Node* destnode)
KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
if (clientgameobj)
{
- parentctrl = (KX_BulletPhysicsController*)clientgameobj->GetPhysicsController();
+ parentKxCtrl = (KX_BulletPhysicsController*)clientgameobj->GetPhysicsController();
+ parentctrl = parentKxCtrl;
+ ccdParent = parentKxCtrl;
}
}
}
}
+ physicsreplica->setParentCtrl(ccdParent);
physicsreplica->PostProcessReplica(motionstate,parentctrl);
physicsreplica->m_userdata = (PHY_IPhysicsController*)physicsreplica;
return physicsreplica;
@@ -196,18 +258,22 @@ SG_Controller* KX_BulletPhysicsController::GetReplica(class SG_Node* destnode)
void KX_BulletPhysicsController::SetSumoTransform(bool nondynaonly)
{
- GetRigidBody()->activate(true);
+ if (GetRigidBody())
+ GetRigidBody()->activate(true);
if (!m_bDyna)
{
- GetRigidBody()->setCollisionFlags(GetRigidBody()->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ GetCollisionObject()->setCollisionFlags(GetRigidBody()->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
} else
{
if (!nondynaonly)
{
btTransform worldTrans;
- GetRigidBody()->getMotionState()->getWorldTransform(worldTrans);
- GetRigidBody()->setCenterOfMassTransform(worldTrans);
+ if (GetRigidBody())
+ {
+ GetRigidBody()->getMotionState()->getWorldTransform(worldTrans);
+ GetRigidBody()->setCenterOfMassTransform(worldTrans);
+ }
/*
scaling?
diff --git a/source/gameengine/Ketsji/KX_BulletPhysicsController.h b/source/gameengine/Ketsji/KX_BulletPhysicsController.h
index 619ac42503f..cdcb82c87ca 100644
--- a/source/gameengine/Ketsji/KX_BulletPhysicsController.h
+++ b/source/gameengine/Ketsji/KX_BulletPhysicsController.h
@@ -7,6 +7,11 @@
class KX_BulletPhysicsController : public KX_IPhysicsController ,public CcdPhysicsController
{
+private:
+ int m_savedCollisionFlags;
+ short int m_savedCollisionFilterGroup;
+ short int m_savedCollisionFilterMask;
+ MT_Scalar m_savedMass;
public:
@@ -25,11 +30,12 @@ public:
virtual void ApplyTorque(const MT_Vector3& torque,bool local);
virtual void ApplyForce(const MT_Vector3& force,bool local);
virtual MT_Vector3 GetLinearVelocity();
+ virtual MT_Vector3 GetAngularVelocity();
virtual MT_Vector3 GetVelocity(const MT_Point3& pos);
virtual void SetAngularVelocity(const MT_Vector3& ang_vel,bool local);
virtual void SetLinearVelocity(const MT_Vector3& lin_vel,bool local);
virtual void getOrientation(MT_Quaternion& orn);
- virtual void setOrientation(const MT_Quaternion& orn);
+ virtual void setOrientation(const MT_Matrix3x3& orn);
virtual void setPosition(const MT_Point3& pos);
virtual void setScaling(const MT_Vector3& scaling);
virtual MT_Scalar GetMass();
@@ -38,14 +44,12 @@ public:
virtual void resolveCombinedVelocities(float linvelX,float linvelY,float linvelZ,float angVelX,float angVelY,float angVelZ);
- virtual void SuspendDynamics();
+ virtual void SuspendDynamics(bool ghost);
virtual void RestoreDynamics();
virtual SG_Controller* GetReplica(class SG_Node* destnode);
- void SetDyna(bool isDynamic) {
- m_bDyna = isDynamic;
- }
+ virtual MT_Scalar GetRadius();
virtual void SetSumoTransform(bool nondynaonly);
diff --git a/source/gameengine/Ketsji/KX_Camera.cpp b/source/gameengine/Ketsji/KX_Camera.cpp
index 86dbd06871f..53b3e348a36 100644
--- a/source/gameengine/Ketsji/KX_Camera.cpp
+++ b/source/gameengine/Ketsji/KX_Camera.cpp
@@ -29,7 +29,8 @@
*/
#include "KX_Camera.h"
-
+#include "KX_Scene.h"
+#include "KX_PythonInit.h"
#include "KX_Python.h"
#include "KX_PyMath.h"
#ifdef HAVE_CONFIG_H
@@ -54,7 +55,9 @@ KX_Camera::KX_Camera(void* sgReplicationInfo,
m_name = "cam";
m_projection_matrix.setIdentity();
m_modelview_matrix.setIdentity();
- SetProperty("camera",new CIntValue(1));
+ CValue* val = new CIntValue(1);
+ SetProperty("camera",val);
+ val->Release();
}
@@ -63,7 +66,22 @@ KX_Camera::~KX_Camera()
}
+CValue* KX_Camera::GetReplica()
+{
+ KX_Camera* replica = new KX_Camera(*this);
+
+ // this will copy properties and so on...
+ CValue::AddDataToReplica(replica);
+ ProcessReplica(replica);
+
+ return replica;
+}
+void KX_Camera::ProcessReplica(KX_Camera* replica)
+{
+ KX_GameObject::ProcessReplica(replica);
+}
+
MT_Transform KX_Camera::GetWorldToCamera() const
{
MT_Transform camtrans;
@@ -186,6 +204,11 @@ float KX_Camera::GetCameraFar() const
return m_camdata.m_clipend;
}
+float KX_Camera::GetFocalLength() const
+{
+ return m_camdata.m_focallength;
+}
+
RAS_CameraData* KX_Camera::GetCameraData()
@@ -388,6 +411,7 @@ PyMethodDef KX_Camera::Methods[] = {
KX_PYMETHODTABLE(KX_Camera, setProjectionMatrix),
KX_PYMETHODTABLE(KX_Camera, enableViewport),
KX_PYMETHODTABLE(KX_Camera, setViewport),
+ KX_PYMETHODTABLE(KX_Camera, setOnTop),
{NULL,NULL} //Sentinel
};
@@ -564,7 +588,7 @@ KX_PYMETHODDEF_DOC(KX_Camera, sphereInsideFrustum,
PyErr_SetString(PyExc_TypeError, "sphereInsideFrustum: Expected arguments: (center, radius)");
- Py_Return;
+ return NULL;
}
KX_PYMETHODDEF_DOC(KX_Camera, boxInsideFrustum,
@@ -742,6 +766,10 @@ KX_PYMETHODDEF_DOC(KX_Camera, enableViewport,
else
EnableViewport(false);
}
+ else {
+ return NULL;
+ }
+
Py_Return;
}
@@ -753,6 +781,20 @@ KX_PYMETHODDEF_DOC(KX_Camera, setViewport,
if (PyArg_ParseTuple(args,"iiii",&left, &bottom, &right, &top))
{
SetViewport(left, bottom, right, top);
+ } else {
+ return NULL;
}
Py_Return;
}
+
+KX_PYMETHODDEF_DOC(KX_Camera, setOnTop,
+"setOnTop()\n"
+"Sets this camera's viewport on top\n")
+{
+ class KX_Scene* scene;
+
+ scene = KX_GetActiveScene();
+ MT_assert(scene);
+ scene->SetCameraOnTop(this);
+ Py_Return;
+}
diff --git a/source/gameengine/Ketsji/KX_Camera.h b/source/gameengine/Ketsji/KX_Camera.h
index a276397c9c3..75d574cd697 100644
--- a/source/gameengine/Ketsji/KX_Camera.h
+++ b/source/gameengine/Ketsji/KX_Camera.h
@@ -131,6 +131,24 @@ public:
KX_Camera(void* sgReplicationInfo,SG_Callbacks callbacks,const RAS_CameraData& camdata, bool frustum_culling = true, PyTypeObject *T = &Type);
virtual ~KX_Camera();
+ /**
+ * Inherited from CValue -- return a new copy of this
+ * instance allocated on the heap. Ownership of the new
+ * object belongs with the caller.
+ */
+ virtual CValue*
+ GetReplica(
+ );
+
+ /**
+ * Inherited from CValue -- Makes sure any internal
+ * data owned by this class is deep copied. Called internally
+ */
+ virtual void
+ ProcessReplica(
+ KX_Camera* replica
+ );
+
MT_Transform GetWorldToCamera() const;
MT_Transform GetCameraToWorld() const;
@@ -166,12 +184,14 @@ public:
*/
const MT_Matrix4x4& GetModelviewMatrix() const;
- /** Gets the focal length. */
+ /** Gets the aperture. */
float GetLens() const;
/** Gets the near clip distance. */
float GetCameraNear() const;
/** Gets the far clip distance. */
float GetCameraFar() const;
+ /** Gets the focal length (only used for stereo rendering) */
+ float GetFocalLength() const;
/** Gets all camera data. */
RAS_CameraData* GetCameraData();
@@ -248,6 +268,7 @@ public:
KX_PYMETHOD_DOC(KX_Camera, enableViewport);
KX_PYMETHOD_DOC(KX_Camera, setViewport);
+ KX_PYMETHOD_DOC(KX_Camera, setOnTop);
virtual PyObject* _getattr(const STR_String& attr); /* lens, near, far, projection_matrix */
virtual int _setattr(const STR_String& attr, PyObject *pyvalue);
diff --git a/source/gameengine/Ketsji/KX_CameraActuator.cpp b/source/gameengine/Ketsji/KX_CameraActuator.cpp
index cb3180cb05e..4d24e83843e 100644
--- a/source/gameengine/Ketsji/KX_CameraActuator.cpp
+++ b/source/gameengine/Ketsji/KX_CameraActuator.cpp
@@ -35,6 +35,8 @@
#include <math.h>
#include "KX_GameObject.h"
+#include "PyObjectPlus.h"
+
STR_String KX_CameraActuator::X_AXIS_STRING = "x";
STR_String KX_CameraActuator::Y_AXIS_STRING = "y";
@@ -49,7 +51,7 @@ STR_String KX_CameraActuator::Y_AXIS_STRING = "y";
KX_CameraActuator::KX_CameraActuator(
SCA_IObject* gameobj,
- CValue *obj,
+ SCA_IObject *obj,
MT_Scalar hght,
MT_Scalar minhght,
MT_Scalar maxhght,
@@ -63,11 +65,14 @@ KX_CameraActuator::KX_CameraActuator(
m_maxHeight (maxhght),
m_x (xytog)
{
+ if (m_ob)
+ m_ob->RegisterActuator(this);
}
KX_CameraActuator::~KX_CameraActuator()
{
- //nothing to do
+ if (m_ob)
+ m_ob->UnregisterActuator(this);
}
CValue*
@@ -81,8 +86,35 @@ GetReplica(
return replica;
};
+void KX_CameraActuator::ProcessReplica()
+{
+ if (m_ob)
+ m_ob->RegisterActuator(this);
+ SCA_IActuator::ProcessReplica();
+}
+
+bool KX_CameraActuator::UnlinkObject(SCA_IObject* clientobj)
+{
+ if (clientobj == m_ob)
+ {
+ // this object is being deleted, we cannot continue to track it.
+ m_ob = NULL;
+ return true;
+ }
+ return false;
+}
+void KX_CameraActuator::Relink(GEN_Map<GEN_HashedPtr, void*> *obj_map)
+{
+ void **h_obj = (*obj_map)[m_ob];
+ if (h_obj) {
+ if (m_ob)
+ m_ob->UnregisterActuator(this);
+ m_ob = (SCA_IObject*)(*h_obj);
+ m_ob->RegisterActuator(this);
+ }
+}
/* three functions copied from blender arith... don't know if there's an equivalent */
@@ -155,14 +187,25 @@ static void Kx_VecUpMat3(float *vec, float mat[][3], short axis)
mat[coz][0]= vec[0];
mat[coz][1]= vec[1];
mat[coz][2]= vec[2];
- Kx_Normalize((float *)mat[coz]);
+ if (Kx_Normalize((float *)mat[coz]) == 0.f) {
+ /* this is a very abnormal situation: the camera has reach the object center exactly
+ We will choose a completely arbitrary direction */
+ mat[coz][0] = 1.0f;
+ mat[coz][1] = 0.0f;
+ mat[coz][2] = 0.0f;
+ }
inp= mat[coz][2];
mat[coy][0]= - inp*mat[coz][0];
mat[coy][1]= - inp*mat[coz][1];
mat[coy][2]= 1.0 - inp*mat[coz][2];
- Kx_Normalize((float *)mat[coy]);
+ if (Kx_Normalize((float *)mat[coy]) == 0.f) {
+ /* the camera is vertical, chose the y axis arbitrary */
+ mat[coy][0] = 0.f;
+ mat[coy][1] = 1.f;
+ mat[coy][2] = 0.f;
+ }
Kx_Crossf(mat[cox], mat[coy], mat[coz]);
@@ -170,8 +213,14 @@ static void Kx_VecUpMat3(float *vec, float mat[][3], short axis)
bool KX_CameraActuator::Update(double curtime, bool frame)
{
- bool result = true;
+ /* wondering... is it really neccesary/desirable to suppress negative */
+ /* events here? */
+ bool bNegativeEvent = IsNegativeEvent();
+ RemoveAllEvents();
+ if (bNegativeEvent || !m_ob)
+ return false;
+
KX_GameObject *obj = (KX_GameObject*) GetParent();
MT_Point3 from = obj->NodeGetWorldPosition();
MT_Matrix3x3 frommat = obj->NodeGetWorldOrientation();
@@ -184,13 +233,6 @@ bool KX_CameraActuator::Update(double curtime, bool frame)
float mindistsq, maxdistsq, distsq;
float mat[3][3];
- /* wondering... is it really neccesary/desirable to suppress negative */
- /* events here? */
- bool bNegativeEvent = IsNegativeEvent();
- RemoveAllEvents();
-
- if (bNegativeEvent) return false;
-
/* The rules: */
/* CONSTRAINT 1: not implemented */
/* CONSTRAINT 2: can camera see actor? */
@@ -304,7 +346,7 @@ bool KX_CameraActuator::Update(double curtime, bool frame)
actormat[2][0]= mat[0][2]; actormat[2][1]= mat[1][2]; actormat[2][2]= mat[2][2];
obj->NodeSetLocalOrientation(actormat);
- return result;
+ return true;
}
CValue *KX_CameraActuator::findObject(char *obName)
@@ -355,16 +397,16 @@ PyParentObject KX_CameraActuator::Parents[] = {
};
PyMethodDef KX_CameraActuator::Methods[] = {
- {"setObject",(PyCFunction) KX_CameraActuator::sPySetObject, METH_VARARGS, SetObject_doc},
- {"getObject",(PyCFunction) KX_CameraActuator::sPyGetObject, METH_NOARGS, GetObject_doc},
- {"setMin" ,(PyCFunction) KX_CameraActuator::sPySetMin, METH_VARARGS, SetMin_doc},
- {"getMin" ,(PyCFunction) KX_CameraActuator::sPyGetMin, METH_NOARGS, GetMin_doc},
- {"setMax" ,(PyCFunction) KX_CameraActuator::sPySetMax, METH_VARARGS, SetMax_doc},
- {"getMax" ,(PyCFunction) KX_CameraActuator::sPyGetMax, METH_NOARGS, GetMax_doc},
- {"setHeight",(PyCFunction) KX_CameraActuator::sPySetHeight, METH_VARARGS, SetHeight_doc},
- {"getHeight",(PyCFunction) KX_CameraActuator::sPyGetHeight, METH_NOARGS, GetHeight_doc},
- {"setXY" ,(PyCFunction) KX_CameraActuator::sPySetXY, METH_VARARGS, SetXY_doc},
- {"getXY" ,(PyCFunction) KX_CameraActuator::sPyGetXY, METH_VARARGS, GetXY_doc},
+ {"setObject",(PyCFunction) KX_CameraActuator::sPySetObject, METH_O, (PY_METHODCHAR)SetObject_doc},
+ {"getObject",(PyCFunction) KX_CameraActuator::sPyGetObject, METH_VARARGS, (PY_METHODCHAR)GetObject_doc},
+ {"setMin" ,(PyCFunction) KX_CameraActuator::sPySetMin, METH_VARARGS, (PY_METHODCHAR)SetMin_doc},
+ {"getMin" ,(PyCFunction) KX_CameraActuator::sPyGetMin, METH_NOARGS, (PY_METHODCHAR)GetMin_doc},
+ {"setMax" ,(PyCFunction) KX_CameraActuator::sPySetMax, METH_VARARGS, (PY_METHODCHAR)SetMax_doc},
+ {"getMax" ,(PyCFunction) KX_CameraActuator::sPyGetMax, METH_NOARGS, (PY_METHODCHAR)GetMax_doc},
+ {"setHeight",(PyCFunction) KX_CameraActuator::sPySetHeight, METH_VARARGS, (PY_METHODCHAR)SetHeight_doc},
+ {"getHeight",(PyCFunction) KX_CameraActuator::sPyGetHeight, METH_NOARGS, (PY_METHODCHAR)GetHeight_doc},
+ {"setXY" ,(PyCFunction) KX_CameraActuator::sPySetXY, METH_VARARGS, (PY_METHODCHAR)SetXY_doc},
+ {"getXY" ,(PyCFunction) KX_CameraActuator::sPyGetXY, METH_VARARGS, (PY_METHODCHAR)GetXY_doc},
{NULL,NULL,NULL,NULL} //Sentinel
};
@@ -372,48 +414,48 @@ PyObject* KX_CameraActuator::_getattr(const STR_String& attr) {
_getattr_up(SCA_IActuator);
}
/* get obj ---------------------------------------------------------- */
-char KX_CameraActuator::GetObject_doc[] =
-"getObject\n"
+const char KX_CameraActuator::GetObject_doc[] =
+"getObject(name_only = 1)\n"
+"name_only - optional arg, when true will return the KX_GameObject rather then its name\n"
"\tReturns the object this sensor reacts to.\n";
-PyObject* KX_CameraActuator::PyGetObject(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_CameraActuator::PyGetObject(PyObject* self, PyObject* args)
{
- return PyString_FromString(m_ob->GetName());
+ int ret_name_only = 1;
+ if (!PyArg_ParseTuple(args, "|i", &ret_name_only))
+ return NULL;
+
+ if (!m_ob)
+ Py_RETURN_NONE;
+
+ if (ret_name_only)
+ return PyString_FromString(m_ob->GetName());
+ else
+ return m_ob->AddRef();
}
/* set obj ---------------------------------------------------------- */
-char KX_CameraActuator::SetObject_doc[] =
-"setObject\n"
+const char KX_CameraActuator::SetObject_doc[] =
+"setObject(object)\n"
+"\t- object: KX_GameObject, string or None\n"
"\tSets the object this sensor reacts to.\n";
-PyObject* KX_CameraActuator::PySetObject(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_CameraActuator::PySetObject(PyObject* self, PyObject* value)
{
-
- PyObject* gameobj;
- if (PyArg_ParseTuple(args, "O!", &KX_GameObject::Type, &gameobj))
- {
- m_ob = (CValue*)gameobj;
- Py_Return;
- }
- PyErr_Clear();
+ KX_GameObject *gameobj;
- char* objectname;
- if (PyArg_ParseTuple(args, "s", &objectname))
- {
- CValue *object = (CValue*)SCA_ILogicBrick::m_sCurrentLogicManager->GetGameObjectByName(STR_String(objectname));
- if(object)
- {
- m_ob = object;
- Py_Return;
- }
- }
+ if (!ConvertPythonToGameObject(value, &gameobj, true))
+ return NULL; // ConvertPythonToGameObject sets the error
- return NULL;
+ if (m_ob != NULL)
+ m_ob->UnregisterActuator(this);
+
+ m_ob = (SCA_IObject*)gameobj;
+ if (m_ob)
+ m_ob->RegisterActuator(this);
+
+ Py_RETURN_NONE;
}
/* get min ---------------------------------------------------------- */
-char KX_CameraActuator::GetMin_doc[] =
+const char KX_CameraActuator::GetMin_doc[] =
"getMin\n"
"\tReturns the minimum value set in the Min: field.\n";
PyObject* KX_CameraActuator::PyGetMin(PyObject* self,
@@ -423,7 +465,7 @@ PyObject* KX_CameraActuator::PyGetMin(PyObject* self,
return PyFloat_FromDouble(m_minHeight);
}
/* set min ---------------------------------------------------------- */
-char KX_CameraActuator::SetMin_doc[] =
+const char KX_CameraActuator::SetMin_doc[] =
"setMin\n"
"\tSets the minimum value.\n";
PyObject* KX_CameraActuator::PySetMin(PyObject* self,
@@ -439,7 +481,7 @@ PyObject* KX_CameraActuator::PySetMin(PyObject* self,
return NULL;
}
/* get min ---------------------------------------------------------- */
-char KX_CameraActuator::GetMax_doc[] =
+const char KX_CameraActuator::GetMax_doc[] =
"getMax\n"
"\tReturns the maximum value set in the Max: field.\n";
PyObject* KX_CameraActuator::PyGetMax(PyObject* self,
@@ -449,7 +491,7 @@ PyObject* KX_CameraActuator::PyGetMax(PyObject* self,
return PyFloat_FromDouble(m_maxHeight);
}
/* set min ---------------------------------------------------------- */
-char KX_CameraActuator::SetMax_doc[] =
+const char KX_CameraActuator::SetMax_doc[] =
"setMax\n"
"\tSets the maximum value.\n";
PyObject* KX_CameraActuator::PySetMax(PyObject* self,
@@ -465,7 +507,7 @@ PyObject* KX_CameraActuator::PySetMax(PyObject* self,
return NULL;
}
/* get height ---------------------------------------------------------- */
-char KX_CameraActuator::GetHeight_doc[] =
+const char KX_CameraActuator::GetHeight_doc[] =
"getHeight\n"
"\tReturns the height value set in the height: field.\n";
PyObject* KX_CameraActuator::PyGetHeight(PyObject* self,
@@ -475,7 +517,7 @@ PyObject* KX_CameraActuator::PyGetHeight(PyObject* self,
return PyFloat_FromDouble(m_height);
}
/* set height ---------------------------------------------------------- */
-char KX_CameraActuator::SetHeight_doc[] =
+const char KX_CameraActuator::SetHeight_doc[] =
"setHeight\n"
"\tSets the height value.\n";
PyObject* KX_CameraActuator::PySetHeight(PyObject* self,
@@ -491,7 +533,7 @@ PyObject* KX_CameraActuator::PySetHeight(PyObject* self,
return NULL;
}
/* set XY ---------------------------------------------------------- */
-char KX_CameraActuator::SetXY_doc[] =
+const char KX_CameraActuator::SetXY_doc[] =
"setXY\n"
"\tSets axis the camera tries to get behind.\n"
"\t1=x, 0=y\n";
@@ -509,7 +551,7 @@ PyObject* KX_CameraActuator::PySetXY(PyObject* self,
}
/* get XY -------------------------------------------------------------*/
-char KX_CameraActuator::GetXY_doc[] =
+const char KX_CameraActuator::GetXY_doc[] =
"getXY\n"
"\tGets the axis the camera tries to get behind.\n"
"\tTrue = X, False = Y\n";
diff --git a/source/gameengine/Ketsji/KX_CameraActuator.h b/source/gameengine/Ketsji/KX_CameraActuator.h
index eb007e403ec..d53d12b3b82 100644
--- a/source/gameengine/Ketsji/KX_CameraActuator.h
+++ b/source/gameengine/Ketsji/KX_CameraActuator.h
@@ -49,7 +49,7 @@ class KX_CameraActuator : public SCA_IActuator
Py_Header;
private :
/** Object that will be tracked. */
- CValue *m_ob;
+ SCA_IObject *m_ob;
/** height (float), */
//const MT_Scalar m_height;
@@ -87,7 +87,7 @@ private :
SCA_IObject *gameobj,
//const CValue *ob,
- CValue *ob,
+ SCA_IObject *ob,
MT_Scalar hght,
MT_Scalar minhght,
MT_Scalar maxhght,
@@ -103,6 +103,7 @@ private :
/** Methods Inherited from CValue */
CValue* GetReplica();
+ virtual void ProcessReplica();
/** Methods inherited from SCA_IActuator */
@@ -110,7 +111,10 @@ private :
double curtime,
bool frame
);
+ virtual bool UnlinkObject(SCA_IObject* clientobj);
+ /** Methods inherited from SCA_ILogicBrick */
+ virtual void Relink(GEN_Map<GEN_HashedPtr, void*> *obj_map);
/* --------------------------------------------------------------------- */
/* Python interface ---------------------------------------------------- */
@@ -119,9 +123,9 @@ private :
virtual PyObject* _getattr(const STR_String& attr);
/* set object to look at */
- KX_PYMETHOD_DOC(KX_CameraActuator,SetObject);
+ KX_PYMETHOD_DOC_O(KX_CameraActuator,SetObject);
/* get current object */
- KX_PYMETHOD_DOC(KX_CameraActuator,GetObject);
+ KX_PYMETHOD_DOC_VARARGS(KX_CameraActuator,GetObject);
KX_PYMETHOD_DOC(KX_CameraActuator,SetMin);
KX_PYMETHOD_DOC(KX_CameraActuator,GetMin);
KX_PYMETHOD_DOC(KX_CameraActuator,SetMax);
diff --git a/source/gameengine/Ketsji/KX_ConstraintActuator.cpp b/source/gameengine/Ketsji/KX_ConstraintActuator.cpp
index bd843d97199..76357e9c58f 100644
--- a/source/gameengine/Ketsji/KX_ConstraintActuator.cpp
+++ b/source/gameengine/Ketsji/KX_ConstraintActuator.cpp
@@ -35,6 +35,7 @@
#include "MT_Point3.h"
#include "MT_Matrix3x3.h"
#include "KX_GameObject.h"
+#include "KX_RayCast.h"
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -45,35 +46,60 @@
/* ------------------------------------------------------------------------- */
KX_ConstraintActuator::KX_ConstraintActuator(SCA_IObject *gameobj,
- int dampTime,
+ int posDampTime,
+ int rotDampTime,
float minBound,
float maxBound,
+ float refDir[3],
int locrotxyz,
- PyTypeObject* T)
- : SCA_IActuator(gameobj, T)
+ int time,
+ int option,
+ char *property,
+ PyTypeObject* T) :
+ m_refDirection(refDir),
+ m_currentTime(0),
+ SCA_IActuator(gameobj, T)
{
- m_dampTime = dampTime;
+ m_posDampTime = posDampTime;
+ m_rotDampTime = rotDampTime;
m_locrot = locrotxyz;
+ m_option = option;
+ m_activeTime = time;
+ if (property) {
+ strncpy(m_property, property, sizeof(m_property));
+ m_property[sizeof(m_property)-1] = 0;
+ } else {
+ m_property[0] = 0;
+ }
/* The units of bounds are determined by the type of constraint. To */
/* make the constraint application easier and more transparent later on, */
/* I think converting the bounds to the applicable domain makes more */
/* sense. */
switch (m_locrot) {
- case KX_ACT_CONSTRAINT_LOCX:
- case KX_ACT_CONSTRAINT_LOCY:
- case KX_ACT_CONSTRAINT_LOCZ:
+ case KX_ACT_CONSTRAINT_ORIX:
+ case KX_ACT_CONSTRAINT_ORIY:
+ case KX_ACT_CONSTRAINT_ORIZ:
+ {
+ MT_Scalar len = m_refDirection.length();
+ if (MT_fuzzyZero(len)) {
+ // missing a valid direction
+ std::cout << "WARNING: Constraint actuator " << GetName() << ": There is no valid reference direction!" << std::endl;
+ m_locrot = KX_ACT_CONSTRAINT_NODEF;
+ } else {
+ m_refDirection /= len;
+ }
+ m_minimumBound = cos(minBound);
+ m_maximumBound = cos(maxBound);
+ m_minimumSine = sin(minBound);
+ m_maximumSine = sin(maxBound);
+ }
+ break;
+ default:
m_minimumBound = minBound;
m_maximumBound = maxBound;
+ m_minimumSine = 0.f;
+ m_maximumSine = 0.f;
break;
- case KX_ACT_CONSTRAINT_ROTX:
- case KX_ACT_CONSTRAINT_ROTY:
- case KX_ACT_CONSTRAINT_ROTZ:
- /* The user interface asks for degrees, we are radian. */
- m_minimumBound = MT_radians(minBound);
- m_maximumBound = MT_radians(maxBound);
- break;
- default:
- ; /* error */
}
} /* End of constructor */
@@ -83,77 +109,426 @@ KX_ConstraintActuator::~KX_ConstraintActuator()
// there's nothing to be done here, really....
} /* end of destructor */
-bool KX_ConstraintActuator::Update(double curtime, bool frame)
+bool KX_ConstraintActuator::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data)
{
- bool result = false;
- bool bNegativeEvent = IsNegativeEvent();
- RemoveAllEvents();
-
- if (bNegativeEvent)
- return false; // do nothing on negative events
-
- /* Constraint clamps the values to the specified range, with a sort of */
- /* low-pass filtered time response, if the damp time is unequal to 0. */
-
- /* Having to retrieve location/rotation and setting it afterwards may not */
- /* be efficient enough... Somthing to look at later. */
- KX_GameObject *parent = (KX_GameObject*) GetParent();
- MT_Point3 position = parent->NodeGetWorldPosition();
- MT_Matrix3x3 rotation = parent->NodeGetWorldOrientation();
-// MT_Vector3 eulerrot = rotation.getEuler();
-
- switch (m_locrot) {
- case KX_ACT_CONSTRAINT_LOCX:
- Clamp(position[0], m_minimumBound, m_maximumBound);
- result = true;
- break;
- case KX_ACT_CONSTRAINT_LOCY:
- Clamp(position[1], m_minimumBound, m_maximumBound);
- result = true;
- break;
- case KX_ACT_CONSTRAINT_LOCZ:
- Clamp(position[2], m_minimumBound, m_maximumBound);
- result = true;
- break;
+ m_hitObject = client->m_gameobject;
-// case KX_ACT_CONSTRAINT_ROTX:
-// /* The angles are Euler angles (I think that's what they are called) */
-// /* but we need to convert from/to the MT_Matrix3x3. */
-// Clamp(eulerrot[0], m_minimumBound, m_maximumBound);
-// break;
-// case KX_ACT_CONSTRAINT_ROTY:
-// Clamp(eulerrot[1], m_minimumBound, m_maximumBound);
-// break;
-// case KX_ACT_CONSTRAINT_ROTZ:
-// Clamp(eulerrot[2], m_minimumBound, m_maximumBound);
-// break;
-// default:
-// ; /* error */
- }
+ bool bFound = false;
- /* Will be replaced by a filtered clamp. */
-
+ if (m_property[0] == 0)
+ {
+ bFound = true;
+ }
+ else
+ {
+ if (m_option & KX_ACT_CONSTRAINT_MATERIAL)
+ {
+ if (client->m_auxilary_info)
+ {
+ bFound = !strcmp(m_property, ((char*)client->m_auxilary_info));
+ }
+ }
+ else
+ {
+ bFound = m_hitObject->GetProperty(m_property) != NULL;
+ }
+ }
+ // update the hit status
+ result->m_hitFound = bFound;
+ // stop looking
+ return true;
+}
- switch (m_locrot) {
- case KX_ACT_CONSTRAINT_LOCX:
- case KX_ACT_CONSTRAINT_LOCY:
- case KX_ACT_CONSTRAINT_LOCZ:
- parent->NodeSetLocalPosition(position);
- break;
+/* this function is used to pre-filter the object before casting the ray on them.
+ This is useful for "X-Ray" option when we want to see "through" unwanted object.
+ */
+bool KX_ConstraintActuator::NeedRayCast(KX_ClientObjectInfo* client)
+{
+ if (client->m_type > KX_ClientObjectInfo::ACTOR)
+ {
+ // Unknown type of object, skip it.
+ // Should not occur as the sensor objects are filtered in RayTest()
+ printf("Invalid client type %d found in ray casting\n", client->m_type);
+ return false;
+ }
+ // no X-Ray function yet
+ return true;
+}
+bool KX_ConstraintActuator::Update(double curtime, bool frame)
+{
-// case KX_ACT_CONSTRAINT_ROTX:
-// case KX_ACT_CONSTRAINT_ROTY:
-// case KX_ACT_CONSTRAINT_ROTZ:
-// rotation.setEuler(eulerrot);
-// parent->NodeSetLocalOrientation(rotation);
- break;
+ bool result = false;
+ bool bNegativeEvent = IsNegativeEvent();
+ RemoveAllEvents();
- default:
- ; /* error */
+ if (!bNegativeEvent) {
+ /* Constraint clamps the values to the specified range, with a sort of */
+ /* low-pass filtered time response, if the damp time is unequal to 0. */
+
+ /* Having to retrieve location/rotation and setting it afterwards may not */
+ /* be efficient enough... Somthing to look at later. */
+ KX_GameObject *obj = (KX_GameObject*) GetParent();
+ MT_Point3 position = obj->NodeGetWorldPosition();
+ MT_Point3 newposition;
+ MT_Vector3 normal, direction, refDirection;
+ MT_Matrix3x3 rotation = obj->NodeGetWorldOrientation();
+ MT_Scalar filter, newdistance, cosangle;
+ int axis, sign;
+
+ if (m_posDampTime) {
+ filter = m_posDampTime/(1.0+m_posDampTime);
+ } else {
+ filter = 0.0;
+ }
+ switch (m_locrot) {
+ case KX_ACT_CONSTRAINT_ORIX:
+ case KX_ACT_CONSTRAINT_ORIY:
+ case KX_ACT_CONSTRAINT_ORIZ:
+ switch (m_locrot) {
+ case KX_ACT_CONSTRAINT_ORIX:
+ direction[0] = rotation[0][0];
+ direction[1] = rotation[1][0];
+ direction[2] = rotation[2][0];
+ axis = 0;
+ break;
+ case KX_ACT_CONSTRAINT_ORIY:
+ direction[0] = rotation[0][1];
+ direction[1] = rotation[1][1];
+ direction[2] = rotation[2][1];
+ axis = 1;
+ break;
+ default:
+ direction[0] = rotation[0][2];
+ direction[1] = rotation[1][2];
+ direction[2] = rotation[2][2];
+ axis = 2;
+ break;
+ }
+ if ((m_maximumBound < (1.0f-FLT_EPSILON)) || (m_minimumBound < (1.0f-FLT_EPSILON))) {
+ // reference direction needs to be evaluated
+ // 1. get the cosine between current direction and target
+ cosangle = direction.dot(m_refDirection);
+ if (cosangle >= (m_maximumBound-FLT_EPSILON) && cosangle <= (m_minimumBound+FLT_EPSILON)) {
+ // no change to do
+ result = true;
+ goto CHECK_TIME;
+ }
+ // 2. define a new reference direction
+ // compute local axis with reference direction as X and
+ // Y in direction X refDirection plane
+ MT_Vector3 zaxis = m_refDirection.cross(direction);
+ if (MT_fuzzyZero2(zaxis.length2())) {
+ // direction and refDirection are identical,
+ // choose any other direction to define plane
+ if (direction[0] < 0.9999)
+ zaxis = m_refDirection.cross(MT_Vector3(1.0,0.0,0.0));
+ else
+ zaxis = m_refDirection.cross(MT_Vector3(0.0,1.0,0.0));
+ }
+ MT_Vector3 yaxis = zaxis.cross(m_refDirection);
+ yaxis.normalize();
+ if (cosangle > m_minimumBound) {
+ // angle is too close to reference direction,
+ // choose a new reference that is exactly at minimum angle
+ refDirection = m_minimumBound * m_refDirection + m_minimumSine * yaxis;
+ } else {
+ // angle is too large, choose new reference direction at maximum angle
+ refDirection = m_maximumBound * m_refDirection + m_maximumSine * yaxis;
+ }
+ } else {
+ refDirection = m_refDirection;
+ }
+ // apply damping on the direction
+ direction = filter*direction + (1.0-filter)*refDirection;
+ obj->AlignAxisToVect(direction, axis);
+ result = true;
+ goto CHECK_TIME;
+ case KX_ACT_CONSTRAINT_DIRPX:
+ case KX_ACT_CONSTRAINT_DIRPY:
+ case KX_ACT_CONSTRAINT_DIRPZ:
+ case KX_ACT_CONSTRAINT_DIRNX:
+ case KX_ACT_CONSTRAINT_DIRNY:
+ case KX_ACT_CONSTRAINT_DIRNZ:
+ switch (m_locrot) {
+ case KX_ACT_CONSTRAINT_DIRPX:
+ normal[0] = rotation[0][0];
+ normal[1] = rotation[1][0];
+ normal[2] = rotation[2][0];
+ axis = 0; // axis according to KX_GameObject::AlignAxisToVect()
+ sign = 0; // X axis will be parrallel to direction of ray
+ break;
+ case KX_ACT_CONSTRAINT_DIRPY:
+ normal[0] = rotation[0][1];
+ normal[1] = rotation[1][1];
+ normal[2] = rotation[2][1];
+ axis = 1;
+ sign = 0;
+ break;
+ case KX_ACT_CONSTRAINT_DIRPZ:
+ normal[0] = rotation[0][2];
+ normal[1] = rotation[1][2];
+ normal[2] = rotation[2][2];
+ axis = 2;
+ sign = 0;
+ break;
+ case KX_ACT_CONSTRAINT_DIRNX:
+ normal[0] = -rotation[0][0];
+ normal[1] = -rotation[1][0];
+ normal[2] = -rotation[2][0];
+ axis = 0;
+ sign = 1;
+ break;
+ case KX_ACT_CONSTRAINT_DIRNY:
+ normal[0] = -rotation[0][1];
+ normal[1] = -rotation[1][1];
+ normal[2] = -rotation[2][1];
+ axis = 1;
+ sign = 1;
+ break;
+ case KX_ACT_CONSTRAINT_DIRNZ:
+ normal[0] = -rotation[0][2];
+ normal[1] = -rotation[1][2];
+ normal[2] = -rotation[2][2];
+ axis = 2;
+ sign = 1;
+ break;
+ }
+ normal.normalize();
+ if (m_option & KX_ACT_CONSTRAINT_LOCAL) {
+ // direction of the ray is along the local axis
+ direction = normal;
+ } else {
+ switch (m_locrot) {
+ case KX_ACT_CONSTRAINT_DIRPX:
+ direction = MT_Vector3(1.0,0.0,0.0);
+ break;
+ case KX_ACT_CONSTRAINT_DIRPY:
+ direction = MT_Vector3(0.0,1.0,0.0);
+ break;
+ case KX_ACT_CONSTRAINT_DIRPZ:
+ direction = MT_Vector3(0.0,0.0,1.0);
+ break;
+ case KX_ACT_CONSTRAINT_DIRNX:
+ direction = MT_Vector3(-1.0,0.0,0.0);
+ break;
+ case KX_ACT_CONSTRAINT_DIRNY:
+ direction = MT_Vector3(0.0,-1.0,0.0);
+ break;
+ case KX_ACT_CONSTRAINT_DIRNZ:
+ direction = MT_Vector3(0.0,0.0,-1.0);
+ break;
+ }
+ }
+ {
+ MT_Point3 topoint = position + (m_maximumBound) * direction;
+ PHY_IPhysicsEnvironment* pe = obj->GetPhysicsEnvironment();
+ KX_IPhysicsController *spc = obj->GetPhysicsController();
+
+ if (!pe) {
+ std::cout << "WARNING: Constraint actuator " << GetName() << ": There is no physics environment!" << std::endl;
+ goto CHECK_TIME;
+ }
+ if (!spc) {
+ // the object is not physical, we probably want to avoid hitting its own parent
+ KX_GameObject *parent = obj->GetParent();
+ if (parent) {
+ spc = parent->GetPhysicsController();
+ parent->Release();
+ }
+ }
+ KX_RayCast::Callback<KX_ConstraintActuator> callback(this,spc);
+ result = KX_RayCast::RayTest(pe, position, topoint, callback);
+ if (result) {
+ MT_Vector3 newnormal = callback.m_hitNormal;
+ // compute new position & orientation
+ if ((m_option & (KX_ACT_CONSTRAINT_NORMAL|KX_ACT_CONSTRAINT_DISTANCE)) == 0) {
+ // if none option is set, the actuator does nothing but detect ray
+ // (works like a sensor)
+ goto CHECK_TIME;
+ }
+ if (m_option & KX_ACT_CONSTRAINT_NORMAL) {
+ MT_Scalar rotFilter;
+ // apply damping on the direction
+ if (m_rotDampTime) {
+ rotFilter = m_rotDampTime/(1.0+m_rotDampTime);
+ } else {
+ rotFilter = filter;
+ }
+ newnormal = rotFilter*normal - (1.0-rotFilter)*newnormal;
+ obj->AlignAxisToVect((sign)?-newnormal:newnormal, axis);
+ if (m_option & KX_ACT_CONSTRAINT_LOCAL) {
+ direction = newnormal;
+ direction.normalize();
+ }
+ }
+ if (m_option & KX_ACT_CONSTRAINT_DISTANCE) {
+ if (m_posDampTime) {
+ newdistance = filter*(position-callback.m_hitPoint).length()+(1.0-filter)*m_minimumBound;
+ } else {
+ newdistance = m_minimumBound;
+ }
+ // logically we should cancel the speed along the ray direction as we set the
+ // position along that axis
+ spc = obj->GetPhysicsController();
+ if (spc && spc->IsDyna()) {
+ MT_Vector3 linV = spc->GetLinearVelocity();
+ // cancel the projection along the ray direction
+ MT_Scalar fallspeed = linV.dot(direction);
+ if (!MT_fuzzyZero(fallspeed))
+ spc->SetLinearVelocity(linV-fallspeed*direction,false);
+ }
+ } else {
+ newdistance = (position-callback.m_hitPoint).length();
+ }
+ newposition = callback.m_hitPoint-newdistance*direction;
+ } else if (m_option & KX_ACT_CONSTRAINT_PERMANENT) {
+ // no contact but still keep running
+ result = true;
+ goto CHECK_TIME;
+ }
+ }
+ break;
+ case KX_ACT_CONSTRAINT_FHPX:
+ case KX_ACT_CONSTRAINT_FHPY:
+ case KX_ACT_CONSTRAINT_FHPZ:
+ case KX_ACT_CONSTRAINT_FHNX:
+ case KX_ACT_CONSTRAINT_FHNY:
+ case KX_ACT_CONSTRAINT_FHNZ:
+ switch (m_locrot) {
+ case KX_ACT_CONSTRAINT_FHPX:
+ normal[0] = -rotation[0][0];
+ normal[1] = -rotation[1][0];
+ normal[2] = -rotation[2][0];
+ direction = MT_Vector3(1.0,0.0,0.0);
+ break;
+ case KX_ACT_CONSTRAINT_FHPY:
+ normal[0] = -rotation[0][1];
+ normal[1] = -rotation[1][1];
+ normal[2] = -rotation[2][1];
+ direction = MT_Vector3(0.0,1.0,0.0);
+ break;
+ case KX_ACT_CONSTRAINT_FHPZ:
+ normal[0] = -rotation[0][2];
+ normal[1] = -rotation[1][2];
+ normal[2] = -rotation[2][2];
+ direction = MT_Vector3(0.0,0.0,1.0);
+ break;
+ case KX_ACT_CONSTRAINT_FHNX:
+ normal[0] = rotation[0][0];
+ normal[1] = rotation[1][0];
+ normal[2] = rotation[2][0];
+ direction = MT_Vector3(-1.0,0.0,0.0);
+ break;
+ case KX_ACT_CONSTRAINT_FHNY:
+ normal[0] = rotation[0][1];
+ normal[1] = rotation[1][1];
+ normal[2] = rotation[2][1];
+ direction = MT_Vector3(0.0,-1.0,0.0);
+ break;
+ case KX_ACT_CONSTRAINT_FHNZ:
+ normal[0] = rotation[0][2];
+ normal[1] = rotation[1][2];
+ normal[2] = rotation[2][2];
+ direction = MT_Vector3(0.0,0.0,-1.0);
+ break;
+ }
+ normal.normalize();
+ {
+ PHY_IPhysicsEnvironment* pe = obj->GetPhysicsEnvironment();
+ KX_IPhysicsController *spc = obj->GetPhysicsController();
+
+ if (!pe) {
+ std::cout << "WARNING: Constraint actuator " << GetName() << ": There is no physics environment!" << std::endl;
+ goto CHECK_TIME;
+ }
+ if (!spc || !spc->IsDyna()) {
+ // the object is not dynamic, it won't support setting speed
+ goto CHECK_TIME;
+ }
+ m_hitObject = NULL;
+ // distance of Fh area is stored in m_minimum
+ MT_Point3 topoint = position + (m_minimumBound+spc->GetRadius()) * direction;
+ KX_RayCast::Callback<KX_ConstraintActuator> callback(this,spc);
+ result = KX_RayCast::RayTest(pe, position, topoint, callback);
+ // we expect a hit object
+ if (!m_hitObject)
+ result = false;
+ if (result)
+ {
+ MT_Vector3 newnormal = callback.m_hitNormal;
+ // compute new position & orientation
+ MT_Scalar distance = (callback.m_hitPoint-position).length()-spc->GetRadius();
+ // estimate the velocity of the hit point
+ MT_Point3 relativeHitPoint;
+ relativeHitPoint = (callback.m_hitPoint-m_hitObject->NodeGetWorldPosition());
+ MT_Vector3 velocityHitPoint = m_hitObject->GetVelocity(relativeHitPoint);
+ MT_Vector3 relativeVelocity = spc->GetLinearVelocity() - velocityHitPoint;
+ MT_Scalar relativeVelocityRay = direction.dot(relativeVelocity);
+ MT_Scalar springExtent = 1.0 - distance/m_minimumBound;
+ // Fh force is stored in m_maximum
+ MT_Scalar springForce = springExtent * m_maximumBound;
+ // damping is stored in m_refDirection [0] = damping, [1] = rot damping
+ MT_Scalar springDamp = relativeVelocityRay * m_refDirection[0];
+ MT_Vector3 newVelocity = spc->GetLinearVelocity()-(springForce+springDamp)*direction;
+ if (m_option & KX_ACT_CONSTRAINT_NORMAL)
+ {
+ newVelocity+=(springForce+springDamp)*(newnormal-newnormal.dot(direction)*direction);
+ }
+ spc->SetLinearVelocity(newVelocity, false);
+ if (m_option & KX_ACT_CONSTRAINT_DOROTFH)
+ {
+ MT_Vector3 angSpring = (normal.cross(newnormal))*m_maximumBound;
+ MT_Vector3 angVelocity = spc->GetAngularVelocity();
+ // remove component that is parallel to normal
+ angVelocity -= angVelocity.dot(newnormal)*newnormal;
+ MT_Vector3 angDamp = angVelocity * ((m_refDirection[1]>MT_EPSILON)?m_refDirection[1]:m_refDirection[0]);
+ spc->SetAngularVelocity(spc->GetAngularVelocity()+(angSpring-angDamp), false);
+ }
+ } else if (m_option & KX_ACT_CONSTRAINT_PERMANENT) {
+ // no contact but still keep running
+ result = true;
+ }
+ // don't set the position with this constraint
+ goto CHECK_TIME;
+ }
+ break;
+ case KX_ACT_CONSTRAINT_LOCX:
+ case KX_ACT_CONSTRAINT_LOCY:
+ case KX_ACT_CONSTRAINT_LOCZ:
+ newposition = position = obj->GetSGNode()->GetLocalPosition();
+ switch (m_locrot) {
+ case KX_ACT_CONSTRAINT_LOCX:
+ Clamp(newposition[0], m_minimumBound, m_maximumBound);
+ break;
+ case KX_ACT_CONSTRAINT_LOCY:
+ Clamp(newposition[1], m_minimumBound, m_maximumBound);
+ break;
+ case KX_ACT_CONSTRAINT_LOCZ:
+ Clamp(newposition[2], m_minimumBound, m_maximumBound);
+ break;
+ }
+ result = true;
+ if (m_posDampTime) {
+ newposition = filter*position + (1.0-filter)*newposition;
+ }
+ obj->NodeSetLocalPosition(newposition);
+ goto CHECK_TIME;
+ }
+ if (result) {
+ // set the new position but take into account parent if any
+ obj->NodeSetWorldPosition(newposition);
+ }
+ CHECK_TIME:
+ if (result && m_activeTime > 0 ) {
+ if (++m_currentTime >= m_activeTime)
+ result = false;
+ }
+ }
+ if (!result) {
+ m_currentTime = 0;
}
-
return result;
} /* end of KX_ConstraintActuator::Update(double curtime,double deltatime) */
@@ -212,14 +587,28 @@ PyParentObject KX_ConstraintActuator::Parents[] = {
};
PyMethodDef KX_ConstraintActuator::Methods[] = {
- {"setDamp", (PyCFunction) KX_ConstraintActuator::sPySetDamp, METH_VARARGS, SetDamp_doc},
- {"getDamp", (PyCFunction) KX_ConstraintActuator::sPyGetDamp, METH_VARARGS, GetDamp_doc},
- {"setMin", (PyCFunction) KX_ConstraintActuator::sPySetMin, METH_VARARGS, SetMin_doc},
- {"getMin", (PyCFunction) KX_ConstraintActuator::sPyGetMin, METH_VARARGS, GetMin_doc},
- {"setMax", (PyCFunction) KX_ConstraintActuator::sPySetMax, METH_VARARGS, SetMax_doc},
- {"getMax", (PyCFunction) KX_ConstraintActuator::sPyGetMax, METH_VARARGS, GetMax_doc},
- {"setLimit", (PyCFunction) KX_ConstraintActuator::sPySetLimit, METH_VARARGS, SetLimit_doc},
- {"getLimit", (PyCFunction) KX_ConstraintActuator::sPyGetLimit, METH_VARARGS, GetLimit_doc},
+ {"setDamp", (PyCFunction) KX_ConstraintActuator::sPySetDamp, METH_VARARGS, (PY_METHODCHAR)SetDamp_doc},
+ {"getDamp", (PyCFunction) KX_ConstraintActuator::sPyGetDamp, METH_NOARGS, (PY_METHODCHAR)GetDamp_doc},
+ {"setRotDamp", (PyCFunction) KX_ConstraintActuator::sPySetRotDamp, METH_VARARGS, (PY_METHODCHAR)SetRotDamp_doc},
+ {"getRotDamp", (PyCFunction) KX_ConstraintActuator::sPyGetRotDamp, METH_NOARGS, (PY_METHODCHAR)GetRotDamp_doc},
+ {"setDirection", (PyCFunction) KX_ConstraintActuator::sPySetDirection, METH_VARARGS, (PY_METHODCHAR)SetDirection_doc},
+ {"getDirection", (PyCFunction) KX_ConstraintActuator::sPyGetDirection, METH_NOARGS, (PY_METHODCHAR)GetDirection_doc},
+ {"setOption", (PyCFunction) KX_ConstraintActuator::sPySetOption, METH_VARARGS, (PY_METHODCHAR)SetOption_doc},
+ {"getOption", (PyCFunction) KX_ConstraintActuator::sPyGetOption, METH_NOARGS, (PY_METHODCHAR)GetOption_doc},
+ {"setTime", (PyCFunction) KX_ConstraintActuator::sPySetTime, METH_VARARGS, (PY_METHODCHAR)SetTime_doc},
+ {"getTime", (PyCFunction) KX_ConstraintActuator::sPyGetTime, METH_NOARGS, (PY_METHODCHAR)GetTime_doc},
+ {"setProperty", (PyCFunction) KX_ConstraintActuator::sPySetProperty, METH_VARARGS, (PY_METHODCHAR)SetProperty_doc},
+ {"getProperty", (PyCFunction) KX_ConstraintActuator::sPyGetProperty, METH_NOARGS, (PY_METHODCHAR)GetProperty_doc},
+ {"setMin", (PyCFunction) KX_ConstraintActuator::sPySetMin, METH_VARARGS, (PY_METHODCHAR)SetMin_doc},
+ {"getMin", (PyCFunction) KX_ConstraintActuator::sPyGetMin, METH_NOARGS, (PY_METHODCHAR)GetMin_doc},
+ {"setDistance", (PyCFunction) KX_ConstraintActuator::sPySetMin, METH_VARARGS, (PY_METHODCHAR)SetDistance_doc},
+ {"getDistance", (PyCFunction) KX_ConstraintActuator::sPyGetMin, METH_NOARGS, (PY_METHODCHAR)GetDistance_doc},
+ {"setMax", (PyCFunction) KX_ConstraintActuator::sPySetMax, METH_VARARGS, (PY_METHODCHAR)SetMax_doc},
+ {"getMax", (PyCFunction) KX_ConstraintActuator::sPyGetMax, METH_NOARGS, (PY_METHODCHAR)GetMax_doc},
+ {"setRayLength", (PyCFunction) KX_ConstraintActuator::sPySetMax, METH_VARARGS, (PY_METHODCHAR)SetRayLength_doc},
+ {"getRayLength", (PyCFunction) KX_ConstraintActuator::sPyGetMax, METH_NOARGS, (PY_METHODCHAR)GetRayLength_doc},
+ {"setLimit", (PyCFunction) KX_ConstraintActuator::sPySetLimit, METH_VARARGS, (PY_METHODCHAR)SetLimit_doc},
+ {"getLimit", (PyCFunction) KX_ConstraintActuator::sPyGetLimit, METH_NOARGS, (PY_METHODCHAR)GetLimit_doc},
{NULL,NULL} //Sentinel
};
@@ -228,10 +617,10 @@ PyObject* KX_ConstraintActuator::_getattr(const STR_String& attr) {
}
/* 2. setDamp */
-char KX_ConstraintActuator::SetDamp_doc[] =
+const char KX_ConstraintActuator::SetDamp_doc[] =
"setDamp(duration)\n"
"\t- duration: integer\n"
-"\tSets the time with which the constraint application is delayed.\n"
+"\tSets the time constant of the orientation and distance constraint.\n"
"\tIf the duration is negative, it is set to 0.\n";
PyObject* KX_ConstraintActuator::PySetDamp(PyObject* self,
PyObject* args,
@@ -241,23 +630,182 @@ PyObject* KX_ConstraintActuator::PySetDamp(PyObject* self,
return NULL;
}
- m_dampTime = dampArg;
- if (m_dampTime < 0) m_dampTime = 0;
+ m_posDampTime = dampArg;
+ if (m_posDampTime < 0) m_posDampTime = 0;
Py_Return;
}
/* 3. getDamp */
-char KX_ConstraintActuator::GetDamp_doc[] =
-"GetDamp()\n"
+const char KX_ConstraintActuator::GetDamp_doc[] =
+"getDamp()\n"
+"\tReturns the damping parameter.\n";
+PyObject* KX_ConstraintActuator::PyGetDamp(PyObject* self){
+ return PyInt_FromLong(m_posDampTime);
+}
+
+/* 2. setRotDamp */
+const char KX_ConstraintActuator::SetRotDamp_doc[] =
+"setRotDamp(duration)\n"
+"\t- duration: integer\n"
+"\tSets the time constant of the orientation constraint.\n"
+"\tIf the duration is negative, it is set to 0.\n";
+PyObject* KX_ConstraintActuator::PySetRotDamp(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ int dampArg;
+ if(!PyArg_ParseTuple(args, "i", &dampArg)) {
+ return NULL;
+ }
+
+ m_rotDampTime = dampArg;
+ if (m_rotDampTime < 0) m_rotDampTime = 0;
+
+ Py_Return;
+}
+/* 3. getRotDamp */
+const char KX_ConstraintActuator::GetRotDamp_doc[] =
+"getRotDamp()\n"
"\tReturns the damping time for application of the constraint.\n";
-PyObject* KX_ConstraintActuator::PyGetDamp(PyObject* self,
+PyObject* KX_ConstraintActuator::PyGetRotDamp(PyObject* self){
+ return PyInt_FromLong(m_rotDampTime);
+}
+
+/* 2. setDirection */
+const char KX_ConstraintActuator::SetDirection_doc[] =
+"setDirection(vector)\n"
+"\t- vector: 3-tuple\n"
+"\tSets the reference direction in world coordinate for the orientation constraint.\n";
+PyObject* KX_ConstraintActuator::PySetDirection(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ float x, y, z;
+ MT_Scalar len;
+ MT_Vector3 dir;
+
+ if(!PyArg_ParseTuple(args, "(fff)", &x, &y, &z)) {
+ return NULL;
+ }
+ dir[0] = x;
+ dir[1] = y;
+ dir[2] = z;
+ len = dir.length();
+ if (MT_fuzzyZero(len)) {
+ std::cout << "Invalid direction" << std::endl;
+ return NULL;
+ }
+ m_refDirection = dir/len;
+
+ Py_Return;
+}
+/* 3. getDirection */
+const char KX_ConstraintActuator::GetDirection_doc[] =
+"getDirection()\n"
+"\tReturns the reference direction of the orientation constraint as a 3-tuple.\n";
+PyObject* KX_ConstraintActuator::PyGetDirection(PyObject* self){
+ PyObject *retVal = PyList_New(3);
+
+ PyList_SetItem(retVal, 0, PyFloat_FromDouble(m_refDirection[0]));
+ PyList_SetItem(retVal, 1, PyFloat_FromDouble(m_refDirection[1]));
+ PyList_SetItem(retVal, 2, PyFloat_FromDouble(m_refDirection[2]));
+ return retVal;
+}
+
+/* 2. setOption */
+const char KX_ConstraintActuator::SetOption_doc[] =
+"setOption(option)\n"
+"\t- option: integer\n"
+"\tSets several options of the distance constraint.\n"
+"\tBinary combination of the following values:\n"
+"\t\t 64 : Activate alignment to surface\n"
+"\t\t128 : Detect material rather than property\n"
+"\t\t256 : No deactivation if ray does not hit target\n"
+"\t\t512 : Activate distance control\n";
+PyObject* KX_ConstraintActuator::PySetOption(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ int option;
+ if(!PyArg_ParseTuple(args, "i", &option)) {
+ return NULL;
+ }
+
+ m_option = option;
+
+ Py_Return;
+}
+/* 3. getOption */
+const char KX_ConstraintActuator::GetOption_doc[] =
+"getOption()\n"
+"\tReturns the option parameter.\n";
+PyObject* KX_ConstraintActuator::PyGetOption(PyObject* self){
+ return PyInt_FromLong(m_option);
+}
+
+/* 2. setTime */
+const char KX_ConstraintActuator::SetTime_doc[] =
+"setTime(duration)\n"
+"\t- duration: integer\n"
+"\tSets the activation time of the actuator.\n"
+"\tThe actuator disables itself after this many frame.\n"
+"\tIf set to 0 or negative, the actuator is not limited in time.\n";
+PyObject* KX_ConstraintActuator::PySetTime(PyObject* self,
PyObject* args,
- PyObject* kwds){
- return PyInt_FromLong(m_dampTime);
+ PyObject* kwds) {
+ int t;
+ if(!PyArg_ParseTuple(args, "i", &t)) {
+ return NULL;
+ }
+
+ if (t < 0)
+ t = 0;
+ m_activeTime = t;
+
+ Py_Return;
+}
+/* 3. getTime */
+const char KX_ConstraintActuator::GetTime_doc[] =
+"getTime()\n"
+"\tReturns the time parameter.\n";
+PyObject* KX_ConstraintActuator::PyGetTime(PyObject* self){
+ return PyInt_FromLong(m_activeTime);
}
+/* 2. setProperty */
+const char KX_ConstraintActuator::SetProperty_doc[] =
+"setProperty(property)\n"
+"\t- property: string\n"
+"\tSets the name of the property or material for the ray detection of the distance constraint.\n"
+"\tIf empty, the ray will detect any collisioning object.\n";
+PyObject* KX_ConstraintActuator::PySetProperty(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ char *property;
+ if (!PyArg_ParseTuple(args, "s", &property)) {
+ return NULL;
+ }
+ if (property == NULL) {
+ m_property[0] = 0;
+ } else {
+ strncpy(m_property, property, sizeof(m_property));
+ m_property[sizeof(m_property)-1] = 0;
+ }
+
+ Py_Return;
+}
+/* 3. getProperty */
+const char KX_ConstraintActuator::GetProperty_doc[] =
+"getProperty()\n"
+"\tReturns the property parameter.\n";
+PyObject* KX_ConstraintActuator::PyGetProperty(PyObject* self){
+ return PyString_FromString(m_property);
+}
+
+/* 4. setDistance */
+const char KX_ConstraintActuator::SetDistance_doc[] =
+"setDistance(distance)\n"
+"\t- distance: float\n"
+"\tSets the target distance in distance constraint\n";
/* 4. setMin */
-char KX_ConstraintActuator::SetMin_doc[] =
+const char KX_ConstraintActuator::SetMin_doc[] =
"setMin(lower_bound)\n"
"\t- lower_bound: float\n"
"\tSets the lower value of the interval to which the value\n"
@@ -271,9 +819,7 @@ PyObject* KX_ConstraintActuator::PySetMin(PyObject* self,
}
switch (m_locrot) {
- case KX_ACT_CONSTRAINT_LOCX:
- case KX_ACT_CONSTRAINT_LOCY:
- case KX_ACT_CONSTRAINT_LOCZ:
+ default:
m_minimumBound = minArg;
break;
case KX_ACT_CONSTRAINT_ROTX:
@@ -281,25 +827,30 @@ PyObject* KX_ConstraintActuator::PySetMin(PyObject* self,
case KX_ACT_CONSTRAINT_ROTZ:
m_minimumBound = MT_radians(minArg);
break;
- default:
- ; /* error */
}
Py_Return;
}
+/* 5. getDistance */
+const char KX_ConstraintActuator::GetDistance_doc[] =
+"getDistance()\n"
+"\tReturns the distance parameter \n";
/* 5. getMin */
-char KX_ConstraintActuator::GetMin_doc[] =
+const char KX_ConstraintActuator::GetMin_doc[] =
"getMin()\n"
"\tReturns the lower value of the interval to which the value\n"
"\tis clipped.\n";
-PyObject* KX_ConstraintActuator::PyGetMin(PyObject* self,
- PyObject* args,
- PyObject* kwds) {
+PyObject* KX_ConstraintActuator::PyGetMin(PyObject* self) {
return PyFloat_FromDouble(m_minimumBound);
}
+/* 6. setRayLength */
+const char KX_ConstraintActuator::SetRayLength_doc[] =
+"setRayLength(length)\n"
+"\t- length: float\n"
+"\tSets the maximum ray length of the distance constraint\n";
/* 6. setMax */
-char KX_ConstraintActuator::SetMax_doc[] =
+const char KX_ConstraintActuator::SetMax_doc[] =
"setMax(upper_bound)\n"
"\t- upper_bound: float\n"
"\tSets the upper value of the interval to which the value\n"
@@ -313,9 +864,7 @@ PyObject* KX_ConstraintActuator::PySetMax(PyObject* self,
}
switch (m_locrot) {
- case KX_ACT_CONSTRAINT_LOCX:
- case KX_ACT_CONSTRAINT_LOCY:
- case KX_ACT_CONSTRAINT_LOCZ:
+ default:
m_maximumBound = maxArg;
break;
case KX_ACT_CONSTRAINT_ROTX:
@@ -323,31 +872,41 @@ PyObject* KX_ConstraintActuator::PySetMax(PyObject* self,
case KX_ACT_CONSTRAINT_ROTZ:
m_maximumBound = MT_radians(maxArg);
break;
- default:
- ; /* error */
}
Py_Return;
}
+/* 7. getRayLength */
+const char KX_ConstraintActuator::GetRayLength_doc[] =
+"getRayLength()\n"
+"\tReturns the length of the ray\n";
/* 7. getMax */
-char KX_ConstraintActuator::GetMax_doc[] =
+const char KX_ConstraintActuator::GetMax_doc[] =
"getMax()\n"
"\tReturns the upper value of the interval to which the value\n"
"\tis clipped.\n";
-PyObject* KX_ConstraintActuator::PyGetMax(PyObject* self,
- PyObject* args,
- PyObject* kwds) {
+PyObject* KX_ConstraintActuator::PyGetMax(PyObject* self) {
return PyFloat_FromDouble(m_maximumBound);
}
/* This setter/getter probably for the constraint type */
/* 8. setLimit */
-char KX_ConstraintActuator::SetLimit_doc[] =
+const char KX_ConstraintActuator::SetLimit_doc[] =
"setLimit(type)\n"
-"\t- type: KX_CONSTRAINTACT_LOCX, KX_CONSTRAINTACT_LOCY,\n"
-"\t KX_CONSTRAINTACT_LOCZ, KX_CONSTRAINTACT_ROTX,\n"
-"\t KX_CONSTRAINTACT_ROTY, or KX_CONSTRAINTACT_ROTZ.\n"
+"\t- type: integer\n"
+"\t 1 : LocX\n"
+"\t 2 : LocY\n"
+"\t 3 : LocZ\n"
+"\t 7 : Distance along +X axis\n"
+"\t 8 : Distance along +Y axis\n"
+"\t 9 : Distance along +Z axis\n"
+"\t 10 : Distance along -X axis\n"
+"\t 11 : Distance along -Y axis\n"
+"\t 12 : Distance along -Z axis\n"
+"\t 13 : Align X axis\n"
+"\t 14 : Align Y axis\n"
+"\t 15 : Align Z axis\n"
"\tSets the type of constraint.\n";
PyObject* KX_ConstraintActuator::PySetLimit(PyObject* self,
PyObject* args,
@@ -362,12 +921,10 @@ PyObject* KX_ConstraintActuator::PySetLimit(PyObject* self,
Py_Return;
}
/* 9. getLimit */
-char KX_ConstraintActuator::GetLimit_doc[] =
-"getLimit(type)\n"
+const char KX_ConstraintActuator::GetLimit_doc[] =
+"getLimit()\n"
"\tReturns the type of constraint.\n";
-PyObject* KX_ConstraintActuator::PyGetLimit(PyObject* self,
- PyObject* args,
- PyObject* kwds) {
+PyObject* KX_ConstraintActuator::PyGetLimit(PyObject* self) {
return PyInt_FromLong(m_locrot);
}
diff --git a/source/gameengine/Ketsji/KX_ConstraintActuator.h b/source/gameengine/Ketsji/KX_ConstraintActuator.h
index a21a5f30de6..28b9b1e6a0b 100644
--- a/source/gameengine/Ketsji/KX_ConstraintActuator.h
+++ b/source/gameengine/Ketsji/KX_ConstraintActuator.h
@@ -34,19 +34,40 @@
#include "SCA_IActuator.h"
#include "MT_Scalar.h"
+#include "MT_Vector3.h"
+#include "KX_ClientObjectInfo.h"
+
+class KX_RayCast;
+class KX_GameObject;
class KX_ConstraintActuator : public SCA_IActuator
{
Py_Header;
protected:
// Damp time (int),
- int m_dampTime;
- // min (float),
+ int m_posDampTime;
+ int m_rotDampTime;
+ // min (float)
float m_minimumBound;
- // max (float),
+ // max (float)
float m_maximumBound;
+ // sinus of minimum angle
+ float m_minimumSine;
+ // sinus of maximum angle
+ float m_maximumSine;
+ // reference direction
+ MT_Vector3 m_refDirection;
// locrotxyz choice (pick one): only one choice allowed at a time!
int m_locrot;
+ // active time of actuator
+ int m_activeTime;
+ int m_currentTime;
+ // option
+ int m_option;
+ // property to check
+ char m_property[32];
+ // hit object
+ KX_GameObject* m_hitObject;
/**
* Clamp <var> to <min>, <max>. Borders are included (in as far as
@@ -56,6 +77,7 @@ protected:
public:
+ // m_locrot
enum KX_CONSTRAINTTYPE {
KX_ACT_CONSTRAINT_NODEF = 0,
KX_ACT_CONSTRAINT_LOCX,
@@ -64,16 +86,46 @@ protected:
KX_ACT_CONSTRAINT_ROTX,
KX_ACT_CONSTRAINT_ROTY,
KX_ACT_CONSTRAINT_ROTZ,
+ KX_ACT_CONSTRAINT_DIRPX,
+ KX_ACT_CONSTRAINT_DIRPY,
+ KX_ACT_CONSTRAINT_DIRPZ,
+ KX_ACT_CONSTRAINT_DIRNX,
+ KX_ACT_CONSTRAINT_DIRNY,
+ KX_ACT_CONSTRAINT_DIRNZ,
+ KX_ACT_CONSTRAINT_ORIX,
+ KX_ACT_CONSTRAINT_ORIY,
+ KX_ACT_CONSTRAINT_ORIZ,
+ KX_ACT_CONSTRAINT_FHPX,
+ KX_ACT_CONSTRAINT_FHPY,
+ KX_ACT_CONSTRAINT_FHPZ,
+ KX_ACT_CONSTRAINT_FHNX,
+ KX_ACT_CONSTRAINT_FHNY,
+ KX_ACT_CONSTRAINT_FHNZ,
KX_ACT_CONSTRAINT_MAX
};
-
+ // match ACT_CONST_... values from BIF_interface.h
+ enum KX_CONSTRAINTOPT {
+ KX_ACT_CONSTRAINT_NORMAL = 64,
+ KX_ACT_CONSTRAINT_MATERIAL = 128,
+ KX_ACT_CONSTRAINT_PERMANENT = 256,
+ KX_ACT_CONSTRAINT_DISTANCE = 512,
+ KX_ACT_CONSTRAINT_LOCAL = 1024,
+ KX_ACT_CONSTRAINT_DOROTFH = 2048
+ };
bool IsValidMode(KX_CONSTRAINTTYPE m);
+ bool RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data);
+ bool NeedRayCast(KX_ClientObjectInfo*);
KX_ConstraintActuator(SCA_IObject* gameobj,
- int damptime,
+ int posDamptime,
+ int rotDampTime,
float min,
float max,
+ float refDir[3],
int locrot,
+ int time,
+ int option,
+ char *property,
PyTypeObject* T=&Type);
virtual ~KX_ConstraintActuator();
virtual CValue* GetReplica() {
@@ -93,14 +145,27 @@ protected:
virtual PyObject* _getattr(const STR_String& attr);
KX_PYMETHOD_DOC(KX_ConstraintActuator,SetDamp);
- KX_PYMETHOD_DOC(KX_ConstraintActuator,GetDamp);
+ KX_PYMETHOD_DOC_NOARGS(KX_ConstraintActuator,GetDamp);
+ KX_PYMETHOD_DOC(KX_ConstraintActuator,SetRotDamp);
+ KX_PYMETHOD_DOC_NOARGS(KX_ConstraintActuator,GetRotDamp);
+ KX_PYMETHOD_DOC(KX_ConstraintActuator,SetDirection);
+ KX_PYMETHOD_DOC_NOARGS(KX_ConstraintActuator,GetDirection);
+ KX_PYMETHOD_DOC(KX_ConstraintActuator,SetOption);
+ KX_PYMETHOD_DOC_NOARGS(KX_ConstraintActuator,GetOption);
+ KX_PYMETHOD_DOC(KX_ConstraintActuator,SetTime);
+ KX_PYMETHOD_DOC_NOARGS(KX_ConstraintActuator,GetTime);
+ KX_PYMETHOD_DOC(KX_ConstraintActuator,SetProperty);
+ KX_PYMETHOD_DOC_NOARGS(KX_ConstraintActuator,GetProperty);
KX_PYMETHOD_DOC(KX_ConstraintActuator,SetMin);
- KX_PYMETHOD_DOC(KX_ConstraintActuator,GetMin);
+ KX_PYMETHOD_DOC_NOARGS(KX_ConstraintActuator,GetMin);
+ static const char SetDistance_doc[];
+ static const char GetDistance_doc[];
KX_PYMETHOD_DOC(KX_ConstraintActuator,SetMax);
- KX_PYMETHOD_DOC(KX_ConstraintActuator,GetMax);
+ KX_PYMETHOD_DOC_NOARGS(KX_ConstraintActuator,GetMax);
+ static const char SetRayLength_doc[];
+ static const char GetRayLength_doc[];
KX_PYMETHOD_DOC(KX_ConstraintActuator,SetLimit);
- KX_PYMETHOD_DOC(KX_ConstraintActuator,GetLimit);
-
+ KX_PYMETHOD_DOC_NOARGS(KX_ConstraintActuator,GetLimit);
};
#endif //__KX_CONSTRAINTACTUATOR
diff --git a/source/gameengine/Ketsji/KX_ConstraintWrapper.cpp b/source/gameengine/Ketsji/KX_ConstraintWrapper.cpp
index 987125ca9ba..c9095ff34f6 100644
--- a/source/gameengine/Ketsji/KX_ConstraintWrapper.cpp
+++ b/source/gameengine/Ketsji/KX_ConstraintWrapper.cpp
@@ -27,6 +27,7 @@
* ***** END GPL LICENSE BLOCK *****
*/
#include <Python.h>
+#include "PyObjectPlus.h"
#include "KX_ConstraintWrapper.h"
#include "PHY_IPhysicsEnvironment.h"
@@ -53,8 +54,7 @@ PyObject* KX_ConstraintWrapper::PyTestMethod(PyObject* self,
PyObject* kwds)
{
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
PyObject* KX_ConstraintWrapper::PyGetConstraintId(PyObject* self,
diff --git a/source/gameengine/Ketsji/KX_ConvertPhysicsObject.h b/source/gameengine/Ketsji/KX_ConvertPhysicsObject.h
index 6653026f28a..53486cecf73 100644
--- a/source/gameengine/Ketsji/KX_ConvertPhysicsObject.h
+++ b/source/gameengine/Ketsji/KX_ConvertPhysicsObject.h
@@ -75,6 +75,7 @@ struct KX_CBounds
struct KX_ObjectProperties
{
bool m_dyna;
+ bool m_softbody;
double m_radius;
bool m_angular_rigidbody;
bool m_in_active_layer;
@@ -86,6 +87,47 @@ struct KX_ObjectProperties
bool m_disableSleeping;
bool m_hasCompoundChildren;
bool m_isCompoundChild;
+
+ /////////////////////////
+
+ int m_gamesoftFlag;
+ float m_soft_linStiff; /* linear stiffness 0..1 */
+ float m_soft_angStiff; /* angular stiffness 0..1 */
+ float m_soft_volume; /* volume preservation 0..1 */
+
+ int m_soft_viterations; /* Velocities solver iterations */
+ int m_soft_piterations; /* Positions solver iterations */
+ int m_soft_diterations; /* Drift solver iterations */
+ int m_soft_citerations; /* Cluster solver iterations */
+
+ float m_soft_kSRHR_CL; /* Soft vs rigid hardness [0,1] (cluster only) */
+ float m_soft_kSKHR_CL; /* Soft vs kinetic hardness [0,1] (cluster only) */
+ float m_soft_kSSHR_CL; /* Soft vs soft hardness [0,1] (cluster only) */
+ float m_soft_kSR_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
+
+ float m_soft_kSK_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
+ float m_soft_kSS_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
+ float m_soft_kVCF; /* Velocities correction factor (Baumgarte) */
+ float m_soft_kDP; /* Damping coefficient [0,1] */
+
+ float m_soft_kDG; /* Drag coefficient [0,+inf] */
+ float m_soft_kLF; /* Lift coefficient [0,+inf] */
+ float m_soft_kPR; /* Pressure coefficient [-inf,+inf] */
+ float m_soft_kVC; /* Volume conversation coefficient [0,+inf] */
+
+ float m_soft_kDF; /* Dynamic friction coefficient [0,1] */
+ float m_soft_kMT; /* Pose matching coefficient [0,1] */
+ float m_soft_kCHR; /* Rigid contacts hardness [0,1] */
+ float m_soft_kKHR; /* Kinetic contacts hardness [0,1] */
+
+ float m_soft_kSHR; /* Soft contacts hardness [0,1] */
+ float m_soft_kAHR; /* Anchors hardness [0,1] */
+ int m_soft_collisionflags; /* Vertex/Face or Signed Distance Field(SDF) or Clusters, Soft versus Soft or Rigid */
+ int m_soft_numclusteriterations; /* number of iterations to refine collision clusters*/
+
+ /////////////////////////
+
+ double m_margin;
KX_BoundBoxClass m_boundclass;
union {
KX_BoxBounds box;
diff --git a/source/gameengine/Ketsji/KX_ConvertPhysicsObjects.cpp b/source/gameengine/Ketsji/KX_ConvertPhysicsObjects.cpp
index 26e0b47b84b..0e7a6d92ec1 100644
--- a/source/gameengine/Ketsji/KX_ConvertPhysicsObjects.cpp
+++ b/source/gameengine/Ketsji/KX_ConvertPhysicsObjects.cpp
@@ -38,6 +38,8 @@
#include "RAS_MeshObject.h"
#include "KX_Scene.h"
#include "SYS_System.h"
+#include "BL_SkinMeshObject.h"
+#include "BulletSoftBody/btSoftBody.h"
#include "PHY_Pro.h" //todo cleanup
#include "KX_ClientObjectInfo.h"
@@ -76,16 +78,16 @@
struct KX_PhysicsInstance
{
DT_VertexBaseHandle m_vertexbase;
- int m_vtxarray;
+ RAS_DisplayArray* m_darray;
RAS_IPolyMaterial* m_material;
-
- KX_PhysicsInstance(DT_VertexBaseHandle vertex_base, int vtxarray, RAS_IPolyMaterial* mat)
+
+ KX_PhysicsInstance(DT_VertexBaseHandle vertex_base, RAS_DisplayArray *darray, RAS_IPolyMaterial* mat)
: m_vertexbase(vertex_base),
- m_vtxarray(vtxarray),
- m_material(mat)
+ m_darray(darray),
+ m_material(mat)
{
}
-
+
~KX_PhysicsInstance()
{
DT_DeleteVertexBase(m_vertexbase);
@@ -100,11 +102,11 @@ static void BL_RegisterSumoObject(KX_GameObject* gameobj,class SM_Scene* sumoSce
static DT_ShapeHandle CreateShapeFromMesh(RAS_MeshObject* meshobj, bool polytope);
void KX_ConvertSumoObject( KX_GameObject* gameobj,
- RAS_MeshObject* meshobj,
- KX_Scene* kxscene,
- PHY_ShapeProps* kxshapeprops,
- PHY_MaterialProps* kxmaterial,
- struct KX_ObjectProperties* objprop)
+ RAS_MeshObject* meshobj,
+ KX_Scene* kxscene,
+ PHY_ShapeProps* kxshapeprops,
+ PHY_MaterialProps* kxmaterial,
+ struct KX_ObjectProperties* objprop)
{
@@ -150,23 +152,23 @@ void KX_ConvertSumoObject( KX_GameObject* gameobj,
objprop->m_boundobject.box.m_extends[1],
objprop->m_boundobject.box.m_extends[2]);
smprop->m_inertia.scale(objprop->m_boundobject.box.m_extends[0]*objprop->m_boundobject.box.m_extends[0],
- objprop->m_boundobject.box.m_extends[1]*objprop->m_boundobject.box.m_extends[1],
- objprop->m_boundobject.box.m_extends[2]*objprop->m_boundobject.box.m_extends[2]);
+ objprop->m_boundobject.box.m_extends[1]*objprop->m_boundobject.box.m_extends[1],
+ objprop->m_boundobject.box.m_extends[2]*objprop->m_boundobject.box.m_extends[2]);
smprop->m_inertia *= smprop->m_mass/MT_Vector3(objprop->m_boundobject.box.m_extends).length();
break;
case KX_BOUNDCYLINDER:
shape = DT_NewCylinder(smprop->m_radius, objprop->m_boundobject.c.m_height);
smprop->m_inertia.scale(smprop->m_mass*smprop->m_radius*smprop->m_radius,
- smprop->m_mass*smprop->m_radius*smprop->m_radius,
- smprop->m_mass*objprop->m_boundobject.c.m_height*objprop->m_boundobject.c.m_height);
+ smprop->m_mass*smprop->m_radius*smprop->m_radius,
+ smprop->m_mass*objprop->m_boundobject.c.m_height*objprop->m_boundobject.c.m_height);
break;
case KX_BOUNDCONE:
shape = DT_NewCone(objprop->m_radius, objprop->m_boundobject.c.m_height);
smprop->m_inertia.scale(smprop->m_mass*smprop->m_radius*smprop->m_radius,
- smprop->m_mass*smprop->m_radius*smprop->m_radius,
- smprop->m_mass*objprop->m_boundobject.c.m_height*objprop->m_boundobject.c.m_height);
+ smprop->m_mass*smprop->m_radius*smprop->m_radius,
+ smprop->m_mass*objprop->m_boundobject.c.m_height*objprop->m_boundobject.c.m_height);
break;
- /* Dynamic mesh objects. WARNING! slow. */
+ /* Dynamic mesh objects. WARNING! slow. */
case KX_BOUNDPOLYTOPE:
polytope = true;
// fall through
@@ -186,15 +188,15 @@ void KX_ConvertSumoObject( KX_GameObject* gameobj,
shape = DT_NewSphere(objprop->m_radius);
smprop->m_inertia *= smprop->m_mass*smprop->m_radius*smprop->m_radius;
break;
-
+
}
-
+
sumoObj = new SM_Object(shape, !objprop->m_ghost?smmaterial:NULL,smprop,NULL);
-
+
sumoObj->setRigidBody(objprop->m_angular_rigidbody?true:false);
-
+
BL_RegisterSumoObject(gameobj,sceneptr,sumoObj,"",true, true);
-
+
}
else {
// non physics object
@@ -320,12 +322,11 @@ static void BL_RegisterSumoObject(
physicscontroller->SetObject(gameobj->GetSGNode());
}
-static DT_ShapeHandle InstancePhysicsComplex(RAS_MeshObject* meshobj, int vtxarray, RAS_IPolyMaterial *mat)
+static DT_ShapeHandle InstancePhysicsComplex(RAS_MeshObject* meshobj, RAS_DisplayArray *darray, RAS_IPolyMaterial *mat)
{
// instance a mesh from a single vertex array & material
- const RAS_TexVert *vertex_array = &((*meshobj->GetVertexCache(mat)[vtxarray])[0]);
- //const KX_IndexArray &index_array = *meshobj->GetIndexCache(mat)[vtxarray];
- DT_VertexBaseHandle vertex_base = DT_NewVertexBase(vertex_array[0].getLocalXYZ(), sizeof(RAS_TexVert));
+ const RAS_TexVert *vertex_array = &darray->m_vertex[0];
+ DT_VertexBaseHandle vertex_base = DT_NewVertexBase(vertex_array[0].getXYZ(), sizeof(RAS_TexVert));
DT_ShapeHandle shape = DT_NewComplexShape(vertex_base);
@@ -337,15 +338,19 @@ static DT_ShapeHandle InstancePhysicsComplex(RAS_MeshObject* meshobj, int vtxarr
// only add polygons that have the collisionflag set
if (poly->IsCollider())
{
- DT_VertexIndices(3, poly->GetVertexIndexBase().m_indexarray);
+ DT_Begin();
+ DT_VertexIndex(poly->GetVertexOffset(0));
+ DT_VertexIndex(poly->GetVertexOffset(1));
+ DT_VertexIndex(poly->GetVertexOffset(2));
+ DT_End();
// tesselate
if (poly->VertexCount() == 4)
{
DT_Begin();
- DT_VertexIndex(poly->GetVertexIndexBase().m_indexarray[0]);
- DT_VertexIndex(poly->GetVertexIndexBase().m_indexarray[2]);
- DT_VertexIndex(poly->GetVertexIndexBase().m_indexarray[3]);
+ DT_VertexIndex(poly->GetVertexOffset(0));
+ DT_VertexIndex(poly->GetVertexOffset(2));
+ DT_VertexIndex(poly->GetVertexOffset(3));
DT_End();
}
}
@@ -354,16 +359,15 @@ static DT_ShapeHandle InstancePhysicsComplex(RAS_MeshObject* meshobj, int vtxarr
//DT_VertexIndices(indices.size(), &indices[0]);
DT_EndComplexShape();
- map_gamemesh_to_instance.insert(GEN_HashedPtr(meshobj), new KX_PhysicsInstance(vertex_base, vtxarray, mat));
+ map_gamemesh_to_instance.insert(GEN_HashedPtr(meshobj), new KX_PhysicsInstance(vertex_base, darray, mat));
return shape;
}
-static DT_ShapeHandle InstancePhysicsPolytope(RAS_MeshObject* meshobj, int vtxarray, RAS_IPolyMaterial *mat)
+static DT_ShapeHandle InstancePhysicsPolytope(RAS_MeshObject* meshobj, RAS_DisplayArray *darray, RAS_IPolyMaterial *mat)
{
// instance a mesh from a single vertex array & material
- const RAS_TexVert *vertex_array = &((*meshobj->GetVertexCache(mat)[vtxarray])[0]);
- //const KX_IndexArray &index_array = *meshobj->GetIndexCache(mat)[vtxarray];
- DT_VertexBaseHandle vertex_base = DT_NewVertexBase(vertex_array[0].getLocalXYZ(), sizeof(RAS_TexVert));
+ const RAS_TexVert *vertex_array = &darray->m_vertex[0];
+ DT_VertexBaseHandle vertex_base = DT_NewVertexBase(vertex_array[0].getXYZ(), sizeof(RAS_TexVert));
std::vector<DT_Index> indices;
for (int p = 0; p < meshobj->NumPolygons(); p++)
@@ -373,12 +377,12 @@ static DT_ShapeHandle InstancePhysicsPolytope(RAS_MeshObject* meshobj, int vtxar
// only add polygons that have the collisionflag set
if (poly->IsCollider())
{
- indices.push_back(poly->GetVertexIndexBase().m_indexarray[0]);
- indices.push_back(poly->GetVertexIndexBase().m_indexarray[1]);
- indices.push_back(poly->GetVertexIndexBase().m_indexarray[2]);
+ indices.push_back(poly->GetVertexOffset(0));
+ indices.push_back(poly->GetVertexOffset(1));
+ indices.push_back(poly->GetVertexOffset(2));
if (poly->VertexCount() == 4)
- indices.push_back(poly->GetVertexIndexBase().m_indexarray[3]);
+ indices.push_back(poly->GetVertexOffset(3));
}
}
@@ -386,7 +390,7 @@ static DT_ShapeHandle InstancePhysicsPolytope(RAS_MeshObject* meshobj, int vtxar
DT_VertexIndices(indices.size(), &indices[0]);
DT_EndPolytope();
- map_gamemesh_to_instance.insert(GEN_HashedPtr(meshobj), new KX_PhysicsInstance(vertex_base, vtxarray, mat));
+ map_gamemesh_to_instance.insert(GEN_HashedPtr(meshobj), new KX_PhysicsInstance(vertex_base, darray, mat));
return shape;
}
@@ -398,8 +402,8 @@ bool KX_ReInstanceShapeFromMesh(RAS_MeshObject* meshobj)
KX_PhysicsInstance *instance = *map_gamemesh_to_instance[GEN_HashedPtr(meshobj)];
if (instance)
{
- const RAS_TexVert *vertex_array = &((*meshobj->GetVertexCache(instance->m_material)[instance->m_vtxarray])[0]);
- DT_ChangeVertexBase(instance->m_vertexbase, vertex_array[0].getLocalXYZ());
+ const RAS_TexVert *vertex_array = &instance->m_darray->m_vertex[0];
+ DT_ChangeVertexBase(instance->m_vertexbase, vertex_array[0].getXYZ());
return true;
}
return false;
@@ -425,7 +429,7 @@ static DT_ShapeHandle CreateShapeFromMesh(RAS_MeshObject* meshobj, bool polytope
// Count the number of collision polygons and check they all come from the same
// vertex array
int numvalidpolys = 0;
- int vtxarray = -1;
+ RAS_DisplayArray *darray = NULL;
RAS_IPolyMaterial *poly_material = NULL;
bool reinstance = true;
@@ -437,14 +441,14 @@ static DT_ShapeHandle CreateShapeFromMesh(RAS_MeshObject* meshobj, bool polytope
if (poly->IsCollider())
{
// check polygon is from the same vertex array
- if (poly->GetVertexIndexBase().m_vtxarray != vtxarray)
+ if (poly->GetDisplayArray() != darray)
{
- if (vtxarray < 0)
- vtxarray = poly->GetVertexIndexBase().m_vtxarray;
+ if (darray == NULL)
+ darray = poly->GetDisplayArray();
else
{
reinstance = false;
- vtxarray = -1;
+ darray = NULL;
}
}
@@ -478,9 +482,9 @@ static DT_ShapeHandle CreateShapeFromMesh(RAS_MeshObject* meshobj, bool polytope
if (reinstance)
{
if (polytope)
- shape = InstancePhysicsPolytope(meshobj, vtxarray, poly_material);
+ shape = InstancePhysicsPolytope(meshobj, darray, poly_material);
else
- shape = InstancePhysicsComplex(meshobj, vtxarray, poly_material);
+ shape = InstancePhysicsComplex(meshobj, darray, poly_material);
}
else
{
@@ -489,7 +493,7 @@ static DT_ShapeHandle CreateShapeFromMesh(RAS_MeshObject* meshobj, bool polytope
std::cout << "CreateShapeFromMesh: " << meshobj->GetName() << " is not suitable for polytope." << std::endl;
if (!poly_material)
std::cout << " Check mesh materials." << std::endl;
- if (vtxarray < 0)
+ if (darray == NULL)
std::cout << " Check number of vertices." << std::endl;
}
@@ -505,18 +509,10 @@ static DT_ShapeHandle CreateShapeFromMesh(RAS_MeshObject* meshobj, bool polytope
if (poly->IsCollider())
{ /* We have to tesselate here because SOLID can only raycast triangles */
DT_Begin();
- /* V1 */
- DT_Vertex(meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
- poly->GetVertexIndexBase().m_indexarray[2],
- poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ());
- /* V2 */
- DT_Vertex(meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
- poly->GetVertexIndexBase().m_indexarray[1],
- poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ());
- /* V3 */
- DT_Vertex(meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
- poly->GetVertexIndexBase().m_indexarray[0],
- poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ());
+ /* V1, V2, V3 */
+ DT_Vertex(poly->GetVertex(2)->getXYZ());
+ DT_Vertex(poly->GetVertex(1)->getXYZ());
+ DT_Vertex(poly->GetVertex(0)->getXYZ());
numvalidpolys++;
DT_End();
@@ -524,18 +520,10 @@ static DT_ShapeHandle CreateShapeFromMesh(RAS_MeshObject* meshobj, bool polytope
if (poly->VertexCount() == 4)
{
DT_Begin();
- /* V1 */
- DT_Vertex(meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
- poly->GetVertexIndexBase().m_indexarray[3],
- poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ());
- /* V3 */
- DT_Vertex(meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
- poly->GetVertexIndexBase().m_indexarray[2],
- poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ());
- /* V4 */
- DT_Vertex(meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
- poly->GetVertexIndexBase().m_indexarray[0],
- poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ());
+ /* V1, V3, V4 */
+ DT_Vertex(poly->GetVertex(3)->getXYZ());
+ DT_Vertex(poly->GetVertex(2)->getXYZ());
+ DT_Vertex(poly->GetVertex(0)->getXYZ());
numvalidpolys++;
DT_End();
@@ -679,196 +667,107 @@ void KX_ConvertODEEngineObject(KX_GameObject* gameobj,
#endif //WIN32
-static GEN_Map<GEN_HashedPtr,btCollisionShape*> map_gamemesh_to_bulletshape;
-
-// forward declarations
-static btCollisionShape* CreateBulletShapeFromMesh(RAS_MeshObject* meshobj, bool polytope)
-{
- if (!meshobj)
- return 0;
-
- btCollisionShape* collisionMeshShape = 0;
- btConvexHullShape* convexHullShape = 0;
- btTriangleMeshShape* concaveShape = 0;
-
- btTriangleMesh* collisionMeshData = 0;
-
- //see if there is any polygons, if not, bail out.
-
- int numPoints = 0;
- btVector3* points = 0;
-
- btCollisionShape** shapeptr = map_gamemesh_to_bulletshape[GEN_HashedPtr(meshobj)];
-
- // Mesh has already been converted: reuse
- if (shapeptr)
- {
- //return *shapeptr;
- }
-
- // Mesh has no polygons!
- int numpolys = meshobj->NumPolygons();
- if (!numpolys)
- {
- return NULL;
- }
-
- // Count the number of collision polygons and check they all come from the same
- // vertex array
- int numvalidpolys = 0;
- int vtxarray = -1;
- RAS_IPolyMaterial *poly_material = NULL;
- bool reinstance = true;
-
- for (int p=0; p<numpolys; p++)
+
+ class KX_SoftBodyDeformer : public RAS_Deformer
{
- RAS_Polygon* poly = meshobj->GetPolygon(p);
+ class RAS_MeshObject* m_pMeshObject;
+ class KX_GameObject* m_gameobj;
- // only add polygons that have the collisionflag set
- if (poly->IsCollider())
+ public:
+ KX_SoftBodyDeformer(RAS_MeshObject* pMeshObject,KX_GameObject* gameobj)
+ :m_pMeshObject(pMeshObject),
+ m_gameobj(gameobj)
{
- // check polygon is from the same vertex array
- if (poly->GetVertexIndexBase().m_vtxarray != vtxarray)
- {
- if (vtxarray < 0)
- vtxarray = poly->GetVertexIndexBase().m_vtxarray;
- else
- {
- reinstance = false;
- vtxarray = -1;
- }
- }
-
- // check poly is from the same material
- if (poly->GetMaterial()->GetPolyMaterial() != poly_material)
- {
- if (poly_material)
- {
- reinstance = false;
- poly_material = NULL;
- }
- else
- poly_material = poly->GetMaterial()->GetPolyMaterial();
- }
-
- // count the number of collision polys
- numvalidpolys++;
+ //printf("KX_SoftBodyDeformer\n");
+ };
- // We have one collision poly, and we can't reinstance, so we
- // might as well break here.
- if (!reinstance)
- break;
+ virtual ~KX_SoftBodyDeformer()
+ {
+ //printf("~KX_SoftBodyDeformer\n");
+ };
+ virtual void Relink(GEN_Map<class GEN_HashedPtr, void*>*map)
+ {
+ //printf("relink\n");
}
- }
-
- // No collision polygons
- if (numvalidpolys < 1)
- return NULL;
+ virtual bool Apply(class RAS_IPolyMaterial *polymat)
+ {
+ KX_BulletPhysicsController* ctrl = (KX_BulletPhysicsController*) m_gameobj->GetPhysicsController();
+ if (!ctrl)
+ return false;
+ btSoftBody* softBody= ctrl->GetSoftBody();
+ if (!softBody)
+ return false;
- if (polytope)
- {
- convexHullShape = new btConvexHullShape(&points[0].getX(),numPoints);
- collisionMeshShape = convexHullShape;
- } else
- {
- collisionMeshData = new btTriangleMesh();
-// concaveShape = new btTriangleMeshShape(collisionMeshData);
- //collisionMeshShape = concaveShape;
+ //printf("apply\n");
+ RAS_MeshSlot::iterator it;
+ RAS_MeshMaterial *mmat;
+ RAS_MeshSlot *slot;
+ size_t i;
- }
+ // update the vertex in m_transverts
+ Update();
- numvalidpolys = 0;
- for (int p2=0; p2<numpolys; p2++)
- {
- RAS_Polygon* poly = meshobj->GetPolygon(p2);
+ // The vertex cache can only be updated for this deformer:
+ // Duplicated objects with more than one ploymaterial (=multiple mesh slot per object)
+ // share the same mesh (=the same cache). As the rendering is done per polymaterial
+ // cycling through the objects, the entire mesh cache cannot be updated in one shot.
+ mmat = m_pMeshObject->GetMeshMaterial(polymat);
+ if(!mmat->m_slots[(void*)m_gameobj])
+ return true;
- // only add polygons that have the collisionflag set
- if (poly->IsCollider())
- {
- //Bullet can raycast any shape, so
- if (polytope)
- {
- for (int i=0;i<poly->VertexCount();i++)
- {
- const float* vtx = meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
- poly->GetVertexIndexBase().m_indexarray[i],
- poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ();
- btPoint3 point(vtx[0],vtx[1],vtx[2]);
- convexHullShape->addPoint(point);
- }
- if (poly->VertexCount())
- numvalidpolys++;
+ slot = *mmat->m_slots[(void*)m_gameobj];
- } else
+ // for each array
+ for(slot->begin(it); !slot->end(it); slot->next(it))
{
- {
- const float* vtx = meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
- poly->GetVertexIndexBase().m_indexarray[2],
- poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ();
- btPoint3 vertex0(vtx[0],vtx[1],vtx[2]);
- vtx = meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
- poly->GetVertexIndexBase().m_indexarray[1],
- poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ();
- btPoint3 vertex1(vtx[0],vtx[1],vtx[2]);
- vtx = meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
- poly->GetVertexIndexBase().m_indexarray[0],
- poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ();
- btPoint3 vertex2(vtx[0],vtx[1],vtx[2]);
- collisionMeshData->addTriangle(vertex0,vertex1,vertex2);
- numvalidpolys++;
- }
- if (poly->VertexCount() == 4)
- {
- const float* vtx = meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
- poly->GetVertexIndexBase().m_indexarray[3],
- poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ();
- btPoint3 vertex0(vtx[0],vtx[1],vtx[2]);
- vtx = meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
- poly->GetVertexIndexBase().m_indexarray[2],
- poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ();
- btPoint3 vertex1(vtx[0],vtx[1],vtx[2]);
- vtx = meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
- poly->GetVertexIndexBase().m_indexarray[0],
- poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ();
- btPoint3 vertex2(vtx[0],vtx[1],vtx[2]);
- collisionMeshData->addTriangle(vertex0,vertex1,vertex2);
- numvalidpolys++;
- }
+ btSoftBody::tNodeArray& nodes(softBody->m_nodes);
- }
- }
- }
+ int index = 0;
+ for(i=it.startvertex; i<it.endvertex; i++,index++) {
+ RAS_TexVert& v = it.vertex[i];
+ btAssert(v.getSoftBodyIndex() >= 0);
+ MT_Point3 pt (
+ nodes[v.getSoftBodyIndex()].m_x.getX(),
+ nodes[v.getSoftBodyIndex()].m_x.getY(),
+ nodes[v.getSoftBodyIndex()].m_x.getZ());
+ v.SetXYZ(pt);
+ MT_Vector3 normal (
+ nodes[v.getSoftBodyIndex()].m_n.getX(),
+ nodes[v.getSoftBodyIndex()].m_n.getY(),
+ nodes[v.getSoftBodyIndex()].m_n.getZ());
+ v.SetNormal(normal);
- if (numvalidpolys > 0)
- {
-
- //map_gamemesh_to_bulletshape.insert(GEN_HashedPtr(meshobj),collisionMeshShape);
- if (!polytope)
+ }
+ }
+ return true;
+ }
+ virtual bool Update(void)
{
- bool useQuantization = true;
- concaveShape = new btBvhTriangleMeshShape( collisionMeshData, useQuantization );
- //concaveShape = new btTriangleMeshShape( collisionMeshData );
-
- concaveShape->recalcLocalAabb();
- collisionMeshShape = concaveShape;
-
- }
-
-
+ //printf("update\n");
+ return true;//??
+ }
+ virtual RAS_Deformer *GetReplica(class KX_GameObject* replica)
+ {
+ KX_SoftBodyDeformer* deformer = new KX_SoftBodyDeformer(replica->GetMesh(0),replica);
+ return deformer;
+ }
- return collisionMeshShape;
- }
+ virtual bool SkipVertexTransform()
+ {
+ return true;
+ }
- delete collisionMeshShape;
- return NULL;
+ protected:
+ //class RAS_MeshObject *m_pMesh;
+ };
-}
+// forward declarations
void KX_ConvertBulletObject( class KX_GameObject* gameobj,
class RAS_MeshObject* meshobj,
@@ -885,6 +784,7 @@ void KX_ConvertBulletObject( class KX_GameObject* gameobj,
bool isbulletdyna = false;
CcdConstructionInfo ci;
class PHY_IMotionState* motionstate = new KX_MotionState(gameobj->GetSGNode());
+ class CcdShapeConstructionInfo *shapeInfo = new CcdShapeConstructionInfo();
@@ -892,125 +792,108 @@ void KX_ConvertBulletObject( class KX_GameObject* gameobj,
{
ci.m_collisionFlags |= btCollisionObject::CF_STATIC_OBJECT;
}
+ if (objprop->m_ghost)
+ {
+ ci.m_collisionFlags |= btCollisionObject::CF_NO_CONTACT_RESPONSE;
+ }
ci.m_MotionState = motionstate;
ci.m_gravity = btVector3(0,0,0);
ci.m_localInertiaTensor =btVector3(0,0,0);
ci.m_mass = objprop->m_dyna ? shapeprops->m_mass : 0.f;
+ ci.m_margin = objprop->m_margin;
+ shapeInfo->m_radius = objprop->m_radius;
isbulletdyna = objprop->m_dyna;
ci.m_localInertiaTensor = btVector3(ci.m_mass/3.f,ci.m_mass/3.f,ci.m_mass/3.f);
- btTransform trans;
- trans.setIdentity();
-
btCollisionShape* bm = 0;
switch (objprop->m_boundclass)
{
case KX_BOUNDSPHERE:
{
- float radius = objprop->m_radius;
- btVector3 inertiaHalfExtents (
- radius,
- radius,
- radius);
+ //float radius = objprop->m_radius;
+ //btVector3 inertiaHalfExtents (
+ // radius,
+ // radius,
+ // radius);
//blender doesn't support multisphere, but for testing:
//bm = new MultiSphereShape(inertiaHalfExtents,,&trans.getOrigin(),&radius,1);
- bm = new btSphereShape(objprop->m_radius);
- bm->calculateLocalInertia(ci.m_mass,ci.m_localInertiaTensor);
+ shapeInfo->m_shapeType = PHY_SHAPE_SPHERE;
+ bm = shapeInfo->CreateBulletShape();
break;
};
case KX_BOUNDBOX:
{
- MT_Vector3 halfExtents (
+ shapeInfo->m_halfExtend.setValue(
objprop->m_boundobject.box.m_extends[0],
- objprop->m_boundobject.box.m_extends[1],
- objprop->m_boundobject.box.m_extends[2]);
-
- halfExtents /= 2.f;
-
- //btVector3 he (halfExtents[0]-CONVEX_DISTANCE_MARGIN ,halfExtents[1]-CONVEX_DISTANCE_MARGIN ,halfExtents[2]-CONVEX_DISTANCE_MARGIN );
- //he = he.absolute();
-
- btVector3 he (halfExtents[0],halfExtents[1],halfExtents[2]);
- he = he.absolute();
-
+ objprop->m_boundobject.box.m_extends[1],
+ objprop->m_boundobject.box.m_extends[2]);
- bm = new btBoxShape(he);
- bm->calculateLocalInertia(ci.m_mass,ci.m_localInertiaTensor);
+ shapeInfo->m_halfExtend /= 2.0;
+ shapeInfo->m_halfExtend = shapeInfo->m_halfExtend.absolute();
+ shapeInfo->m_shapeType = PHY_SHAPE_BOX;
+ bm = shapeInfo->CreateBulletShape();
break;
};
case KX_BOUNDCYLINDER:
{
- btVector3 halfExtents (
+ shapeInfo->m_halfExtend.setValue(
objprop->m_boundobject.c.m_radius,
objprop->m_boundobject.c.m_radius,
objprop->m_boundobject.c.m_height * 0.5f
);
- bm = new btCylinderShapeZ(halfExtents);
- bm->calculateLocalInertia(ci.m_mass,ci.m_localInertiaTensor);
-
+ shapeInfo->m_shapeType = PHY_SHAPE_CYLINDER;
+ bm = shapeInfo->CreateBulletShape();
break;
}
- case KX_BOUNDCONE:
+ case KX_BOUNDCONE:
{
- btVector3 halfExtents (objprop->m_boundobject.box.m_extends[0],
- objprop->m_boundobject.box.m_extends[1],
- objprop->m_boundobject.box.m_extends[2]);
-
-
- halfExtents /= 2.f;
-
- bm = new btConeShapeZ(objprop->m_boundobject.c.m_radius,objprop->m_boundobject.c.m_height);
- bm->calculateLocalInertia(ci.m_mass,ci.m_localInertiaTensor);
-
+ shapeInfo->m_radius = objprop->m_boundobject.c.m_radius;
+ shapeInfo->m_height = objprop->m_boundobject.c.m_height;
+ shapeInfo->m_shapeType = PHY_SHAPE_CONE;
+ bm = shapeInfo->CreateBulletShape();
break;
}
- case KX_BOUNDPOLYTOPE:
- {
- bm = CreateBulletShapeFromMesh(meshobj,true);
- if (bm)
+ case KX_BOUNDPOLYTOPE:
+ {
+ shapeInfo->SetMesh(meshobj, true,false);
+ bm = shapeInfo->CreateBulletShape();
+ break;
+ }
+ case KX_BOUNDMESH:
+ {
+
+ if (!ci.m_mass ||objprop->m_softbody)
+ {
+ // mesh shapes can be shared, check first if we already have a shape on that mesh
+ class CcdShapeConstructionInfo *sharedShapeInfo = CcdShapeConstructionInfo::FindMesh(meshobj, false);
+ if (sharedShapeInfo != NULL)
{
- bm->calculateLocalInertia(ci.m_mass,ci.m_localInertiaTensor);
- }
- break;
- }
- case KX_BOUNDMESH:
- {
- if (!ci.m_mass)
- {
- bm = CreateBulletShapeFromMesh(meshobj,false);
- ci.m_localInertiaTensor.setValue(0.f,0.f,0.f);
- //no moving concave meshes, so don't bother calculating inertia
- //bm->calculateLocalInertia(ci.m_mass,ci.m_localInertiaTensor);
+ delete shapeInfo;
+ shapeInfo = sharedShapeInfo;
+ shapeInfo->AddRef();
+ } else
+ {
+ shapeInfo->SetMesh(meshobj, false,false);
}
+ if (objprop->m_softbody)
+ shapeInfo->setVertexWeldingThreshold(0.01f); //todo: expose this to the UI
- break;
- }
-
- default:
- //interpret the shape as a concave triangle-mesh
- {
- if (meshobj)
+ bm = shapeInfo->CreateBulletShape();
+ //no moving concave meshes, so don't bother calculating inertia
+ //bm->calculateLocalInertia(ci.m_mass,ci.m_localInertiaTensor);
+ } else
{
- bm = CreateBulletShapeFromMesh(meshobj,false);
- ci.m_localInertiaTensor.setValue(0.f,0.f,0.f);
-
- // assert(0);
-
- /*
- meshobj->ScheduleCollisionPolygons();
-
- KX_DeformableMesh* gfxmesh = new KX_DeformableMesh(meshobj);
- gfxmesh->sendFixedMapping();
- //trianglemesh
- bm = new TriangleMeshInterface(gfxmesh,trans);
- */
+ shapeInfo->SetMesh(meshobj, false,true);
+ bm = shapeInfo->CreateBulletShape();
}
+
+ break;
}
}
@@ -1018,10 +901,13 @@ void KX_ConvertBulletObject( class KX_GameObject* gameobj,
// ci.m_localInertiaTensor.setValue(0.1f,0.1f,0.1f);
if (!bm)
+ {
+ delete motionstate;
+ delete shapeInfo;
return;
+ }
- bm->setMargin(0.06);
-
+ bm->setMargin(ci.m_margin);
if (objprop->m_isCompoundChild)
@@ -1030,30 +916,46 @@ void KX_ConvertBulletObject( class KX_GameObject* gameobj,
//take relative transform into account!
KX_BulletPhysicsController* parentCtrl = (KX_BulletPhysicsController*)objprop->m_dynamic_parent->GetPhysicsController();
assert(parentCtrl);
+ CcdShapeConstructionInfo* parentShapeInfo = parentCtrl->GetShapeInfo();
btRigidBody* rigidbody = parentCtrl->GetRigidBody();
btCollisionShape* colShape = rigidbody->getCollisionShape();
assert(colShape->isCompound());
btCompoundShape* compoundShape = (btCompoundShape*)colShape;
- btTransform childTrans;
- childTrans.setIdentity();
- NodeList& children = objprop->m_dynamic_parent->GetSGNode()->GetSGChildren();
- MT_Point3 childPos = gameobj->GetSGNode()->GetLocalPosition();
- MT_Matrix3x3 childRot = gameobj->GetSGNode()->GetLocalOrientation();
- MT_Vector3 childScale = gameobj->GetSGNode()->GetLocalScale();
+ // compute the local transform from parent, this may include a parent inverse node
+ SG_Node* gameNode = gameobj->GetSGNode();
+ SG_Node* parentInverseNode = gameNode->GetSGParent();
+ if (parentInverseNode && parentInverseNode->GetSGClientObject() != NULL)
+ // this is not a parent inverse node, cancel it
+ parentInverseNode = NULL;
+ // now combine the parent inverse node and the game node
+ MT_Point3 childPos = gameNode->GetLocalPosition();
+ MT_Matrix3x3 childRot = gameNode->GetLocalOrientation();
+ MT_Vector3 childScale = gameNode->GetLocalScale();
+ if (parentInverseNode)
+ {
+ const MT_Point3& parentInversePos = parentInverseNode->GetLocalPosition();
+ const MT_Matrix3x3& parentInverseRot = parentInverseNode->GetLocalOrientation();
+ const MT_Vector3& parentInverseScale = parentInverseNode->GetLocalScale();
+ childRot = parentInverseRot * childRot;
+ childScale = parentInverseScale * childScale;
+ childPos = parentInversePos+parentInverseScale*(parentInverseRot*childPos);
+ }
- bm->setLocalScaling(btVector3(childScale.x(),childScale.y(),childScale.z()));
- childTrans.setOrigin(btVector3(childPos.x(),childPos.y(),childPos.z()));
+ shapeInfo->m_childScale.setValue(childScale.x(),childScale.y(),childScale.z());
+ bm->setLocalScaling(shapeInfo->m_childScale);
+
+ shapeInfo->m_childTrans.setOrigin(btVector3(childPos.x(),childPos.y(),childPos.z()));
float rotval[12];
childRot.getValue(rotval);
btMatrix3x3 newRot;
newRot.setValue(rotval[0],rotval[1],rotval[2],rotval[4],rotval[5],rotval[6],rotval[8],rotval[9],rotval[10]);
newRot = newRot.transpose();
- childTrans.setBasis(newRot);
-
-
- compoundShape->addChildShape(childTrans,bm);
+ shapeInfo->m_childTrans.setBasis(newRot);
+ parentShapeInfo->AddShape(shapeInfo);
+
+ compoundShape->addChildShape(shapeInfo->m_childTrans,bm);
//do some recalc?
//recalc inertia for rigidbody
if (!rigidbody->isStaticOrKinematicObject())
@@ -1068,12 +970,16 @@ void KX_ConvertBulletObject( class KX_GameObject* gameobj,
if (objprop->m_hasCompoundChildren)
{
- //replace shape by compoundShape
+ // create a compound shape info
+ CcdShapeConstructionInfo *compoundShapeInfo = new CcdShapeConstructionInfo();
+ compoundShapeInfo->m_shapeType = PHY_SHAPE_COMPOUND;
+ compoundShapeInfo->AddShape(shapeInfo);
+ // create the compound shape manually as we already have the child shape
btCompoundShape* compoundShape = new btCompoundShape();
- btTransform identTrans;
- identTrans.setIdentity();
- compoundShape->addChildShape(identTrans,bm);
+ compoundShape->addChildShape(shapeInfo->m_childTrans,bm);
+ // now replace the shape
bm = compoundShape;
+ shapeInfo = compoundShapeInfo;
}
@@ -1109,9 +1015,7 @@ void KX_ConvertBulletObject( class KX_GameObject* gameobj,
ci.m_collisionShape = bm;
-
-
-
+ ci.m_shapeInfo = shapeInfo;
ci.m_friction = smmaterial->m_friction;//tweak the friction a bit, so the default 0.5 works nice
ci.m_restitution = smmaterial->m_restitution;
ci.m_physicsEnv = env;
@@ -1121,7 +1025,69 @@ void KX_ConvertBulletObject( class KX_GameObject* gameobj,
//need a bit of damping, else system doesn't behave well
ci.m_inertiaFactor = shapeprops->m_inertia/0.4f;//defaults to 0.4, don't want to change behaviour
+ ci.m_do_anisotropic = shapeprops->m_do_anisotropic;
+ ci.m_anisotropicFriction.setValue(shapeprops->m_friction_scaling[0],shapeprops->m_friction_scaling[1],shapeprops->m_friction_scaling[2]);
+
+
+//////////
+ //do Fh, do Rot Fh
+ ci.m_do_fh = shapeprops->m_do_fh;
+ ci.m_do_rot_fh = shapeprops->m_do_rot_fh ;
+ ci.m_fh_damping = smmaterial->m_fh_damping;
+ ci.m_fh_distance = smmaterial->m_fh_distance;
+ ci.m_fh_normal = smmaterial->m_fh_normal;
+ ci.m_fh_spring = smmaterial->m_fh_spring;
+ ci.m_radius = objprop->m_radius;
+
+
+ ///////////////////
+ ci.m_gamesoftFlag = objprop->m_gamesoftFlag;
+ ci.m_soft_linStiff = objprop->m_soft_linStiff;
+ ci.m_soft_angStiff = objprop->m_soft_angStiff; /* angular stiffness 0..1 */
+ ci.m_soft_volume= objprop->m_soft_volume; /* volume preservation 0..1 */
+
+ ci.m_soft_viterations= objprop->m_soft_viterations; /* Velocities solver iterations */
+ ci.m_soft_piterations= objprop->m_soft_piterations; /* Positions solver iterations */
+ ci.m_soft_diterations= objprop->m_soft_diterations; /* Drift solver iterations */
+ ci.m_soft_citerations= objprop->m_soft_citerations; /* Cluster solver iterations */
+
+ ci.m_soft_kSRHR_CL= objprop->m_soft_kSRHR_CL; /* Soft vs rigid hardness [0,1] (cluster only) */
+ ci.m_soft_kSKHR_CL= objprop->m_soft_kSKHR_CL; /* Soft vs kinetic hardness [0,1] (cluster only) */
+ ci.m_soft_kSSHR_CL= objprop->m_soft_kSSHR_CL; /* Soft vs soft hardness [0,1] (cluster only) */
+ ci.m_soft_kSR_SPLT_CL= objprop->m_soft_kSR_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
+
+ ci.m_soft_kSK_SPLT_CL= objprop->m_soft_kSK_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
+ ci.m_soft_kSS_SPLT_CL= objprop->m_soft_kSS_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
+ ci.m_soft_kVCF= objprop->m_soft_kVCF; /* Velocities correction factor (Baumgarte) */
+ ci.m_soft_kDP= objprop->m_soft_kDP; /* Damping coefficient [0,1] */
+
+ ci.m_soft_kDG= objprop->m_soft_kDG; /* Drag coefficient [0,+inf] */
+ ci.m_soft_kLF= objprop->m_soft_kLF; /* Lift coefficient [0,+inf] */
+ ci.m_soft_kPR= objprop->m_soft_kPR; /* Pressure coefficient [-inf,+inf] */
+ ci.m_soft_kVC= objprop->m_soft_kVC; /* Volume conversation coefficient [0,+inf] */
+
+ ci.m_soft_kDF= objprop->m_soft_kDF; /* Dynamic friction coefficient [0,1] */
+ ci.m_soft_kMT= objprop->m_soft_kMT; /* Pose matching coefficient [0,1] */
+ ci.m_soft_kCHR= objprop->m_soft_kCHR; /* Rigid contacts hardness [0,1] */
+ ci.m_soft_kKHR= objprop->m_soft_kKHR; /* Kinetic contacts hardness [0,1] */
+
+ ci.m_soft_kSHR= objprop->m_soft_kSHR; /* Soft contacts hardness [0,1] */
+ ci.m_soft_kAHR= objprop->m_soft_kAHR; /* Anchors hardness [0,1] */
+ ci.m_soft_collisionflags= objprop->m_soft_collisionflags; /* Vertex/Face or Signed Distance Field(SDF) or Clusters, Soft versus Soft or Rigid */
+ ci.m_soft_numclusteriterations= objprop->m_soft_numclusteriterations; /* number of iterations to refine collision clusters*/
+
+ ////////////////////
+
+ ci.m_collisionFilterGroup = (isbulletdyna) ? short(CcdConstructionInfo::DefaultFilter) : short(CcdConstructionInfo::StaticFilter);
+ ci.m_collisionFilterMask = (isbulletdyna) ? short(CcdConstructionInfo::AllFilter) : short(CcdConstructionInfo::AllFilter ^ CcdConstructionInfo::StaticFilter);
+ ci.m_bRigid = objprop->m_dyna && objprop->m_angular_rigidbody;
+ ci.m_bSoft = objprop->m_softbody;
+ MT_Vector3 scaling = gameobj->NodeGetWorldScaling();
+ ci.m_scaling.setValue(scaling[0], scaling[1], scaling[2]);
KX_BulletPhysicsController* physicscontroller = new KX_BulletPhysicsController(ci,isbulletdyna);
+ // shapeInfo is reference counted, decrement now as we don't use it anymore
+ if (shapeInfo)
+ shapeInfo->Release();
if (objprop->m_in_active_layer)
{
@@ -1132,15 +1098,23 @@ void KX_ConvertBulletObject( class KX_GameObject* gameobj,
gameobj->SetPhysicsController(physicscontroller,isbulletdyna);
physicscontroller->setNewClientInfo(gameobj->getClientInfo());
- btRigidBody* rbody = physicscontroller->GetRigidBody();
-
- if (objprop->m_disableSleeping)
- rbody->setActivationState(DISABLE_DEACTIVATION);
-
- if (objprop->m_ghost)
{
- rbody->setCollisionFlags(rbody->getCollisionFlags() | btCollisionObject::CF_NO_CONTACT_RESPONSE);
+ btRigidBody* rbody = physicscontroller->GetRigidBody();
+
+ if (rbody && objprop->m_disableSleeping)
+ rbody->setActivationState(DISABLE_DEACTIVATION);
}
+
+ CcdPhysicsController* parentCtrl = objprop->m_dynamic_parent ? (KX_BulletPhysicsController*)objprop->m_dynamic_parent->GetPhysicsController() : 0;
+ physicscontroller->setParentCtrl(parentCtrl);
+
+
+ //Now done directly in ci.m_collisionFlags so that it propagates to replica
+ //if (objprop->m_ghost)
+ //{
+ // rbody->setCollisionFlags(rbody->getCollisionFlags() | btCollisionObject::CF_NO_CONTACT_RESPONSE);
+ //}
+
if (objprop->m_dyna && !objprop->m_angular_rigidbody)
{
/*
@@ -1155,8 +1129,10 @@ void KX_ConvertBulletObject( class KX_GameObject* gameobj,
*/
//env->createConstraint(physicscontroller,0,PHY_ANGULAR_CONSTRAINT,0,0,0,0,0,1);
- physicscontroller->GetRigidBody()->setAngularFactor(0.f);
-
+
+ //Now done directly in ci.m_bRigid so that it propagates to replica
+ //physicscontroller->GetRigidBody()->setAngularFactor(0.f);
+ ;
}
bool isActor = objprop->m_isactor;
@@ -1180,22 +1156,25 @@ void KX_ConvertBulletObject( class KX_GameObject* gameobj,
physicscontroller->SetObject(gameobj->GetSGNode());
+
+ ///test for soft bodies
+ if (objprop->m_softbody && physicscontroller)
+ {
+ btSoftBody* softBody = physicscontroller->GetSoftBody();
+ if (softBody && gameobj->GetMesh(0))//only the first mesh, if any
+ {
+ //should be a mesh then, so add a soft body deformer
+ KX_SoftBodyDeformer* softbodyDeformer = new KX_SoftBodyDeformer( gameobj->GetMesh(0),gameobj);
+ gameobj->SetDeformer(softbodyDeformer);
+
+ }
+ }
+
}
void KX_ClearBulletSharedShapes()
{
- int numshapes = map_gamemesh_to_bulletshape.size();
- int i;
- btCollisionShape*shape=0;
- for (i=0;i<numshapes ;i++)
- {
- shape = *map_gamemesh_to_bulletshape.at(i);
- //delete shape;
- }
-
- map_gamemesh_to_bulletshape.clear();
-
}
#endif
diff --git a/source/gameengine/Ketsji/KX_GameActuator.cpp b/source/gameengine/Ketsji/KX_GameActuator.cpp
index fcd32d5f4fe..76459e46731 100644
--- a/source/gameengine/Ketsji/KX_GameActuator.cpp
+++ b/source/gameengine/Ketsji/KX_GameActuator.cpp
@@ -34,6 +34,7 @@
//#include <iostream>
#include "KX_Scene.h"
#include "KX_KetsjiEngine.h"
+#include "KX_PythonInit.h" /* for config load/saving */
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -125,6 +126,71 @@ bool KX_GameActuator::Update()
}
break;
}
+ case KX_GAME_SAVECFG:
+ {
+ if (m_ketsjiengine)
+ {
+ char mashal_path[512];
+ char *marshal_buffer = NULL;
+ int marshal_length;
+ FILE *fp = NULL;
+
+ pathGamePythonConfig(mashal_path);
+ marshal_length = saveGamePythonConfig(&marshal_buffer);
+
+ if (marshal_length && marshal_buffer) {
+ fp = fopen(mashal_path, "wb");
+ if (fp) {
+ if (fwrite(marshal_buffer, 1, marshal_length, fp) != marshal_length) {
+ printf("Warning: could not write marshal data\n");
+ }
+ fclose(fp);
+ } else {
+ printf("Warning: could not open marshal file\n");
+ }
+ } else {
+ printf("Warning: could not create marshal buffer\n");
+ }
+ }
+ break;
+ }
+ case KX_GAME_LOADCFG:
+ {
+ if (m_ketsjiengine)
+ {
+ char mashal_path[512];
+ char *marshal_buffer;
+ int marshal_length;
+ FILE *fp = NULL;
+ int result;
+
+ pathGamePythonConfig(mashal_path);
+
+ fp = fopen(mashal_path, "rb");
+ if (fp) {
+ // obtain file size:
+ fseek (fp , 0 , SEEK_END);
+ marshal_length = ftell(fp);
+ rewind(fp);
+
+ marshal_buffer = (char*) malloc (sizeof(char)*marshal_length);
+
+ result = fread (marshal_buffer, 1, marshal_length, fp);
+
+ if (result == marshal_length) {
+ loadGamePythonConfig(marshal_buffer, marshal_length);
+ } else {
+ printf("warning: could not read all of '%s'\n", mashal_path);
+ }
+
+ free(marshal_buffer);
+ fclose(fp);
+ } else {
+ printf("warning: could not open '%s'\n", mashal_path);
+ }
+ }
+ break;
+ }
default:
; /* do nothing? this is an internal error !!! */
}
@@ -175,13 +241,13 @@ PyParentObject KX_GameActuator::Parents[] =
PyMethodDef KX_GameActuator::Methods[] =
{
- {"getFile", (PyCFunction) KX_GameActuator::sPyGetFile, METH_VARARGS, GetFile_doc},
- {"setFile", (PyCFunction) KX_GameActuator::sPySetFile, METH_VARARGS, SetFile_doc},
+ {"getFile", (PyCFunction) KX_GameActuator::sPyGetFile, METH_VARARGS, (PY_METHODCHAR)GetFile_doc},
+ {"setFile", (PyCFunction) KX_GameActuator::sPySetFile, METH_VARARGS, (PY_METHODCHAR)SetFile_doc},
{NULL,NULL} //Sentinel
};
/* getFile */
-char KX_GameActuator::GetFile_doc[] =
+const char KX_GameActuator::GetFile_doc[] =
"getFile()\n"
"get the name of the file to start.\n";
PyObject* KX_GameActuator::PyGetFile(PyObject* self, PyObject* args, PyObject* kwds)
@@ -190,7 +256,7 @@ PyObject* KX_GameActuator::PyGetFile(PyObject* self, PyObject* args, PyObject* k
}
/* setFile */
-char KX_GameActuator::SetFile_doc[] =
+const char KX_GameActuator::SetFile_doc[] =
"setFile(name)\n"
"set the name of the file to start.\n";
PyObject* KX_GameActuator::PySetFile(PyObject* self, PyObject* args, PyObject* kwds)
diff --git a/source/gameengine/Ketsji/KX_GameActuator.h b/source/gameengine/Ketsji/KX_GameActuator.h
index 8565dc46caa..bb3448995dc 100644
--- a/source/gameengine/Ketsji/KX_GameActuator.h
+++ b/source/gameengine/Ketsji/KX_GameActuator.h
@@ -54,6 +54,8 @@ protected:
KX_GAME_START,
KX_GAME_RESTART,
KX_GAME_QUIT,
+ KX_GAME_SAVECFG,
+ KX_GAME_LOADCFG,
KX_GAME_MAX
};
diff --git a/source/gameengine/Ketsji/KX_GameObject.cpp b/source/gameengine/Ketsji/KX_GameObject.cpp
index 1cb64585ff8..a168beb9a70 100644
--- a/source/gameengine/Ketsji/KX_GameObject.cpp
+++ b/source/gameengine/Ketsji/KX_GameObject.cpp
@@ -51,6 +51,7 @@ typedef unsigned long uint_ptr;
#include "KX_GameObject.h"
#include "RAS_MeshObject.h"
#include "KX_MeshProxy.h"
+#include "KX_PolyProxy.h"
#include <stdio.h> // printf
#include "SG_Controller.h"
#include "KX_IPhysicsController.h"
@@ -58,8 +59,13 @@ typedef unsigned long uint_ptr;
#include "SG_Controller.h"
#include "KX_ClientObjectInfo.h"
#include "RAS_BucketManager.h"
-
+#include "KX_RayCast.h"
+#include "KX_PythonInit.h"
#include "KX_PyMath.h"
+#include "SCA_IActuator.h"
+#include "SCA_ISensor.h"
+
+#include "PyObjectPlus.h" /* python stuff */
// This file defines relationships between parents and children
// in the game engine.
@@ -73,36 +79,56 @@ KX_GameObject::KX_GameObject(
) :
SCA_IObject(T),
m_bDyna(false),
+ m_layer(0),
+ m_pBlenderObject(NULL),
+ m_pBlenderGroupObject(NULL),
m_bSuspendDynamics(false),
m_bUseObjectColor(false),
+ m_bIsNegativeScaling(false),
m_bVisible(true),
+ m_bCulled(true),
m_pPhysicsController1(NULL),
+ m_pPhysicsEnvironment(NULL),
+ m_xray(false),
+ m_pHitObject(NULL),
m_isDeformable(false)
{
m_ignore_activity_culling = false;
m_pClient_info = new KX_ClientObjectInfo(this, KX_ClientObjectInfo::ACTOR);
m_pSGNode = new SG_Node(this,sgReplicationInfo,callbacks);
-
+
// define the relationship between this node and it's parent.
KX_NormalParentRelation * parent_relation =
KX_NormalParentRelation::New();
m_pSGNode->SetParentRelation(parent_relation);
-
-
};
KX_GameObject::~KX_GameObject()
{
+ RemoveMeshes();
+
// is this delete somewhere ?
//if (m_sumoObj)
// delete m_sumoObj;
delete m_pClient_info;
//if (m_pSGNode)
// delete m_pSGNode;
-
+ if (m_pSGNode)
+ {
+ // must go through controllers and make sure they will not use us anymore
+ // This is important for KX_BulletPhysicsControllers that unregister themselves
+ // from the object when they are deleted.
+ SGControllerList::iterator contit;
+ SGControllerList& controllers = m_pSGNode->GetSGControllerList();
+ for (contit = controllers.begin();contit!=controllers.end();++contit)
+ {
+ (*contit)->ClearObject();
+ }
+ m_pSGNode->SetSGClientObject(NULL);
+ }
}
@@ -186,7 +212,73 @@ KX_GameObject* KX_GameObject::GetParent()
}
+void KX_GameObject::SetParent(KX_Scene *scene, KX_GameObject* obj)
+{
+ // check on valid node in case a python controller holds a reference to a deleted object
+ if (obj && GetSGNode() && obj->GetSGNode() && GetSGNode()->GetSGParent() != obj->GetSGNode())
+ {
+ // Make sure the objects have some scale
+ MT_Vector3 scale1 = NodeGetWorldScaling();
+ MT_Vector3 scale2 = obj->NodeGetWorldScaling();
+ if (fabs(scale2[0]) < FLT_EPSILON ||
+ fabs(scale2[1]) < FLT_EPSILON ||
+ fabs(scale2[2]) < FLT_EPSILON ||
+ fabs(scale1[0]) < FLT_EPSILON ||
+ fabs(scale1[1]) < FLT_EPSILON ||
+ fabs(scale1[2]) < FLT_EPSILON) { return; }
+
+ // Remove us from our old parent and set our new parent
+ RemoveParent(scene);
+ obj->GetSGNode()->AddChild(GetSGNode());
+
+ if (m_pPhysicsController1)
+ {
+ m_pPhysicsController1->SuspendDynamics(true);
+ }
+ // Set us to our new scale, position, and orientation
+ scale2[0] = 1.0/scale2[0];
+ scale2[1] = 1.0/scale2[1];
+ scale2[2] = 1.0/scale2[2];
+ scale1 = scale1 * scale2;
+ MT_Matrix3x3 invori = obj->NodeGetWorldOrientation().inverse();
+ MT_Vector3 newpos = invori*(NodeGetWorldPosition()-obj->NodeGetWorldPosition())*scale2;
+
+ NodeSetLocalScale(scale1);
+ NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
+ NodeSetLocalOrientation(invori*NodeGetWorldOrientation());
+ NodeUpdateGS(0.f,true);
+ // object will now be a child, it must be removed from the parent list
+ CListValue* rootlist = scene->GetRootParentList();
+ if (rootlist->RemoveValue(this))
+ // the object was in parent list, decrement ref count as it's now removed
+ Release();
+ }
+}
+
+void KX_GameObject::RemoveParent(KX_Scene *scene)
+{
+ // check on valid node in case a python controller holds a reference to a deleted object
+ if (GetSGNode() && GetSGNode()->GetSGParent())
+ {
+ // Set us to the right spot
+ GetSGNode()->SetLocalScale(GetSGNode()->GetWorldScaling());
+ GetSGNode()->SetLocalOrientation(GetSGNode()->GetWorldOrientation());
+ GetSGNode()->SetLocalPosition(GetSGNode()->GetWorldPosition());
+ // Remove us from our parent
+ GetSGNode()->DisconnectFromParent();
+ NodeUpdateGS(0.f,true);
+ // the object is now a root object, add it to the parentlist
+ CListValue* rootlist = scene->GetRootParentList();
+ if (!rootlist->SearchValue(this))
+ // object was not in root list, add it now and increment ref count
+ rootlist->Add(AddRef());
+ if (m_pPhysicsController1)
+ {
+ m_pPhysicsController1->RestoreDynamics();
+ }
+ }
+}
void KX_GameObject::ProcessReplica(KX_GameObject* replica)
{
@@ -194,6 +286,7 @@ void KX_GameObject::ProcessReplica(KX_GameObject* replica)
replica->m_pSGNode = NULL;
replica->m_pClient_info = new KX_ClientObjectInfo(*m_pClient_info);
replica->m_pClient_info->m_gameobject = replica;
+ replica->m_state = 0;
}
@@ -201,11 +294,11 @@ void KX_GameObject::ProcessReplica(KX_GameObject* replica)
CValue* KX_GameObject::GetReplica()
{
KX_GameObject* replica = new KX_GameObject(*this);
-
+
// this will copy properties and so on...
CValue::AddDataToReplica(replica);
ProcessReplica(replica);
-
+
return replica;
}
@@ -241,12 +334,12 @@ void KX_GameObject::ApplyMovement(const MT_Vector3& dloc,bool local)
void KX_GameObject::ApplyRotation(const MT_Vector3& drot,bool local)
{
MT_Matrix3x3 rotmat(drot);
- rotmat.transpose();
-
- if (m_pPhysicsController1) // (IsDynamic())
- m_pPhysicsController1->RelativeRotate(rotmat,local);
- // in worldspace
+
GetSGNode()->RelativeRotate(rotmat,local);
+
+ if (m_pPhysicsController1) { // (IsDynamic())
+ m_pPhysicsController1->RelativeRotate(rotmat,local);
+ }
}
@@ -264,31 +357,54 @@ double* KX_GameObject::GetOpenGLMatrix()
trans.setBasis(GetSGNode()->GetWorldOrientation());
MT_Vector3 scaling = GetSGNode()->GetWorldScaling();
-
+ m_bIsNegativeScaling = ((scaling[0] < 0.0) ^ (scaling[1] < 0.0) ^ (scaling[2] < 0.0)) ? true : false;
trans.scale(scaling[0], scaling[1], scaling[2]);
trans.getValue(fl);
return fl;
}
+void KX_GameObject::AddMeshUser()
+{
+ for (size_t i=0;i<m_meshes.size();i++)
+ m_meshes[i]->AddMeshUser(this);
+
+ UpdateBuckets(false);
+}
+
+static void UpdateBuckets_recursive(SG_Node* node)
+{
+ NodeList& children = node->GetSGChildren();
+ for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
+ {
+ SG_Node* childnode = (*childit);
+ KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
+ if (clientgameobj != NULL) // This is a GameObject
+ clientgameobj->UpdateBuckets(0);
+
+ // if the childobj is NULL then this may be an inverse parent link
+ // so a non recursive search should still look down this node.
+ UpdateBuckets_recursive(childnode);
+ }
+}
-void KX_GameObject::Bucketize()
+void KX_GameObject::UpdateBuckets( bool recursive )
{
double* fl = GetOpenGLMatrix();
for (size_t i=0;i<m_meshes.size();i++)
- m_meshes[i]->Bucketize(fl, this, m_bUseObjectColor, m_objectColor);
+ m_meshes[i]->UpdateBuckets(this, fl, m_bUseObjectColor, m_objectColor, m_bVisible, m_bCulled);
+
+ if (recursive) {
+ UpdateBuckets_recursive(m_pSGNode);
+ }
}
-
-
void KX_GameObject::RemoveMeshes()
{
- double* fl = GetOpenGLMatrix();
-
for (size_t i=0;i<m_meshes.size();i++)
- m_meshes[i]->RemoveFromBuckets(fl, this);
+ m_meshes[i]->RemoveFromBuckets(this);
//note: meshes can be shared, and are deleted by KX_BlenderSceneConverter
@@ -332,34 +448,25 @@ void KX_GameObject::ResetDebugColor()
SetDebugColor(0xff000000);
}
+void KX_GameObject::InitIPO(bool ipo_as_force,
+ bool ipo_add,
+ bool ipo_local)
+{
+ SGControllerList::iterator it = GetSGNode()->GetSGControllerList().begin();
+ while (it != GetSGNode()->GetSGControllerList().end()) {
+ (*it)->SetOption(SG_Controller::SG_CONTR_IPO_RESET, true);
+ (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_AS_FORCE, ipo_as_force);
+ (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_ADD, ipo_add);
+ (*it)->SetOption(SG_Controller::SG_CONTR_IPO_LOCAL, ipo_local);
+ it++;
+ }
+}
void KX_GameObject::UpdateIPO(float curframetime,
- bool recurse,
- bool ipo_as_force,
- bool force_local)
+ bool recurse)
{
-
- // The ipo-actuator needs a sumo reference... this is retrieved (unfortunately)
- // by the iposgcontr itself...
-// ipocontr->SetSumoReference(gameobj->GetSumoScene(),
-// gameobj->GetSumoObject());
-
-
- // The ipo has to be treated as a force, and not a displacement!
- // For this case, we send some settings to the controller. This
- // may need some caching...
- if (ipo_as_force) {
- SGControllerList::iterator it = GetSGNode()->GetSGControllerList().begin();
-
- while (it != GetSGNode()->GetSGControllerList().end()) {
- (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_AS_FORCE, ipo_as_force);
- (*it)->SetOption(SG_Controller::SG_CONTR_IPO_FORCES_ACT_LOCAL, force_local);
- it++;
- }
- }
-
- // The rest is the 'normal' update procedure.
+ // just the 'normal' update procedure.
GetSGNode()->SetSimulatedTime(curframetime,recurse);
GetSGNode()->UpdateWorldData(curframetime);
UpdateTransform();
@@ -368,6 +475,7 @@ void KX_GameObject::UpdateIPO(float curframetime,
// IPO update
void
KX_GameObject::UpdateMaterialData(
+ dword matname_hash,
MT_Vector4 rgba,
MT_Vector3 specrgb,
MT_Scalar hard,
@@ -380,15 +488,34 @@ KX_GameObject::UpdateMaterialData(
{
int mesh = 0;
if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0) {
- RAS_MaterialBucket::Set::iterator mit = m_meshes[mesh]->GetFirstMaterial();
+ list<RAS_MeshMaterial>::iterator mit = m_meshes[mesh]->GetFirstMaterial();
+
for(; mit != m_meshes[mesh]->GetLastMaterial(); ++mit)
{
- RAS_IPolyMaterial* poly = (*mit)->GetPolyMaterial();
+ RAS_IPolyMaterial* poly = mit->m_bucket->GetPolyMaterial();
+
if(poly->GetFlag() & RAS_BLENDERMAT )
{
- SetObjectColor(rgba);
KX_BlenderMaterial *m = static_cast<KX_BlenderMaterial*>(poly);
- m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha);
+
+ if (matname_hash == NULL)
+ {
+ m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha);
+ // if mesh has only one material attached to it then use original hack with no need to edit vertices (better performance)
+ SetObjectColor(rgba);
+ }
+ else
+ {
+ if (matname_hash == poly->GetMaterialNameHash())
+ {
+ m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha);
+ m_meshes[mesh]->SetVertexColor(poly,rgba);
+
+ // no break here, because one blender material can be split into several game engine materials
+ // (e.g. one uvsphere material is split into one material at poles with ras_mode TRIANGLE and one material for the body
+ // if here was a break then would miss some vertices if material was split
+ }
+ }
}
}
}
@@ -401,56 +528,75 @@ KX_GameObject::GetVisible(
return m_bVisible;
}
+static void setVisible_recursive(SG_Node* node, bool v)
+{
+ NodeList& children = node->GetSGChildren();
+
+ for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
+ {
+ SG_Node* childnode = (*childit);
+ KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
+ if (clientgameobj != NULL) // This is a GameObject
+ clientgameobj->SetVisible(v, 0);
+
+ // if the childobj is NULL then this may be an inverse parent link
+ // so a non recursive search should still look down this node.
+ setVisible_recursive(childnode, v);
+ }
+}
+
+
void
KX_GameObject::SetVisible(
- bool v
+ bool v,
+ bool recursive
)
{
m_bVisible = v;
+ if (recursive)
+ setVisible_recursive(m_pSGNode, v);
}
-// used by Python, and the actuatorshould _not_ be misused by the
-// scene!
-void
-KX_GameObject::MarkVisible(
- bool visible
+bool
+KX_GameObject::GetCulled(
+ void
)
{
- /* If explicit visibility settings are used, this is
- * determined on this level. Maybe change this to mesh level
- * later on? */
-
- double* fl = GetOpenGLMatrixPtr()->getPointer();
- for (size_t i=0;i<m_meshes.size();i++)
- {
- m_meshes[i]->MarkVisible(fl,this,visible,m_bUseObjectColor,m_objectColor);
- }
+ return m_bCulled;
}
+void
+KX_GameObject::SetCulled(
+ bool c
+ )
+{
+ m_bCulled = c;
+}
-// Always use the flag?
-void
-KX_GameObject::MarkVisible(
- void
+
+void
+KX_GameObject::SetLayer(
+ int l
)
{
- double* fl = GetOpenGLMatrixPtr()->getPointer();
- for (size_t i=0;i<m_meshes.size();i++)
- {
- m_meshes[i]->MarkVisible(fl,
- this,
- m_bVisible,
- m_bUseObjectColor,
- m_objectColor
- );
- }
+ m_layer = l;
}
+int
+KX_GameObject::GetLayer(
+ void
+ )
+{
+ return m_layer;
+}
void KX_GameObject::addLinearVelocity(const MT_Vector3& lin_vel,bool local)
{
- if (m_pPhysicsController1)
- m_pPhysicsController1->SetLinearVelocity(lin_vel + m_pPhysicsController1->GetLinearVelocity(),local);
+ if (m_pPhysicsController1)
+ {
+ MT_Vector3 lv = local ? NodeGetWorldOrientation() * lin_vel : lin_vel;
+ m_pPhysicsController1->SetLinearVelocity(lv + m_pPhysicsController1->GetLinearVelocity(), 0);
+ }
}
@@ -492,62 +638,205 @@ void KX_GameObject::SetObjectColor(const MT_Vector4& rgbavec)
m_objectColor = rgbavec;
}
+void KX_GameObject::AlignAxisToVect(const MT_Vector3& dir, int axis, float fac)
+{
+ MT_Matrix3x3 orimat;
+ MT_Vector3 vect,ori,z,x,y;
+ MT_Scalar len;
+ // check on valid node in case a python controller holds a reference to a deleted object
+ if (!GetSGNode())
+ return;
-MT_Vector3 KX_GameObject::GetLinearVelocity()
-{
- MT_Vector3 velocity(0.0,0.0,0.0);
+ vect = dir;
+ len = vect.length();
+ if (MT_fuzzyZero(len))
+ {
+ cout << "alignAxisToVect() Error: Null vector!\n";
+ return;
+ }
+
+ if (fac<=0.0) {
+ return;
+ }
+ // normalize
+ vect /= len;
+ orimat = GetSGNode()->GetWorldOrientation();
+ switch (axis)
+ {
+ case 0: //x axis
+ ori = MT_Vector3(orimat[0][2], orimat[1][2], orimat[2][2]); //pivot axis
+ if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON) //is the vector paralell to the pivot?
+ ori = MT_Vector3(orimat[0][1], orimat[1][1], orimat[2][1]); //change the pivot!
+ if (fac == 1.0) {
+ x = vect;
+ } else {
+ x = (vect * fac) + ((orimat * MT_Vector3(1.0, 0.0, 0.0)) * (1-fac));
+ len = x.length();
+ if (MT_fuzzyZero(len)) x = vect;
+ else x /= len;
+ }
+ y = ori.cross(x);
+ z = x.cross(y);
+ break;
+ case 1: //y axis
+ ori = MT_Vector3(orimat[0][0], orimat[1][0], orimat[2][0]);
+ if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON)
+ ori = MT_Vector3(orimat[0][2], orimat[1][2], orimat[2][2]);
+ if (fac == 1.0) {
+ y = vect;
+ } else {
+ y = (vect * fac) + ((orimat * MT_Vector3(0.0, 1.0, 0.0)) * (1-fac));
+ len = y.length();
+ if (MT_fuzzyZero(len)) y = vect;
+ else y /= len;
+ }
+ z = ori.cross(y);
+ x = y.cross(z);
+ break;
+ case 2: //z axis
+ ori = MT_Vector3(orimat[0][1], orimat[1][1], orimat[2][1]);
+ if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON)
+ ori = MT_Vector3(orimat[0][0], orimat[1][0], orimat[2][0]);
+ if (fac == 1.0) {
+ z = vect;
+ } else {
+ z = (vect * fac) + ((orimat * MT_Vector3(0.0, 0.0, 1.0)) * (1-fac));
+ len = z.length();
+ if (MT_fuzzyZero(len)) z = vect;
+ else z /= len;
+ }
+ x = ori.cross(z);
+ y = z.cross(x);
+ break;
+ default: //wrong input?
+ cout << "alignAxisToVect(): Wrong axis '" << axis <<"'\n";
+ return;
+ }
+ x.normalize(); //normalize the vectors
+ y.normalize();
+ z.normalize();
+ orimat = MT_Matrix3x3( x[0],y[0],z[0],
+ x[1],y[1],z[1],
+ x[2],y[2],z[2]);
+ if (GetSGNode()->GetSGParent() != NULL)
+ {
+ // the object is a child, adapt its local orientation so that
+ // the global orientation is aligned as we want.
+ MT_Matrix3x3 invori = GetSGNode()->GetSGParent()->GetWorldOrientation().inverse();
+ NodeSetLocalOrientation(invori*orimat);
+ }
+ else
+ NodeSetLocalOrientation(orimat);
+}
+
+MT_Scalar KX_GameObject::GetMass()
+{
+ if (m_pPhysicsController1)
+ {
+ return m_pPhysicsController1->GetMass();
+ }
+ return 0.0;
+}
+
+MT_Vector3 KX_GameObject::GetLinearVelocity(bool local)
+{
+ MT_Vector3 velocity(0.0,0.0,0.0), locvel;
+ MT_Matrix3x3 ori;
if (m_pPhysicsController1)
{
velocity = m_pPhysicsController1->GetLinearVelocity();
+
+ if (local)
+ {
+ ori = GetSGNode()->GetWorldOrientation();
+
+ locvel = velocity * ori;
+ return locvel;
+ }
}
- return velocity;
-
+ return velocity;
+}
+
+MT_Vector3 KX_GameObject::GetAngularVelocity(bool local)
+{
+ MT_Vector3 velocity(0.0,0.0,0.0), locvel;
+ MT_Matrix3x3 ori;
+ if (m_pPhysicsController1)
+ {
+ velocity = m_pPhysicsController1->GetAngularVelocity();
+
+ if (local)
+ {
+ ori = GetSGNode()->GetWorldOrientation();
+
+ locvel = velocity * ori;
+ return locvel;
+ }
+ }
+ return velocity;
}
+MT_Vector3 KX_GameObject::GetVelocity(const MT_Point3& point)
+{
+ if (m_pPhysicsController1)
+ {
+ return m_pPhysicsController1->GetVelocity(point);
+ }
+ return MT_Vector3(0.0,0.0,0.0);
+}
// scenegraph node stuff
void KX_GameObject::NodeSetLocalPosition(const MT_Point3& trans)
{
- if (m_pPhysicsController1)
+ // check on valid node in case a python controller holds a reference to a deleted object
+ if (!GetSGNode())
+ return;
+
+ if (m_pPhysicsController1 && !GetSGNode()->GetSGParent())
{
+ // don't update physic controller if the object is a child:
+ // 1) the transformation will not be right
+ // 2) in this case, the physic controller is necessarily a static object
+ // that is updated from the normal kinematic synchronization
m_pPhysicsController1->setPosition(trans);
}
- if (GetSGNode())
- GetSGNode()->SetLocalPosition(trans);
+ GetSGNode()->SetLocalPosition(trans);
}
void KX_GameObject::NodeSetLocalOrientation(const MT_Matrix3x3& rot)
{
- if (m_pPhysicsController1)
- {
- m_pPhysicsController1->setOrientation(rot.getRotation());
- }
- if (GetSGNode())
- GetSGNode()->SetLocalOrientation(rot);
- else
+ // check on valid node in case a python controller holds a reference to a deleted object
+ if (!GetSGNode())
+ return;
+
+ if (m_pPhysicsController1 && !GetSGNode()->GetSGParent())
{
- int i;
- i=0;
+ // see note above
+ m_pPhysicsController1->setOrientation(rot);
}
+ GetSGNode()->SetLocalOrientation(rot);
}
void KX_GameObject::NodeSetLocalScale(const MT_Vector3& scale)
{
- if (m_pPhysicsController1)
+ // check on valid node in case a python controller holds a reference to a deleted object
+ if (!GetSGNode())
+ return;
+
+ if (m_pPhysicsController1 && !GetSGNode()->GetSGParent())
{
+ // see note above
m_pPhysicsController1->setScaling(scale);
}
-
- if (GetSGNode())
- GetSGNode()->SetLocalScale(scale);
+ GetSGNode()->SetLocalScale(scale);
}
@@ -555,9 +844,44 @@ void KX_GameObject::NodeSetLocalScale(const MT_Vector3& scale)
void KX_GameObject::NodeSetRelativeScale(const MT_Vector3& scale)
{
if (GetSGNode())
+ {
GetSGNode()->RelativeScale(scale);
+ if (m_pPhysicsController1 && (!GetSGNode()->GetSGParent()))
+ {
+ // see note above
+ // we can use the local scale: it's the same thing for a root object
+ // and the world scale is not yet updated
+ MT_Vector3 newscale = GetSGNode()->GetLocalScale();
+ m_pPhysicsController1->setScaling(newscale);
+ }
+ }
}
+void KX_GameObject::NodeSetWorldPosition(const MT_Point3& trans)
+{
+ SG_Node* parent = m_pSGNode->GetSGParent();
+ if (parent != NULL)
+ {
+ // Make sure the objects have some scale
+ MT_Vector3 scale = parent->GetWorldScaling();
+ if (fabs(scale[0]) < FLT_EPSILON ||
+ fabs(scale[1]) < FLT_EPSILON ||
+ fabs(scale[2]) < FLT_EPSILON)
+ {
+ return;
+ }
+ scale[0] = 1.0/scale[0];
+ scale[1] = 1.0/scale[1];
+ scale[2] = 1.0/scale[2];
+ MT_Matrix3x3 invori = parent->GetWorldOrientation().inverse();
+ MT_Vector3 newpos = invori*(trans-parent->GetWorldPosition())*scale;
+ NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
+ }
+ else
+ {
+ NodeSetLocalPosition(trans);
+ }
+}
void KX_GameObject::NodeUpdateGS(double time,bool bInitiator)
@@ -570,6 +894,13 @@ void KX_GameObject::NodeUpdateGS(double time,bool bInitiator)
const MT_Matrix3x3& KX_GameObject::NodeGetWorldOrientation() const
{
+ static MT_Matrix3x3 defaultOrientation = MT_Matrix3x3( 1.0, 0.0, 0.0,
+ 0.0, 1.0, 0.0,
+ 0.0, 0.0, 1.0);
+
+ // check on valid node in case a python controller holds a reference to a deleted object
+ if (!GetSGNode())
+ return defaultOrientation;
return GetSGNode()->GetWorldOrientation();
}
@@ -577,6 +908,12 @@ const MT_Matrix3x3& KX_GameObject::NodeGetWorldOrientation() const
const MT_Vector3& KX_GameObject::NodeGetWorldScaling() const
{
+ static MT_Vector3 defaultScaling = MT_Vector3(1.0, 1.0, 1.0);
+
+ // check on valid node in case a python controller holds a reference to a deleted object
+ if (!GetSGNode())
+ return defaultScaling;
+
return GetSGNode()->GetWorldScaling();
}
@@ -584,6 +921,12 @@ const MT_Vector3& KX_GameObject::NodeGetWorldScaling() const
const MT_Point3& KX_GameObject::NodeGetWorldPosition() const
{
+ static MT_Point3 defaultPosition = MT_Point3(0.0, 0.0, 0.0);
+
+ // check on valid node in case a python controller holds a reference to a deleted object
+ if (!GetSGNode())
+ return defaultPosition;
+
return GetSGNode()->GetWorldPosition();
}
@@ -604,7 +947,7 @@ void KX_GameObject::Resume(void)
}
}
-void KX_GameObject::Suspend(void)
+void KX_GameObject::Suspend()
{
if ((!m_ignore_activity_culling)
&& (!m_suspended)) {
@@ -623,25 +966,44 @@ void KX_GameObject::Suspend(void)
PyMethodDef KX_GameObject::Methods[] = {
- {"setVisible",(PyCFunction) KX_GameObject::sPySetVisible, METH_VARARGS},
- {"setPosition", (PyCFunction) KX_GameObject::sPySetPosition, METH_VARARGS},
- {"getPosition", (PyCFunction) KX_GameObject::sPyGetPosition, METH_VARARGS},
- {"getOrientation", (PyCFunction) KX_GameObject::sPyGetOrientation, METH_VARARGS},
- {"setOrientation", (PyCFunction) KX_GameObject::sPySetOrientation, METH_VARARGS},
+ {"getPosition", (PyCFunction) KX_GameObject::sPyGetPosition, METH_NOARGS},
+ {"setPosition", (PyCFunction) KX_GameObject::sPySetPosition, METH_O},
+ {"setWorldPosition", (PyCFunction) KX_GameObject::sPySetWorldPosition, METH_O},
{"getLinearVelocity", (PyCFunction) KX_GameObject::sPyGetLinearVelocity, METH_VARARGS},
+ {"setLinearVelocity", (PyCFunction) KX_GameObject::sPySetLinearVelocity, METH_VARARGS},
+ {"getAngularVelocity", (PyCFunction) KX_GameObject::sPyGetAngularVelocity, METH_VARARGS},
+ {"setAngularVelocity", (PyCFunction) KX_GameObject::sPySetAngularVelocity, METH_VARARGS},
{"getVelocity", (PyCFunction) KX_GameObject::sPyGetVelocity, METH_VARARGS},
- {"getMass", (PyCFunction) KX_GameObject::sPyGetMass, METH_VARARGS},
- {"getReactionForce", (PyCFunction) KX_GameObject::sPyGetReactionForce, METH_VARARGS},
+ {"getMass", (PyCFunction) KX_GameObject::sPyGetMass, METH_NOARGS},
+ {"getReactionForce", (PyCFunction) KX_GameObject::sPyGetReactionForce, METH_NOARGS},
+ {"getOrientation", (PyCFunction) KX_GameObject::sPyGetOrientation, METH_NOARGS},
+ {"setOrientation", (PyCFunction) KX_GameObject::sPySetOrientation, METH_O},
+ {"getVisible",(PyCFunction) KX_GameObject::sPyGetVisible, METH_NOARGS},
+ {"setVisible",(PyCFunction) KX_GameObject::sPySetVisible, METH_VARARGS},
+ {"getState",(PyCFunction) KX_GameObject::sPyGetState, METH_NOARGS},
+ {"setState",(PyCFunction) KX_GameObject::sPySetState, METH_O},
+ {"alignAxisToVect",(PyCFunction) KX_GameObject::sPyAlignAxisToVect, METH_VARARGS},
+ {"getAxisVect",(PyCFunction) KX_GameObject::sPyGetAxisVect, METH_O},
+ {"suspendDynamics", (PyCFunction)KX_GameObject::sPySuspendDynamics,METH_NOARGS},
+ {"restoreDynamics", (PyCFunction)KX_GameObject::sPyRestoreDynamics,METH_NOARGS},
+ {"enableRigidBody", (PyCFunction)KX_GameObject::sPyEnableRigidBody,METH_NOARGS},
+ {"disableRigidBody", (PyCFunction)KX_GameObject::sPyDisableRigidBody,METH_NOARGS},
{"applyImpulse", (PyCFunction) KX_GameObject::sPyApplyImpulse, METH_VARARGS},
- {"setCollisionMargin", (PyCFunction) KX_GameObject::sPySetCollisionMargin, METH_VARARGS},
- {"suspendDynamics", (PyCFunction)KX_GameObject::sPySuspendDynamics,METH_VARARGS},
- {"restoreDynamics", (PyCFunction)KX_GameObject::sPyRestoreDynamics,METH_VARARGS},
- {"enableRigidBody", (PyCFunction)KX_GameObject::sPyEnableRigidBody,METH_VARARGS},
- {"disableRigidBody", (PyCFunction)KX_GameObject::sPyDisableRigidBody,METH_VARARGS},
- {"getParent", (PyCFunction)KX_GameObject::sPyGetParent,METH_VARARGS},
+ {"setCollisionMargin", (PyCFunction) KX_GameObject::sPySetCollisionMargin, METH_O},
+ {"getParent", (PyCFunction)KX_GameObject::sPyGetParent,METH_NOARGS},
+ {"setParent", (PyCFunction)KX_GameObject::sPySetParent,METH_O},
+ {"removeParent", (PyCFunction)KX_GameObject::sPyRemoveParent,METH_NOARGS},
+ {"getChildren", (PyCFunction)KX_GameObject::sPyGetChildren,METH_NOARGS},
+ {"getChildrenRecursive", (PyCFunction)KX_GameObject::sPyGetChildrenRecursive,METH_NOARGS},
{"getMesh", (PyCFunction)KX_GameObject::sPyGetMesh,METH_VARARGS},
- {"getPhysicsId", (PyCFunction)KX_GameObject::sPyGetPhysicsId,METH_VARARGS},
+ {"getPhysicsId", (PyCFunction)KX_GameObject::sPyGetPhysicsId,METH_NOARGS},
+ {"getPropertyNames", (PyCFunction)KX_GameObject::sPyGetPropertyNames,METH_NOARGS},
+ {"replaceMesh",(PyCFunction) KX_GameObject::sPyReplaceMesh, METH_O},
+ {"endObject",(PyCFunction) KX_GameObject::sPyEndObject, METH_NOARGS},
+ KX_PYMETHODTABLE(KX_GameObject, rayCastTo),
+ KX_PYMETHODTABLE(KX_GameObject, rayCast),
KX_PYMETHODTABLE(KX_GameObject, getDistanceTo),
+ KX_PYMETHODTABLE(KX_GameObject, getVectTo),
{NULL,NULL} //Sentinel
};
@@ -663,19 +1025,40 @@ bool KX_GameObject::ConvertPythonVectorArgs(PyObject* args,
}
*/
-
-PyObject* KX_GameObject::sPySetPosition(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_GameObject::PyReplaceMesh(PyObject* self, PyObject* value)
{
- return ((KX_GameObject*) self)->PySetPosition(self, args, kwds);
+ KX_Scene *scene = KX_GetActiveScene();
+ char* meshname;
+ void* mesh_pt;
+
+ meshname = PyString_AsString(value);
+ if (meshname==NULL) {
+ PyErr_SetString(PyExc_ValueError, "Expected a mesh name");
+ return NULL;
+ }
+ mesh_pt = SCA_ILogicBrick::m_sCurrentLogicManager->GetMeshByName(STR_String(meshname));
+
+ if (mesh_pt==NULL) {
+ PyErr_SetString(PyExc_ValueError, "The mesh name given does not exist");
+ return NULL;
+ }
+ scene->ReplaceMesh(this, (class RAS_MeshObject*)mesh_pt);
+
+ Py_RETURN_NONE;
}
+
+PyObject* KX_GameObject::PyEndObject(PyObject* self)
+{
+
+ KX_Scene *scene = KX_GetActiveScene();
+ scene->DelayedRemoveObject(this);
+ Py_RETURN_NONE;
+
+}
-PyObject* KX_GameObject::PyGetPosition(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_GameObject::PyGetPosition(PyObject* self)
{
return PyObjectFrom(NodeGetWorldPosition());
}
@@ -729,7 +1112,7 @@ PyObject* KX_GameObject::_getattr(const STR_String& attr)
parent->AddRef();
return parent;
}
- Py_Return;
+ Py_RETURN_NONE;
}
if (attr == "visible")
@@ -746,27 +1129,53 @@ PyObject* KX_GameObject::_getattr(const STR_String& attr)
if (attr == "name")
return PyString_FromString(m_name.ReadPtr());
+ if (attr == "timeOffset") {
+ if (m_pSGNode->GetSGParent()->IsSlowParent()) {
+ return PyFloat_FromDouble(static_cast<KX_SlowParentRelation *>(m_pSGNode->GetSGParent()->GetParentRelation())->GetTimeOffset());
+ } else {
+ return PyFloat_FromDouble(0.0);
+ }
+ }
+
_getattr_up(SCA_IObject);
}
int KX_GameObject::_setattr(const STR_String& attr, PyObject *value) // _setattr method
{
- if (attr == "mass")
+ if (attr == "mass") {
+ PyErr_SetString(PyExc_AttributeError, "attribute \"mass\" is read only");
return 1;
+ }
- if (attr == "parent")
+ if (attr == "parent") {
+ PyErr_SetString(PyExc_AttributeError, "attribute \"mass\" is read only\nUse setParent()");
return 1;
+ }
if (PyInt_Check(value))
{
int val = PyInt_AsLong(value);
if (attr == "visible")
{
- SetVisible(val != 0);
+ SetVisible(val != 0, false);
+ UpdateBuckets(false);
return 0;
}
}
+
+ if (PyFloat_Check(value))
+ {
+ MT_Scalar val = PyFloat_AsDouble(value);
+ if (attr == "timeOffset") {
+ if (m_pSGNode->GetSGParent() && m_pSGNode->GetSGParent()->IsSlowParent()) {
+ static_cast<KX_SlowParentRelation *>(m_pSGNode->GetSGParent()->GetParentRelation())->SetTimeOffset(val);
+ return 0;
+ } else {
+ return 0;
+ }
+ }
+ }
if (PySequence_Check(value))
{
@@ -778,6 +1187,7 @@ int KX_GameObject::_setattr(const STR_String& attr, PyObject *value) // _setattr
if (PyMatTo(value, rot))
{
NodeSetLocalOrientation(rot);
+ NodeUpdateGS(0.f,true);
return 0;
}
return 1;
@@ -790,6 +1200,7 @@ int KX_GameObject::_setattr(const STR_String& attr, PyObject *value) // _setattr
{
rot.setRotation(qrot);
NodeSetLocalOrientation(rot);
+ NodeUpdateGS(0.f,true);
return 0;
}
return 1;
@@ -802,11 +1213,12 @@ int KX_GameObject::_setattr(const STR_String& attr, PyObject *value) // _setattr
{
rot.setEuler(erot);
NodeSetLocalOrientation(rot);
+ NodeUpdateGS(0.f,true);
return 0;
}
return 1;
}
-
+ PyErr_SetString(PyExc_AttributeError, "could not set the orientation from a 3x3 matrix, quaternion or euler sequence");
return 1;
}
@@ -816,6 +1228,7 @@ int KX_GameObject::_setattr(const STR_String& attr, PyObject *value) // _setattr
if (PyVecTo(value, pos))
{
NodeSetLocalPosition(pos);
+ NodeUpdateGS(0.f,true);
return 0;
}
return 1;
@@ -827,6 +1240,7 @@ int KX_GameObject::_setattr(const STR_String& attr, PyObject *value) // _setattr
if (PyVecTo(value, scale))
{
NodeSetLocalScale(scale);
+ NodeUpdateGS(0.f,true);
return 0;
}
return 1;
@@ -842,44 +1256,117 @@ int KX_GameObject::_setattr(const STR_String& attr, PyObject *value) // _setattr
}
}
+ /* Need to have parent settable here too */
+
return SCA_IObject::_setattr(attr, value);
}
-PyObject* KX_GameObject::PyGetLinearVelocity(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_GameObject::PyGetLinearVelocity(PyObject* self, PyObject* args)
{
// only can get the velocity if we have a physics object connected to us...
- return PyObjectFrom(GetLinearVelocity());
+ int local = 0;
+ if (PyArg_ParseTuple(args,"|i",&local))
+ {
+ return PyObjectFrom(GetLinearVelocity((local!=0)));
+ }
+ else
+ {
+ return NULL;
+ }
}
-
-
-PyObject* KX_GameObject::PySetVisible(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_GameObject::PySetLinearVelocity(PyObject* self, PyObject* args)
{
- int visible = 1;
+ int local = 0;
+ PyObject* pyvect;
- if (PyArg_ParseTuple(args,"i",&visible))
+ if (PyArg_ParseTuple(args,"O|i",&pyvect,&local)) {
+ MT_Vector3 velocity;
+ if (PyVecTo(pyvect, velocity)) {
+ setLinearVelocity(velocity, (local!=0));
+ Py_RETURN_NONE;
+ }
+ }
+ return NULL;
+}
+
+PyObject* KX_GameObject::PyGetAngularVelocity(PyObject* self, PyObject* args)
+{
+ // only can get the velocity if we have a physics object connected to us...
+ int local = 0;
+ if (PyArg_ParseTuple(args,"|i",&local))
{
- MarkVisible(visible!=0);
- m_bVisible = (visible!=0);
+ return PyObjectFrom(GetAngularVelocity((local!=0)));
}
else
{
- return NULL;
+ return NULL;
}
- Py_Return;
+}
+
+PyObject* KX_GameObject::PySetAngularVelocity(PyObject* self, PyObject* args)
+{
+ int local = 0;
+ PyObject* pyvect;
+ if (PyArg_ParseTuple(args,"O|i",&pyvect,&local)) {
+ MT_Vector3 velocity;
+ if (PyVecTo(pyvect, velocity)) {
+ setAngularVelocity(velocity, (local!=0));
+ Py_RETURN_NONE;
+ }
+ }
+ return NULL;
+}
+
+PyObject* KX_GameObject::PySetVisible(PyObject* self, PyObject* args)
+{
+ int visible, recursive = 0;
+ if (!PyArg_ParseTuple(args,"i|i",&visible, &recursive))
+ return NULL;
+
+ SetVisible(visible ? true:false, recursive ? true:false);
+ UpdateBuckets(recursive ? true:false);
+ Py_RETURN_NONE;
+
+}
+
+PyObject* KX_GameObject::PyGetVisible(PyObject* self)
+{
+ return PyInt_FromLong(m_bVisible);
+}
+
+PyObject* KX_GameObject::PyGetState(PyObject* self)
+{
+ int state = 0;
+ state |= GetState();
+ return PyInt_FromLong(state);
+}
+
+PyObject* KX_GameObject::PySetState(PyObject* self, PyObject* value)
+{
+ int state_i = PyInt_AsLong(value);
+ unsigned int state = 0;
+
+ if (state_i == -1 && PyErr_Occurred()) {
+ PyErr_SetString(PyExc_TypeError, "expected an int bit field");
+ return NULL;
+ }
+
+ state |= state_i;
+ if ((state & ((1<<30)-1)) == 0) {
+ PyErr_SetString(PyExc_AttributeError, "The state bitfield was not between 0 and 30 (1<<0 and 1<<29)");
+ return NULL;
+ }
+ SetState(state);
+
+ Py_RETURN_NONE;
}
-PyObject* KX_GameObject::PyGetVelocity(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_GameObject::PyGetVelocity(PyObject* self, PyObject* args)
{
// only can get the velocity if we have a physics object connected to us...
MT_Vector3 velocity(0.0,0.0,0.0);
@@ -892,6 +1379,9 @@ PyObject* KX_GameObject::PyGetVelocity(PyObject* self,
if (pypos)
PyVecTo(pypos, point);
}
+ else {
+ return NULL;
+ }
if (m_pPhysicsController1)
{
@@ -903,26 +1393,14 @@ PyObject* KX_GameObject::PyGetVelocity(PyObject* self,
-PyObject* KX_GameObject::PyGetMass(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_GameObject::PyGetMass(PyObject* self)
{
- PyObject* pymass = NULL;
-
- float mass = GetPhysicsController()->GetMass();
- pymass = PyFloat_FromDouble(mass);
-
- if (pymass)
- return pymass;
-
- Py_Return;
+ return PyFloat_FromDouble(GetPhysicsController()->GetMass());
}
-PyObject* KX_GameObject::PyGetReactionForce(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_GameObject::PyGetReactionForce(PyObject* self)
{
// only can get the velocity if we have a physics object connected to us...
return PyObjectFrom(GetPhysicsController()->getReactionForce());
@@ -930,32 +1408,25 @@ PyObject* KX_GameObject::PyGetReactionForce(PyObject* self,
-PyObject* KX_GameObject::PyEnableRigidBody(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_GameObject::PyEnableRigidBody(PyObject* self)
{
-
GetPhysicsController()->setRigidBody(true);
- Py_Return;
+ Py_RETURN_NONE;
}
-PyObject* KX_GameObject::PyDisableRigidBody(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_GameObject::PyDisableRigidBody(PyObject* self)
{
GetPhysicsController()->setRigidBody(false);
- Py_Return;
+ Py_RETURN_NONE;
}
-PyObject* KX_GameObject::PyGetParent(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_GameObject::PyGetParent(PyObject* self)
{
KX_GameObject* parent = this->GetParent();
if (parent)
@@ -963,69 +1434,128 @@ PyObject* KX_GameObject::PyGetParent(PyObject* self,
parent->AddRef();
return parent;
}
- Py_Return;
+ Py_RETURN_NONE;
+}
+
+PyObject* KX_GameObject::PySetParent(PyObject* self, PyObject* value)
+{
+ if (!PyObject_TypeCheck(value, &KX_GameObject::Type)) {
+ PyErr_SetString(PyExc_TypeError, "expected a KX_GameObject type");
+ return NULL;
+ }
+
+ // The object we want to set as parent
+ CValue *m_ob = (CValue*)value;
+ KX_GameObject *obj = ((KX_GameObject*)m_ob);
+ KX_Scene *scene = KX_GetActiveScene();
+
+ this->SetParent(scene, obj);
+
+ Py_RETURN_NONE;
}
+PyObject* KX_GameObject::PyRemoveParent(PyObject* self)
+{
+ KX_Scene *scene = KX_GetActiveScene();
+ this->RemoveParent(scene);
+ Py_RETURN_NONE;
+}
-PyObject* KX_GameObject::PyGetMesh(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+static void walk_children(SG_Node* node, CListValue* list, bool recursive)
{
- int mesh = 0;
+ NodeList& children = node->GetSGChildren();
- if (PyArg_ParseTuple(args, "|i", &mesh))
+ for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
{
- if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0)
+ SG_Node* childnode = (*childit);
+ CValue* childobj = (CValue*)childnode->GetSGClientObject();
+ if (childobj != NULL) // This is a GameObject
{
- KX_MeshProxy* meshproxy = new KX_MeshProxy(m_meshes[mesh]);
- return meshproxy;
+ // add to the list
+ list->Add(childobj->AddRef());
+ }
+
+ // if the childobj is NULL then this may be an inverse parent link
+ // so a non recursive search should still look down this node.
+ if (recursive || childobj==NULL) {
+ walk_children(childnode, list, recursive);
}
}
- Py_Return;
}
+PyObject* KX_GameObject::PyGetChildren(PyObject* self)
+{
+ CListValue* list = new CListValue();
+ walk_children(m_pSGNode, list, 0);
+ return list;
+}
+PyObject* KX_GameObject::PyGetChildrenRecursive(PyObject* self)
+{
+ CListValue* list = new CListValue();
+ walk_children(m_pSGNode, list, 1);
+ return list;
+}
-
-
-PyObject* KX_GameObject::PySetCollisionMargin(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_GameObject::PyGetMesh(PyObject* self, PyObject* args)
{
- float collisionMargin;
- if (PyArg_ParseTuple(args, "f", &collisionMargin))
+ int mesh = 0;
+
+ if (!PyArg_ParseTuple(args, "|i", &mesh))
+ return NULL; // python sets a simple error
+
+ if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0)
{
- if (m_pPhysicsController1)
- {
- m_pPhysicsController1->setMargin(collisionMargin);
- Py_Return;
- }
+ KX_MeshProxy* meshproxy = new KX_MeshProxy(m_meshes[mesh]);
+ return meshproxy;
+ }
+
+ Py_RETURN_NONE;
+}
+
+
+
+
+PyObject* KX_GameObject::PySetCollisionMargin(PyObject* self, PyObject* value)
+{
+ float collisionMargin = PyFloat_AsDouble(value);
+
+ if (collisionMargin==-1 && PyErr_Occurred()) {
+ PyErr_SetString(PyExc_TypeError, "expected a float");
+ return NULL;
}
+ if (m_pPhysicsController1)
+ {
+ m_pPhysicsController1->setMargin(collisionMargin);
+ Py_RETURN_NONE;
+ }
+ PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
return NULL;
}
-PyObject* KX_GameObject::PyApplyImpulse(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_GameObject::PyApplyImpulse(PyObject* self, PyObject* args)
{
PyObject* pyattach;
PyObject* pyimpulse;
+
+ if (!m_pPhysicsController1) {
+ PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
+ return NULL;
+ }
+
if (PyArg_ParseTuple(args, "OO", &pyattach, &pyimpulse))
{
MT_Point3 attach;
MT_Vector3 impulse;
- if (m_pPhysicsController1)
+ if (PyVecTo(pyattach, attach) && PyVecTo(pyimpulse, impulse))
{
- if (PyVecTo(pyattach, attach) && PyVecTo(pyimpulse, impulse))
- {
- m_pPhysicsController1->applyImpulse(attach, impulse);
- Py_Return;
- }
+ m_pPhysicsController1->applyImpulse(attach, impulse);
+ Py_RETURN_NONE;
}
}
@@ -1035,102 +1565,109 @@ PyObject* KX_GameObject::PyApplyImpulse(PyObject* self,
-PyObject* KX_GameObject::PySuspendDynamics(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_GameObject::PySuspendDynamics(PyObject* self)
{
- if (m_bSuspendDynamics)
- {
- Py_Return;
- }
-
- if (m_pPhysicsController1)
- {
- m_pPhysicsController1->SuspendDynamics();
- }
- m_bSuspendDynamics = true;
-
- Py_Return;
+ SuspendDynamics();
+ Py_RETURN_NONE;
}
-PyObject* KX_GameObject::PyRestoreDynamics(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_GameObject::PyRestoreDynamics(PyObject* self)
{
-
- if (!m_bSuspendDynamics)
- {
- Py_Return;
- }
-
- if (m_pPhysicsController1)
- {
- m_pPhysicsController1->RestoreDynamics();
- }
- m_bSuspendDynamics = false;
-
- Py_Return;
+ RestoreDynamics();
+ Py_RETURN_NONE;
}
-PyObject* KX_GameObject::PyGetOrientation(PyObject* self,
- PyObject* args,
- PyObject* kwds) //keywords
+PyObject* KX_GameObject::PyGetOrientation(PyObject* self) //keywords
{
return PyObjectFrom(NodeGetWorldOrientation());
}
-PyObject* KX_GameObject::PySetOrientation(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_GameObject::PySetOrientation(PyObject* self, PyObject* value)
{
- PyObject* pylist;
-
- if (PyArg_ParseTuple(args,"O",&pylist))
+ MT_Matrix3x3 matrix;
+ if (PyObject_IsMT_Matrix(value, 3) && PyMatTo(value, matrix))
{
- MT_Matrix3x3 matrix;
- if (PyObject_IsMT_Matrix(pylist, 3) && PyMatTo(pylist, matrix))
- {
- NodeSetLocalOrientation(matrix);
- Py_Return;
- }
+ NodeSetLocalOrientation(matrix);
+ NodeUpdateGS(0.f,true);
+ Py_RETURN_NONE;
+ }
+
+ MT_Quaternion quat;
+ if (PyVecTo(value, quat))
+ {
+ matrix.setRotation(quat);
+ NodeSetLocalOrientation(matrix);
+ NodeUpdateGS(0.f,true);
+ Py_RETURN_NONE;
+ }
+ return NULL;
+}
+
+PyObject* KX_GameObject::PyAlignAxisToVect(PyObject* self, PyObject* args)
+{
+ PyObject* pyvect;
+ int axis = 2; //z axis is the default
+ float fac = 1.0;
- MT_Quaternion quat;
- if (PyVecTo(pylist, quat))
+ if (PyArg_ParseTuple(args,"O|if",&pyvect,&axis, &fac))
+ {
+ MT_Vector3 vect;
+ if (PyVecTo(pyvect, vect))
{
- matrix.setRotation(quat);
- NodeSetLocalOrientation(matrix);
- Py_Return;
+ if (fac<=0.0) Py_RETURN_NONE; // Nothing to do.
+ if (fac> 1.0) fac= 1.0;
+
+ AlignAxisToVect(vect,axis,fac);
+ NodeUpdateGS(0.f,true);
+ Py_RETURN_NONE;
}
}
return NULL;
}
+PyObject* KX_GameObject::PyGetAxisVect(PyObject* self, PyObject* value)
+{
+ MT_Vector3 vect;
+ if (PyVecTo(value, vect))
+ {
+ return PyObjectFrom(NodeGetWorldOrientation() * vect);
+ }
+ return NULL;
+}
-
-PyObject* KX_GameObject::PySetPosition(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_GameObject::PySetPosition(PyObject* self, PyObject* value)
{
MT_Point3 pos;
- if (PyVecArgTo(args, pos))
+ if (PyVecTo(value, pos))
{
NodeSetLocalPosition(pos);
NodeUpdateGS(0.f,true);
- Py_Return;
+ Py_RETURN_NONE;
}
-
+
return NULL;
}
-PyObject* KX_GameObject::PyGetPhysicsId(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_GameObject::PySetWorldPosition(PyObject* self, PyObject* value)
+{
+ MT_Point3 pos;
+ if (PyVecTo(value, pos))
+ {
+ NodeSetWorldPosition(pos);
+ NodeUpdateGS(0.f,true);
+ Py_RETURN_NONE;
+ }
+
+ return NULL;
+}
+
+PyObject* KX_GameObject::PyGetPhysicsId(PyObject* self)
{
KX_IPhysicsController* ctrl = GetPhysicsController();
uint_ptr physid=0;
@@ -1141,6 +1678,11 @@ PyObject* KX_GameObject::PyGetPhysicsId(PyObject* self,
return PyInt_FromLong((long)physid);
}
+PyObject* KX_GameObject::PyGetPropertyNames(PyObject* self)
+{
+ return ConvertKeysToPython();
+}
+
KX_PYMETHODDEF_DOC(KX_GameObject, getDistanceTo,
"getDistanceTo(other): get distance to another point/KX_GameObject")
{
@@ -1152,20 +1694,356 @@ KX_PYMETHODDEF_DOC(KX_GameObject, getDistanceTo,
PyErr_Clear();
PyObject *pyother;
- if (PyArg_ParseTuple(args, "O!", &KX_GameObject::Type, &pyother))
+ KX_GameObject *other;
+ if (PyArg_ParseTuple(args, "O", &pyother) && ConvertPythonToGameObject(pyother, &other, false))
{
- KX_GameObject *other = static_cast<KX_GameObject*>(pyother);
return PyFloat_FromDouble(NodeGetWorldPosition().distance(other->NodeGetWorldPosition()));
}
return NULL;
}
+KX_PYMETHODDEF_DOC(KX_GameObject, getVectTo,
+"getVectTo(other): get vector and the distance to another point/KX_GameObject\n"
+"Returns a 3-tuple with (distance,worldVector,localVector)\n")
+{
+ MT_Point3 toPoint, fromPoint;
+ MT_Vector3 toDir, locToDir;
+ MT_Scalar distance;
+
+ PyObject *returnValue;
+ PyObject *pyother;
+
+ if (!PyVecArgTo(args, toPoint))
+ {
+ PyErr_Clear();
+
+ KX_GameObject *other;
+ if (PyArg_ParseTuple(args, "O", &pyother) && ConvertPythonToGameObject(pyother, &other, false))
+ {
+ toPoint = other->NodeGetWorldPosition();
+ } else
+ {
+ PyErr_SetString(PyExc_TypeError, "Expected a 3D Vector or GameObject type");
+ return NULL;
+ }
+ }
+
+ fromPoint = NodeGetWorldPosition();
+ toDir = toPoint-fromPoint;
+ distance = toDir.length();
+
+ if (MT_fuzzyZero(distance))
+ {
+ //cout << "getVectTo() Error: Null vector!\n";
+ locToDir = toDir = MT_Vector3(0.0,0.0,0.0);
+ distance = 0.0;
+ } else {
+ toDir.normalize();
+ locToDir = toDir * NodeGetWorldOrientation();
+ }
+
+ returnValue = PyTuple_New(3);
+ if (returnValue) { // very unlikely to fail, python sets a memory error here.
+ PyTuple_SET_ITEM(returnValue, 0, PyFloat_FromDouble(distance));
+ PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(toDir));
+ PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(locToDir));
+ }
+ return returnValue;
+}
+
+bool KX_GameObject::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data)
+{
+ KX_GameObject* hitKXObj = client->m_gameobject;
+
+ // if X-ray option is selected, the unwnted objects were not tested, so get here only with true hit
+ // if not, all objects were tested and the front one may not be the correct one.
+ if (m_xray || m_testPropName.Length() == 0 || hitKXObj->GetProperty(m_testPropName) != NULL)
+ {
+ m_pHitObject = hitKXObj;
+ return true;
+ }
+ // return true to stop RayCast::RayTest from looping, the above test was decisive
+ // We would want to loop only if we want to get more than one hit point
+ return true;
+}
+
+/* this function is used to pre-filter the object before casting the ray on them.
+ This is useful for "X-Ray" option when we want to see "through" unwanted object.
+ */
+bool KX_GameObject::NeedRayCast(KX_ClientObjectInfo* client)
+{
+ KX_GameObject* hitKXObj = client->m_gameobject;
+
+ if (client->m_type > KX_ClientObjectInfo::ACTOR)
+ {
+ // Unknown type of object, skip it.
+ // Should not occur as the sensor objects are filtered in RayTest()
+ printf("Invalid client type %d found in ray casting\n", client->m_type);
+ return false;
+ }
+
+ // if X-Ray option is selected, skip object that don't match the criteria as we see through them
+ // if not, test all objects because we don't know yet which one will be on front
+ if (!m_xray || m_testPropName.Length() == 0 || hitKXObj->GetProperty(m_testPropName) != NULL)
+ {
+ return true;
+ }
+ // skip the object
+ return false;
+}
+
+KX_PYMETHODDEF_DOC(KX_GameObject, rayCastTo,
+"rayCastTo(other,dist,prop): look towards another point/KX_GameObject and return first object hit within dist that matches prop\n"
+" prop = property name that object must have; can be omitted => detect any object\n"
+" dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to other\n"
+" other = 3-tuple or object reference")
+{
+ MT_Point3 toPoint;
+ PyObject* pyarg;
+ float dist = 0.0f;
+ char *propName = NULL;
+
+ if (!PyArg_ParseTuple(args,"O|fs", &pyarg, &dist, &propName)) {
+ return NULL; // python sets simple error
+ }
+
+ if (!PyVecTo(pyarg, toPoint))
+ {
+ KX_GameObject *other;
+ PyErr_Clear();
+
+ if (ConvertPythonToGameObject(pyarg, &other, false))
+ {
+ toPoint = other->NodeGetWorldPosition();
+ } else
+ {
+ PyErr_SetString(PyExc_TypeError, "the first argument to rayCastTo must be a vector or a KX_GameObject");
+ return NULL;
+ }
+ }
+ MT_Point3 fromPoint = NodeGetWorldPosition();
+ if (dist != 0.0f)
+ {
+ MT_Vector3 toDir = toPoint-fromPoint;
+ toDir.normalize();
+ toPoint = fromPoint + (dist) * toDir;
+ }
+
+ PHY_IPhysicsEnvironment* pe = GetPhysicsEnvironment();
+ KX_IPhysicsController *spc = GetPhysicsController();
+ KX_GameObject *parent = GetParent();
+ if (!spc && parent)
+ spc = parent->GetPhysicsController();
+ if (parent)
+ parent->Release();
+
+ m_pHitObject = NULL;
+ if (propName)
+ m_testPropName = propName;
+ else
+ m_testPropName.SetLength(0);
+ KX_RayCast::Callback<KX_GameObject> callback(this,spc);
+ KX_RayCast::RayTest(pe, fromPoint, toPoint, callback);
+
+ if (m_pHitObject)
+ {
+ m_pHitObject->AddRef();
+ return m_pHitObject;
+ }
+ Py_RETURN_NONE;
+}
+
+KX_PYMETHODDEF_DOC(KX_GameObject, rayCast,
+ "rayCast(to,from,dist,prop,face,xray,poly): cast a ray and return 3-tuple (object,hit,normal) or 4-tuple (object,hit,normal,polygon) of contact point with object within dist that matches prop.\n"
+ " If no hit, return (None,None,None) or (None,None,None,None).\n"
+" to = 3-tuple or object reference for destination of ray (if object, use center of object)\n"
+" from = 3-tuple or object reference for origin of ray (if object, use center of object)\n"
+" Can be None or omitted => start from self object center\n"
+" dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to to\n"
+" prop = property name that object must have; can be omitted => detect any object\n"
+" face = normal option: 1=>return face normal; 0 or omitted => normal is oriented towards origin\n"
+" xray = X-ray option: 1=>skip objects that don't match prop; 0 or omitted => stop on first object\n"
+" poly = polygon option: 1=>return value is a 4-tuple and the 4th element is a KX_PolyProxy object\n"
+" which can be None if hit object has no mesh or if there is no hit\n"
+" If 0 or omitted, return value is a 3-tuple\n"
+"Note: The object on which you call this method matters: the ray will ignore it.\n"
+" prop and xray option interact as follow:\n"
+" prop off, xray off: return closest hit or no hit if there is no object on the full extend of the ray\n"
+" prop off, xray on : idem\n"
+" prop on, xray off: return closest hit if it matches prop, no hit otherwise\n"
+" prop on, xray on : return closest hit matching prop or no hit if there is no object matching prop on the full extend of the ray\n")
+{
+ MT_Point3 toPoint;
+ MT_Point3 fromPoint;
+ PyObject* pyto;
+ PyObject* pyfrom = NULL;
+ float dist = 0.0f;
+ char *propName = NULL;
+ KX_GameObject *other;
+ int face=0, xray=0, poly=0;
+
+ if (!PyArg_ParseTuple(args,"O|Ofsiii", &pyto, &pyfrom, &dist, &propName, &face, &xray, &poly)) {
+ return NULL; // Python sets a simple error
+ }
+
+ if (!PyVecTo(pyto, toPoint))
+ {
+ PyErr_Clear();
+
+ if (ConvertPythonToGameObject(pyto, &other, false))
+ {
+ toPoint = other->NodeGetWorldPosition();
+ } else
+ {
+ PyErr_SetString(PyExc_TypeError, "the first argument to rayCast must be a vector or a KX_GameObject");
+ return NULL;
+ }
+ }
+ if (!pyfrom || pyfrom == Py_None)
+ {
+ fromPoint = NodeGetWorldPosition();
+ }
+ else if (!PyVecTo(pyfrom, fromPoint))
+ {
+ PyErr_Clear();
+
+ if (ConvertPythonToGameObject(pyfrom, &other, false))
+ {
+ fromPoint = other->NodeGetWorldPosition();
+ } else
+ {
+ PyErr_SetString(PyExc_TypeError, "the second optional argument to rayCast must be a vector or a KX_GameObject");
+ return NULL;
+ }
+ }
+
+ if (dist != 0.0f) {
+ MT_Vector3 toDir = toPoint-fromPoint;
+ if (MT_fuzzyZero(toDir.length2())) {
+ return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
+ }
+ toDir.normalize();
+ toPoint = fromPoint + (dist) * toDir;
+ } else if (MT_fuzzyZero((toPoint-fromPoint).length2())) {
+ return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
+ }
+
+ PHY_IPhysicsEnvironment* pe = GetPhysicsEnvironment();
+ KX_IPhysicsController *spc = GetPhysicsController();
+ KX_GameObject *parent = GetParent();
+ if (!spc && parent)
+ spc = parent->GetPhysicsController();
+ if (parent)
+ parent->Release();
+
+ m_pHitObject = NULL;
+ if (propName)
+ m_testPropName = propName;
+ else
+ m_testPropName.SetLength(0);
+ m_xray = xray;
+ // to get the hit results
+ KX_RayCast::Callback<KX_GameObject> callback(this,spc,NULL,face);
+ KX_RayCast::RayTest(pe, fromPoint, toPoint, callback);
+
+ if (m_pHitObject)
+ {
+ PyObject* returnValue = (poly) ? PyTuple_New(4) : PyTuple_New(3);
+ if (returnValue) { // unlikely this would ever fail, if it does python sets an error
+ PyTuple_SET_ITEM(returnValue, 0, m_pHitObject->AddRef());
+ PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(callback.m_hitPoint));
+ PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(callback.m_hitNormal));
+ if (poly)
+ {
+ if (callback.m_hitMesh)
+ {
+ // if this field is set, then we can trust that m_hitPolygon is a valid polygon
+ RAS_Polygon* poly = callback.m_hitMesh->GetPolygon(callback.m_hitPolygon);
+ KX_PolyProxy* polyproxy = new KX_PolyProxy(callback.m_hitMesh, poly);
+ PyTuple_SET_ITEM(returnValue, 3, polyproxy);
+ }
+ else
+ {
+ Py_INCREF(Py_None);
+ PyTuple_SET_ITEM(returnValue, 3, Py_None);
+ }
+ }
+ }
+ return returnValue;
+ }
+ // no hit
+ if (poly)
+ return Py_BuildValue("OOOO", Py_None, Py_None, Py_None, Py_None);
+ else
+ return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
+}
+
/* ---------------------------------------------------------------------
* Some stuff taken from the header
* --------------------------------------------------------------------- */
void KX_GameObject::Relink(GEN_Map<GEN_HashedPtr, void*> *map_parameter)
{
- /* intentionally empty ? */
+ // we will relink the sensors and actuators that use object references
+ // if the object is part of the replicated hierarchy, use the new
+ // object reference instead
+ SCA_SensorList& sensorlist = GetSensors();
+ SCA_SensorList::iterator sit;
+ for (sit=sensorlist.begin(); sit != sensorlist.end(); sit++)
+ {
+ (*sit)->Relink(map_parameter);
+ }
+ SCA_ActuatorList& actuatorlist = GetActuators();
+ SCA_ActuatorList::iterator ait;
+ for (ait=actuatorlist.begin(); ait != actuatorlist.end(); ait++)
+ {
+ (*ait)->Relink(map_parameter);
+ }
}
+bool ConvertPythonToGameObject(PyObject * value, KX_GameObject **object, bool py_none_ok)
+{
+ if (value==NULL) {
+ PyErr_SetString(PyExc_TypeError, "Error in ConvertPythonToGameObject, python pointer NULL, should never happen");
+ *object = NULL;
+ return false;
+ }
+
+ if (value==Py_None) {
+ *object = NULL;
+
+ if (py_none_ok) {
+ return true;
+ } else {
+ PyErr_SetString(PyExc_TypeError, "Expected KX_GameObject or a string for a name of a KX_GameObject, None is invalid");
+ return false;
+ }
+ return (py_none_ok ? true : false);
+ }
+
+ if (PyString_Check(value)) {
+ *object = (KX_GameObject *)SCA_ILogicBrick::m_sCurrentLogicManager->GetGameObjectByName(STR_String( PyString_AsString(value) ));
+
+ if (*object) {
+ return true;
+ } else {
+ PyErr_SetString(PyExc_ValueError, "Requested name did not match any KX_GameObject");
+ return false;
+ }
+ }
+
+ if (PyObject_TypeCheck(value, &KX_GameObject::Type)) {
+ *object = static_cast<KX_GameObject*>(value);
+ return true;
+ }
+
+ *object = NULL;
+
+ if (py_none_ok) {
+ PyErr_SetString(PyExc_TypeError, "Expect a KX_GameObject, a string or None");
+ } else {
+ PyErr_SetString(PyExc_TypeError, "Expect a KX_GameObject or a string");
+ }
+
+ return false;
+}
diff --git a/source/gameengine/Ketsji/KX_GameObject.h b/source/gameengine/Ketsji/KX_GameObject.h
index c82ee9cfdab..20b15787d27 100644
--- a/source/gameengine/Ketsji/KX_GameObject.h
+++ b/source/gameengine/Ketsji/KX_GameObject.h
@@ -44,17 +44,21 @@
#include "MT_CmMatrix4x4.h"
#include "GEN_Map.h"
#include "GEN_HashedPtr.h"
-
-#define KX_FIXED_FRAME_PER_SEC 25.0f
-#define KX_FIXED_SEC_PER_FRAME (1.0f / KX_FIXED_FRAME_PER_SEC)
+#include "KX_Scene.h"
+#include "KX_KetsjiEngine.h" /* for m_anim_framerate */
+#include "KX_IPhysicsController.h" /* for suspend/resume */
+#include "DNA_object_types.h"
+#include "SCA_LogicManager.h" /* for ConvertPythonToGameObject to search object names */
#define KX_OB_DYNAMIC 1
//Forward declarations.
struct KX_ClientObjectInfo;
+class KX_RayCast;
class RAS_MeshObject;
class KX_IPhysicsController;
-
+class PHY_IPhysicsEnvironment;
+struct Object;
/**
* KX_GameObject is the main class for dynamic objects.
@@ -68,17 +72,28 @@ protected:
KX_ClientObjectInfo* m_pClient_info;
STR_String m_name;
STR_String m_text;
+ int m_layer;
std::vector<RAS_MeshObject*> m_meshes;
+ struct Object* m_pBlenderObject;
+ struct Object* m_pBlenderGroupObject;
bool m_bSuspendDynamics;
bool m_bUseObjectColor;
+ bool m_bIsNegativeScaling;
MT_Vector4 m_objectColor;
- // Is this object set to be visible? Only useful for the
- // visibility subsystem right now.
- bool m_bVisible;
+ // visible = user setting
+ // culled = while rendering, depending on camera
+ bool m_bVisible;
+ bool m_bCulled;
KX_IPhysicsController* m_pPhysicsController1;
+ // used for ray casting
+ PHY_IPhysicsEnvironment* m_pPhysicsEnvironment;
+ STR_String m_testPropName;
+ bool m_xray;
+ KX_GameObject* m_pHitObject;
+
SG_Node* m_pSGNode;
MT_CmMatrix4x4 m_OpenGL_4x4Matrix;
@@ -125,6 +140,15 @@ public:
GetParent(
);
+ /**
+ * Sets the parent of this object to a game object
+ */
+ void SetParent(KX_Scene *scene, KX_GameObject *obj);
+
+ /**
+ * Removes the parent of this object to a game object
+ */
+ void RemoveParent(KX_Scene *scene);
/**
* Construct a game object. This class also inherits the
@@ -235,8 +259,42 @@ public:
/**
* Return the linear velocity of the game object.
*/
- MT_Vector3
+ MT_Vector3
GetLinearVelocity(
+ bool local=false
+ );
+
+ /**
+ * Return the linear velocity of a given point in world coordinate
+ * but relative to center of object ([0,0,0]=center of object)
+ */
+ MT_Vector3
+ GetVelocity(
+ const MT_Point3& position
+ );
+
+ /**
+ * Return the mass of the object
+ */
+ MT_Scalar
+ GetMass();
+
+ /**
+ * Return the angular velocity of the game object.
+ */
+ MT_Vector3
+ GetAngularVelocity(
+ bool local=false
+ );
+
+ /**
+ * Align the object to a given normal.
+ */
+ void
+ AlignAxisToVect(
+ const MT_Vector3& vect,
+ int axis = 2,
+ float fac = 1.0
);
/**
@@ -259,6 +317,19 @@ public:
/**
+ * @return a pointer to the physics environment in use during the game, for rayCasting
+ */
+ PHY_IPhysicsEnvironment* GetPhysicsEnvironment()
+ {
+ return m_pPhysicsEnvironment;
+ }
+
+ void SetPhysicsEnvironment(PHY_IPhysicsEnvironment* physicsEnvironment)
+ {
+ m_pPhysicsEnvironment = physicsEnvironment;
+ }
+
+ /**
* @return a pointer to the physics controller owned by this class.
*/
@@ -270,6 +341,14 @@ public:
m_pPhysicsController1 = physicscontroller;
}
+ virtual class RAS_Deformer* GetDeformer()
+ {
+ return 0;
+ }
+ virtual void SetDeformer(class RAS_Deformer* deformer)
+ {
+
+ }
/**
* @section Coordinate system manipulation functions
@@ -283,6 +362,9 @@ public:
void NodeSetRelativeScale( const MT_Vector3& scale );
+ // adapt local position so that world position is set to desired position
+ void NodeSetWorldPosition(const MT_Point3& trans);
+
void
NodeUpdateGS(
double time,
@@ -320,6 +402,37 @@ public:
}
/**
+ * @section blender object accessor functions.
+ */
+
+ struct Object* GetBlenderObject( )
+ {
+ return m_pBlenderObject;
+ }
+
+ void SetBlenderObject( struct Object* obj)
+ {
+ m_pBlenderObject = obj;
+ }
+
+ struct Object* GetBlenderGroupObject( )
+ {
+ return m_pBlenderGroupObject;
+ }
+
+ void SetBlenderGroupObject( struct Object* obj)
+ {
+ m_pBlenderGroupObject = obj;
+ }
+
+ bool IsDupliGroup()
+ {
+ return (m_pBlenderObject &&
+ (m_pBlenderObject->transflag & OB_DUPLIGROUP) &&
+ m_pBlenderObject->dup_group != NULL) ? true : false;
+ }
+
+ /**
* Set the Scene graph node for this game object.
* warning - it is your responsibility to make sure
* all controllers look at this new node. You must
@@ -337,7 +450,18 @@ public:
{
return m_bDyna;
}
-
+
+ /**
+ * Check if this object has a vertex parent relationship
+ */
+ bool IsVertexParent( )
+ {
+ return (m_pSGNode && m_pSGNode->GetSGParent() && m_pSGNode->GetSGParent()->IsVertexParent());
+ }
+
+ bool RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data);
+ bool NeedRayCast(KX_ClientObjectInfo* client);
+
/**
* @section Physics accessors for this node.
@@ -408,20 +532,29 @@ public:
);
/**
+ * Function to set IPO option at start of IPO
+ */
+ void
+ InitIPO(
+ bool ipo_as_force,
+ bool ipo_add,
+ bool ipo_local
+ );
+
+ /**
* Odd function to update an ipo. ???
*/
void
UpdateIPO(
float curframetime,
- bool recurse,
- bool ipo_as_force,
- bool force_ipo_local
+ bool recurse
);
/**
* Updates Material Ipo data
*/
void
UpdateMaterialData(
+ dword matname_hash,
MT_Vector4 rgba,
MT_Vector3 specrgb,
MT_Scalar hard,
@@ -434,18 +567,23 @@ public:
/**
* @section Mesh accessor functions.
*/
+
+ /**
+ * Update buckets to indicate that there is a new
+ * user of this object's meshes.
+ */
+ void
+ AddMeshUser(
+ );
/**
- * Run through the meshes associated with this
- * object and bucketize them. See RAS_Mesh for
- * more details on this function. Interesting to
- * note that polygon bucketizing seems to happen on a per
- * object basis. Which may explain why there is such
- * a big performance gain when all static objects
- * are joined into 1.
+ * Update buckets with data about the mesh after
+ * creating or duplicating the object, changing
+ * visibility, object color, .. .
*/
void
- Bucketize(
+ UpdateBuckets(
+ bool recursive
);
/**
@@ -506,42 +644,74 @@ public:
ResetDebugColor(
);
- /**
- * Set the visibility of the meshes associated with this
- * object.
+ /**
+ * Was this object marked visible? (only for the explicit
+ * visibility system).
*/
- void
- MarkVisible(
- bool visible
+ bool
+ GetVisible(
+ void
);
- /**
- * Set the visibility according to the visibility flag.
+ /**
+ * Set visibility flag of this object
*/
- void
- MarkVisible(
void
+ SetVisible(
+ bool b,
+ bool recursive
);
/**
- * Was this object marked visible? (only for the ewxplicit
- * visibility system).
+ * Was this object culled?
*/
bool
- GetVisible(
+ GetCulled(
void
);
/**
- * Set visibility flag of this object
+ * Set culled flag of this object
*/
void
- SetVisible(
- bool b
+ SetCulled(
+ bool c
);
+ /**
+ * Change the layer of the object (when it is added in another layer
+ * than the original layer)
+ */
+ void
+ SetLayer(
+ int l
+ );
+
+ /**
+ * Get the object layer
+ */
+ int
+ GetLayer(
+ void
+ );
/**
+ * Get the negative scaling state
+ */
+ bool
+ IsNegativeScaling(
+ void
+ ) { return m_bIsNegativeScaling; }
+
+ /**
+ * Is this a light?
+ */
+ virtual bool
+ IsLight(
+ void
+ ) { return false; }
+
+ /**
* @section Logic bubbling methods.
*/
@@ -555,6 +725,32 @@ public:
*/
void Resume(void);
+ void SuspendDynamics(void) {
+ if (m_bSuspendDynamics)
+ {
+ return;
+ }
+
+ if (m_pPhysicsController1)
+ {
+ m_pPhysicsController1->SuspendDynamics();
+ }
+ m_bSuspendDynamics = true;
+ }
+
+ void RestoreDynamics(void) {
+ if (!m_bSuspendDynamics)
+ {
+ return;
+ }
+
+ if (m_pPhysicsController1)
+ {
+ m_pPhysicsController1->RestoreDynamics();
+ }
+ m_bSuspendDynamics = false;
+ }
+
KX_ClientObjectInfo* getClientInfo() { return m_pClient_info; }
/**
* @section Python interface functions.
@@ -573,39 +769,45 @@ public:
PyObject *value
); // _setattr method
- PyObject*
- PySetPosition(
- PyObject* self,
- PyObject* args,
- PyObject* kwds
- );
-
- static
- PyObject*
- sPySetPosition(
- PyObject* self,
- PyObject* args,
- PyObject* kwds
- );
-
- KX_PYMETHOD(KX_GameObject,GetPosition);
- KX_PYMETHOD(KX_GameObject,GetLinearVelocity);
- KX_PYMETHOD(KX_GameObject,GetVelocity);
- KX_PYMETHOD(KX_GameObject,GetMass);
- KX_PYMETHOD(KX_GameObject,GetReactionForce);
- KX_PYMETHOD(KX_GameObject,GetOrientation);
- KX_PYMETHOD(KX_GameObject,SetOrientation);
- KX_PYMETHOD(KX_GameObject,SetVisible);
- KX_PYMETHOD(KX_GameObject,SuspendDynamics);
- KX_PYMETHOD(KX_GameObject,RestoreDynamics);
- KX_PYMETHOD(KX_GameObject,EnableRigidBody);
- KX_PYMETHOD(KX_GameObject,DisableRigidBody);
- KX_PYMETHOD(KX_GameObject,ApplyImpulse);
- KX_PYMETHOD(KX_GameObject,SetCollisionMargin);
- KX_PYMETHOD(KX_GameObject,GetMesh);
- KX_PYMETHOD(KX_GameObject,GetParent);
- KX_PYMETHOD(KX_GameObject,GetPhysicsId);
+ KX_PYMETHOD_NOARGS(KX_GameObject,GetPosition);
+ KX_PYMETHOD_O(KX_GameObject,SetPosition);
+ KX_PYMETHOD_O(KX_GameObject,SetWorldPosition);
+ KX_PYMETHOD_VARARGS(KX_GameObject,GetLinearVelocity);
+ KX_PYMETHOD_VARARGS(KX_GameObject,SetLinearVelocity);
+ KX_PYMETHOD_VARARGS(KX_GameObject,GetAngularVelocity);
+ KX_PYMETHOD_VARARGS(KX_GameObject,SetAngularVelocity);
+ KX_PYMETHOD_VARARGS(KX_GameObject,GetVelocity);
+ KX_PYMETHOD_NOARGS(KX_GameObject,GetMass);
+ KX_PYMETHOD_NOARGS(KX_GameObject,GetReactionForce);
+ KX_PYMETHOD_NOARGS(KX_GameObject,GetOrientation);
+ KX_PYMETHOD_O(KX_GameObject,SetOrientation);
+ KX_PYMETHOD_NOARGS(KX_GameObject,GetVisible);
+ KX_PYMETHOD_VARARGS(KX_GameObject,SetVisible);
+ KX_PYMETHOD_NOARGS(KX_GameObject,GetState);
+ KX_PYMETHOD_O(KX_GameObject,SetState);
+ KX_PYMETHOD_VARARGS(KX_GameObject,AlignAxisToVect);
+ KX_PYMETHOD_O(KX_GameObject,GetAxisVect);
+ KX_PYMETHOD_NOARGS(KX_GameObject,SuspendDynamics);
+ KX_PYMETHOD_NOARGS(KX_GameObject,RestoreDynamics);
+ KX_PYMETHOD_NOARGS(KX_GameObject,EnableRigidBody);
+ KX_PYMETHOD_NOARGS(KX_GameObject,DisableRigidBody);
+ KX_PYMETHOD_VARARGS(KX_GameObject,ApplyImpulse);
+ KX_PYMETHOD_O(KX_GameObject,SetCollisionMargin);
+ KX_PYMETHOD_NOARGS(KX_GameObject,GetParent);
+ KX_PYMETHOD_O(KX_GameObject,SetParent);
+ KX_PYMETHOD_NOARGS(KX_GameObject,RemoveParent);
+ KX_PYMETHOD_NOARGS(KX_GameObject,GetChildren);
+ KX_PYMETHOD_NOARGS(KX_GameObject,GetChildrenRecursive);
+ KX_PYMETHOD_VARARGS(KX_GameObject,GetMesh);
+ KX_PYMETHOD_NOARGS(KX_GameObject,GetPhysicsId);
+ KX_PYMETHOD_NOARGS(KX_GameObject,GetPropertyNames);
+ KX_PYMETHOD_O(KX_GameObject,ReplaceMesh);
+ KX_PYMETHOD_NOARGS(KX_GameObject,EndObject);
+ KX_PYMETHOD_DOC(KX_GameObject,rayCastTo);
+ KX_PYMETHOD_DOC(KX_GameObject,rayCast);
KX_PYMETHOD_DOC(KX_GameObject,getDistanceTo);
+ KX_PYMETHOD_DOC(KX_GameObject,getVectTo);
+
private :
/**
@@ -623,5 +825,8 @@ private :
};
+/* utility conversion function */
+bool ConvertPythonToGameObject(PyObject * value, KX_GameObject **object, bool py_none_ok);
+
#endif //__KX_GAMEOBJECT
diff --git a/source/gameengine/Ketsji/KX_IPO_SGController.cpp b/source/gameengine/Ketsji/KX_IPO_SGController.cpp
index bb4b75c6c4a..67d54cf0b0b 100644
--- a/source/gameengine/Ketsji/KX_IPO_SGController.cpp
+++ b/source/gameengine/Ketsji/KX_IPO_SGController.cpp
@@ -48,20 +48,24 @@ typedef unsigned long uint_ptr;
#include "KX_ScalarInterpolator.h"
#include "KX_GameObject.h"
#include "KX_IPhysicsController.h"
+#include "DNA_ipo_types.h"
+#include "BLI_arithb.h"
// All objects should start on frame 1! Will we ever need an object to
// start on another frame, the 1.0 should change.
KX_IpoSGController::KX_IpoSGController()
-: m_modify_position(false),
- m_modify_orientation(false),
- m_modify_scaling(false),
- m_ipo_as_force(false),
- m_force_ipo_acts_local(false),
+: m_ipo_as_force(false),
+ m_ipo_add(false),
+ m_ipo_local(false),
m_modified(true),
- m_ipotime(1.0)
+ m_ipo_start_initialized(false),
+ m_ipotime(1.0),
+ m_ipo_start_euler(0.0,0.0,0.0),
+ m_ipo_euler_initialized(false)
{
m_game_object = NULL;
-
+ for (int i=0; i < KX_MAX_IPO_CHANNELS; i++)
+ m_ipo_channels_active[i] = false;
}
@@ -74,8 +78,23 @@ void KX_IpoSGController::SetOption(
m_ipo_as_force = (value != 0);
m_modified = true;
break;
- case SG_CONTR_IPO_FORCES_ACT_LOCAL:
- m_force_ipo_acts_local = (value != 0);
+ case SG_CONTR_IPO_IPO_ADD:
+ m_ipo_add = (value != 0);
+ m_modified = true;
+ break;
+ case SG_CONTR_IPO_RESET:
+ if (m_ipo_start_initialized && value) {
+ m_ipo_start_initialized = false;
+ m_modified = true;
+ }
+ break;
+ case SG_CONTR_IPO_LOCAL:
+ if (value/* && ((SG_Node*)m_pObject)->GetSGParent() == NULL*/) {
+ // only accept local Ipo if the object has no parent
+ m_ipo_local = true;
+ } else {
+ m_ipo_local = false;
+ }
m_modified = true;
break;
default:
@@ -112,35 +131,200 @@ bool KX_IpoSGController::Update(double currentTime)
}
SG_Spatial* ob = (SG_Spatial*)m_pObject;
-
- if (m_modify_position) {
- if (m_ipo_as_force) {
-
- if (m_game_object && ob) {
- m_game_object->GetPhysicsController()->ApplyForce(m_force_ipo_acts_local ?
+
+ //initialization on the first frame of the IPO
+ if (! m_ipo_start_initialized && currentTime > 0.0) {
+ m_ipo_start_point = ob->GetLocalPosition();
+ m_ipo_start_orient = ob->GetLocalOrientation();
+ m_ipo_start_scale = ob->GetLocalScale();
+ m_ipo_start_initialized = true;
+ if (!m_ipo_euler_initialized) {
+ // do it only once to avoid angle discontinuities
+ m_ipo_start_orient.getEuler(m_ipo_start_euler[0], m_ipo_start_euler[1], m_ipo_start_euler[2]);
+ m_ipo_euler_initialized = true;
+ }
+ }
+
+ //modifies position?
+ if (m_ipo_channels_active[OB_LOC_X] || m_ipo_channels_active[OB_LOC_Y] || m_ipo_channels_active[OB_LOC_Z] || m_ipo_channels_active[OB_DLOC_X] || m_ipo_channels_active[OB_DLOC_Y] || m_ipo_channels_active[OB_DLOC_Z])
+ {
+ if (m_ipo_as_force == true)
+ {
+ if (m_game_object && ob && m_game_object->GetPhysicsController())
+ {
+ m_game_object->GetPhysicsController()->ApplyForce(m_ipo_local ?
ob->GetWorldOrientation() * m_ipo_xform.GetPosition() :
m_ipo_xform.GetPosition(), false);
}
-
- } else {
- ob->SetLocalPosition(m_ipo_xform.GetPosition());
+ }
+ else
+ {
+ // Local ipo should be defined with the object position at (0,0,0)
+ // Local transform is applied to the object based on initial position
+ MT_Point3 newPosition(0.0,0.0,0.0);
+
+ if (!m_ipo_add)
+ newPosition = ob->GetLocalPosition();
+ //apply separate IPO channels if there is any data in them
+ //Loc and dLoc act by themselves or are additive
+ //LocX and dLocX
+ if (m_ipo_channels_active[OB_LOC_X]) {
+ newPosition[0] = (m_ipo_channels_active[OB_DLOC_X] ? m_ipo_xform.GetPosition()[0] + m_ipo_xform.GetDeltaPosition()[0] : m_ipo_xform.GetPosition()[0]);
+ }
+ else if (m_ipo_channels_active[OB_DLOC_X] && m_ipo_start_initialized) {
+ newPosition[0] = (((!m_ipo_add)?m_ipo_start_point[0]:0.0) + m_ipo_xform.GetDeltaPosition()[0]);
+ }
+ //LocY and dLocY
+ if (m_ipo_channels_active[OB_LOC_Y]) {
+ newPosition[1] = (m_ipo_channels_active[OB_DLOC_Y] ? m_ipo_xform.GetPosition()[1] + m_ipo_xform.GetDeltaPosition()[1] : m_ipo_xform.GetPosition()[1]);
+ }
+ else if (m_ipo_channels_active[OB_DLOC_Y] && m_ipo_start_initialized) {
+ newPosition[1] = (((!m_ipo_add)?m_ipo_start_point[1]:0.0) + m_ipo_xform.GetDeltaPosition()[1]);
+ }
+ //LocZ and dLocZ
+ if (m_ipo_channels_active[OB_LOC_Z]) {
+ newPosition[2] = (m_ipo_channels_active[OB_DLOC_Z] ? m_ipo_xform.GetPosition()[2] + m_ipo_xform.GetDeltaPosition()[2] : m_ipo_xform.GetPosition()[2]);
+ }
+ else if (m_ipo_channels_active[OB_DLOC_Z] && m_ipo_start_initialized) {
+ newPosition[2] = (((!m_ipo_add)?m_ipo_start_point[2]:0.0) + m_ipo_xform.GetDeltaPosition()[2]);
+ }
+ if (m_ipo_add) {
+ if (m_ipo_local)
+ newPosition = m_ipo_start_point + m_ipo_start_scale*(m_ipo_start_orient*newPosition);
+ else
+ newPosition = m_ipo_start_point + newPosition;
+ }
+ ob->SetLocalPosition(newPosition);
}
}
- if (m_modify_orientation) {
+ //modifies orientation?
+ if (m_ipo_channels_active[OB_ROT_X] || m_ipo_channels_active[OB_ROT_Y] || m_ipo_channels_active[OB_ROT_Z] || m_ipo_channels_active[OB_DROT_X] || m_ipo_channels_active[OB_DROT_Y] || m_ipo_channels_active[OB_DROT_Z]) {
if (m_ipo_as_force) {
if (m_game_object && ob) {
- m_game_object->ApplyTorque(m_force_ipo_acts_local ?
+ m_game_object->ApplyTorque(m_ipo_local ?
ob->GetWorldOrientation() * m_ipo_xform.GetEulerAngles() :
m_ipo_xform.GetEulerAngles(), false);
}
+ } else if (m_ipo_add) {
+ if (m_ipo_start_initialized) {
+ double yaw=0, pitch=0, roll=0; //delta Euler angles
- } else {
- ob->SetLocalOrientation(MT_Matrix3x3(m_ipo_xform.GetEulerAngles()));
+ //RotX and dRotX
+ if (m_ipo_channels_active[OB_ROT_X])
+ yaw += m_ipo_xform.GetEulerAngles()[0];
+ if (m_ipo_channels_active[OB_DROT_X])
+ yaw += m_ipo_xform.GetDeltaEulerAngles()[0];
+
+ //RotY dRotY
+ if (m_ipo_channels_active[OB_ROT_Y])
+ pitch += m_ipo_xform.GetEulerAngles()[1];
+ if (m_ipo_channels_active[OB_DROT_Y])
+ pitch += m_ipo_xform.GetDeltaEulerAngles()[1];
+
+ //RotZ and dRotZ
+ if (m_ipo_channels_active[OB_ROT_Z])
+ roll += m_ipo_xform.GetEulerAngles()[2];
+ if (m_ipo_channels_active[OB_DROT_Z])
+ roll += m_ipo_xform.GetDeltaEulerAngles()[2];
+
+ MT_Matrix3x3 rotation(MT_Vector3(yaw, pitch, roll));
+ if (m_ipo_local)
+ rotation = m_ipo_start_orient * rotation;
+ else
+ rotation = rotation * m_ipo_start_orient;
+ ob->SetLocalOrientation(rotation);
+ }
+ } else if (m_ipo_channels_active[OB_ROT_X] || m_ipo_channels_active[OB_ROT_Y] || m_ipo_channels_active[OB_ROT_Z]) {
+ if (m_ipo_euler_initialized) {
+ // assume all channel absolute
+ // All 3 channels should be specified but if they are not, we will take
+ // the value at the start of the game to avoid angle sign reversal
+ double yaw=m_ipo_start_euler[0], pitch=m_ipo_start_euler[1], roll=m_ipo_start_euler[2];
+
+ //RotX and dRotX
+ if (m_ipo_channels_active[OB_ROT_X]) {
+ yaw = (m_ipo_channels_active[OB_DROT_X] ? (m_ipo_xform.GetEulerAngles()[0] + m_ipo_xform.GetDeltaEulerAngles()[0]) : m_ipo_xform.GetEulerAngles()[0] );
+ }
+ else if (m_ipo_channels_active[OB_DROT_X]) {
+ yaw += m_ipo_xform.GetDeltaEulerAngles()[0];
+ }
+
+ //RotY dRotY
+ if (m_ipo_channels_active[OB_ROT_Y]) {
+ pitch = (m_ipo_channels_active[OB_DROT_Y] ? (m_ipo_xform.GetEulerAngles()[1] + m_ipo_xform.GetDeltaEulerAngles()[1]) : m_ipo_xform.GetEulerAngles()[1] );
+ }
+ else if (m_ipo_channels_active[OB_DROT_Y]) {
+ pitch += m_ipo_xform.GetDeltaEulerAngles()[1];
+ }
+
+ //RotZ and dRotZ
+ if (m_ipo_channels_active[OB_ROT_Z]) {
+ roll = (m_ipo_channels_active[OB_DROT_Z] ? (m_ipo_xform.GetEulerAngles()[2] + m_ipo_xform.GetDeltaEulerAngles()[2]) : m_ipo_xform.GetEulerAngles()[2] );
+ }
+ else if (m_ipo_channels_active[OB_DROT_Z]) {
+ roll += m_ipo_xform.GetDeltaEulerAngles()[2];
+ }
+ ob->SetLocalOrientation(MT_Vector3(yaw, pitch, roll));
+ }
+ } else if (m_ipo_start_initialized) {
+ // only DROT, treat as Add
+ double yaw=0, pitch=0, roll=0; //delta Euler angles
+
+ //dRotX
+ if (m_ipo_channels_active[OB_DROT_X])
+ yaw = m_ipo_xform.GetDeltaEulerAngles()[0];
+
+ //dRotY
+ if (m_ipo_channels_active[OB_DROT_Y])
+ pitch = m_ipo_xform.GetDeltaEulerAngles()[1];
+
+ //dRotZ
+ if (m_ipo_channels_active[OB_DROT_Z])
+ roll = m_ipo_xform.GetDeltaEulerAngles()[2];
+
+ // dRot are always local
+ MT_Matrix3x3 rotation(MT_Vector3(yaw, pitch, roll));
+ rotation = m_ipo_start_orient * rotation;
+ ob->SetLocalOrientation(rotation);
+ }
+ }
+ //modifies scale?
+ if (m_ipo_channels_active[OB_SIZE_X] || m_ipo_channels_active[OB_SIZE_Y] || m_ipo_channels_active[OB_SIZE_Z] || m_ipo_channels_active[OB_DSIZE_X] || m_ipo_channels_active[OB_DSIZE_Y] || m_ipo_channels_active[OB_DSIZE_Z]) {
+ //default is no scale change
+ MT_Vector3 newScale(1.0,1.0,1.0);
+ if (!m_ipo_add)
+ newScale = ob->GetLocalScale();
+
+ if (m_ipo_channels_active[OB_SIZE_X]) {
+ newScale[0] = (m_ipo_channels_active[OB_DSIZE_X] ? (m_ipo_xform.GetScaling()[0] + m_ipo_xform.GetDeltaScaling()[0]) : m_ipo_xform.GetScaling()[0]);
+ }
+ else if (m_ipo_channels_active[OB_DSIZE_X] && m_ipo_start_initialized) {
+ newScale[0] = (m_ipo_xform.GetDeltaScaling()[0] + ((!m_ipo_add)?m_ipo_start_scale[0]:0.0));
+ }
+
+ //RotY dRotY
+ if (m_ipo_channels_active[OB_SIZE_Y]) {
+ newScale[1] = (m_ipo_channels_active[OB_DSIZE_Y] ? (m_ipo_xform.GetScaling()[1] + m_ipo_xform.GetDeltaScaling()[1]): m_ipo_xform.GetScaling()[1]);
+ }
+ else if (m_ipo_channels_active[OB_DSIZE_Y] && m_ipo_start_initialized) {
+ newScale[1] = (m_ipo_xform.GetDeltaScaling()[1] + ((!m_ipo_add)?m_ipo_start_scale[1]:0.0));
}
+
+ //RotZ and dRotZ
+ if (m_ipo_channels_active[OB_SIZE_Z]) {
+ newScale[2] = (m_ipo_channels_active[OB_DSIZE_Z] ? (m_ipo_xform.GetScaling()[2] + m_ipo_xform.GetDeltaScaling()[2]) : m_ipo_xform.GetScaling()[2]);
+ }
+ else if (m_ipo_channels_active[OB_DSIZE_Z] && m_ipo_start_initialized) {
+ newScale[2] = (m_ipo_xform.GetDeltaScaling()[2] + ((!m_ipo_add)?m_ipo_start_scale[2]:1.0));
+ }
+
+ if (m_ipo_add) {
+ newScale = m_ipo_start_scale * newScale;
+ }
+
+ ob->SetLocalScale(newScale);
}
- if (m_modify_scaling)
- ob->SetLocalScale(m_ipo_xform.GetScaling());
m_modified=false;
}
diff --git a/source/gameengine/Ketsji/KX_IPO_SGController.h b/source/gameengine/Ketsji/KX_IPO_SGController.h
index a010e8e3e6c..031b74294ce 100644
--- a/source/gameengine/Ketsji/KX_IPO_SGController.h
+++ b/source/gameengine/Ketsji/KX_IPO_SGController.h
@@ -35,27 +35,49 @@
#include "KX_IPOTransform.h"
#include "KX_IInterpolator.h"
+#define KX_MAX_IPO_CHANNELS 19 //note- [0] is not used
+
class KX_IpoSGController : public SG_Controller
{
KX_IPOTransform m_ipo_xform;
T_InterpolatorList m_interpolators;
- /* Why not bools? */
- short m_modify_position : 1;
- short m_modify_orientation : 1;
- short m_modify_scaling : 1;
+
+ /** Flag for each IPO channel that can be applied to a game object */
+ bool m_ipo_channels_active[KX_MAX_IPO_CHANNELS];
/** Interpret the ipo as a force rather than a displacement? */
bool m_ipo_as_force;
- /** Ipo-as-force acts in local rather than in global coordinates? */
- bool m_force_ipo_acts_local;
+ /** Add Ipo curve to current loc/rot/scale */
+ bool m_ipo_add;
+ /** Ipo must be applied in local coordinate rather than in global coordinates (used for force and Add mode)*/
+ bool m_ipo_local;
+
/** Were settings altered since the last update? */
bool m_modified;
/** Local time of this ipo.*/
double m_ipotime;
+ /** Location of the object when the IPO is first fired (for local transformations) */
+ class MT_Point3 m_ipo_start_point;
+
+ /** Orientation of the object when the IPO is first fired (for local transformations) */
+ class MT_Matrix3x3 m_ipo_start_orient;
+
+ /** Scale of the object when the IPO is first fired (for local transformations) */
+ class MT_Vector3 m_ipo_start_scale;
+
+ /** if IPO initial position has been set for local normal IPO */
+ bool m_ipo_start_initialized;
+
+ /** Euler angles at the start of the game, needed for incomplete ROT Ipo curves */
+ class MT_Vector3 m_ipo_start_euler;
+
+ /** true is m_ipo_start_euler has been initialized */
+ bool m_ipo_euler_initialized;
+
/** A reference to the original game object. */
class KX_GameObject* m_game_object;
@@ -77,16 +99,12 @@ public:
/** Set reference to the corresponding game object. */
void SetGameObject(class KX_GameObject*);
- void SetModifyPosition(bool modifypos) {
- m_modify_position=modifypos;
- }
- void SetModifyOrientation(bool modifyorient) {
- m_modify_orientation=modifyorient;
- }
- void SetModifyScaling(bool modifyscale) {
- m_modify_scaling=modifyscale;
+ void SetIPOChannelActive(int index, bool value) {
+ //indexes found in makesdna\DNA_ipo_types.h
+ m_ipo_channels_active[index] = value;
}
+
KX_IPOTransform& GetIPOTransform()
{
return m_ipo_xform;
@@ -102,3 +120,4 @@ public:
#endif //__IPO_SGCONTROLLER_H
+
diff --git a/source/gameengine/Ketsji/KX_IPhysicsController.h b/source/gameengine/Ketsji/KX_IPhysicsController.h
index 009db40d3e8..4ea283e9f98 100644
--- a/source/gameengine/Ketsji/KX_IPhysicsController.h
+++ b/source/gameengine/Ketsji/KX_IPhysicsController.h
@@ -64,20 +64,22 @@ public:
virtual void ApplyTorque(const MT_Vector3& torque,bool local)=0;
virtual void ApplyForce(const MT_Vector3& force,bool local)=0;
virtual MT_Vector3 GetLinearVelocity()=0;
+ virtual MT_Vector3 GetAngularVelocity()=0;
virtual MT_Vector3 GetVelocity(const MT_Point3& pos)=0;
virtual void SetAngularVelocity(const MT_Vector3& ang_vel,bool local)=0;
virtual void SetLinearVelocity(const MT_Vector3& lin_vel,bool local)=0;
virtual void resolveCombinedVelocities(float linvelX,float linvelY,float linvelZ,float angVelX,float angVelY,float angVelZ) = 0;
virtual void getOrientation(MT_Quaternion& orn)=0;
- virtual void setOrientation(const MT_Quaternion& orn)=0;
+ virtual void setOrientation(const MT_Matrix3x3& orn)=0;
+ //virtual void setOrientation(const MT_Quaternion& orn)=0;
virtual void setPosition(const MT_Point3& pos)=0;
virtual void setScaling(const MT_Vector3& scaling)=0;
virtual MT_Scalar GetMass()=0;
virtual MT_Vector3 getReactionForce()=0;
virtual void setRigidBody(bool rigid)=0;
- virtual void SuspendDynamics()=0;
+ virtual void SuspendDynamics(bool ghost=false)=0;
virtual void RestoreDynamics()=0;
virtual SG_Controller* GetReplica(class SG_Node* destnode)=0;
@@ -86,7 +88,11 @@ public:
m_bDyna = isDynamic;
}
+ bool IsDyna(void) {
+ return m_bDyna;
+ }
+ virtual MT_Scalar GetRadius()=0;
virtual void SetSumoTransform(bool nondynaonly)=0;
// todo: remove next line !
virtual void SetSimulatedTime(double time)=0;
diff --git a/source/gameengine/Ketsji/KX_ISceneConverter.h b/source/gameengine/Ketsji/KX_ISceneConverter.h
index cb749801827..3709fa8c784 100644
--- a/source/gameengine/Ketsji/KX_ISceneConverter.h
+++ b/source/gameengine/Ketsji/KX_ISceneConverter.h
@@ -32,6 +32,8 @@
#include "STR_String.h"
#include "KX_Python.h"
+struct Scene;
+
class KX_ISceneConverter
{
@@ -52,6 +54,8 @@ public:
class RAS_IRenderTools* rendertools,
class RAS_ICanvas* canvas)=0;
+ virtual void RemoveScene(class KX_Scene *scene)=0;
+
virtual void SetAlwaysUseExpandFraming(bool to_what) = 0;
virtual void SetNewFileName(const STR_String& filename) = 0;
@@ -72,6 +76,11 @@ public:
virtual void SetMaterials(bool val) =0;
virtual bool GetMaterials()=0;
+ // use blender glsl materials
+ virtual void SetGLSLMaterials(bool val) =0;
+ virtual bool GetGLSLMaterials()=0;
+
+ virtual struct Scene* GetBlenderSceneForName(const STR_String& name)=0;
};
#endif //__KX_ISCENECONVERTER_H
diff --git a/source/gameengine/Ketsji/KX_IpoActuator.cpp b/source/gameengine/Ketsji/KX_IpoActuator.cpp
index 3af1316ba5d..f5e17118ffb 100644
--- a/source/gameengine/Ketsji/KX_IpoActuator.cpp
+++ b/source/gameengine/Ketsji/KX_IpoActuator.cpp
@@ -37,6 +37,7 @@
#include "KX_IpoActuator.h"
#include "KX_GameObject.h"
+#include "FloatValue.h"
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -59,49 +60,17 @@ STR_String KX_IpoActuator::S_KX_ACT_IPO_FROM_PROP_STRING = "FromProp";
/* ------------------------------------------------------------------------- */
/* Native functions */
/* ------------------------------------------------------------------------- */
-/** Another poltergeist? This seems to be a very transient class... */
-class CIpoAction : public CAction
-{
- float m_curtime;
- bool m_recurse;
- KX_GameObject* m_gameobj;
- bool m_ipo_as_force;
- bool m_force_ipo_local;
-
-public:
- CIpoAction(KX_GameObject* gameobj,
- float curtime,
- bool recurse,
- bool ipo_as_force,
- bool force_ipo_local) :
- m_curtime(curtime) ,
- m_recurse(recurse),
- m_gameobj(gameobj),
- m_ipo_as_force(ipo_as_force),
- m_force_ipo_local(force_ipo_local)
- {
- /* intentionally empty */
- };
-
- virtual void Execute() const
- {
- m_gameobj->UpdateIPO(
- m_curtime,
- m_recurse,
- m_ipo_as_force,
- m_force_ipo_local);
- };
-
-};
KX_IpoActuator::KX_IpoActuator(SCA_IObject* gameobj,
const STR_String& propname,
+ const STR_String& framePropname,
float starttime,
float endtime,
bool recurse,
int acttype,
bool ipo_as_force,
- bool force_ipo_local,
+ bool ipo_add,
+ bool ipo_local,
PyTypeObject* T)
: SCA_IActuator(gameobj,T),
m_bNegativeEvent(false),
@@ -111,8 +80,10 @@ KX_IpoActuator::KX_IpoActuator(SCA_IObject* gameobj,
m_localtime(starttime),
m_direction(1),
m_propname(propname),
+ m_framepropname(framePropname),
m_ipo_as_force(ipo_as_force),
- m_force_ipo_local(force_ipo_local),
+ m_ipo_add(ipo_add),
+ m_ipo_local(ipo_local),
m_type((IpoActType)acttype)
{
m_starttime = -2.0*fabs(m_endframe - m_startframe) - 1.0;
@@ -160,18 +131,17 @@ bool KX_IpoActuator::ClampLocalTime()
void KX_IpoActuator::SetStartTime(float curtime)
{
- float direction = m_startframe < m_endframe ? 1.0 : -1.0;
+ float direction = m_startframe < m_endframe ? 1.0f : -1.0f;
- curtime = curtime - KX_KetsjiEngine::GetSuspendedDelta();
if (m_direction > 0)
- m_starttime = curtime - direction*(m_localtime - m_startframe)/KX_FIXED_FRAME_PER_SEC;
+ m_starttime = curtime - direction*(m_localtime - m_startframe)/KX_KetsjiEngine::GetAnimFrameRate();
else
- m_starttime = curtime - direction*(m_endframe - m_localtime)/KX_FIXED_FRAME_PER_SEC;
+ m_starttime = curtime - direction*(m_endframe - m_localtime)/KX_KetsjiEngine::GetAnimFrameRate();
}
void KX_IpoActuator::SetLocalTime(float curtime)
{
- float delta_time = ((curtime - m_starttime) - KX_KetsjiEngine::GetSuspendedDelta())*KX_FIXED_FRAME_PER_SEC;
+ float delta_time = (curtime - m_starttime)*KX_KetsjiEngine::GetAnimFrameRate();
// negative delta_time is caused by floating point inaccuracy
// perhaps the inaccuracy could be reduced a bit
@@ -195,36 +165,28 @@ bool KX_IpoActuator::Update(double curtime, bool frame)
// maybe there are events for us in the queue !
bool bNegativeEvent = false;
int numevents = 0;
+ bool bIpoStart = false;
+
+ curtime -= KX_KetsjiEngine::GetSuspendedDelta();
if (frame)
{
numevents = m_events.size();
- for (vector<CValue*>::iterator i=m_events.end(); !(i==m_events.begin());)
- {
- --i;
- if ((*i)->GetNumber() == 0.0f)
- bNegativeEvent = true;
-
- (*i)->Release();
- }
- m_events.clear();
-
- if (m_type != KX_ACT_IPO_PLAY)
- {
- if (bNegativeEvent)
- RemoveAllEvents();
- }
+ bNegativeEvent = IsNegativeEvent();
+ RemoveAllEvents();
}
- double start_smaller_then_end = ( m_startframe < m_endframe ? 1.0 : -1.0);
+ float start_smaller_then_end = ( m_startframe < m_endframe ? 1.0f : -1.0f);
bool result=true;
if (!bNegativeEvent)
{
- if (m_starttime < -2.0*start_smaller_then_end*(m_endframe - m_startframe))
+ if (m_starttime < -2.0f*start_smaller_then_end*(m_endframe - m_startframe))
{
- m_starttime = curtime - KX_KetsjiEngine::GetSuspendedDelta();
+ // start for all Ipo, initial start for LOOP_STOP
+ m_starttime = curtime;
m_bIpoPlaying = true;
+ bIpoStart = true;
}
}
@@ -235,17 +197,10 @@ bool KX_IpoActuator::Update(double curtime, bool frame)
{
// Check if playing forwards. result = ! finished
- if (!bNegativeEvent)
- {
- if (start_smaller_then_end > 0.0)
- result = (m_localtime < m_endframe && !(m_localtime == m_startframe && bNegativeEvent));
- else
- result = (m_localtime > m_endframe && !(m_localtime == m_startframe && bNegativeEvent));
- }
+ if (start_smaller_then_end > 0.f)
+ result = (m_localtime < m_endframe && m_bIpoPlaying);
else
- {
- result = (m_bIpoPlaying && (m_localtime < m_endframe));
- }
+ result = (m_localtime > m_endframe && m_bIpoPlaying);
if (result)
{
@@ -253,18 +208,13 @@ bool KX_IpoActuator::Update(double curtime, bool frame)
/* Perform clamping */
ClampLocalTime();
-
- CIpoAction ipoaction(
- (KX_GameObject*)GetParent(),
- m_localtime,
- m_recurse,
- m_ipo_as_force,
- m_force_ipo_local);
- GetParent()->Execute(ipoaction);
+
+ if (bIpoStart)
+ ((KX_GameObject*)GetParent())->InitIPO(m_ipo_as_force, m_ipo_add, m_ipo_local);
+ ((KX_GameObject*)GetParent())->UpdateIPO(m_localtime,m_recurse);
} else
{
m_localtime=m_startframe;
- SetStartTime(curtime);
m_direction=1;
}
break;
@@ -272,7 +222,7 @@ bool KX_IpoActuator::Update(double curtime, bool frame)
case KX_ACT_IPO_PINGPONG:
{
result = true;
- if (bNegativeEvent && ((m_localtime == m_startframe )|| (m_localtime == m_endframe)))
+ if (bNegativeEvent && !m_bIpoPlaying)
result = false;
else
SetLocalTime(curtime);
@@ -283,39 +233,35 @@ bool KX_IpoActuator::Update(double curtime, bool frame)
m_direction = -m_direction;
}
- CIpoAction ipoaction(
- (KX_GameObject*) GetParent(),
- m_localtime,
- m_recurse,
- m_ipo_as_force,
- m_force_ipo_local);
- GetParent()->Execute(ipoaction);
+ if (bIpoStart && m_direction > 0)
+ ((KX_GameObject*)GetParent())->InitIPO(m_ipo_as_force, m_ipo_add, m_ipo_local);
+ ((KX_GameObject*)GetParent())->UpdateIPO(m_localtime,m_recurse);
break;
}
case KX_ACT_IPO_FLIPPER:
{
- result = !(bNegativeEvent && (m_localtime == m_startframe));
+ if (bNegativeEvent && !m_bIpoPlaying)
+ result = false;
if (numevents)
{
+ float oldDirection = m_direction;
if (bNegativeEvent)
m_direction = -1;
else
m_direction = 1;
- SetStartTime(curtime);
+ if (m_direction != oldDirection)
+ // changing direction, reset start time
+ SetStartTime(curtime);
}
SetLocalTime(curtime);
if (ClampLocalTime() && m_localtime == m_startframe)
result = false;
-
- CIpoAction ipoaction(
- (KX_GameObject*) GetParent(),
- m_localtime,
- m_recurse,
- m_ipo_as_force,
- m_force_ipo_local);
- GetParent()->Execute(ipoaction);
+
+ if (bIpoStart)
+ ((KX_GameObject*)GetParent())->InitIPO(m_ipo_as_force, m_ipo_add, m_ipo_local);
+ ((KX_GameObject*)GetParent())->UpdateIPO(m_localtime,m_recurse);
break;
}
@@ -329,18 +275,26 @@ bool KX_IpoActuator::Update(double curtime, bool frame)
m_bNegativeEvent = false;
numevents = 0;
}
- SetStartTime(curtime);
+ if (!m_bIpoPlaying)
+ {
+ // Ipo was stopped, make sure we will restart from where it stopped
+ SetStartTime(curtime);
+ if (!bNegativeEvent)
+ // positive signal will restart the Ipo
+ m_bIpoPlaying = true;
+ }
+
} // fall through to loopend, and quit the ipo animation immediatly
}
case KX_ACT_IPO_LOOPEND:
{
if (numevents){
- if (bNegativeEvent){
+ if (bNegativeEvent && m_bIpoPlaying){
m_bNegativeEvent = true;
}
}
- if (bNegativeEvent && m_localtime == m_startframe){
+ if (bNegativeEvent && !m_bIpoPlaying){
result = false;
}
else
@@ -353,8 +307,12 @@ bool KX_IpoActuator::Update(double curtime, bool frame)
if (!m_bNegativeEvent){
/* Perform wraparound */
SetLocalTime(curtime);
- m_localtime = m_startframe + fmod(m_localtime, m_startframe - m_endframe);
+ if (start_smaller_then_end > 0.f)
+ m_localtime = m_startframe + fmod(m_localtime - m_startframe, m_endframe - m_startframe);
+ else
+ m_localtime = m_startframe - fmod(m_startframe - m_localtime, m_startframe - m_endframe);
SetStartTime(curtime);
+ bIpoStart = true;
}
else
{
@@ -366,13 +324,9 @@ bool KX_IpoActuator::Update(double curtime, bool frame)
}
}
- CIpoAction ipoaction(
- (KX_GameObject*) GetParent(),
- m_localtime,
- m_recurse,
- m_ipo_as_force,
- m_force_ipo_local);
- GetParent()->Execute(ipoaction);
+ if (m_bIpoPlaying && bIpoStart)
+ ((KX_GameObject*)GetParent())->InitIPO(m_ipo_as_force, m_ipo_add, m_ipo_local);
+ ((KX_GameObject*)GetParent())->UpdateIPO(m_localtime,m_recurse);
break;
}
@@ -392,14 +346,9 @@ bool KX_IpoActuator::Update(double curtime, bool frame)
{
m_localtime = propval->GetNumber();
- CIpoAction ipoaction(
- (KX_GameObject*) GetParent(),
- m_localtime,
- m_recurse,
- m_ipo_as_force,
- m_force_ipo_local);
- GetParent()->Execute(ipoaction);
-
+ if (bIpoStart)
+ ((KX_GameObject*)GetParent())->InitIPO(m_ipo_as_force, m_ipo_add, m_ipo_local);
+ ((KX_GameObject*)GetParent())->UpdateIPO(m_localtime,m_recurse);
} else
{
result = false;
@@ -410,9 +359,26 @@ bool KX_IpoActuator::Update(double curtime, bool frame)
default:
result = false;
}
-
- if (!result && m_type != KX_ACT_IPO_LOOPSTOP)
- m_starttime = -2.0*start_smaller_then_end*(m_endframe - m_startframe) - 1.0;
+
+ /* Set the property if its defined */
+ if (m_framepropname[0] != '\0') {
+ CValue* propowner = GetParent();
+ CValue* oldprop = propowner->GetProperty(m_framepropname);
+ CValue* newval = new CFloatValue(m_localtime);
+ if (oldprop) {
+ oldprop->SetValue(newval);
+ } else {
+ propowner->SetProperty(m_framepropname, newval);
+ }
+ newval->Release();
+ }
+
+ if (!result)
+ {
+ if (m_type != KX_ACT_IPO_LOOPSTOP)
+ m_starttime = -2.0*start_smaller_then_end*(m_endframe - m_startframe) - 1.0;
+ m_bIpoPlaying = false;
+ }
return result;
}
@@ -474,30 +440,20 @@ PyParentObject KX_IpoActuator::Parents[] = {
};
PyMethodDef KX_IpoActuator::Methods[] = {
- {"set", (PyCFunction) KX_IpoActuator::sPySet,
- METH_VARARGS, Set_doc},
- {"setProperty", (PyCFunction) KX_IpoActuator::sPySetProperty,
- METH_VARARGS, SetProperty_doc},
- {"setStart", (PyCFunction) KX_IpoActuator::sPySetStart,
- METH_VARARGS, SetStart_doc},
- {"getStart", (PyCFunction) KX_IpoActuator::sPyGetStart,
- METH_VARARGS, GetStart_doc},
- {"setEnd", (PyCFunction) KX_IpoActuator::sPySetEnd,
- METH_VARARGS, SetEnd_doc},
- {"getEnd", (PyCFunction) KX_IpoActuator::sPyGetEnd,
- METH_VARARGS, GetEnd_doc},
- {"setIpoAsForce", (PyCFunction) KX_IpoActuator::sPySetIpoAsForce,
- METH_VARARGS, SetIpoAsForce_doc},
- {"getIpoAsForce", (PyCFunction) KX_IpoActuator::sPyGetIpoAsForce,
- METH_VARARGS, GetIpoAsForce_doc},
- {"setType", (PyCFunction) KX_IpoActuator::sPySetType,
- METH_VARARGS, SetType_doc},
- {"getType", (PyCFunction) KX_IpoActuator::sPyGetType,
- METH_VARARGS, GetType_doc},
- {"setForceIpoActsLocal", (PyCFunction) KX_IpoActuator::sPySetForceIpoActsLocal,
- METH_VARARGS, SetForceIpoActsLocal_doc},
- {"getForceIpoActsLocal", (PyCFunction) KX_IpoActuator::sPyGetForceIpoActsLocal,
- METH_VARARGS, GetForceIpoActsLocal_doc},
+ {"set", (PyCFunction) KX_IpoActuator::sPySet, METH_VARARGS, (PY_METHODCHAR)Set_doc},
+ {"setProperty", (PyCFunction) KX_IpoActuator::sPySetProperty, METH_VARARGS, (PY_METHODCHAR)SetProperty_doc},
+ {"setStart", (PyCFunction) KX_IpoActuator::sPySetStart, METH_VARARGS, (PY_METHODCHAR)SetStart_doc},
+ {"getStart", (PyCFunction) KX_IpoActuator::sPyGetStart, METH_NOARGS, (PY_METHODCHAR)GetStart_doc},
+ {"setEnd", (PyCFunction) KX_IpoActuator::sPySetEnd, METH_VARARGS, (PY_METHODCHAR)SetEnd_doc},
+ {"getEnd", (PyCFunction) KX_IpoActuator::sPyGetEnd, METH_NOARGS, (PY_METHODCHAR)GetEnd_doc},
+ {"setIpoAsForce", (PyCFunction) KX_IpoActuator::sPySetIpoAsForce, METH_VARARGS, (PY_METHODCHAR)SetIpoAsForce_doc},
+ {"getIpoAsForce", (PyCFunction) KX_IpoActuator::sPyGetIpoAsForce, METH_NOARGS, (PY_METHODCHAR)GetIpoAsForce_doc},
+ {"setIpoAdd", (PyCFunction) KX_IpoActuator::sPySetIpoAdd, METH_VARARGS, (PY_METHODCHAR)SetIpoAdd_doc},
+ {"getIpoAdd", (PyCFunction) KX_IpoActuator::sPyGetIpoAdd, METH_NOARGS, (PY_METHODCHAR)GetIpoAdd_doc},
+ {"setType", (PyCFunction) KX_IpoActuator::sPySetType, METH_VARARGS, (PY_METHODCHAR)SetType_doc},
+ {"getType", (PyCFunction) KX_IpoActuator::sPyGetType, METH_NOARGS, (PY_METHODCHAR)GetType_doc},
+ {"setForceIpoActsLocal", (PyCFunction) KX_IpoActuator::sPySetForceIpoActsLocal, METH_VARARGS, (PY_METHODCHAR)SetForceIpoActsLocal_doc},
+ {"getForceIpoActsLocal", (PyCFunction) KX_IpoActuator::sPyGetForceIpoActsLocal, METH_NOARGS, (PY_METHODCHAR)GetForceIpoActsLocal_doc},
{NULL,NULL} //Sentinel
};
@@ -508,12 +464,12 @@ PyObject* KX_IpoActuator::_getattr(const STR_String& attr) {
/* set --------------------------------------------------------------------- */
-char KX_IpoActuator::Set_doc[] =
-"set(mode, startframe, endframe, force?)\n"
-"\t - mode: Play, PingPong, Flipper, LoopStop, LoopEnd or FromProp (string)\n"
+const char KX_IpoActuator::Set_doc[] =
+"set(type, startframe, endframe, mode?)\n"
+"\t - type: Play, PingPong, Flipper, LoopStop, LoopEnd or FromProp (string)\n"
"\t - startframe: first frame to use (int)\n"
"\t - endframe : last frame to use (int)\n"
-"\t - force? : interpret this ipo as a force? (KX_TRUE, KX_FALSE)"
+"\t - mode? : special mode (0=normal, 1=interpret location as force, 2=additive)"
"\tSet the properties of the actuator.\n";
PyObject* KX_IpoActuator::PySet(PyObject* self,
PyObject* args,
@@ -540,7 +496,8 @@ PyObject* KX_IpoActuator::PySet(PyObject* self,
m_type = modenum;
m_startframe = startFrame;
m_endframe = stopFrame;
- m_ipo_as_force = PyArgToBool(forceToggle);
+ m_ipo_as_force = forceToggle == 1;
+ m_ipo_add = forceToggle == 2;
break;
default:
; /* error */
@@ -550,7 +507,7 @@ PyObject* KX_IpoActuator::PySet(PyObject* self,
}
/* set property ----------------------------------------------------------- */
-char KX_IpoActuator::SetProperty_doc[] =
+const char KX_IpoActuator::SetProperty_doc[] =
"setProperty(propname)\n"
"\t - propname: name of the property (string)\n"
"\tSet the property to be used in FromProp mode.\n";
@@ -570,7 +527,7 @@ PyObject* KX_IpoActuator::PySetProperty(PyObject* self,
}
/* 4. setStart: */
-char KX_IpoActuator::SetStart_doc[] =
+const char KX_IpoActuator::SetStart_doc[] =
"setStart(frame)\n"
"\t - frame: first frame to use (int)\n"
"\tSet the frame from which the ipo starts playing.\n";
@@ -587,17 +544,15 @@ PyObject* KX_IpoActuator::PySetStart(PyObject* self,
Py_Return;
}
/* 5. getStart: */
-char KX_IpoActuator::GetStart_doc[] =
+const char KX_IpoActuator::GetStart_doc[] =
"getStart()\n"
"\tReturns the frame from which the ipo starts playing.\n";
-PyObject* KX_IpoActuator::PyGetStart(PyObject* self,
- PyObject* args,
- PyObject* kwds) {
+PyObject* KX_IpoActuator::PyGetStart(PyObject* self) {
return PyFloat_FromDouble(m_startframe);
}
/* 6. setEnd: */
-char KX_IpoActuator::SetEnd_doc[] =
+const char KX_IpoActuator::SetEnd_doc[] =
"setEnd(frame)\n"
"\t - frame: last frame to use (int)\n"
"\tSet the frame at which the ipo stops playing.\n";
@@ -614,17 +569,15 @@ PyObject* KX_IpoActuator::PySetEnd(PyObject* self,
Py_Return;
}
/* 7. getEnd: */
-char KX_IpoActuator::GetEnd_doc[] =
+const char KX_IpoActuator::GetEnd_doc[] =
"getEnd()\n"
"\tReturns the frame at which the ipo stops playing.\n";
-PyObject* KX_IpoActuator::PyGetEnd(PyObject* self,
- PyObject* args,
- PyObject* kwds) {
+PyObject* KX_IpoActuator::PyGetEnd(PyObject* self) {
return PyFloat_FromDouble(m_endframe);
}
/* 6. setIpoAsForce: */
-char KX_IpoActuator::SetIpoAsForce_doc[] =
+const char KX_IpoActuator::SetIpoAsForce_doc[] =
"setIpoAsForce(force?)\n"
"\t - force? : interpret this ipo as a force? (KX_TRUE, KX_FALSE)\n"
"\tSet whether to interpret the ipo as a force rather than a displacement.\n";
@@ -638,21 +591,49 @@ PyObject* KX_IpoActuator::PySetIpoAsForce(PyObject* self,
}
m_ipo_as_force = PyArgToBool(boolArg);
+ if (m_ipo_as_force)
+ m_ipo_add = false;
Py_Return;
}
/* 7. getIpoAsForce: */
-char KX_IpoActuator::GetIpoAsForce_doc[] =
+const char KX_IpoActuator::GetIpoAsForce_doc[] =
"getIpoAsForce()\n"
"\tReturns whether to interpret the ipo as a force rather than a displacement.\n";
-PyObject* KX_IpoActuator::PyGetIpoAsForce(PyObject* self,
- PyObject* args,
- PyObject* kwds) {
+PyObject* KX_IpoActuator::PyGetIpoAsForce(PyObject* self) {
return BoolToPyArg(m_ipo_as_force);
}
+/* 6. setIpoAsForce: */
+const char KX_IpoActuator::SetIpoAdd_doc[] =
+"setIpoAdd(add?)\n"
+"\t - add? : add flag (KX_TRUE, KX_FALSE)\n"
+"\tSet whether to interpret the ipo as additive rather than absolute.\n";
+PyObject* KX_IpoActuator::PySetIpoAdd(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ int boolArg;
+
+ if (!PyArg_ParseTuple(args, "i", &boolArg)) {
+ return NULL;
+ }
+
+ m_ipo_add = PyArgToBool(boolArg);
+ if (m_ipo_add)
+ m_ipo_as_force = false;
+
+ Py_Return;
+}
+/* 7. getIpoAsForce: */
+const char KX_IpoActuator::GetIpoAdd_doc[] =
+"getIpoAsAdd()\n"
+"\tReturns whether to interpret the ipo as additive rather than absolute.\n";
+PyObject* KX_IpoActuator::PyGetIpoAdd(PyObject* self) {
+ return BoolToPyArg(m_ipo_add);
+}
+
/* 8. setType: */
-char KX_IpoActuator::SetType_doc[] =
+const char KX_IpoActuator::SetType_doc[] =
"setType(mode)\n"
"\t - mode: Play, PingPong, Flipper, LoopStop, LoopEnd or FromProp (string)\n"
"\tSet the operation mode of the actuator.\n";
@@ -673,17 +654,15 @@ PyObject* KX_IpoActuator::PySetType(PyObject* self,
Py_Return;
}
/* 9. getType: */
-char KX_IpoActuator::GetType_doc[] =
+const char KX_IpoActuator::GetType_doc[] =
"getType()\n"
"\tReturns the operation mode of the actuator.\n";
-PyObject* KX_IpoActuator::PyGetType(PyObject* self,
- PyObject* args,
- PyObject* kwds) {
+PyObject* KX_IpoActuator::PyGetType(PyObject* self) {
return PyInt_FromLong(m_type);
}
/* 10. setForceIpoActsLocal: */
-char KX_IpoActuator::SetForceIpoActsLocal_doc[] =
+const char KX_IpoActuator::SetForceIpoActsLocal_doc[] =
"setForceIpoActsLocal(local?)\n"
"\t - local? : Apply the ipo-as-force in the object's local\n"
"\t coordinates? (KX_TRUE, KX_FALSE)\n"
@@ -698,19 +677,17 @@ PyObject* KX_IpoActuator::PySetForceIpoActsLocal(PyObject* self,
return NULL;
}
- m_force_ipo_local = PyArgToBool(boolArg);
+ m_ipo_local = PyArgToBool(boolArg);
Py_Return;
}
/* 11. getForceIpoActsLocal: */
-char KX_IpoActuator::GetForceIpoActsLocal_doc[] =
+const char KX_IpoActuator::GetForceIpoActsLocal_doc[] =
"getForceIpoActsLocal()\n"
"\tReturn whether to apply the force in the object's local\n"
"\tcoordinates rather than the world global coordinates.\n";
-PyObject* KX_IpoActuator::PyGetForceIpoActsLocal(PyObject* self,
- PyObject* args,
- PyObject* kwds) {
- return BoolToPyArg(m_force_ipo_local);
+PyObject* KX_IpoActuator::PyGetForceIpoActsLocal(PyObject* self) {
+ return BoolToPyArg(m_ipo_local);
}
diff --git a/source/gameengine/Ketsji/KX_IpoActuator.h b/source/gameengine/Ketsji/KX_IpoActuator.h
index 79e8daa3f87..8e5baed0530 100644
--- a/source/gameengine/Ketsji/KX_IpoActuator.h
+++ b/source/gameengine/Ketsji/KX_IpoActuator.h
@@ -72,11 +72,17 @@ protected:
/** Name of the property (only used in from_prop mode). */
STR_String m_propname;
+ /** Name of the property where we write the current frame number */
+ STR_String m_framepropname;
+
/** Interpret the ipo as a force? */
bool m_ipo_as_force;
- /** Apply a force-ipo locally? */
- bool m_force_ipo_local;
+ /** Add Ipo curve to current loc/rot/scale */
+ bool m_ipo_add;
+
+ /** The Ipo curve is applied in local coordinates */
+ bool m_ipo_local;
bool m_bIpoPlaying;
@@ -108,12 +114,14 @@ public:
KX_IpoActuator(SCA_IObject* gameobj,
const STR_String& propname,
+ const STR_String& framePropname,
float starttime,
float endtime,
bool recurse,
int acttype,
bool ipo_as_force,
- bool force_ipo_local,
+ bool ipo_add,
+ bool ipo_local,
PyTypeObject* T=&Type);
virtual ~KX_IpoActuator() {};
@@ -139,15 +147,17 @@ public:
KX_PYMETHOD_DOC(KX_IpoActuator,SetProperty);
/* KX_PYMETHOD_DOC(KX_IpoActuator,SetKey2Key); */
KX_PYMETHOD_DOC(KX_IpoActuator,SetStart);
- KX_PYMETHOD_DOC(KX_IpoActuator,GetStart);
+ KX_PYMETHOD_DOC_NOARGS(KX_IpoActuator,GetStart);
KX_PYMETHOD_DOC(KX_IpoActuator,SetEnd);
- KX_PYMETHOD_DOC(KX_IpoActuator,GetEnd);
+ KX_PYMETHOD_DOC_NOARGS(KX_IpoActuator,GetEnd);
KX_PYMETHOD_DOC(KX_IpoActuator,SetIpoAsForce);
- KX_PYMETHOD_DOC(KX_IpoActuator,GetIpoAsForce);
+ KX_PYMETHOD_DOC_NOARGS(KX_IpoActuator,GetIpoAsForce);
+ KX_PYMETHOD_DOC(KX_IpoActuator,SetIpoAdd);
+ KX_PYMETHOD_DOC_NOARGS(KX_IpoActuator,GetIpoAdd);
KX_PYMETHOD_DOC(KX_IpoActuator,SetType);
- KX_PYMETHOD_DOC(KX_IpoActuator,GetType);
+ KX_PYMETHOD_DOC_NOARGS(KX_IpoActuator,GetType);
KX_PYMETHOD_DOC(KX_IpoActuator,SetForceIpoActsLocal);
- KX_PYMETHOD_DOC(KX_IpoActuator,GetForceIpoActsLocal);
+ KX_PYMETHOD_DOC_NOARGS(KX_IpoActuator,GetForceIpoActsLocal);
};
diff --git a/source/gameengine/Ketsji/KX_KetsjiEngine.cpp b/source/gameengine/Ketsji/KX_KetsjiEngine.cpp
index 64bfa90d4d6..8bcda4479e1 100644
--- a/source/gameengine/Ketsji/KX_KetsjiEngine.cpp
+++ b/source/gameengine/Ketsji/KX_KetsjiEngine.cpp
@@ -55,6 +55,7 @@
#include "KX_Scene.h"
#include "MT_CmMatrix4x4.h"
#include "KX_Camera.h"
+#include "KX_Light.h"
#include "KX_PythonInit.h"
#include "KX_PyConstraintBinding.h"
#include "PHY_IPhysicsEnvironment.h"
@@ -71,6 +72,7 @@
#include "KX_TimeCategoryLogger.h"
#include "RAS_FramingManager.h"
+#include "stdio.h"
// If define: little test for Nzc: guarded drawing. If the canvas is
// not valid, skip rendering this frame.
@@ -91,9 +93,10 @@ const char KX_KetsjiEngine::m_profileLabels[tc_numCategories][15] = {
};
double KX_KetsjiEngine::m_ticrate = DEFAULT_LOGIC_TIC_RATE;
-
+double KX_KetsjiEngine::m_anim_framerate = 25.0;
double KX_KetsjiEngine::m_suspendedtime = 0.0;
double KX_KetsjiEngine::m_suspendeddelta = 0.0;
+double KX_KetsjiEngine::m_average_framerate = 0.0;
/**
@@ -116,7 +119,6 @@ KX_KetsjiEngine::KX_KetsjiEngine(KX_ISystem* system)
m_bInitialized(false),
m_activecam(0),
m_bFixedTime(false),
- m_game2ipo(false),
m_firstframe(true),
@@ -133,6 +135,8 @@ KX_KetsjiEngine::KX_KetsjiEngine(KX_ISystem* system)
m_overrideCam(false),
m_overrideCamUseOrtho(false),
+ m_overrideCamNear(0.0),
+ m_overrideCamFar(0.0),
m_stereo(false),
m_curreye(0),
@@ -146,6 +150,8 @@ KX_KetsjiEngine::KX_KetsjiEngine(KX_ISystem* system)
m_showBackground(false),
m_show_debug_properties(false),
+ m_game2ipo(false),
+
// Default behavior is to hide the cursor every frame.
m_hideCursor(false),
@@ -229,7 +235,10 @@ void KX_KetsjiEngine::SetRasterizer(RAS_IRasterizer* rasterizer)
}
-
+/*
+ * At the moment the GameLogic module is imported into 'pythondictionary' after this function is called.
+ * if this function ever changes to assign a copy, make sure the game logic module is imported into this dictionary before hand.
+ */
void KX_KetsjiEngine::SetPythonDictionary(PyObject* pythondictionary)
{
MT_assert(pythondictionary);
@@ -269,30 +278,73 @@ void KX_KetsjiEngine::StartEngine(bool clearIpo)
}
-bool KX_KetsjiEngine::BeginFrame()
+void KX_KetsjiEngine::ClearFrame()
{
- bool result = false;
+ // clear unless we're drawing overlapping stereo
+ if(m_rasterizer->InterlacedStereo() &&
+ m_rasterizer->GetEye() == RAS_IRasterizer::RAS_STEREO_RIGHTEYE)
+ return;
- RAS_Rect vp;
- KX_Scene* firstscene = *m_scenes.begin();
- const RAS_FrameSettings &framesettings = firstscene->GetFramingType();
+ // clear the viewports with the background color of the first scene
+ bool doclear = false;
+ KX_SceneList::iterator sceneit;
+ RAS_Rect clearvp, area, viewport;
- // set the area used for rendering
- m_rasterizer->SetRenderArea();
+ for (sceneit = m_scenes.begin(); sceneit != m_scenes.end(); sceneit++)
+ {
+ KX_Scene* scene = *sceneit;
+ //const RAS_FrameSettings &framesettings = scene->GetFramingType();
+ list<class KX_Camera*>* cameras = scene->GetCameras();
+
+ list<KX_Camera*>::iterator it;
+ for(it = cameras->begin(); it != cameras->end(); it++)
+ {
+ GetSceneViewport(scene, (*it), area, viewport);
+
+ if(!doclear) {
+ clearvp = viewport;
+ doclear = true;
+ }
+ else {
+ if(viewport.GetLeft() < clearvp.GetLeft())
+ clearvp.SetLeft(viewport.GetLeft());
+ if(viewport.GetBottom() < clearvp.GetBottom())
+ clearvp.SetBottom(viewport.GetBottom());
+ if(viewport.GetRight() > clearvp.GetRight())
+ clearvp.SetRight(viewport.GetRight());
+ if(viewport.GetTop() > clearvp.GetTop())
+ clearvp.SetTop(viewport.GetTop());
+
+ }
+ }
+ }
+
+ if(doclear) {
+ KX_Scene* firstscene = *m_scenes.begin();
+ SetBackGround(firstscene->GetWorldInfo());
+
+ m_canvas->SetViewPort(clearvp.GetLeft(), clearvp.GetBottom(),
+ clearvp.GetRight(), clearvp.GetTop());
+ m_rasterizer->ClearColorBuffer();
+ }
+}
- RAS_FramingManager::ComputeViewport(framesettings, m_canvas->GetDisplayArea(), vp);
+bool KX_KetsjiEngine::BeginFrame()
+{
+ // set the area used for rendering (stereo can assign only a subset)
+ m_rasterizer->SetRenderArea();
if (m_canvas->BeginDraw())
{
- result = true;
+ ClearFrame();
+
+ m_rasterizer->BeginFrame(m_drawingmode , m_kxsystem->GetTimeInSeconds());
+ m_rendertools->BeginFrame(m_rasterizer);
- m_canvas->SetViewPort(vp.GetLeft(), vp.GetBottom(), vp.GetRight(), vp.GetTop());
- SetBackGround( firstscene->GetWorldInfo() );
- m_rasterizer->BeginFrame( m_drawingmode , m_kxsystem->GetTimeInSeconds());
- m_rendertools->BeginFrame( m_rasterizer);
+ return true;
}
- return result;
+ return false;
}
@@ -304,6 +356,12 @@ void KX_KetsjiEngine::EndFrame()
{
RenderDebugProperties();
}
+
+ m_average_framerate = m_logger->GetAverage();
+ if (m_average_framerate < 1e-6)
+ m_average_framerate = 1e-6;
+ m_average_framerate = 1.0/m_average_framerate;
+
// Go to next profiling measurement, time spend after this call is shown in the next frame.
m_logger->NextMeasurement(m_kxsystem->GetTimeInSeconds());
@@ -315,8 +373,6 @@ void KX_KetsjiEngine::EndFrame()
m_canvas->EndDraw();
-
-
}
//#include "PIL_time.h"
@@ -414,7 +470,7 @@ else
m_logger->StartLog(tc_physics, m_kxsystem->GetTimeInSeconds(), true);
// set Python hooks for each scene
PHY_SetActiveEnvironment(scene->GetPhysicsEnvironment());
- PHY_SetActiveScene(scene);
+ KX_SetActiveScene(scene);
scene->GetPhysicsEnvironment()->endFrame();
@@ -512,7 +568,7 @@ else
// set Python hooks for each scene
PHY_SetActiveEnvironment(scene->GetPhysicsEnvironment());
- PHY_SetActiveScene(scene);
+ KX_SetActiveScene(scene);
m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
scene->UpdateParents(m_clockTime);
@@ -595,7 +651,7 @@ void KX_KetsjiEngine::Render()
);
}
// clear the -whole- viewport
- m_canvas->ClearBuffer(RAS_ICanvas::COLOR_BUFFER);
+ m_canvas->ClearBuffer(RAS_ICanvas::COLOR_BUFFER|RAS_ICanvas::DEPTH_BUFFER);
}
m_rasterizer->SetEye(RAS_IRasterizer::RAS_STEREO_LEFTEYE);
@@ -613,25 +669,25 @@ void KX_KetsjiEngine::Render()
// pass the scene's worldsettings to the rasterizer
SetWorldSettings(scene->GetWorldInfo());
+ // shadow buffers
+ RenderShadowBuffers(scene);
+
// Avoid drawing the scene with the active camera twice when it's viewport is enabled
- if(!cam->GetViewport())
+ if(cam && !cam->GetViewport())
{
if (scene->IsClearingZBuffer())
m_rasterizer->ClearDepthBuffer();
m_rendertools->SetAuxilaryClientInfo(scene);
- //Initialize scene viewport.
- SetupRenderFrame(scene, cam);
-
// do the rendering
RenderFrame(scene, cam);
}
- set<class KX_Camera*>* cameras = scene->GetCameras();
+ list<class KX_Camera*>* cameras = scene->GetCameras();
// Draw the scene once for each camera with an enabled viewport
- set<KX_Camera*>::iterator it = cameras->begin();
+ list<KX_Camera*>::iterator it = cameras->begin();
while(it != cameras->end())
{
if((*it)->GetViewport())
@@ -641,9 +697,6 @@ void KX_KetsjiEngine::Render()
m_rendertools->SetAuxilaryClientInfo(scene);
- //Initialize scene viewport.
- SetupRenderFrame(scene, (*it));
-
// do the rendering
RenderFrame(scene, (*it));
}
@@ -676,10 +729,6 @@ void KX_KetsjiEngine::Render()
//pass the scene, for picking and raycasting (shadows)
m_rendertools->SetAuxilaryClientInfo(scene);
- //Initialize scene viewport.
- //SetupRenderFrame(scene);
- SetupRenderFrame(scene, cam);
-
// do the rendering
//RenderFrame(scene);
RenderFrame(scene, cam);
@@ -839,8 +888,13 @@ void KX_KetsjiEngine::SetCameraOverrideViewMatrix(const MT_CmMatrix4x4& mat)
m_overrideCamViewMat = mat;
}
-
-void KX_KetsjiEngine::SetupRenderFrame(KX_Scene *scene, KX_Camera* cam)
+void KX_KetsjiEngine::SetCameraOverrideClipping(float near, float far)
+{
+ m_overrideCamNear = near;
+ m_overrideCamFar = far;
+}
+
+void KX_KetsjiEngine::GetSceneViewport(KX_Scene *scene, KX_Camera* cam, RAS_Rect& area, RAS_Rect& viewport)
{
// In this function we make sure the rasterizer settings are upto
// date. We compute the viewport so that logic
@@ -848,14 +902,26 @@ void KX_KetsjiEngine::SetupRenderFrame(KX_Scene *scene, KX_Camera* cam)
// Note we postpone computation of the projection matrix
// so that we are using the latest camera position.
+ if (cam->GetViewport()) {
+ RAS_Rect userviewport;
- RAS_Rect viewport;
+ userviewport.SetLeft(cam->GetViewportLeft());
+ userviewport.SetBottom(cam->GetViewportBottom());
+ userviewport.SetRight(cam->GetViewportRight());
+ userviewport.SetTop(cam->GetViewportTop());
- if (cam->GetViewport()) {
- viewport.SetLeft(cam->GetViewportLeft());
- viewport.SetBottom(cam->GetViewportBottom());
- viewport.SetRight(cam->GetViewportRight());
- viewport.SetTop(cam->GetViewportTop());
+ // Don't do bars on user specified viewport
+ RAS_FrameSettings settings = scene->GetFramingType();
+ if(settings.FrameType() == RAS_FrameSettings::e_frame_bars)
+ settings.SetFrameType(RAS_FrameSettings::e_frame_extend);
+
+ RAS_FramingManager::ComputeViewport(
+ scene->GetFramingType(),
+ userviewport,
+ viewport
+ );
+
+ area = userviewport;
}
else if ( m_overrideCam || (scene->GetName() != m_overrideSceneName) || m_overrideCamUseOrtho ) {
RAS_FramingManager::ComputeViewport(
@@ -863,42 +929,95 @@ void KX_KetsjiEngine::SetupRenderFrame(KX_Scene *scene, KX_Camera* cam)
m_canvas->GetDisplayArea(),
viewport
);
+
+ area = m_canvas->GetDisplayArea();
} else {
viewport.SetLeft(0);
viewport.SetBottom(0);
viewport.SetRight(int(m_canvas->GetWidth()));
viewport.SetTop(int(m_canvas->GetHeight()));
+
+ area = m_canvas->GetDisplayArea();
}
- // store the computed viewport in the scene
+}
- scene->SetSceneViewport(viewport);
+void KX_KetsjiEngine::RenderShadowBuffers(KX_Scene *scene)
+{
+ CListValue *objectlist = scene->GetObjectList();
+ int i, drawmode;
- // set the viewport for this frame and scene
- m_canvas->SetViewPort(
- viewport.GetLeft(),
- viewport.GetBottom(),
- viewport.GetRight(),
- viewport.GetTop()
- );
+ m_rendertools->SetAuxilaryClientInfo(scene);
-}
+ for(i=0; i<objectlist->GetCount(); i++) {
+ KX_GameObject *gameobj = (KX_GameObject*)objectlist->GetValue(i);
+
+ if(!gameobj->IsLight())
+ continue;
+
+ KX_LightObject *light = (KX_LightObject*)gameobj;
+
+ light->Update();
+
+ if(m_drawingmode == RAS_IRasterizer::KX_TEXTURED && light->HasShadowBuffer()) {
+ /* make temporary camera */
+ RAS_CameraData camdata = RAS_CameraData();
+ KX_Camera *cam = new KX_Camera(scene, scene->m_callbacks, camdata, false);
+ cam->SetName("__shadow__cam__");
+
+ MT_Transform camtrans;
+
+ /* switch drawmode for speed */
+ drawmode = m_rasterizer->GetDrawingMode();
+ m_rasterizer->SetDrawingMode(RAS_IRasterizer::KX_SHADOW);
+
+ /* binds framebuffer object, sets up camera .. */
+ light->BindShadowBuffer(m_rasterizer, cam, camtrans);
+ /* update scene */
+ scene->UpdateMeshTransformations();
+ scene->CalculateVisibleMeshes(m_rasterizer, cam, light->GetShadowLayer());
+
+ /* render */
+ m_rasterizer->ClearDepthBuffer();
+ scene->RenderBuckets(camtrans, m_rasterizer, m_rendertools);
+
+ /* unbind framebuffer object, restore drawmode, free camera */
+ light->UnbindShadowBuffer(m_rasterizer);
+ m_rasterizer->SetDrawingMode(drawmode);
+ cam->Release();
+ }
+ }
+}
// update graphics
void KX_KetsjiEngine::RenderFrame(KX_Scene* scene, KX_Camera* cam)
{
- float left, right, bottom, top, nearfrust, farfrust;
+ bool override_camera;
+ RAS_Rect viewport, area;
+ float left, right, bottom, top, nearfrust, farfrust, focallength;
const float ortho = 100.0;
// KX_Camera* cam = scene->GetActiveCamera();
if (!cam)
return;
+
+ GetSceneViewport(scene, cam, area, viewport);
+
+ // store the computed viewport in the scene
+ scene->SetSceneViewport(viewport);
+
+ // set the viewport for this frame and scene
+ m_canvas->SetViewPort(viewport.GetLeft(), viewport.GetBottom(),
+ viewport.GetRight(), viewport.GetTop());
// see KX_BlenderMaterial::Activate
//m_rasterizer->SetAmbient();
m_rasterizer->DisplayFog();
- if (m_overrideCam && (scene->GetName() == m_overrideSceneName) && m_overrideCamUseOrtho) {
+ override_camera = m_overrideCam && (scene->GetName() == m_overrideSceneName);
+ override_camera = override_camera && (cam->GetName() == "__default__cam__");
+
+ if (override_camera && m_overrideCamUseOrtho) {
MT_CmMatrix4x4 projmat = m_overrideCamProjMat;
m_rasterizer->SetProjectionMatrix(projmat);
} else if (cam->hasValidProjectionMatrix() && !cam->GetViewport() )
@@ -908,11 +1027,17 @@ void KX_KetsjiEngine::RenderFrame(KX_Scene* scene, KX_Camera* cam)
{
RAS_FrameFrustum frustum;
float lens = cam->GetLens();
+ bool orthographic = !cam->GetCameraData()->m_perspective;
nearfrust = cam->GetCameraNear();
farfrust = cam->GetCameraFar();
+ focallength = cam->GetFocalLength();
- if (!cam->GetCameraData()->m_perspective)
- {
+ if(override_camera) {
+ nearfrust = m_overrideCamNear;
+ farfrust = m_overrideCamFar;
+ }
+
+ if (orthographic) {
lens *= ortho;
nearfrust = (nearfrust + 1.0)*ortho;
farfrust *= ortho;
@@ -920,8 +1045,8 @@ void KX_KetsjiEngine::RenderFrame(KX_Scene* scene, KX_Camera* cam)
RAS_FramingManager::ComputeFrustum(
scene->GetFramingType(),
- m_canvas->GetDisplayArea(),
- scene->GetSceneViewport(),
+ area,
+ viewport,
lens,
nearfrust,
farfrust,
@@ -936,8 +1061,8 @@ void KX_KetsjiEngine::RenderFrame(KX_Scene* scene, KX_Camera* cam)
farfrust = frustum.camfar;
MT_Matrix4x4 projmat = m_rasterizer->GetFrustumMatrix(
- left, right, bottom, top, nearfrust, farfrust);
-
+ left, right, bottom, top, nearfrust, farfrust, focallength);
+
cam->SetProjectionMatrix(projmat);
// Otherwise the projection matrix for each eye will be the same...
@@ -963,13 +1088,18 @@ void KX_KetsjiEngine::RenderFrame(KX_Scene* scene, KX_Camera* cam)
scene->CalculateVisibleMeshes(m_rasterizer,cam);
scene->RenderBuckets(camtrans, m_rasterizer, m_rendertools);
+
+ PostRenderFrame();
+}
+void KX_KetsjiEngine::PostRenderFrame()
+{
+ m_rendertools->PushMatrix();
+ m_rendertools->Render2DFilters(m_canvas);
m_rendertools->MotionBlur(m_rasterizer);
-
+ m_rendertools->PopMatrix();
}
-
-
void KX_KetsjiEngine::StopEngine()
{
if (m_bInitialized)
@@ -985,7 +1115,7 @@ void KX_KetsjiEngine::StopEngine()
for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++)
{
KX_Scene* scene = *sceneit;
- delete scene;
+ m_sceneconverter->RemoveScene(scene);
}
m_scenes.clear();
@@ -1039,6 +1169,8 @@ void KX_KetsjiEngine::PostProcessScene(KX_Scene* scene)
scene->SetActiveCamera(activecam);
scene->GetObjectList()->Add(activecam->AddRef());
scene->GetRootParentList()->Add(activecam->AddRef());
+ //done with activecam
+ activecam->Release();
}
scene->UpdateParents(0.0);
@@ -1111,19 +1243,49 @@ void KX_KetsjiEngine::RenderDebugProperties()
CValue* propobj = (*it)->m_obj;
STR_String objname = propobj->GetName();
STR_String propname = (*it)->m_name;
- CValue* propval = propobj->GetProperty(propname);
- if (propval)
+ if (propname == "__state__")
{
- STR_String text = propval->GetText();
- debugtxt = objname + "." + propname + " = " + text;
+ // reserve name for object state
+ KX_GameObject* gameobj = static_cast<KX_GameObject*>(propobj);
+ unsigned int state = gameobj->GetState();
+ debugtxt = objname + "." + propname + " = ";
+ bool first = true;
+ for (int statenum=1;state;state >>= 1, statenum++)
+ {
+ if (state & 1)
+ {
+ if (!first)
+ {
+ debugtxt += ",";
+ }
+ debugtxt += STR_String(statenum);
+ first = false;
+ }
+ }
m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED,
- debugtxt.Ptr(),
- xcoord,
- ycoord,
- m_canvas->GetWidth(),
- m_canvas->GetHeight());
+ debugtxt.Ptr(),
+ xcoord,
+ ycoord,
+ m_canvas->GetWidth(),
+ m_canvas->GetHeight());
ycoord += 14;
}
+ else
+ {
+ CValue* propval = propobj->GetProperty(propname);
+ if (propval)
+ {
+ STR_String text = propval->GetText();
+ debugtxt = objname + "." + propname + " = " + text;
+ m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED,
+ debugtxt.Ptr(),
+ xcoord,
+ ycoord,
+ m_canvas->GetWidth(),
+ m_canvas->GetHeight());
+ ycoord += 14;
+ }
+ }
}
}
}
@@ -1207,7 +1369,7 @@ void KX_KetsjiEngine::RemoveScheduledScenes()
KX_Scene* scene = *sceneit;
if (scene->GetName()==scenename)
{
- delete scene;
+ m_sceneconverter->RemoveScene(scene);
m_scenes.erase(sceneit);
break;
}
@@ -1221,12 +1383,13 @@ void KX_KetsjiEngine::RemoveScheduledScenes()
KX_Scene* KX_KetsjiEngine::CreateScene(const STR_String& scenename)
{
-
+ Scene *scene = m_sceneconverter->GetBlenderSceneForName(scenename);
KX_Scene* tmpscene = new KX_Scene(m_keyboarddevice,
m_mousedevice,
m_networkdevice,
m_audiodevice,
- scenename);
+ scenename,
+ scene);
m_sceneconverter->ConvertScene(scenename,
tmpscene,
@@ -1305,7 +1468,7 @@ void KX_KetsjiEngine::ReplaceScheduledScenes()
KX_Scene* scene = *sceneit;
if (scene->GetName() == oldscenename)
{
- delete scene;
+ m_sceneconverter->RemoveScene(scene);
KX_Scene* tmpscene = CreateScene(newscenename);
m_scenes[i]=tmpscene;
PostProcessScene(tmpscene);
@@ -1372,6 +1535,26 @@ void KX_KetsjiEngine::SetTicRate(double ticrate)
m_ticrate = ticrate;
}
+double KX_KetsjiEngine::GetAnimFrameRate()
+{
+ return m_anim_framerate;
+}
+
+double KX_KetsjiEngine::GetClockTime(void) const
+{
+ return m_clockTime;
+}
+
+void KX_KetsjiEngine::SetAnimFrameRate(double framerate)
+{
+ m_anim_framerate = framerate;
+}
+
+double KX_KetsjiEngine::GetAverageFrameRate()
+{
+ return m_average_framerate;
+}
+
void KX_KetsjiEngine::SetTimingDisplay(bool frameRate, bool profile, bool properties)
{
m_show_framerate = frameRate;
@@ -1464,3 +1647,4 @@ void KX_KetsjiEngine::GetOverrideFrameColor(float& r, float& g, float& b) const
}
+
diff --git a/source/gameengine/Ketsji/KX_KetsjiEngine.h b/source/gameengine/Ketsji/KX_KetsjiEngine.h
index e727452423b..4184202c518 100644
--- a/source/gameengine/Ketsji/KX_KetsjiEngine.h
+++ b/source/gameengine/Ketsji/KX_KetsjiEngine.h
@@ -103,6 +103,7 @@ private:
double m_remainingTime;
static double m_ticrate;
+ static double m_anim_framerate; /* for animation playback only - ipo and action */
static double m_suspendedtime;
static double m_suspendeddelta;
@@ -123,6 +124,8 @@ private:
bool m_overrideCamUseOrtho;
MT_CmMatrix4x4 m_overrideCamProjMat;
MT_CmMatrix4x4 m_overrideCamViewMat;
+ float m_overrideCamNear;
+ float m_overrideCamFar;
bool m_stereo;
int m_curreye;
@@ -148,6 +151,8 @@ private:
/** Labels for profiling display. */
static const char m_profileLabels[tc_numCategories][15];
+ /** Last estimated framerate */
+ static double m_average_framerate;
/** Show the framerate on the game display? */
bool m_show_framerate;
/** Show profiling info on the game display? */
@@ -174,9 +179,10 @@ private:
/** Blue component of framing bar color. */
float m_overrideFrameColorB;
- void SetupRenderFrame(KX_Scene *scene, KX_Camera* cam);
void RenderFrame(KX_Scene* scene, KX_Camera* cam);
+ void PostRenderFrame();
void RenderDebugProperties();
+ void RenderShadowBuffers(KX_Scene *scene);
void SetBackGround(KX_WorldInfo* worldinfo);
void SetWorldSettings(KX_WorldInfo* worldinfo);
void DoSound(KX_Scene* scene);
@@ -198,6 +204,8 @@ public:
void SetSceneConverter(KX_ISceneConverter* sceneconverter);
void SetGame2IpoMode(bool game2ipo,int startFrame);
+ RAS_IRasterizer* GetRasterizer(){return m_rasterizer;};
+
///returns true if an update happened to indicate -> Render
bool NextFrame();
void Render();
@@ -221,6 +229,8 @@ public:
void SuspendScene(const STR_String& scenename);
void ResumeScene(const STR_String& scenename);
+ void GetSceneViewport(KX_Scene* scene, KX_Camera* cam, RAS_Rect& area, RAS_Rect& viewport);
+
void SetDrawType(int drawingtype);
void SetCameraZoom(float camzoom);
@@ -229,6 +239,7 @@ public:
void SetCameraOverrideUseOrtho(bool useOrtho);
void SetCameraOverrideProjectionMatrix(const MT_CmMatrix4x4& mat);
void SetCameraOverrideViewMatrix(const MT_CmMatrix4x4& mat);
+ void SetCameraOverrideClipping(float near, float far);
/**
* Sets display of all frames.
@@ -243,6 +254,11 @@ public:
bool GetUseFixedTime(void) const;
/**
+ * Returns current render frame clock time
+ */
+ double GetClockTime(void) const;
+
+ /**
* Returns the difference between the local time of the scene (when it
* was running and not suspended) and the "curtime"
*/
@@ -258,6 +274,20 @@ public:
static void SetTicRate(double ticrate);
/**
+ * Gets the framerate for playing animations. (actions and ipos)
+ */
+ static double GetAnimFrameRate();
+ /**
+ * Sets the framerate for playing animations. (actions and ipos)
+ */
+ static void SetAnimFrameRate(double framerate);
+
+ /**
+ * Gets the last estimated average framerate
+ */
+ static double GetAverageFrameRate();
+
+ /**
* Activates or deactivates timing information display.
* @param frameRate Display for frame rate on or off.
* @param profile Display for individual components on or off.
@@ -334,8 +364,10 @@ protected:
KX_Scene* CreateScene(const STR_String& scenename);
bool BeginFrame();
+ void ClearFrame();
void EndFrame();
};
#endif //__KX_KETSJI_ENGINE
+
diff --git a/source/gameengine/Ketsji/KX_Light.cpp b/source/gameengine/Ketsji/KX_Light.cpp
index 3ae09c01270..e0f171e78e0 100644
--- a/source/gameengine/Ketsji/KX_Light.cpp
+++ b/source/gameengine/Ketsji/KX_Light.cpp
@@ -36,14 +36,19 @@
#endif
#include "KX_Light.h"
+#include "KX_Camera.h"
+#include "RAS_IRasterizer.h"
#include "RAS_IRenderTools.h"
#include "KX_PyMath.h"
+#include "DNA_object_types.h"
+#include "GPU_material.h"
KX_LightObject::KX_LightObject(void* sgReplicationInfo,SG_Callbacks callbacks,
class RAS_IRenderTools* rendertools,
const RAS_LightObject& lightobj,
+ bool glsl,
PyTypeObject* T
)
:
@@ -53,11 +58,19 @@ KX_LightObject::KX_LightObject(void* sgReplicationInfo,SG_Callbacks callbacks,
m_lightobj = lightobj;
m_lightobj.m_worldmatrix = GetOpenGLMatrixPtr();
m_rendertools->AddLight(&m_lightobj);
+ m_glsl = glsl;
+ m_blenderscene = ((KX_Scene*)sgReplicationInfo)->GetBlenderScene();
};
KX_LightObject::~KX_LightObject()
{
+ GPULamp *lamp;
+
+ if((lamp = GetGPULamp())) {
+ float obmat[4][4] = {{0}};
+ GPU_lamp_update(lamp, 0, obmat);
+ }
m_rendertools->RemoveLight(&m_lightobj);
}
@@ -67,7 +80,7 @@ CValue* KX_LightObject::GetReplica()
{
KX_LightObject* replica = new KX_LightObject(*this);
-
+
// this will copy properties and so on...
CValue::AddDataToReplica(replica);
@@ -75,9 +88,90 @@ CValue* KX_LightObject::GetReplica()
replica->m_lightobj.m_worldmatrix = replica->GetOpenGLMatrixPtr();
m_rendertools->AddLight(&replica->m_lightobj);
+
return replica;
}
+GPULamp *KX_LightObject::GetGPULamp()
+{
+ if(m_glsl)
+ return GPU_lamp_from_blender(m_blenderscene, GetBlenderObject(), GetBlenderGroupObject());
+ else
+ return false;
+}
+
+void KX_LightObject::Update()
+{
+ GPULamp *lamp;
+
+ if((lamp = GetGPULamp())) {
+ float obmat[4][4];
+ double *dobmat = GetOpenGLMatrixPtr()->getPointer();
+
+ for(int i=0; i<4; i++)
+ for(int j=0; j<4; j++, dobmat++)
+ obmat[i][j] = (float)*dobmat;
+
+ GPU_lamp_update(lamp, m_lightobj.m_layer, obmat);
+ }
+}
+
+bool KX_LightObject::HasShadowBuffer()
+{
+ GPULamp *lamp;
+
+ if((lamp = GetGPULamp()))
+ return GPU_lamp_has_shadow_buffer(lamp);
+ else
+ return false;
+}
+
+int KX_LightObject::GetShadowLayer()
+{
+ GPULamp *lamp;
+
+ if((lamp = GetGPULamp()))
+ return GPU_lamp_shadow_layer(lamp);
+ else
+ return 0;
+}
+
+void KX_LightObject::BindShadowBuffer(RAS_IRasterizer *ras, KX_Camera *cam, MT_Transform& camtrans)
+{
+ GPULamp *lamp;
+ float viewmat[4][4], winmat[4][4];
+ int winsize;
+
+ /* bind framebuffer */
+ lamp = GetGPULamp();
+ GPU_lamp_shadow_buffer_bind(lamp, viewmat, &winsize, winmat);
+
+ /* setup camera transformation */
+ MT_Matrix4x4 modelviewmat((float*)viewmat);
+ MT_Matrix4x4 projectionmat((float*)winmat);
+
+ MT_Transform trans = MT_Transform((float*)viewmat);
+ camtrans.invert(trans);
+
+ cam->SetModelviewMatrix(modelviewmat);
+ cam->SetProjectionMatrix(projectionmat);
+
+ cam->NodeSetLocalPosition(camtrans.getOrigin());
+ cam->NodeSetLocalOrientation(camtrans.getBasis());
+ cam->NodeUpdateGS(0,true);
+
+ /* setup rasterizer transformations */
+ ras->SetProjectionMatrix(projectionmat);
+ ras->SetViewMatrix(modelviewmat, cam->NodeGetWorldPosition(),
+ cam->GetCameraLocation(), cam->GetCameraOrientation());
+}
+
+void KX_LightObject::UnbindShadowBuffer(RAS_IRasterizer *ras)
+{
+ GPULamp *lamp = GetGPULamp();
+ GPU_lamp_shadow_buffer_unbind(lamp);
+}
+
PyObject* KX_LightObject::_getattr(const STR_String& attr)
{
if (attr == "layer")
@@ -223,7 +317,7 @@ char KX_LightObject::doc[] = "Module KX_LightObject\n\n"
"\t\tThe effect radius of the light.\n"
"\tcolour -> list [r, g, b].\n"
"\tcolor -> list [r, g, b].\n"
-"\t\tThe colour of the light.\n"
+"\t\tThe color of the light.\n"
"\tlin_attenuation -> float.\n"
"\t\tThe attenuation factor for the light.\n"
"\tspotsize -> float.\n"
diff --git a/source/gameengine/Ketsji/KX_Light.h b/source/gameengine/Ketsji/KX_Light.h
index 236d3e4e12e..e5dbf0b7f4a 100644
--- a/source/gameengine/Ketsji/KX_Light.h
+++ b/source/gameengine/Ketsji/KX_Light.h
@@ -32,22 +32,41 @@
#include "RAS_LightObject.h"
#include "KX_GameObject.h"
+struct GPULamp;
+struct Scene;
+class KX_Camera;
+class RAS_IRasterizer;
+class RAS_IRenderTools;
+class MT_Transform;
+
class KX_LightObject : public KX_GameObject
{
Py_Header;
protected:
RAS_LightObject m_lightobj;
class RAS_IRenderTools* m_rendertools; //needed for registering and replication of lightobj
- static char doc[];
+ bool m_glsl;
+ Scene* m_blenderscene;
+ static char doc[];
public:
- KX_LightObject(void* sgReplicationInfo,SG_Callbacks callbacks,class RAS_IRenderTools* rendertools,const struct RAS_LightObject& lightobj, PyTypeObject *T = &Type);
+ KX_LightObject(void* sgReplicationInfo,SG_Callbacks callbacks,class RAS_IRenderTools* rendertools,const struct RAS_LightObject& lightobj, bool glsl, PyTypeObject *T = &Type);
virtual ~KX_LightObject();
virtual CValue* GetReplica();
RAS_LightObject* GetLightData() { return &m_lightobj;}
+
+ /* GLSL shadow */
+ struct GPULamp *GetGPULamp();
+ bool HasShadowBuffer();
+ int GetShadowLayer();
+ void BindShadowBuffer(class RAS_IRasterizer *ras, class KX_Camera *cam, class MT_Transform& camtrans);
+ void UnbindShadowBuffer(class RAS_IRasterizer *ras);
+ void Update();
virtual PyObject* _getattr(const STR_String& attr); /* lens, near, far, projection_matrix */
virtual int _setattr(const STR_String& attr, PyObject *pyvalue);
+
+ virtual bool IsLight(void) { return true; }
};
#endif //__KX_LIGHT
diff --git a/source/gameengine/Ketsji/KX_MaterialIpoController.cpp b/source/gameengine/Ketsji/KX_MaterialIpoController.cpp
index c0757a32b9c..85d514bd22f 100644
--- a/source/gameengine/Ketsji/KX_MaterialIpoController.cpp
+++ b/source/gameengine/Ketsji/KX_MaterialIpoController.cpp
@@ -3,6 +3,8 @@
#include "KX_ScalarInterpolator.h"
#include "KX_GameObject.h"
+#include "BLO_sys_types.h" // for intptr_t support
+
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
@@ -37,6 +39,7 @@ bool KX_MaterialIpoController::Update(double currentTime)
//kxgameobj->SetObjectColor(m_rgba);
kxgameobj->UpdateMaterialData(
+ m_matname_hash,
m_rgba,
m_specrgb,
m_hard,
@@ -75,10 +78,10 @@ SG_Controller* KX_MaterialIpoController::GetReplica(class SG_Node* destnode)
iporeplica->AddInterpolator(copyipo);
MT_Scalar* scaal = ((KX_ScalarInterpolator*)*i)->GetTarget();
- long orgbase = (long)this;
- long orgloc = (long)scaal;
- long offset = orgloc-orgbase;
- long newaddrbase = (long)iporeplica + offset;
+ intptr_t orgbase = (intptr_t)this;
+ intptr_t orgloc = (intptr_t)scaal;
+ intptr_t offset = orgloc-orgbase;
+ intptr_t newaddrbase = (intptr_t)iporeplica + offset;
MT_Scalar* blaptr = (MT_Scalar*) newaddrbase;
copyipo->SetNewTarget((MT_Scalar*)blaptr);
}
diff --git a/source/gameengine/Ketsji/KX_MaterialIpoController.h b/source/gameengine/Ketsji/KX_MaterialIpoController.h
index e76ddeefb04..4d2e258bf94 100644
--- a/source/gameengine/Ketsji/KX_MaterialIpoController.h
+++ b/source/gameengine/Ketsji/KX_MaterialIpoController.h
@@ -7,6 +7,8 @@
#include "SG_Spatial.h"
#include "KX_IInterpolator.h"
+#include "STR_String.h" //typedef dword
+
class KX_MaterialIpoController : public SG_Controller
{
public:
@@ -23,10 +25,12 @@ private:
bool m_modified;
double m_ipotime;
+ dword m_matname_hash;
public:
- KX_MaterialIpoController() :
+ KX_MaterialIpoController(dword matname_hash) :
m_modified(true),
- m_ipotime(0.0)
+ m_ipotime(0.0),
+ m_matname_hash(matname_hash)
{}
virtual ~KX_MaterialIpoController();
virtual SG_Controller* GetReplica(class SG_Node* destnode);
diff --git a/source/gameengine/Ketsji/KX_MeshProxy.cpp b/source/gameengine/Ketsji/KX_MeshProxy.cpp
index 5c8fef1fca0..5cc102248f2 100644
--- a/source/gameengine/Ketsji/KX_MeshProxy.cpp
+++ b/source/gameengine/Ketsji/KX_MeshProxy.cpp
@@ -35,6 +35,7 @@
#include "RAS_MeshObject.h"
#include "KX_VertexProxy.h"
+#include "KX_PolyProxy.h"
#include "KX_PolygonMaterial.h"
#include "KX_BlenderMaterial.h"
@@ -42,6 +43,8 @@
#include "KX_PyMath.h"
#include "KX_ConvertPhysicsObject.h"
+#include "PyObjectPlus.h"
+
PyTypeObject KX_MeshProxy::Type = {
PyObject_HEAD_INIT(&PyType_Type)
0,
@@ -71,10 +74,12 @@ PyParentObject KX_MeshProxy::Parents[] = {
PyMethodDef KX_MeshProxy::Methods[] = {
{"getNumMaterials", (PyCFunction)KX_MeshProxy::sPyGetNumMaterials,METH_VARARGS},
+{"getNumPolygons", (PyCFunction)KX_MeshProxy::sPyGetNumPolygons,METH_NOARGS},
{"getMaterialName", (PyCFunction)KX_MeshProxy::sPyGetMaterialName,METH_VARARGS},
{"getTextureName", (PyCFunction)KX_MeshProxy::sPyGetTextureName,METH_VARARGS},
{"getVertexArrayLength", (PyCFunction)KX_MeshProxy::sPyGetVertexArrayLength,METH_VARARGS},
{"getVertex", (PyCFunction)KX_MeshProxy::sPyGetVertex,METH_VARARGS},
+{"getPolygon", (PyCFunction)KX_MeshProxy::sPyGetPolygon,METH_VARARGS},
KX_PYMETHODTABLE(KX_MeshProxy, reinstancePhysicsMesh),
//{"getIndexArrayLength", (PyCFunction)KX_MeshProxy::sPyGetIndexArrayLength,METH_VARARGS},
@@ -93,10 +98,11 @@ KX_MeshProxy::_getattr(const STR_String& attr)
if (attr == "materials")
{
PyObject *materials = PyList_New(0);
- RAS_MaterialBucket::Set::iterator mit = m_meshobj->GetFirstMaterial();
+ list<RAS_MeshMaterial>::iterator mit = m_meshobj->GetFirstMaterial();
for(; mit != m_meshobj->GetLastMaterial(); ++mit)
{
- RAS_IPolyMaterial *polymat = (*mit)->GetPolyMaterial();
+ RAS_IPolyMaterial *polymat = mit->m_bucket->GetPolyMaterial();
+
if(polymat->GetFlag() & RAS_BLENDERMAT)
{
KX_BlenderMaterial *mat = static_cast<KX_BlenderMaterial*>(polymat);
@@ -146,6 +152,12 @@ PyObject* KX_MeshProxy::PyGetNumMaterials(PyObject* self,
return PyInt_FromLong(num);
}
+PyObject* KX_MeshProxy::PyGetNumPolygons(PyObject* self)
+{
+ int num = m_meshobj->NumPolygons();
+ return PyInt_FromLong(num);
+}
+
PyObject* KX_MeshProxy::PyGetMaterialName(PyObject* self,
PyObject* args,
PyObject* kwds)
@@ -157,6 +169,9 @@ PyObject* KX_MeshProxy::PyGetMaterialName(PyObject* self,
{
matname = m_meshobj->GetMaterialName(matid);
}
+ else {
+ return NULL;
+ }
return PyString_FromString(matname.Ptr());
@@ -174,6 +189,9 @@ PyObject* KX_MeshProxy::PyGetTextureName(PyObject* self,
{
matname = m_meshobj->GetTextureName(matid);
}
+ else {
+ return NULL;
+ }
return PyString_FromString(matname.Ptr());
@@ -189,11 +207,14 @@ PyObject* KX_MeshProxy::PyGetVertexArrayLength(PyObject* self,
if (PyArg_ParseTuple(args,"i",&matid))
{
- RAS_IPolyMaterial* mat = m_meshobj->GetMaterialBucket(matid)->GetPolyMaterial();
+ RAS_MeshMaterial *mmat = m_meshobj->GetMeshMaterial(matid);
+ RAS_IPolyMaterial* mat = mmat->m_bucket->GetPolyMaterial();
+
if (mat)
- {
- length = m_meshobj->GetVertexArrayLength(mat);
- }
+ length = m_meshobj->NumVertices(mat);
+ }
+ else {
+ return NULL;
}
return PyInt_FromLong(length);
@@ -217,14 +238,39 @@ PyObject* KX_MeshProxy::PyGetVertex(PyObject* self,
vertexob = new KX_VertexProxy(this, vertex);
}
}
+ else {
+ return NULL;
+ }
return vertexob;
}
+PyObject* KX_MeshProxy::PyGetPolygon(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
+{
+ int polyindex= 1;
+ PyObject* polyob = NULL;
+
+ if (!PyArg_ParseTuple(args,"i",&polyindex))
+ return NULL;
+
+ RAS_Polygon* polygon = m_meshobj->GetPolygon(polyindex);
+ if (polygon)
+ {
+ polyob = new KX_PolyProxy(m_meshobj, polygon);
+ }
+ else
+ {
+ PyErr_SetString(PyExc_AttributeError, "Invalid polygon index");
+ }
+ return polyob;
+}
+
KX_PYMETHODDEF_DOC(KX_MeshProxy, reinstancePhysicsMesh,
"Reinstance the physics mesh.")
{
//this needs to be reviewed, it is dependend on Sumo/Solid. Who is using this ?
- return Py_None;//Py_Success(KX_ReInstanceShapeFromMesh(m_meshobj));
+ Py_RETURN_NONE;//(KX_ReInstanceShapeFromMesh(m_meshobj)) ? Py_RETURN_TRUE : Py_RETURN_FALSE;
}
diff --git a/source/gameengine/Ketsji/KX_MeshProxy.h b/source/gameengine/Ketsji/KX_MeshProxy.h
index 7c6202c15a4..3335c349673 100644
--- a/source/gameengine/Ketsji/KX_MeshProxy.h
+++ b/source/gameengine/Ketsji/KX_MeshProxy.h
@@ -57,10 +57,12 @@ public:
KX_PYMETHOD(KX_MeshProxy,GetNumMaterials);
KX_PYMETHOD(KX_MeshProxy,GetMaterialName);
KX_PYMETHOD(KX_MeshProxy,GetTextureName);
+ KX_PYMETHOD_NOARGS(KX_MeshProxy,GetNumPolygons);
// both take materialid (int)
KX_PYMETHOD(KX_MeshProxy,GetVertexArrayLength);
KX_PYMETHOD(KX_MeshProxy,GetVertex);
+ KX_PYMETHOD(KX_MeshProxy,GetPolygon);
KX_PYMETHOD_DOC(KX_MeshProxy, reinstancePhysicsMesh);
};
diff --git a/source/gameengine/Ketsji/KX_MouseFocusSensor.cpp b/source/gameengine/Ketsji/KX_MouseFocusSensor.cpp
index 60b90138abe..28279b9a6b8 100644
--- a/source/gameengine/Ketsji/KX_MouseFocusSensor.cpp
+++ b/source/gameengine/Ketsji/KX_MouseFocusSensor.cpp
@@ -62,43 +62,54 @@ KX_MouseFocusSensor::KX_MouseFocusSensor(SCA_MouseManager* eventmgr,
int focusmode,
RAS_ICanvas* canvas,
KX_Scene* kxscene,
+ KX_KetsjiEngine *kxengine,
SCA_IObject* gameobj,
PyTypeObject* T)
: SCA_MouseSensor(eventmgr, startx, starty, mousemode, gameobj, T),
m_focusmode(focusmode),
m_gp_canvas(canvas),
- m_kxscene(kxscene)
+ m_kxscene(kxscene),
+ m_kxengine(kxengine)
{
+ Init();
+}
- m_mouse_over_in_previous_frame = false;
+void KX_MouseFocusSensor::Init()
+{
+ m_mouse_over_in_previous_frame = (m_invert)?true:false;
m_positive_event = false;
m_hitObject = 0;
-
+ m_reset = true;
}
bool KX_MouseFocusSensor::Evaluate(CValue* event)
{
bool result = false;
bool obHasFocus = false;
+ bool reset = m_reset && m_level;
// cout << "evaluate focus mouse sensor "<<endl;
-
+ m_reset = false;
if (m_focusmode) {
/* Focus behaviour required. Test mouse-on. The rest is
* equivalent to handling a key. */
obHasFocus = ParentObjectHasFocus();
if (!obHasFocus) {
+ m_positive_event = false;
if (m_mouse_over_in_previous_frame) {
- m_positive_event = false;
- result = true;
+ result = true;
}
} else {
+ m_positive_event = true;
if (!m_mouse_over_in_previous_frame) {
- m_positive_event = true;
result = true;
}
}
+ if (reset) {
+ // force an event
+ result = true;
+ }
} else {
/* No focus behaviour required: revert to the basic mode. This
* mode is never used, because the converter never makes this
@@ -113,16 +124,10 @@ bool KX_MouseFocusSensor::Evaluate(CValue* event)
return result;
}
-bool KX_MouseFocusSensor::RayHit(KX_ClientObjectInfo* client_info, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data)
+bool KX_MouseFocusSensor::RayHit(KX_ClientObjectInfo* client_info, KX_RayCast* result, void * const data)
{
KX_GameObject* hitKXObj = client_info->m_gameobject;
- if (client_info->m_type > KX_ClientObjectInfo::ACTOR)
- {
- // false hit
- return false;
- }
-
/* Is this me? In the ray test, there are a lot of extra checks
* for aliasing artefacts from self-hits. That doesn't happen
* here, so a simple test suffices. Or does the camera also get
@@ -133,8 +138,8 @@ bool KX_MouseFocusSensor::RayHit(KX_ClientObjectInfo* client_info, MT_Point3& hi
if ((m_focusmode == 2) || hitKXObj == thisObj)
{
m_hitObject = hitKXObj;
- m_hitPosition = hit_point;
- m_hitNormal = hit_normal;
+ m_hitPosition = result->m_hitPoint;
+ m_hitNormal = result->m_hitNormal;
return true;
}
@@ -149,8 +154,6 @@ bool KX_MouseFocusSensor::ParentObjectHasFocus(void)
m_hitObject = 0;
m_hitPosition = MT_Vector3(0,0,0);
m_hitNormal = MT_Vector3(1,0,0);
- MT_Point3 resultpoint;
- MT_Vector3 resultnormal;
/* All screen handling in the gameengine is done by GL,
* specifically the model/view and projection parts. The viewport
@@ -192,11 +195,14 @@ bool KX_MouseFocusSensor::ParentObjectHasFocus(void)
* calculations don't bomb. Maybe we should explicitly guard for
* division by 0.0...*/
- /**
- * Get the scenes current viewport.
- */
+ KX_Camera* cam = m_kxscene->GetActiveCamera();
+
+ /* get the scenes current viewport. we recompute it because there
+ * may be multiple cameras and m_kxscene->GetSceneViewport() only
+ * has the one that was last drawn */
- const RAS_Rect & viewport = m_kxscene->GetSceneViewport();
+ RAS_Rect area, viewport;
+ m_kxengine->GetSceneViewport(m_kxscene, cam, area, viewport);
float height = float(viewport.m_y2 - viewport.m_y1 + 1);
float width = float(viewport.m_x2 - viewport.m_x1 + 1);
@@ -204,9 +210,9 @@ bool KX_MouseFocusSensor::ParentObjectHasFocus(void)
float x_lb = float(viewport.m_x1);
float y_lb = float(viewport.m_y1);
- KX_Camera* cam = m_kxscene->GetActiveCamera();
/* There's some strangeness I don't fully get here... These values
* _should_ be wrong! */
+
/* old: */
float nearclip = 0.0;
@@ -271,7 +277,8 @@ bool KX_MouseFocusSensor::ParentObjectHasFocus(void)
bool result = false;
- result = KX_RayCast::RayTest(physics_controller, physics_environment, frompoint3, topoint3, resultpoint, resultnormal, KX_RayCast::Callback<KX_MouseFocusSensor>(this));
+ KX_RayCast::Callback<KX_MouseFocusSensor> callback(this,physics_controller);
+ KX_RayCast::RayTest(physics_environment, frompoint3, topoint3, callback);
result = (m_hitObject!=0);
@@ -313,14 +320,12 @@ PyParentObject KX_MouseFocusSensor::Parents[] = {
};
PyMethodDef KX_MouseFocusSensor::Methods[] = {
- {"getRayTarget", (PyCFunction) KX_MouseFocusSensor::sPyGetRayTarget,
- METH_VARARGS, GetRayTarget_doc},
- {"getRaySource", (PyCFunction) KX_MouseFocusSensor::sPyGetRaySource,
- METH_VARARGS, GetRaySource_doc},
- {"getHitObject",(PyCFunction) KX_MouseFocusSensor::sPyGetHitObject,METH_VARARGS, GetHitObject_doc},
- {"getHitPosition",(PyCFunction) KX_MouseFocusSensor::sPyGetHitPosition,METH_VARARGS, GetHitPosition_doc},
- {"getHitNormal",(PyCFunction) KX_MouseFocusSensor::sPyGetHitNormal,METH_VARARGS, GetHitNormal_doc},
- {"getRayDirection",(PyCFunction) KX_MouseFocusSensor::sPyGetRayDirection,METH_VARARGS, GetRayDirection_doc},
+ {"getRayTarget", (PyCFunction) KX_MouseFocusSensor::sPyGetRayTarget, METH_VARARGS, (PY_METHODCHAR)GetRayTarget_doc},
+ {"getRaySource", (PyCFunction) KX_MouseFocusSensor::sPyGetRaySource, METH_VARARGS, (PY_METHODCHAR)GetRaySource_doc},
+ {"getHitObject",(PyCFunction) KX_MouseFocusSensor::sPyGetHitObject,METH_VARARGS, (PY_METHODCHAR)GetHitObject_doc},
+ {"getHitPosition",(PyCFunction) KX_MouseFocusSensor::sPyGetHitPosition,METH_VARARGS, (PY_METHODCHAR)GetHitPosition_doc},
+ {"getHitNormal",(PyCFunction) KX_MouseFocusSensor::sPyGetHitNormal,METH_VARARGS, (PY_METHODCHAR)GetHitNormal_doc},
+ {"getRayDirection",(PyCFunction) KX_MouseFocusSensor::sPyGetRayDirection,METH_VARARGS, (PY_METHODCHAR)GetRayDirection_doc},
{NULL,NULL} //Sentinel
@@ -331,7 +336,7 @@ PyObject* KX_MouseFocusSensor::_getattr(const STR_String& attr) {
}
-char KX_MouseFocusSensor::GetHitObject_doc[] =
+const char KX_MouseFocusSensor::GetHitObject_doc[] =
"getHitObject()\n"
"\tReturns the name of the object that was hit by this ray.\n";
PyObject* KX_MouseFocusSensor::PyGetHitObject(PyObject* self,
@@ -346,7 +351,7 @@ PyObject* KX_MouseFocusSensor::PyGetHitObject(PyObject* self,
}
-char KX_MouseFocusSensor::GetHitPosition_doc[] =
+const char KX_MouseFocusSensor::GetHitPosition_doc[] =
"getHitPosition()\n"
"\tReturns the position (in worldcoordinates) where the object was hit by this ray.\n";
PyObject* KX_MouseFocusSensor::PyGetHitPosition(PyObject* self,
@@ -366,7 +371,7 @@ PyObject* KX_MouseFocusSensor::PyGetHitPosition(PyObject* self,
}
-char KX_MouseFocusSensor::GetRayDirection_doc[] =
+const char KX_MouseFocusSensor::GetRayDirection_doc[] =
"getRayDirection()\n"
"\tReturns the direction from the ray (in worldcoordinates) .\n";
PyObject* KX_MouseFocusSensor::PyGetRayDirection(PyObject* self,
@@ -387,7 +392,7 @@ PyObject* KX_MouseFocusSensor::PyGetRayDirection(PyObject* self,
}
-char KX_MouseFocusSensor::GetHitNormal_doc[] =
+const char KX_MouseFocusSensor::GetHitNormal_doc[] =
"getHitNormal()\n"
"\tReturns the normal (in worldcoordinates) of the object at the location where the object was hit by this ray.\n";
PyObject* KX_MouseFocusSensor::PyGetHitNormal(PyObject* self,
@@ -408,7 +413,7 @@ PyObject* KX_MouseFocusSensor::PyGetHitNormal(PyObject* self,
/* getRayTarget */
-char KX_MouseFocusSensor::GetRayTarget_doc[] =
+const char KX_MouseFocusSensor::GetRayTarget_doc[] =
"getRayTarget()\n"
"\tReturns the target of the ray that seeks the focus object,\n"
"\tin worldcoordinates.";
@@ -425,7 +430,7 @@ PyObject* KX_MouseFocusSensor::PyGetRayTarget(PyObject* self,
}
/* getRayTarget */
-char KX_MouseFocusSensor::GetRaySource_doc[] =
+const char KX_MouseFocusSensor::GetRaySource_doc[] =
"getRaySource()\n"
"\tReturns the source of the ray that seeks the focus object,\n"
"\tin worldcoordinates.";
diff --git a/source/gameengine/Ketsji/KX_MouseFocusSensor.h b/source/gameengine/Ketsji/KX_MouseFocusSensor.h
index 86f32fbf4be..6731444699b 100644
--- a/source/gameengine/Ketsji/KX_MouseFocusSensor.h
+++ b/source/gameengine/Ketsji/KX_MouseFocusSensor.h
@@ -33,6 +33,8 @@
#include "SCA_MouseSensor.h"
+class KX_RayCast;
+
/**
* The mouse focus sensor extends the basic SCA_MouseSensor. It has
* been placed in KX because it needs access to the rasterizer and
@@ -54,6 +56,7 @@ class KX_MouseFocusSensor : public SCA_MouseSensor
int focusmode,
RAS_ICanvas* canvas,
KX_Scene* kxscene,
+ KX_KetsjiEngine* kxengine,
SCA_IObject* gameobj,
PyTypeObject* T=&Type );
@@ -68,6 +71,7 @@ class KX_MouseFocusSensor : public SCA_MouseSensor
* @attention Overrides default evaluate.
*/
virtual bool Evaluate(CValue* event);
+ virtual void Init();
virtual bool IsPositiveTrigger() {
bool result = m_positive_event;
@@ -75,7 +79,9 @@ class KX_MouseFocusSensor : public SCA_MouseSensor
return result;
};
- bool RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data);
+ bool RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data);
+ bool NeedRayCast(KX_ClientObjectInfo* client) { return true; }
+
/* --------------------------------------------------------------------- */
@@ -138,12 +144,6 @@ class KX_MouseFocusSensor : public SCA_MouseSensor
/**
- * Ref to the engine, for retrieving a reference to the current
- * scene. */
- class KX_KetsjiEngine* m_engine;
-
-
- /**
* The active canvas. The size of this canvas determines a part of
* the start position of the picking ray. */
RAS_ICanvas* m_gp_canvas;
@@ -153,6 +153,9 @@ class KX_MouseFocusSensor : public SCA_MouseSensor
* determines a part of the start location of the picking ray. */
KX_Scene* m_kxscene;
+ /**
+ * The KX engine is needed for computing the viewport */
+ KX_KetsjiEngine* m_kxengine;
};
#endif //__KX_MOUSESENSOR
diff --git a/source/gameengine/Ketsji/KX_NearSensor.cpp b/source/gameengine/Ketsji/KX_NearSensor.cpp
index d893990735f..bae87c28123 100644
--- a/source/gameengine/Ketsji/KX_NearSensor.cpp
+++ b/source/gameengine/Ketsji/KX_NearSensor.cpp
@@ -75,6 +75,21 @@ KX_NearSensor::KX_NearSensor(SCA_EventManager* eventmgr,
SynchronizeTransform();
}
+void KX_NearSensor::SynchronizeTransform()
+{
+ // The near and radar sensors are using a different physical object which is
+ // not linked to the parent object, must synchronize it.
+ if (m_physCtrl)
+ {
+ KX_GameObject* parent = ((KX_GameObject*)GetParent());
+ MT_Vector3 pos = parent->NodeGetWorldPosition();
+ MT_Quaternion orn = parent->NodeGetWorldOrientation().getRotation();
+ m_physCtrl->setPosition(pos.x(),pos.y(),pos.z());
+ m_physCtrl->setOrientation(orn.x(),orn.y(),orn.z(),orn.w());
+ m_physCtrl->calcXform();
+ }
+}
+
void KX_NearSensor::RegisterSumo(KX_TouchEventManager *touchman)
{
if (m_physCtrl)
@@ -83,14 +98,19 @@ void KX_NearSensor::RegisterSumo(KX_TouchEventManager *touchman)
}
}
+void KX_NearSensor::UnregisterSumo(KX_TouchEventManager* touchman)
+{
+ if (m_physCtrl)
+ {
+ touchman->GetPhysicsEnvironment()->removeSensor(m_physCtrl);
+ }
+}
+
CValue* KX_NearSensor::GetReplica()
{
KX_NearSensor* replica = new KX_NearSensor(*this);
replica->m_colliders = new CListValue();
- replica->m_bCollision = false;
- replica->m_bTriggered= false;
- replica->m_hitObject = NULL;
- replica->m_bLastTriggered = false;
+ replica->Init();
// this will copy properties and so on...
CValue::AddDataToReplica(replica);
@@ -123,9 +143,6 @@ CValue* KX_NearSensor::GetReplica()
void KX_NearSensor::ReParent(SCA_IObject* parent)
{
-
- SCA_ISensor::ReParent(parent);
-
m_client_info->m_gameobject = static_cast<KX_GameObject*>(parent);
m_client_info->m_sensors.push_back(this);
@@ -139,6 +156,7 @@ void KX_NearSensor::ReParent(SCA_IObject* parent)
*/
((KX_GameObject*)GetParent())->GetSGNode()->ComputeWorldTransforms(NULL);
SynchronizeTransform();
+ SCA_ISensor::ReParent(parent);
}
@@ -172,13 +190,13 @@ bool KX_NearSensor::Evaluate(CValue* event)
{
if (m_physCtrl)
{
- m_physCtrl->SetMargin(m_ResetMargin);
+ m_physCtrl->SetRadius(m_ResetMargin);
}
} else
{
if (m_physCtrl)
{
- m_physCtrl->SetMargin(m_Margin);
+ m_physCtrl->SetRadius(m_Margin);
}
}
@@ -188,7 +206,36 @@ bool KX_NearSensor::Evaluate(CValue* event)
return result;
}
+// this function is called at broad phase stage to check if the two controller
+// need to interact at all. It is used for Near/Radar sensor that don't need to
+// check collision with object not included in filter
+bool KX_NearSensor::BroadPhaseFilterCollision(void*obj1,void*obj2)
+{
+ KX_GameObject* parent = static_cast<KX_GameObject*>(GetParent());
+
+ // need the mapping from PHY_IPhysicsController to gameobjects now
+ assert(obj1==m_physCtrl && obj2);
+ KX_ClientObjectInfo* client_info = static_cast<KX_ClientObjectInfo*>((static_cast<PHY_IPhysicsController*>(obj2))->getNewClientInfo());
+ KX_GameObject* gameobj = ( client_info ?
+ client_info->m_gameobject :
+ NULL);
+
+ if (gameobj && (gameobj != parent))
+ {
+ // only take valid colliders
+ if (client_info->m_type == KX_ClientObjectInfo::ACTOR)
+ {
+ if ((m_touchedpropname.Length() == 0) ||
+ (gameobj->GetProperty(m_touchedpropname)))
+ {
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
bool KX_NearSensor::NewHandleCollision(void* obj1,void* obj2,const PHY_CollData * coll_data)
{
@@ -205,20 +252,24 @@ bool KX_NearSensor::NewHandleCollision(void* obj1,void* obj2,const PHY_CollData
client_info->m_gameobject :
NULL);
- if (gameobj && (gameobj != parent))
+ // Add the same check as in SCA_ISensor::Activate(),
+ // we don't want to record collision when the sensor is not active.
+ if (m_links && !m_suspended &&
+ gameobj /* done in BroadPhaseFilterCollision() && (gameobj != parent)*/)
{
if (!m_colliders->SearchValue(gameobj))
m_colliders->Add(gameobj->AddRef());
// only take valid colliders
- if (client_info->m_type == KX_ClientObjectInfo::ACTOR)
- {
- if ((m_touchedpropname.Length() == 0) ||
- (gameobj->GetProperty(m_touchedpropname)))
- {
+ // These checks are done already in BroadPhaseFilterCollision()
+ //if (client_info->m_type == KX_ClientObjectInfo::ACTOR)
+ //{
+ // if ((m_touchedpropname.Length() == 0) ||
+ // (gameobj->GetProperty(m_touchedpropname)))
+ // {
m_bTriggered = true;
m_hitObject = gameobj;
- }
- }
+ // }
+ //}
}
return DT_CONTINUE;
@@ -260,14 +311,10 @@ PyParentObject KX_NearSensor::Parents[] = {
PyMethodDef KX_NearSensor::Methods[] = {
- {"setProperty",
- (PyCFunction) KX_NearSensor::sPySetProperty, METH_VARARGS, SetProperty_doc},
- {"getProperty",
- (PyCFunction) KX_NearSensor::sPyGetProperty, METH_VARARGS, GetProperty_doc},
- {"getHitObject",
- (PyCFunction) KX_NearSensor::sPyGetHitObject, METH_VARARGS, GetHitObject_doc},
- {"getHitObjectList",
- (PyCFunction) KX_NearSensor::sPyGetHitObjectList, METH_VARARGS, GetHitObjectList_doc},
+ {"setProperty", (PyCFunction) KX_NearSensor::sPySetProperty, METH_VARARGS, (PY_METHODCHAR)SetProperty_doc},
+ {"getProperty", (PyCFunction) KX_NearSensor::sPyGetProperty, METH_VARARGS, (PY_METHODCHAR)GetProperty_doc},
+ {"getHitObject",(PyCFunction) KX_NearSensor::sPyGetHitObject, METH_VARARGS, (PY_METHODCHAR)GetHitObject_doc},
+ {"getHitObjectList", (PyCFunction) KX_NearSensor::sPyGetHitObjectList, METH_VARARGS, (PY_METHODCHAR)GetHitObjectList_doc},
{NULL,NULL} //Sentinel
};
diff --git a/source/gameengine/Ketsji/KX_NearSensor.h b/source/gameengine/Ketsji/KX_NearSensor.h
index 096822f99ed..3f7078ef9fd 100644
--- a/source/gameengine/Ketsji/KX_NearSensor.h
+++ b/source/gameengine/Ketsji/KX_NearSensor.h
@@ -68,13 +68,16 @@ public:
PyTypeObject* T=&Type);
*/
virtual ~KX_NearSensor();
+ virtual void SynchronizeTransform();
virtual CValue* GetReplica();
virtual bool Evaluate(CValue* event);
virtual void ReParent(SCA_IObject* parent);
virtual bool NewHandleCollision(void* obj1,void* obj2,
const PHY_CollData * coll_data);
+ virtual bool BroadPhaseFilterCollision(void*obj1,void*obj2);
virtual void RegisterSumo(KX_TouchEventManager *touchman);
+ virtual void UnregisterSumo(KX_TouchEventManager* touchman);
virtual PyObject* _getattr(const STR_String& attr);
diff --git a/source/gameengine/Ketsji/KX_ObjectActuator.cpp b/source/gameengine/Ketsji/KX_ObjectActuator.cpp
index 22a406792f9..98e73d4f0d7 100644
--- a/source/gameengine/Ketsji/KX_ObjectActuator.cpp
+++ b/source/gameengine/Ketsji/KX_ObjectActuator.cpp
@@ -50,6 +50,7 @@ KX_ObjectActuator(
const MT_Vector3& drot,
const MT_Vector3& linV,
const MT_Vector3& angV,
+ const short damping,
const KX_LocalFlags& flag,
PyTypeObject* T
) :
@@ -60,9 +61,23 @@ KX_ObjectActuator(
m_drot(drot),
m_linear_velocity(linV),
m_angular_velocity(angV),
+ m_linear_length2(0.0),
+ m_current_linear_factor(0.0),
+ m_current_angular_factor(0.0),
+ m_damping(damping),
m_bitLocalFlag (flag),
- m_active_combined_velocity (false)
+ m_active_combined_velocity (false),
+ m_linear_damping_active(false),
+ m_angular_damping_active(false),
+ m_error_accumulator(0.0,0.0,0.0),
+ m_previous_error(0.0,0.0,0.0)
{
+ if (m_bitLocalFlag.ServoControl)
+ {
+ // in servo motion, the force is local if the target velocity is local
+ m_bitLocalFlag.Force = m_bitLocalFlag.LinearVelocity;
+ }
+ UpdateFuzzyFlags();
}
bool KX_ObjectActuator::Update()
@@ -79,51 +94,153 @@ bool KX_ObjectActuator::Update()
// it should reconcile the externally set velocity with it's
// own velocity.
if (m_active_combined_velocity) {
- parent->ResolveCombinedVelocities(
- m_linear_velocity,
- m_angular_velocity,
- (m_bitLocalFlag.LinearVelocity) != 0,
- (m_bitLocalFlag.AngularVelocity) != 0
- );
+ if (parent)
+ parent->ResolveCombinedVelocities(
+ m_linear_velocity,
+ m_angular_velocity,
+ (m_bitLocalFlag.LinearVelocity) != 0,
+ (m_bitLocalFlag.AngularVelocity) != 0
+ );
m_active_combined_velocity = false;
}
+ m_linear_damping_active = false;
+ m_angular_damping_active = false;
+ m_error_accumulator.setValue(0.0,0.0,0.0);
+ m_previous_error.setValue(0.0,0.0,0.0);
return false;
- } else
- if (parent)
+ } else if (parent)
{
- /* Probably better to use some flags, so these MT_zero tests can be */
- /* skipped. */
- if (!MT_fuzzyZero(m_force))
- {
- parent->ApplyForce(m_force,(m_bitLocalFlag.Force) != 0);
- }
- if (!MT_fuzzyZero(m_torque))
- {
- parent->ApplyTorque(m_torque,(m_bitLocalFlag.Torque) != 0);
- }
- if (!MT_fuzzyZero(m_dloc))
+ if (m_bitLocalFlag.ServoControl)
{
- parent->ApplyMovement(m_dloc,(m_bitLocalFlag.DLoc) != 0);
- }
- if (!MT_fuzzyZero(m_drot))
- {
- parent->ApplyRotation(m_drot,(m_bitLocalFlag.DRot) != 0);
- }
- if (!MT_fuzzyZero(m_linear_velocity))
+ // In this mode, we try to reach a target speed using force
+ // As we don't know the friction, we must implement a generic
+ // servo control to achieve the speed in a configurable
+ // v = current velocity
+ // V = target velocity
+ // e = V-v = speed error
+ // dt = time interval since previous update
+ // I = sum(e(t)*dt)
+ // dv = e(t) - e(t-1)
+ // KP, KD, KI : coefficient
+ // F = KP*e+KI*I+KD*dv
+ MT_Scalar mass = parent->GetMass();
+ if (mass < MT_EPSILON)
+ return false;
+ MT_Vector3 v = parent->GetLinearVelocity(m_bitLocalFlag.LinearVelocity);
+ MT_Vector3 e = m_linear_velocity - v;
+ MT_Vector3 dv = e - m_previous_error;
+ MT_Vector3 I = m_error_accumulator + e;
+
+ m_force = m_torque.x()*e+m_torque.y()*I+m_torque.z()*dv;
+ // to automatically adapt the PID coefficient to mass;
+ m_force *= mass;
+ if (m_bitLocalFlag.Torque)
+ {
+ if (m_force[0] > m_dloc[0])
+ {
+ m_force[0] = m_dloc[0];
+ I[0] = m_error_accumulator[0];
+ } else if (m_force[0] < m_drot[0])
+ {
+ m_force[0] = m_drot[0];
+ I[0] = m_error_accumulator[0];
+ }
+ }
+ if (m_bitLocalFlag.DLoc)
+ {
+ if (m_force[1] > m_dloc[1])
+ {
+ m_force[1] = m_dloc[1];
+ I[1] = m_error_accumulator[1];
+ } else if (m_force[1] < m_drot[1])
+ {
+ m_force[1] = m_drot[1];
+ I[1] = m_error_accumulator[1];
+ }
+ }
+ if (m_bitLocalFlag.DRot)
+ {
+ if (m_force[2] > m_dloc[2])
+ {
+ m_force[2] = m_dloc[2];
+ I[2] = m_error_accumulator[2];
+ } else if (m_force[2] < m_drot[2])
+ {
+ m_force[2] = m_drot[2];
+ I[2] = m_error_accumulator[2];
+ }
+ }
+ m_previous_error = e;
+ m_error_accumulator = I;
+ parent->ApplyForce(m_force,(m_bitLocalFlag.LinearVelocity) != 0);
+ } else
{
- if (m_bitLocalFlag.AddOrSetLinV) {
- parent->addLinearVelocity(m_linear_velocity,(m_bitLocalFlag.LinearVelocity) != 0);
- } else {
+ if (!m_bitLocalFlag.ZeroForce)
+ {
+ parent->ApplyForce(m_force,(m_bitLocalFlag.Force) != 0);
+ }
+ if (!m_bitLocalFlag.ZeroTorque)
+ {
+ parent->ApplyTorque(m_torque,(m_bitLocalFlag.Torque) != 0);
+ }
+ if (!m_bitLocalFlag.ZeroDLoc)
+ {
+ parent->ApplyMovement(m_dloc,(m_bitLocalFlag.DLoc) != 0);
+ }
+ if (!m_bitLocalFlag.ZeroDRot)
+ {
+ parent->ApplyRotation(m_drot,(m_bitLocalFlag.DRot) != 0);
+ }
+ if (!m_bitLocalFlag.ZeroLinearVelocity)
+ {
+ if (m_bitLocalFlag.AddOrSetLinV) {
+ parent->addLinearVelocity(m_linear_velocity,(m_bitLocalFlag.LinearVelocity) != 0);
+ } else {
+ m_active_combined_velocity = true;
+ if (m_damping > 0) {
+ MT_Vector3 linV;
+ if (!m_linear_damping_active) {
+ // delta and the start speed (depends on the existing speed in that direction)
+ linV = parent->GetLinearVelocity(m_bitLocalFlag.LinearVelocity);
+ // keep only the projection along the desired direction
+ m_current_linear_factor = linV.dot(m_linear_velocity)/m_linear_length2;
+ m_linear_damping_active = true;
+ }
+ if (m_current_linear_factor < 1.0)
+ m_current_linear_factor += 1.0/m_damping;
+ if (m_current_linear_factor > 1.0)
+ m_current_linear_factor = 1.0;
+ linV = m_current_linear_factor * m_linear_velocity;
+ parent->setLinearVelocity(linV,(m_bitLocalFlag.LinearVelocity) != 0);
+ } else {
+ parent->setLinearVelocity(m_linear_velocity,(m_bitLocalFlag.LinearVelocity) != 0);
+ }
+ }
+ }
+ if (!m_bitLocalFlag.ZeroAngularVelocity)
+ {
m_active_combined_velocity = true;
- parent->setLinearVelocity(m_linear_velocity,(m_bitLocalFlag.LinearVelocity) != 0);
+ if (m_damping > 0) {
+ MT_Vector3 angV;
+ if (!m_angular_damping_active) {
+ // delta and the start speed (depends on the existing speed in that direction)
+ angV = parent->GetAngularVelocity(m_bitLocalFlag.AngularVelocity);
+ // keep only the projection along the desired direction
+ m_current_angular_factor = angV.dot(m_angular_velocity)/m_angular_length2;
+ m_angular_damping_active = true;
+ }
+ if (m_current_angular_factor < 1.0)
+ m_current_angular_factor += 1.0/m_damping;
+ if (m_current_angular_factor > 1.0)
+ m_current_angular_factor = 1.0;
+ angV = m_current_angular_factor * m_angular_velocity;
+ parent->setAngularVelocity(angV,(m_bitLocalFlag.AngularVelocity) != 0);
+ } else {
+ parent->setAngularVelocity(m_angular_velocity,(m_bitLocalFlag.AngularVelocity) != 0);
+ }
}
}
- if (!MT_fuzzyZero(m_angular_velocity))
- {
- parent->setAngularVelocity(m_angular_velocity,(m_bitLocalFlag.AngularVelocity) != 0);
- m_active_combined_velocity = true;
- }
}
return true;
@@ -187,18 +304,29 @@ PyParentObject KX_ObjectActuator::Parents[] = {
};
PyMethodDef KX_ObjectActuator::Methods[] = {
- {"getForce", (PyCFunction) KX_ObjectActuator::sPyGetForce, METH_VARARGS},
+ {"getForce", (PyCFunction) KX_ObjectActuator::sPyGetForce, METH_NOARGS},
{"setForce", (PyCFunction) KX_ObjectActuator::sPySetForce, METH_VARARGS},
- {"getTorque", (PyCFunction) KX_ObjectActuator::sPyGetTorque, METH_VARARGS},
+ {"getTorque", (PyCFunction) KX_ObjectActuator::sPyGetTorque, METH_NOARGS},
{"setTorque", (PyCFunction) KX_ObjectActuator::sPySetTorque, METH_VARARGS},
- {"getDLoc", (PyCFunction) KX_ObjectActuator::sPyGetDLoc, METH_VARARGS},
+ {"getDLoc", (PyCFunction) KX_ObjectActuator::sPyGetDLoc, METH_NOARGS},
{"setDLoc", (PyCFunction) KX_ObjectActuator::sPySetDLoc, METH_VARARGS},
- {"getDRot", (PyCFunction) KX_ObjectActuator::sPyGetDRot, METH_VARARGS},
+ {"getDRot", (PyCFunction) KX_ObjectActuator::sPyGetDRot, METH_NOARGS},
{"setDRot", (PyCFunction) KX_ObjectActuator::sPySetDRot, METH_VARARGS},
- {"getLinearVelocity", (PyCFunction) KX_ObjectActuator::sPyGetLinearVelocity, METH_VARARGS},
+ {"getLinearVelocity", (PyCFunction) KX_ObjectActuator::sPyGetLinearVelocity, METH_NOARGS},
{"setLinearVelocity", (PyCFunction) KX_ObjectActuator::sPySetLinearVelocity, METH_VARARGS},
- {"getAngularVelocity", (PyCFunction) KX_ObjectActuator::sPyGetAngularVelocity, METH_VARARGS},
+ {"getAngularVelocity", (PyCFunction) KX_ObjectActuator::sPyGetAngularVelocity, METH_NOARGS},
{"setAngularVelocity", (PyCFunction) KX_ObjectActuator::sPySetAngularVelocity, METH_VARARGS},
+ {"setDamping", (PyCFunction) KX_ObjectActuator::sPySetDamping, METH_VARARGS},
+ {"getDamping", (PyCFunction) KX_ObjectActuator::sPyGetDamping, METH_NOARGS},
+ {"setForceLimitX", (PyCFunction) KX_ObjectActuator::sPySetForceLimitX, METH_VARARGS},
+ {"getForceLimitX", (PyCFunction) KX_ObjectActuator::sPyGetForceLimitX, METH_NOARGS},
+ {"setForceLimitY", (PyCFunction) KX_ObjectActuator::sPySetForceLimitY, METH_VARARGS},
+ {"getForceLimitY", (PyCFunction) KX_ObjectActuator::sPyGetForceLimitY, METH_NOARGS},
+ {"setForceLimitZ", (PyCFunction) KX_ObjectActuator::sPySetForceLimitZ, METH_VARARGS},
+ {"getForceLimitZ", (PyCFunction) KX_ObjectActuator::sPyGetForceLimitZ, METH_NOARGS},
+ {"setPID", (PyCFunction) KX_ObjectActuator::sPyGetPID, METH_NOARGS},
+ {"getPID", (PyCFunction) KX_ObjectActuator::sPySetPID, METH_VARARGS},
+
{NULL,NULL} //Sentinel
@@ -212,9 +340,7 @@ PyObject* KX_ObjectActuator::_getattr(const STR_String& attr) {
/* Removed! */
/* 2. getForce */
-PyObject* KX_ObjectActuator::PyGetForce(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_ObjectActuator::PyGetForce(PyObject* self)
{
PyObject *retVal = PyList_New(4);
@@ -238,13 +364,12 @@ PyObject* KX_ObjectActuator::PySetForce(PyObject* self,
}
m_force.setValue(vecArg);
m_bitLocalFlag.Force = PyArgToBool(bToggle);
+ UpdateFuzzyFlags();
Py_Return;
}
/* 4. getTorque */
-PyObject* KX_ObjectActuator::PyGetTorque(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_ObjectActuator::PyGetTorque(PyObject* self)
{
PyObject *retVal = PyList_New(4);
@@ -268,13 +393,12 @@ PyObject* KX_ObjectActuator::PySetTorque(PyObject* self,
}
m_torque.setValue(vecArg);
m_bitLocalFlag.Torque = PyArgToBool(bToggle);
+ UpdateFuzzyFlags();
Py_Return;
}
/* 6. getDLoc */
-PyObject* KX_ObjectActuator::PyGetDLoc(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_ObjectActuator::PyGetDLoc(PyObject* self)
{
PyObject *retVal = PyList_New(4);
@@ -298,13 +422,12 @@ PyObject* KX_ObjectActuator::PySetDLoc(PyObject* self,
}
m_dloc.setValue(vecArg);
m_bitLocalFlag.DLoc = PyArgToBool(bToggle);
+ UpdateFuzzyFlags();
Py_Return;
}
/* 8. getDRot */
-PyObject* KX_ObjectActuator::PyGetDRot(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_ObjectActuator::PyGetDRot(PyObject* self)
{
PyObject *retVal = PyList_New(4);
@@ -328,13 +451,12 @@ PyObject* KX_ObjectActuator::PySetDRot(PyObject* self,
}
m_drot.setValue(vecArg);
m_bitLocalFlag.DRot = PyArgToBool(bToggle);
+ UpdateFuzzyFlags();
Py_Return;
}
/* 10. getLinearVelocity */
-PyObject* KX_ObjectActuator::PyGetLinearVelocity(PyObject* self,
- PyObject* args,
- PyObject* kwds) {
+PyObject* KX_ObjectActuator::PyGetLinearVelocity(PyObject* self) {
PyObject *retVal = PyList_New(4);
PyList_SetItem(retVal, 0, PyFloat_FromDouble(m_linear_velocity[0]));
@@ -357,14 +479,13 @@ PyObject* KX_ObjectActuator::PySetLinearVelocity(PyObject* self,
}
m_linear_velocity.setValue(vecArg);
m_bitLocalFlag.LinearVelocity = PyArgToBool(bToggle);
+ UpdateFuzzyFlags();
Py_Return;
}
/* 12. getAngularVelocity */
-PyObject* KX_ObjectActuator::PyGetAngularVelocity(PyObject* self,
- PyObject* args,
- PyObject* kwds) {
+PyObject* KX_ObjectActuator::PyGetAngularVelocity(PyObject* self) {
PyObject *retVal = PyList_New(4);
PyList_SetItem(retVal, 0, PyFloat_FromDouble(m_angular_velocity[0]));
@@ -386,10 +507,133 @@ PyObject* KX_ObjectActuator::PySetAngularVelocity(PyObject* self,
}
m_angular_velocity.setValue(vecArg);
m_bitLocalFlag.AngularVelocity = PyArgToBool(bToggle);
+ UpdateFuzzyFlags();
+ Py_Return;
+}
+
+/* 13. setDamping */
+PyObject* KX_ObjectActuator::PySetDamping(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ int damping = 0;
+ if (!PyArg_ParseTuple(args, "i", &damping) || damping < 0 || damping > 1000) {
+ return NULL;
+ }
+ m_damping = damping;
+ Py_Return;
+}
+
+/* 13. getVelocityDamping */
+PyObject* KX_ObjectActuator::PyGetDamping(PyObject* self) {
+ return Py_BuildValue("i",m_damping);
+}
+/* 6. getForceLimitX */
+PyObject* KX_ObjectActuator::PyGetForceLimitX(PyObject* self)
+{
+ PyObject *retVal = PyList_New(3);
+
+ PyList_SetItem(retVal, 0, PyFloat_FromDouble(m_drot[0]));
+ PyList_SetItem(retVal, 1, PyFloat_FromDouble(m_dloc[0]));
+ PyList_SetItem(retVal, 2, BoolToPyArg(m_bitLocalFlag.Torque));
+
+ return retVal;
+}
+/* 7. setForceLimitX */
+PyObject* KX_ObjectActuator::PySetForceLimitX(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
+{
+ float vecArg[2];
+ int bToggle = 0;
+ if(!PyArg_ParseTuple(args, "ffi", &vecArg[0], &vecArg[1], &bToggle)) {
+ return NULL;
+ }
+ m_drot[0] = vecArg[0];
+ m_dloc[0] = vecArg[1];
+ m_bitLocalFlag.Torque = PyArgToBool(bToggle);
+ Py_Return;
+}
+
+/* 6. getForceLimitY */
+PyObject* KX_ObjectActuator::PyGetForceLimitY(PyObject* self)
+{
+ PyObject *retVal = PyList_New(3);
+
+ PyList_SetItem(retVal, 0, PyFloat_FromDouble(m_drot[1]));
+ PyList_SetItem(retVal, 1, PyFloat_FromDouble(m_dloc[1]));
+ PyList_SetItem(retVal, 2, BoolToPyArg(m_bitLocalFlag.DLoc));
+
+ return retVal;
+}
+/* 7. setForceLimitY */
+PyObject* KX_ObjectActuator::PySetForceLimitY(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
+{
+ float vecArg[2];
+ int bToggle = 0;
+ if(!PyArg_ParseTuple(args, "ffi", &vecArg[0], &vecArg[1], &bToggle)) {
+ return NULL;
+ }
+ m_drot[1] = vecArg[0];
+ m_dloc[1] = vecArg[1];
+ m_bitLocalFlag.DLoc = PyArgToBool(bToggle);
+ Py_Return;
+}
+
+/* 6. getForceLimitZ */
+PyObject* KX_ObjectActuator::PyGetForceLimitZ(PyObject* self)
+{
+ PyObject *retVal = PyList_New(3);
+
+ PyList_SetItem(retVal, 0, PyFloat_FromDouble(m_drot[2]));
+ PyList_SetItem(retVal, 1, PyFloat_FromDouble(m_dloc[2]));
+ PyList_SetItem(retVal, 2, BoolToPyArg(m_bitLocalFlag.DRot));
+
+ return retVal;
+}
+/* 7. setForceLimitZ */
+PyObject* KX_ObjectActuator::PySetForceLimitZ(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
+{
+ float vecArg[2];
+ int bToggle = 0;
+ if(!PyArg_ParseTuple(args, "ffi", &vecArg[0], &vecArg[1], &bToggle)) {
+ return NULL;
+ }
+ m_drot[2] = vecArg[0];
+ m_dloc[2] = vecArg[1];
+ m_bitLocalFlag.DRot = PyArgToBool(bToggle);
+ Py_Return;
+}
+
+/* 4. getPID */
+PyObject* KX_ObjectActuator::PyGetPID(PyObject* self)
+{
+ PyObject *retVal = PyList_New(3);
+
+ PyList_SetItem(retVal, 0, PyFloat_FromDouble(m_torque[0]));
+ PyList_SetItem(retVal, 1, PyFloat_FromDouble(m_torque[1]));
+ PyList_SetItem(retVal, 2, PyFloat_FromDouble(m_torque[2]));
+
+ return retVal;
+}
+/* 5. setPID */
+PyObject* KX_ObjectActuator::PySetPID(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
+{
+ float vecArg[3];
+ if (!PyArg_ParseTuple(args, "fff", &vecArg[0], &vecArg[1], &vecArg[2])) {
+ return NULL;
+ }
+ m_torque.setValue(vecArg);
Py_Return;
}
+
/* eof */
diff --git a/source/gameengine/Ketsji/KX_ObjectActuator.h b/source/gameengine/Ketsji/KX_ObjectActuator.h
index edbae154b8b..aa686f41233 100644
--- a/source/gameengine/Ketsji/KX_ObjectActuator.h
+++ b/source/gameengine/Ketsji/KX_ObjectActuator.h
@@ -46,7 +46,12 @@ struct KX_LocalFlags {
DLoc(false),
LinearVelocity(false),
AngularVelocity(false),
- AddOrSetLinV(false)
+ AddOrSetLinV(false),
+ ZeroForce(false),
+ ZeroDRot(false),
+ ZeroDLoc(false),
+ ZeroLinearVelocity(false),
+ ZeroAngularVelocity(false)
{
}
@@ -57,6 +62,13 @@ struct KX_LocalFlags {
unsigned short LinearVelocity : 1;
unsigned short AngularVelocity : 1;
unsigned short AddOrSetLinV : 1;
+ unsigned short ServoControl : 1;
+ unsigned short ZeroForce : 1;
+ unsigned short ZeroTorque : 1;
+ unsigned short ZeroDRot : 1;
+ unsigned short ZeroDLoc : 1;
+ unsigned short ZeroLinearVelocity : 1;
+ unsigned short ZeroAngularVelocity : 1;
};
class KX_ObjectActuator : public SCA_IActuator
@@ -69,6 +81,15 @@ class KX_ObjectActuator : public SCA_IActuator
MT_Vector3 m_drot;
MT_Vector3 m_linear_velocity;
MT_Vector3 m_angular_velocity;
+ MT_Scalar m_linear_length2;
+ MT_Scalar m_angular_length2;
+ // used in damping
+ MT_Scalar m_current_linear_factor;
+ MT_Scalar m_current_angular_factor;
+ short m_damping;
+ // used in servo control
+ MT_Vector3 m_previous_error;
+ MT_Vector3 m_error_accumulator;
KX_LocalFlags m_bitLocalFlag;
// A hack bool -- oh no sorry everyone
@@ -77,6 +98,8 @@ class KX_ObjectActuator : public SCA_IActuator
// setting linear velocity.
bool m_active_combined_velocity;
+ bool m_linear_damping_active;
+ bool m_angular_damping_active;
public:
enum KX_OBJECT_ACT_VEC_TYPE {
@@ -103,6 +126,7 @@ public:
const MT_Vector3& drot,
const MT_Vector3& linV,
const MT_Vector3& angV,
+ const short damping,
const KX_LocalFlags& flag,
PyTypeObject* T=&Type
);
@@ -110,6 +134,17 @@ public:
CValue* GetReplica();
void SetForceLoc(const double force[3]) { /*m_force=force;*/ }
+ void UpdateFuzzyFlags()
+ {
+ m_bitLocalFlag.ZeroForce = MT_fuzzyZero(m_force);
+ m_bitLocalFlag.ZeroTorque = MT_fuzzyZero(m_torque);
+ m_bitLocalFlag.ZeroDLoc = MT_fuzzyZero(m_dloc);
+ m_bitLocalFlag.ZeroDRot = MT_fuzzyZero(m_drot);
+ m_bitLocalFlag.ZeroLinearVelocity = MT_fuzzyZero(m_linear_velocity);
+ m_linear_length2 = (m_bitLocalFlag.ZeroLinearVelocity) ? 0.0 : m_linear_velocity.length2();
+ m_bitLocalFlag.ZeroAngularVelocity = MT_fuzzyZero(m_angular_velocity);
+ m_angular_length2 = (m_bitLocalFlag.ZeroAngularVelocity) ? 0.0 : m_angular_velocity.length2();
+ }
virtual bool Update();
@@ -120,18 +155,28 @@ public:
virtual PyObject* _getattr(const STR_String& attr);
- KX_PYMETHOD(KX_ObjectActuator,GetForce);
+ KX_PYMETHOD_NOARGS(KX_ObjectActuator,GetForce);
KX_PYMETHOD(KX_ObjectActuator,SetForce);
- KX_PYMETHOD(KX_ObjectActuator,GetTorque);
+ KX_PYMETHOD_NOARGS(KX_ObjectActuator,GetTorque);
KX_PYMETHOD(KX_ObjectActuator,SetTorque);
- KX_PYMETHOD(KX_ObjectActuator,GetDLoc);
+ KX_PYMETHOD_NOARGS(KX_ObjectActuator,GetDLoc);
KX_PYMETHOD(KX_ObjectActuator,SetDLoc);
- KX_PYMETHOD(KX_ObjectActuator,GetDRot);
+ KX_PYMETHOD_NOARGS(KX_ObjectActuator,GetDRot);
KX_PYMETHOD(KX_ObjectActuator,SetDRot);
- KX_PYMETHOD(KX_ObjectActuator,GetLinearVelocity);
+ KX_PYMETHOD_NOARGS(KX_ObjectActuator,GetLinearVelocity);
KX_PYMETHOD(KX_ObjectActuator,SetLinearVelocity);
- KX_PYMETHOD(KX_ObjectActuator,GetAngularVelocity);
+ KX_PYMETHOD_NOARGS(KX_ObjectActuator,GetAngularVelocity);
KX_PYMETHOD(KX_ObjectActuator,SetAngularVelocity);
+ KX_PYMETHOD(KX_ObjectActuator,SetDamping);
+ KX_PYMETHOD_NOARGS(KX_ObjectActuator,GetDamping);
+ KX_PYMETHOD_NOARGS(KX_ObjectActuator,GetForceLimitX);
+ KX_PYMETHOD(KX_ObjectActuator,SetForceLimitX);
+ KX_PYMETHOD_NOARGS(KX_ObjectActuator,GetForceLimitY);
+ KX_PYMETHOD(KX_ObjectActuator,SetForceLimitY);
+ KX_PYMETHOD_NOARGS(KX_ObjectActuator,GetForceLimitZ);
+ KX_PYMETHOD(KX_ObjectActuator,SetForceLimitZ);
+ KX_PYMETHOD_NOARGS(KX_ObjectActuator,GetPID);
+ KX_PYMETHOD(KX_ObjectActuator,SetPID);
};
#endif //__KX_OBJECTACTUATOR
diff --git a/source/gameengine/Ketsji/KX_OdePhysicsController.cpp b/source/gameengine/Ketsji/KX_OdePhysicsController.cpp
index 4e45ce484e3..6a701a5f25b 100644
--- a/source/gameengine/Ketsji/KX_OdePhysicsController.cpp
+++ b/source/gameengine/Ketsji/KX_OdePhysicsController.cpp
@@ -133,8 +133,9 @@ void KX_OdePhysicsController::SetLinearVelocity(const MT_Vector3& lin_vel,bool l
ODEPhysicsController::SetLinearVelocity(lin_vel[0],lin_vel[1],lin_vel[2],local);
}
-void KX_OdePhysicsController::setOrientation(const MT_Quaternion& orn)
+void KX_OdePhysicsController::setOrientation(const MT_Matrix3x3& rot)
{
+ MT_Quaternion orn = rot.getRotation();
ODEPhysicsController::setOrientation(orn[0],orn[1],orn[2],orn[3]);
}
@@ -168,6 +169,11 @@ MT_Scalar KX_OdePhysicsController::GetMass()
return ODEPhysicsController::getMass();
}
+MT_Scalar KX_OdePhysicsController::GetRadius()
+{
+ return MT_Scalar(0.f);
+}
+
MT_Vector3 KX_OdePhysicsController::getReactionForce()
{
return MT_Vector3(0,0,0);
@@ -177,7 +183,7 @@ void KX_OdePhysicsController::setRigidBody(bool rigid)
}
-void KX_OdePhysicsController::SuspendDynamics()
+void KX_OdePhysicsController::SuspendDynamics(bool)
{
ODEPhysicsController::SuspendDynamics();
}
diff --git a/source/gameengine/Ketsji/KX_OdePhysicsController.h b/source/gameengine/Ketsji/KX_OdePhysicsController.h
index 07a0bee9775..53050f6ce3e 100644
--- a/source/gameengine/Ketsji/KX_OdePhysicsController.h
+++ b/source/gameengine/Ketsji/KX_OdePhysicsController.h
@@ -67,16 +67,16 @@ public:
virtual void SetLinearVelocity(const MT_Vector3& lin_vel,bool local);
virtual void resolveCombinedVelocities(float linvelX,float linvelY,float linvelZ,float angVelX,float angVelY,float angVelZ);
virtual void getOrientation(MT_Quaternion& orn);
- virtual void setOrientation(const MT_Quaternion& orn);
+ virtual void setOrientation(const MT_Matrix3x3& orn);
virtual void setPosition(const MT_Point3& pos);
virtual void setScaling(const MT_Vector3& scaling);
virtual MT_Scalar GetMass();
virtual MT_Vector3 getReactionForce();
virtual void setRigidBody(bool rigid);
- virtual void SuspendDynamics();
+ virtual void SuspendDynamics(bool);
virtual void RestoreDynamics();
-
+ virtual MT_Scalar GetRadius();
virtual SG_Controller* GetReplica(class SG_Node* destnode);
diff --git a/source/gameengine/Ketsji/KX_ParentActuator.cpp b/source/gameengine/Ketsji/KX_ParentActuator.cpp
new file mode 100644
index 00000000000..89549ca6b57
--- /dev/null
+++ b/source/gameengine/Ketsji/KX_ParentActuator.cpp
@@ -0,0 +1,221 @@
+/**
+ * Set or remove an objects parent
+ *
+ * $Id: SCA_ParentActuator.cpp 13932 2008-03-01 19:05:41Z ben2610 $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "KX_ParentActuator.h"
+#include "KX_GameObject.h"
+#include "KX_PythonInit.h"
+
+#include "PyObjectPlus.h"
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/* ------------------------------------------------------------------------- */
+/* Native functions */
+/* ------------------------------------------------------------------------- */
+
+KX_ParentActuator::KX_ParentActuator(SCA_IObject *gameobj,
+ int mode,
+ SCA_IObject *ob,
+ PyTypeObject* T)
+ : SCA_IActuator(gameobj, T),
+ m_mode(mode),
+ m_ob(ob)
+{
+ if (m_ob)
+ m_ob->RegisterActuator(this);
+}
+
+
+
+KX_ParentActuator::~KX_ParentActuator()
+{
+ if (m_ob)
+ m_ob->UnregisterActuator(this);
+}
+
+
+
+CValue* KX_ParentActuator::GetReplica()
+{
+ KX_ParentActuator* replica = new KX_ParentActuator(*this);
+ // replication just copy the m_base pointer => common random generator
+ replica->ProcessReplica();
+ CValue::AddDataToReplica(replica);
+
+ return replica;
+}
+
+void KX_ParentActuator::ProcessReplica()
+{
+ if (m_ob)
+ m_ob->RegisterActuator(this);
+ SCA_IActuator::ProcessReplica();
+}
+
+
+bool KX_ParentActuator::UnlinkObject(SCA_IObject* clientobj)
+{
+ if (clientobj == m_ob)
+ {
+ // this object is being deleted, we cannot continue to track it.
+ m_ob = NULL;
+ return true;
+ }
+ return false;
+}
+
+void KX_ParentActuator::Relink(GEN_Map<GEN_HashedPtr, void*> *obj_map)
+{
+ void **h_obj = (*obj_map)[m_ob];
+ if (h_obj) {
+ if (m_ob)
+ m_ob->UnregisterActuator(this);
+ m_ob = (SCA_IObject*)(*h_obj);
+ m_ob->RegisterActuator(this);
+ }
+}
+
+
+
+bool KX_ParentActuator::Update()
+{
+ bool bNegativeEvent = IsNegativeEvent();
+ RemoveAllEvents();
+
+ if (bNegativeEvent)
+ return false; // do nothing on negative events
+
+ KX_GameObject *obj = (KX_GameObject*) GetParent();
+ KX_Scene *scene = KX_GetActiveScene();
+ switch (m_mode) {
+ case KX_PARENT_SET:
+ if (m_ob)
+ obj->SetParent(scene, (KX_GameObject*)m_ob);
+ break;
+ case KX_PARENT_REMOVE:
+ obj->RemoveParent(scene);
+ break;
+ };
+
+ return false;
+}
+
+/* ------------------------------------------------------------------------- */
+/* Python functions */
+/* ------------------------------------------------------------------------- */
+
+/* Integration hooks ------------------------------------------------------- */
+PyTypeObject KX_ParentActuator::Type = {
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0,
+ "KX_ParentActuator",
+ sizeof(KX_ParentActuator),
+ 0,
+ PyDestructor,
+ 0,
+ __getattr,
+ __setattr,
+ 0, //&MyPyCompare,
+ __repr,
+ 0, //&cvalue_as_number,
+ 0,
+ 0,
+ 0,
+ 0
+};
+
+PyParentObject KX_ParentActuator::Parents[] = {
+ &KX_ParentActuator::Type,
+ &SCA_IActuator::Type,
+ &SCA_ILogicBrick::Type,
+ &CValue::Type,
+ NULL
+};
+
+PyMethodDef KX_ParentActuator::Methods[] = {
+ {"setObject", (PyCFunction) KX_ParentActuator::sPySetObject, METH_O, (PY_METHODCHAR)SetObject_doc},
+ {"getObject", (PyCFunction) KX_ParentActuator::sPyGetObject, METH_VARARGS, (PY_METHODCHAR)GetObject_doc},
+ {NULL,NULL} //Sentinel
+};
+
+PyObject* KX_ParentActuator::_getattr(const STR_String& attr) {
+ _getattr_up(SCA_IActuator);
+}
+
+/* 1. setObject */
+const char KX_ParentActuator::SetObject_doc[] =
+"setObject(object)\n"
+"\t- object: KX_GameObject, string or None\n"
+"\tSet the object to set as parent.\n";
+PyObject* KX_ParentActuator::PySetObject(PyObject* self, PyObject* value) {
+ KX_GameObject *gameobj;
+
+ if (!ConvertPythonToGameObject(value, &gameobj, true))
+ return NULL; // ConvertPythonToGameObject sets the error
+
+ if (m_ob != NULL)
+ m_ob->UnregisterActuator(this);
+
+ m_ob = (SCA_IObject*)gameobj;
+ if (m_ob)
+ m_ob->RegisterActuator(this);
+
+ Py_RETURN_NONE;
+}
+
+/* 2. getObject */
+
+/* get obj ---------------------------------------------------------- */
+const char KX_ParentActuator::GetObject_doc[] =
+"getObject(name_only = 1)\n"
+"name_only - optional arg, when true will return the KX_GameObject rather then its name\n"
+"\tReturns the object that is set to.\n";
+PyObject* KX_ParentActuator::PyGetObject(PyObject* self, PyObject* args)
+{
+ int ret_name_only = 1;
+ if (!PyArg_ParseTuple(args, "|i", &ret_name_only))
+ return NULL;
+
+ if (!m_ob)
+ Py_RETURN_NONE;
+
+ if (ret_name_only)
+ return PyString_FromString(m_ob->GetName());
+ else
+ return m_ob->AddRef();
+}
+
+/* eof */
diff --git a/source/gameengine/Ketsji/KX_ParentActuator.h b/source/gameengine/Ketsji/KX_ParentActuator.h
new file mode 100644
index 00000000000..e2b30ba2d0f
--- /dev/null
+++ b/source/gameengine/Ketsji/KX_ParentActuator.h
@@ -0,0 +1,89 @@
+/**
+ * Set or remove an objects parent
+ *
+ *
+ * $Id: KX_ParentActuator.h 3271 2004-10-16 11:41:50Z kester $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __KX_PARENTACTUATOR
+#define __KX_PARENTACTUATOR
+
+#include "SCA_IActuator.h"
+#include "SCA_LogicManager.h"
+
+class KX_ParentActuator : public SCA_IActuator
+{
+ Py_Header;
+
+ /** Mode */
+ int m_mode;
+
+ /** Object to set as parent */
+ SCA_IObject *m_ob;
+
+
+
+ public:
+ enum KX_PARENTACT_MODE
+ {
+ KX_PARENT_NODEF = 0,
+ KX_PARENT_SET,
+ KX_PARENT_REMOVE,
+
+ };
+
+ KX_ParentActuator(class SCA_IObject* gameobj,
+ int mode,
+ SCA_IObject *ob,
+ PyTypeObject* T=&Type);
+ virtual ~KX_ParentActuator();
+ virtual bool Update();
+
+ virtual CValue* GetReplica();
+ virtual void ProcessReplica();
+ virtual void Relink(GEN_Map<GEN_HashedPtr, void*> *obj_map);
+ virtual bool UnlinkObject(SCA_IObject* clientobj);
+
+ /* --------------------------------------------------------------------- */
+ /* Python interface ---------------------------------------------------- */
+ /* --------------------------------------------------------------------- */
+
+ virtual PyObject* _getattr(const STR_String& attr);
+
+ /* 1. setObject */
+ KX_PYMETHOD_DOC_O(KX_ParentActuator,SetObject);
+ /* 2. getObject */
+ KX_PYMETHOD_DOC_VARARGS(KX_ParentActuator,GetObject);
+
+}; /* end of class KX_ParentActuator : public SCA_PropertyActuator */
+
+#endif
+
diff --git a/source/gameengine/Ketsji/KX_PhysicsObjectWrapper.cpp b/source/gameengine/Ketsji/KX_PhysicsObjectWrapper.cpp
index 27cfaefc076..da4f05ced7c 100644
--- a/source/gameengine/Ketsji/KX_PhysicsObjectWrapper.cpp
+++ b/source/gameengine/Ketsji/KX_PhysicsObjectWrapper.cpp
@@ -27,6 +27,8 @@
* ***** END GPL LICENSE BLOCK *****
*/
#include <Python.h>
+#include "PyObjectPlus.h"
+
#include "KX_PhysicsObjectWrapper.h"
#include "PHY_IPhysicsEnvironment.h"
#include "PHY_IPhysicsController.h"
@@ -58,7 +60,10 @@ PyObject* KX_PhysicsObjectWrapper::PySetPosition(PyObject* self,
{
m_ctrl->setPosition(x,y,z);
}
- Py_INCREF(Py_None); return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
@@ -72,7 +77,10 @@ PyObject* KX_PhysicsObjectWrapper::PySetLinearVelocity(PyObject* self,
{
m_ctrl->SetLinearVelocity(x,y,z,local != 0);
}
- Py_INCREF(Py_None); return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
PyObject* KX_PhysicsObjectWrapper::PySetAngularVelocity(PyObject* self,
@@ -85,7 +93,10 @@ PyObject* KX_PhysicsObjectWrapper::PySetAngularVelocity(PyObject* self,
{
m_ctrl->SetAngularVelocity(x,y,z,local != 0);
}
- Py_INCREF(Py_None); return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
PyObject* KX_PhysicsObjectWrapper::PySetActive(PyObject* self,
@@ -97,7 +108,10 @@ PyObject* KX_PhysicsObjectWrapper::PySetActive(PyObject* self,
{
m_ctrl->SetActive(active!=0);
}
- Py_INCREF(Py_None); return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
diff --git a/source/gameengine/Ketsji/KX_PolyProxy.cpp b/source/gameengine/Ketsji/KX_PolyProxy.cpp
new file mode 100644
index 00000000000..c6f6bc2db01
--- /dev/null
+++ b/source/gameengine/Ketsji/KX_PolyProxy.cpp
@@ -0,0 +1,265 @@
+/**
+ * $Id$
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include "KX_PolyProxy.h"
+#include "KX_MeshProxy.h"
+#include "RAS_MeshObject.h"
+#include "KX_BlenderMaterial.h"
+#include "KX_PolygonMaterial.h"
+
+#include "KX_PyMath.h"
+
+PyTypeObject KX_PolyProxy::Type = {
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0,
+ "KX_PolyProxy",
+ sizeof(KX_PolyProxy),
+ 0,
+ PyDestructor,
+ 0,
+ __getattr,
+ __setattr,
+ 0, //&MyPyCompare,
+ __repr,
+ 0, //&cvalue_as_number,
+ 0,
+ 0,
+ 0,
+ 0
+};
+
+PyParentObject KX_PolyProxy::Parents[] = {
+ &KX_PolyProxy::Type,
+ &SCA_IObject::Type,
+ &CValue::Type,
+ NULL
+};
+
+PyMethodDef KX_PolyProxy::Methods[] = {
+ KX_PYMETHODTABLE_NOARG(KX_PolyProxy,getMaterialIndex),
+ KX_PYMETHODTABLE_NOARG(KX_PolyProxy,getNumVertex),
+ KX_PYMETHODTABLE_NOARG(KX_PolyProxy,isVisible),
+ KX_PYMETHODTABLE_NOARG(KX_PolyProxy,isCollider),
+ KX_PYMETHODTABLE_NOARG(KX_PolyProxy,getMaterialName),
+ KX_PYMETHODTABLE_NOARG(KX_PolyProxy,getTextureName),
+ KX_PYMETHODTABLE(KX_PolyProxy,getVertexIndex),
+ KX_PYMETHODTABLE_NOARG(KX_PolyProxy,getMesh),
+ KX_PYMETHODTABLE_NOARG(KX_PolyProxy,getMaterial),
+ {NULL,NULL} //Sentinel
+};
+
+PyObject*
+KX_PolyProxy::_getattr(const STR_String& attr)
+{
+ if (attr == "matname")
+ {
+ return PyString_FromString(m_polygon->GetMaterial()->GetPolyMaterial()->GetMaterialName());
+ }
+ if (attr == "texture")
+ {
+ return PyString_FromString(m_polygon->GetMaterial()->GetPolyMaterial()->GetTextureName());
+ }
+ if (attr == "material")
+ {
+ RAS_IPolyMaterial *polymat = m_polygon->GetMaterial()->GetPolyMaterial();
+ if(polymat->GetFlag() & RAS_BLENDERMAT)
+ {
+ KX_BlenderMaterial* mat = static_cast<KX_BlenderMaterial*>(polymat);
+ Py_INCREF(mat);
+ return mat;
+ }
+ else
+ {
+ KX_PolygonMaterial* mat = static_cast<KX_PolygonMaterial*>(polymat);
+ Py_INCREF(mat);
+ return mat;
+ }
+ }
+ if (attr == "matid")
+ {
+ // we'll have to scan through the material bucket of the mes and compare with
+ // the one of the polygon
+ RAS_MaterialBucket* polyBucket = m_polygon->GetMaterial();
+ unsigned int matid;
+ for (matid=0; matid<m_mesh->NumMaterials(); matid++)
+ {
+ RAS_MeshMaterial* meshMat = m_mesh->GetMeshMaterial(matid);
+ if (meshMat->m_bucket == polyBucket)
+ // found it
+ break;
+ }
+ return PyInt_FromLong(matid);
+ }
+ if (attr == "v1")
+ {
+ return PyInt_FromLong(m_polygon->GetVertexOffset(0));
+ }
+ if (attr == "v2")
+ {
+ return PyInt_FromLong(m_polygon->GetVertexOffset(1));
+ }
+ if (attr == "v3")
+ {
+ return PyInt_FromLong(m_polygon->GetVertexOffset(2));
+ }
+ if (attr == "v4")
+ {
+ return PyInt_FromLong(((m_polygon->VertexCount()>3)?m_polygon->GetVertexOffset(3):0));
+ }
+ if (attr == "visible")
+ {
+ return PyInt_FromLong(m_polygon->IsVisible());
+ }
+ if (attr == "collide")
+ {
+ return PyInt_FromLong(m_polygon->IsCollider());
+ }
+ _getattr_up(SCA_IObject);
+}
+
+KX_PolyProxy::KX_PolyProxy(const RAS_MeshObject*mesh, RAS_Polygon* polygon)
+: m_mesh((RAS_MeshObject*)mesh),
+ m_polygon(polygon)
+{
+}
+
+KX_PolyProxy::~KX_PolyProxy()
+{
+}
+
+
+// stuff for cvalue related things
+CValue* KX_PolyProxy::Calc(VALUE_OPERATOR, CValue *) { return NULL;}
+CValue* KX_PolyProxy::CalcFinal(VALUE_DATA_TYPE, VALUE_OPERATOR, CValue *) { return NULL;}
+STR_String sPolyName="polygone";
+const STR_String & KX_PolyProxy::GetText() {return sPolyName;};
+float KX_PolyProxy::GetNumber() { return -1;}
+STR_String KX_PolyProxy::GetName() { return sPolyName;}
+void KX_PolyProxy::SetName(STR_String) { };
+CValue* KX_PolyProxy::GetReplica() { return NULL;}
+void KX_PolyProxy::ReplicaSetName(STR_String) {};
+
+
+// stuff for python integration
+
+KX_PYMETHODDEF_DOC_NOARG(KX_PolyProxy, getMaterialIndex,
+"getMaterialIndex() : return the material index of the polygon in the mesh\n")
+{
+ RAS_MaterialBucket* polyBucket = m_polygon->GetMaterial();
+ unsigned int matid;
+ for (matid=0; matid<m_mesh->NumMaterials(); matid++)
+ {
+ RAS_MeshMaterial* meshMat = m_mesh->GetMeshMaterial(matid);
+ if (meshMat->m_bucket == polyBucket)
+ // found it
+ break;
+ }
+ return PyInt_FromLong(matid);
+}
+
+KX_PYMETHODDEF_DOC_NOARG(KX_PolyProxy, getNumVertex,
+"getNumVertex() : returns the number of vertex of the polygon, 3 or 4\n")
+{
+ return PyInt_FromLong(m_polygon->VertexCount());
+}
+
+KX_PYMETHODDEF_DOC_NOARG(KX_PolyProxy, isVisible,
+"isVisible() : returns whether the polygon is visible or not\n")
+{
+ return PyInt_FromLong(m_polygon->IsVisible());
+}
+
+KX_PYMETHODDEF_DOC_NOARG(KX_PolyProxy, isCollider,
+"isCollider() : returns whether the polygon is receives collision or not\n")
+{
+ return PyInt_FromLong(m_polygon->IsCollider());
+}
+
+KX_PYMETHODDEF_DOC_NOARG(KX_PolyProxy, getMaterialName,
+"getMaterialName() : returns the polygon material name, \"NoMaterial\" if no material\n")
+{
+ return PyString_FromString(m_polygon->GetMaterial()->GetPolyMaterial()->GetMaterialName());
+}
+
+KX_PYMETHODDEF_DOC_NOARG(KX_PolyProxy, getTextureName,
+"getTexturelName() : returns the polygon texture name, \"NULL\" if no texture\n")
+{
+ return PyString_FromString(m_polygon->GetMaterial()->GetPolyMaterial()->GetTextureName());
+}
+
+KX_PYMETHODDEF_DOC(KX_PolyProxy, getVertexIndex,
+"getVertexIndex(vertex) : returns the mesh vertex index of a polygon vertex\n"
+"vertex: index of the vertex in the polygon: 0->3\n"
+"return value can be used to retrieve the vertex details through mesh proxy\n"
+"Note: getVertexIndex(3) on a triangle polygon returns 0\n")
+{
+ int index;
+ if (!PyArg_ParseTuple(args,"i",&index))
+ {
+ return NULL;
+ }
+ if (index < 0 || index > 3)
+ {
+ PyErr_SetString(PyExc_AttributeError, "Valid range for index is 0-3");
+ return NULL;
+ }
+ if (index < m_polygon->VertexCount())
+ {
+ return PyInt_FromLong(m_polygon->GetVertexOffset(index));
+ }
+ return PyInt_FromLong(0);
+}
+
+KX_PYMETHODDEF_DOC_NOARG(KX_PolyProxy, getMesh,
+"getMesh() : returns a mesh proxy\n")
+{
+ KX_MeshProxy* meshproxy = new KX_MeshProxy((RAS_MeshObject*)m_mesh);
+ return meshproxy;
+}
+
+KX_PYMETHODDEF_DOC_NOARG(KX_PolyProxy, getMaterial,
+"getMaterial() : returns a material\n")
+{
+ RAS_IPolyMaterial *polymat = m_polygon->GetMaterial()->GetPolyMaterial();
+ if(polymat->GetFlag() & RAS_BLENDERMAT)
+ {
+ KX_BlenderMaterial* mat = static_cast<KX_BlenderMaterial*>(polymat);
+ Py_INCREF(mat);
+ return mat;
+ }
+ else
+ {
+ KX_PolygonMaterial* mat = static_cast<KX_PolygonMaterial*>(polymat);
+ Py_INCREF(mat);
+ return mat;
+ }
+}
diff --git a/source/gameengine/Ketsji/KX_PolyProxy.h b/source/gameengine/Ketsji/KX_PolyProxy.h
new file mode 100644
index 00000000000..506e2c2a656
--- /dev/null
+++ b/source/gameengine/Ketsji/KX_PolyProxy.h
@@ -0,0 +1,71 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef __KX_POLYROXY
+#define __KX_POLYPROXY
+
+#include "SCA_IObject.h"
+
+class KX_PolyProxy : public SCA_IObject
+{
+ Py_Header;
+protected:
+ class RAS_Polygon* m_polygon;
+ class RAS_MeshObject* m_mesh;
+public:
+ KX_PolyProxy(const class RAS_MeshObject*mesh, class RAS_Polygon* polygon);
+ virtual ~KX_PolyProxy();
+
+ // stuff for cvalue related things
+ CValue* Calc(VALUE_OPERATOR op, CValue *val) ;
+ CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val);
+ const STR_String & GetText();
+ float GetNumber();
+ STR_String GetName();
+ void SetName(STR_String name); // Set the name of the value
+ void ReplicaSetName(STR_String name);
+ CValue* GetReplica();
+
+
+// stuff for python integration
+ virtual PyObject* _getattr(const STR_String& attr);
+
+ KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,getMaterialIndex)
+ KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,getNumVertex)
+ KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,isVisible)
+ KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,isCollider)
+ KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,getMaterialName)
+ KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,getTextureName)
+ KX_PYMETHOD_DOC(KX_PolyProxy,getVertexIndex)
+ KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,getMesh)
+ KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,getMaterial)
+
+};
+
+#endif //__KX_POLYPROXY
+
diff --git a/source/gameengine/Ketsji/KX_PolygonMaterial.cpp b/source/gameengine/Ketsji/KX_PolygonMaterial.cpp
index 70333b33d2c..c9180bf3a80 100644
--- a/source/gameengine/Ketsji/KX_PolygonMaterial.cpp
+++ b/source/gameengine/Ketsji/KX_PolygonMaterial.cpp
@@ -35,10 +35,6 @@
#include "BKE_global.h"
#include "BKE_image.h"
-extern "C" {
-//XXX #include "BDR_drawmesh.h"
-}
-
#include "DNA_material_types.h"
#include "DNA_texture_types.h"
#include "DNA_image_types.h"
@@ -46,6 +42,8 @@ extern "C" {
#include "IMB_imbuf_types.h"
+#include "GPU_draw.h"
+
#include "MEM_guardedalloc.h"
#include "RAS_LightObject.h"
@@ -59,11 +57,10 @@ KX_PolygonMaterial::KX_PolygonMaterial(const STR_String &texname,
int tilexrep,
int tileyrep,
int mode,
- bool transparant,
+ int transp,
+ bool alpha,
bool zsort,
int lightlayer,
- bool bIsTriangle,
- void* clientobject,
struct MTFace* tface,
unsigned int* mcol,
PyTypeObject *T)
@@ -74,11 +71,10 @@ KX_PolygonMaterial::KX_PolygonMaterial(const STR_String &texname,
tilexrep,
tileyrep,
mode,
- transparant,
+ transp,
+ alpha,
zsort,
- lightlayer,
- bIsTriangle,
- clientobject),
+ lightlayer),
m_tface(tface),
m_mcol(mcol),
m_material(material),
@@ -138,38 +134,29 @@ void KX_PolygonMaterial::DefaultActivate(RAS_IRasterizer* rasty, TCachingInfo& c
if (GetCachingInfo() != cachingInfo)
{
if (!cachingInfo)
- {
- //XXX set_tpage(NULL);
- }
+ GPU_set_tpage(NULL);
+
cachingInfo = GetCachingInfo();
if ((m_drawingmode & 4)&& (rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED))
{
- update_realtime_texture((struct MTFace*) m_tface, rasty->GetTime());
- //XXX set_tpage(m_tface);
- rasty->EnableTextures(true);
+ Image *ima = (Image*)m_tface->tpage;
+ GPU_update_image_time(ima, rasty->GetTime());
+ GPU_set_tpage(m_tface);
}
else
- {
- //XXX set_tpage(NULL);
- rasty->EnableTextures(false);
- }
+ GPU_set_tpage(NULL);
if(m_drawingmode & RAS_IRasterizer::KX_TWOSIDE)
- {
rasty->SetCullFace(false);
- }
else
- {
rasty->SetCullFace(true);
- }
- if (m_drawingmode & RAS_IRasterizer::KX_LINES) {
+ if ((m_drawingmode & RAS_IRasterizer::KX_LINES) ||
+ (rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME))
rasty->SetLines(true);
- }
- else {
+ else
rasty->SetLines(false);
- }
}
rasty->SetSpecularity(m_specular[0],m_specular[1],m_specular[2],m_specularity);
@@ -245,13 +232,14 @@ PyObject* KX_PolygonMaterial::_getattr(const STR_String& attr)
if (attr == "drawingmode")
return PyInt_FromLong(m_drawingmode);
if (attr == "transparent")
- return PyInt_FromLong(m_transparant);
+ return PyInt_FromLong(m_alpha);
if (attr == "zsort")
return PyInt_FromLong(m_zsort);
if (attr == "lightlayer")
return PyInt_FromLong(m_lightlayer);
if (attr == "triangle")
- return PyInt_FromLong(m_bIsTriangle);
+ // deprecated, triangle/quads shouldn't have been a material property
+ return 0;
if (attr == "diffuse")
return PyObjectFrom(m_diffuse);
@@ -312,7 +300,7 @@ int KX_PolygonMaterial::_setattr(const STR_String &attr, PyObject *pyvalue)
if (attr == "transparent")
{
- m_transparant = value;
+ m_alpha = value;
return 0;
}
@@ -331,7 +319,7 @@ int KX_PolygonMaterial::_setattr(const STR_String &attr, PyObject *pyvalue)
// This probably won't work...
if (attr == "triangle")
{
- m_bIsTriangle = value;
+ // deprecated, triangle/quads shouldn't have been a material property
return 0;
}
}
@@ -384,7 +372,9 @@ KX_PYMETHODDEF_DOC(KX_PolygonMaterial, updateTexture, "updateTexture(tface, rast
{
MTFace *tface = (MTFace*) PyCObject_AsVoidPtr(pytface);
RAS_IRasterizer *rasty = (RAS_IRasterizer*) PyCObject_AsVoidPtr(pyrasty);
- update_realtime_texture(tface, rasty->GetTime());
+ Image *ima = (Image*)tface->tpage;
+ GPU_update_image_time(ima, rasty->GetTime());
+
Py_Return;
}
@@ -397,7 +387,7 @@ KX_PYMETHODDEF_DOC(KX_PolygonMaterial, setTexture, "setTexture(tface)")
if (PyArg_ParseTuple(args, "O!", &PyCObject_Type, &pytface))
{
MTFace *tface = (MTFace*) PyCObject_AsVoidPtr(pytface);
- //XXX set_tpage(tface);
+ GPU_set_tpage(tface);
Py_Return;
}
diff --git a/source/gameengine/Ketsji/KX_PolygonMaterial.h b/source/gameengine/Ketsji/KX_PolygonMaterial.h
index 19015494e06..fe116f757db 100644
--- a/source/gameengine/Ketsji/KX_PolygonMaterial.h
+++ b/source/gameengine/Ketsji/KX_PolygonMaterial.h
@@ -64,11 +64,10 @@ public:
int tilexrep,
int tileyrep,
int mode,
- bool transparant,
+ int transp,
+ bool alpha,
bool zsort,
int lightlayer,
- bool bIsTriangle,
- void* clientobject,
struct MTFace* tface,
unsigned int* mcol,
PyTypeObject *T = &Type);
diff --git a/source/gameengine/Ketsji/KX_PyConstraintBinding.cpp b/source/gameengine/Ketsji/KX_PyConstraintBinding.cpp
index 172882ff18d..fb37eded450 100644
--- a/source/gameengine/Ketsji/KX_PyConstraintBinding.cpp
+++ b/source/gameengine/Ketsji/KX_PyConstraintBinding.cpp
@@ -34,6 +34,8 @@
#include "PHY_IPhysicsController.h"
#include "PHY_IVehicle.h"
+#include "PyObjectPlus.h"
+
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
@@ -82,13 +84,16 @@ static PyObject* gPySetGravity(PyObject* self,
PyObject* kwds)
{
float x,y,z;
- int len = PyTuple_Size(args);
- if ((len == 3) && PyArg_ParseTuple(args,"fff",&x,&y,&z))
+ if (PyArg_ParseTuple(args,"fff",&x,&y,&z))
{
if (PHY_GetActiveEnvironment())
PHY_GetActiveEnvironment()->setGravity(x,y,z);
}
- Py_INCREF(Py_None); return Py_None;
+ else {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
}
static PyObject* gPySetDebugMode(PyObject* self,
@@ -105,7 +110,11 @@ static PyObject* gPySetDebugMode(PyObject* self,
}
}
- Py_INCREF(Py_None); return Py_None;
+ else {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
}
@@ -122,7 +131,10 @@ static PyObject* gPySetNumTimeSubSteps(PyObject* self,
PHY_GetActiveEnvironment()->setNumTimeSubSteps(substep);
}
}
- Py_INCREF(Py_None); return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
@@ -138,7 +150,10 @@ static PyObject* gPySetNumIterations(PyObject* self,
PHY_GetActiveEnvironment()->setNumIterations(iter);
}
}
- Py_INCREF(Py_None); return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
@@ -155,7 +170,10 @@ static PyObject* gPySetDeactivationTime(PyObject* self,
PHY_GetActiveEnvironment()->setDeactivationTime(deactive_time);
}
}
- Py_INCREF(Py_None); return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
@@ -171,7 +189,10 @@ static PyObject* gPySetDeactivationLinearTreshold(PyObject* self,
PHY_GetActiveEnvironment()->setDeactivationLinearTreshold( linearDeactivationTreshold);
}
}
- Py_INCREF(Py_None); return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
@@ -187,7 +208,10 @@ static PyObject* gPySetDeactivationAngularTreshold(PyObject* self,
PHY_GetActiveEnvironment()->setDeactivationAngularTreshold( angularDeactivationTreshold);
}
}
- Py_INCREF(Py_None); return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
static PyObject* gPySetContactBreakingTreshold(PyObject* self,
@@ -202,7 +226,10 @@ static PyObject* gPySetContactBreakingTreshold(PyObject* self,
PHY_GetActiveEnvironment()->setContactBreakingTreshold( contactBreakingTreshold);
}
}
- Py_INCREF(Py_None); return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
@@ -218,7 +245,10 @@ static PyObject* gPySetCcdMode(PyObject* self,
PHY_GetActiveEnvironment()->setCcdMode( ccdMode);
}
}
- Py_INCREF(Py_None); return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
static PyObject* gPySetSorConstant(PyObject* self,
@@ -233,7 +263,10 @@ static PyObject* gPySetSorConstant(PyObject* self,
PHY_GetActiveEnvironment()->setSolverSorConstant( sor);
}
}
- Py_INCREF(Py_None); return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
static PyObject* gPySetSolverTau(PyObject* self,
@@ -248,7 +281,10 @@ static PyObject* gPySetSolverTau(PyObject* self,
PHY_GetActiveEnvironment()->setSolverTau( tau);
}
}
- Py_INCREF(Py_None); return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
@@ -264,7 +300,10 @@ static PyObject* gPySetSolverDamping(PyObject* self,
PHY_GetActiveEnvironment()->setSolverDamping( damping);
}
}
- Py_INCREF(Py_None); return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
static PyObject* gPySetLinearAirDamping(PyObject* self,
@@ -279,7 +318,10 @@ static PyObject* gPySetLinearAirDamping(PyObject* self,
PHY_GetActiveEnvironment()->setLinearAirDamping( damping);
}
}
- Py_INCREF(Py_None); return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
@@ -295,7 +337,10 @@ static PyObject* gPySetUseEpa(PyObject* self,
PHY_GetActiveEnvironment()->setUseEpa(epa);
}
}
- Py_INCREF(Py_None); return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
static PyObject* gPySetSolverType(PyObject* self,
PyObject* args,
@@ -309,7 +354,10 @@ static PyObject* gPySetSolverType(PyObject* self,
PHY_GetActiveEnvironment()->setSolverType(solverType);
}
}
- Py_INCREF(Py_None); return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
@@ -338,8 +386,11 @@ static PyObject* gPyGetVehicleConstraint(PyObject* self,
}
}
+ else {
+ return NULL;
+ }
- Py_INCREF(Py_None); return Py_None;
+ Py_RETURN_NONE;
}
@@ -384,7 +435,7 @@ static PyObject* gPyCreateConstraint(PyObject* self,
PHY_IPhysicsController* physctrl2 = (PHY_IPhysicsController*) physicsid2;
if (physctrl) //TODO:check for existance of this pointer!
{
- int constraintid = PHY_GetActiveEnvironment()->createConstraint(physctrl,physctrl2,(enum PHY_ConstraintType)constrainttype,pivotX,pivotY,pivotZ,axisX,axisY,axisZ);
+ int constraintid = PHY_GetActiveEnvironment()->createConstraint(physctrl,physctrl2,(enum PHY_ConstraintType)constrainttype,pivotX,pivotY,pivotZ,axisX,axisY,axisZ,0);
KX_ConstraintWrapper* wrap = new KX_ConstraintWrapper((enum PHY_ConstraintType)constrainttype,constraintid,PHY_GetActiveEnvironment());
@@ -395,8 +446,11 @@ static PyObject* gPyCreateConstraint(PyObject* self,
}
}
+ else {
+ return NULL;
+ }
- Py_INCREF(Py_None); return Py_None;
+ Py_RETURN_NONE;
}
@@ -421,6 +475,9 @@ static PyObject* gPyGetAppliedImpulse(PyObject* self,
appliedImpulse = PHY_GetActiveEnvironment()->getAppliedImpulse(constraintid);
}
}
+ else {
+ return NULL;
+ }
return PyFloat_FromDouble(appliedImpulse);
}
@@ -443,60 +500,64 @@ static PyObject* gPyRemoveConstraint(PyObject* self,
PHY_GetActiveEnvironment()->removeConstraint(constraintid);
}
}
- Py_INCREF(Py_None); return Py_None;
+ else {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
}
static struct PyMethodDef physicsconstraints_methods[] = {
{"setGravity",(PyCFunction) gPySetGravity,
- METH_VARARGS, gPySetGravity__doc__},
+ METH_VARARGS, (PY_METHODCHAR)gPySetGravity__doc__},
{"setDebugMode",(PyCFunction) gPySetDebugMode,
- METH_VARARGS, gPySetDebugMode__doc__},
+ METH_VARARGS, (PY_METHODCHAR)gPySetDebugMode__doc__},
/// settings that influence quality of the rigidbody dynamics
{"setNumIterations",(PyCFunction) gPySetNumIterations,
- METH_VARARGS, gPySetNumIterations__doc__},
+ METH_VARARGS, (PY_METHODCHAR)gPySetNumIterations__doc__},
{"setNumTimeSubSteps",(PyCFunction) gPySetNumTimeSubSteps,
- METH_VARARGS, gPySetNumTimeSubSteps__doc__},
+ METH_VARARGS, (PY_METHODCHAR)gPySetNumTimeSubSteps__doc__},
{"setDeactivationTime",(PyCFunction) gPySetDeactivationTime,
- METH_VARARGS, gPySetDeactivationTime__doc__},
+ METH_VARARGS, (PY_METHODCHAR)gPySetDeactivationTime__doc__},
{"setDeactivationLinearTreshold",(PyCFunction) gPySetDeactivationLinearTreshold,
- METH_VARARGS, gPySetDeactivationLinearTreshold__doc__},
+ METH_VARARGS, (PY_METHODCHAR)gPySetDeactivationLinearTreshold__doc__},
{"setDeactivationAngularTreshold",(PyCFunction) gPySetDeactivationAngularTreshold,
- METH_VARARGS, gPySetDeactivationAngularTreshold__doc__},
+ METH_VARARGS, (PY_METHODCHAR)gPySetDeactivationAngularTreshold__doc__},
{"setContactBreakingTreshold",(PyCFunction) gPySetContactBreakingTreshold,
- METH_VARARGS, gPySetContactBreakingTreshold__doc__},
+ METH_VARARGS, (PY_METHODCHAR)gPySetContactBreakingTreshold__doc__},
{"setCcdMode",(PyCFunction) gPySetCcdMode,
- METH_VARARGS, gPySetCcdMode__doc__},
+ METH_VARARGS, (PY_METHODCHAR)gPySetCcdMode__doc__},
{"setSorConstant",(PyCFunction) gPySetSorConstant,
- METH_VARARGS, gPySetSorConstant__doc__},
+ METH_VARARGS, (PY_METHODCHAR)gPySetSorConstant__doc__},
{"setSolverTau",(PyCFunction) gPySetSolverTau,
- METH_VARARGS, gPySetSolverTau__doc__},
+ METH_VARARGS, (PY_METHODCHAR)gPySetSolverTau__doc__},
{"setSolverDamping",(PyCFunction) gPySetSolverDamping,
- METH_VARARGS, gPySetSolverDamping__doc__},
+ METH_VARARGS, (PY_METHODCHAR)gPySetSolverDamping__doc__},
{"setLinearAirDamping",(PyCFunction) gPySetLinearAirDamping,
- METH_VARARGS, gPySetLinearAirDamping__doc__},
+ METH_VARARGS, (PY_METHODCHAR)gPySetLinearAirDamping__doc__},
{"setUseEpa",(PyCFunction) gPySetUseEpa,
- METH_VARARGS, gPySetUseEpa__doc__},
+ METH_VARARGS, (PY_METHODCHAR)gPySetUseEpa__doc__},
{"setSolverType",(PyCFunction) gPySetSolverType,
- METH_VARARGS, gPySetSolverType__doc__},
+ METH_VARARGS, (PY_METHODCHAR)gPySetSolverType__doc__},
{"createConstraint",(PyCFunction) gPyCreateConstraint,
- METH_VARARGS, gPyCreateConstraint__doc__},
+ METH_VARARGS, (PY_METHODCHAR)gPyCreateConstraint__doc__},
{"getVehicleConstraint",(PyCFunction) gPyGetVehicleConstraint,
- METH_VARARGS, gPyGetVehicleConstraint__doc__},
+ METH_VARARGS, (PY_METHODCHAR)gPyGetVehicleConstraint__doc__},
{"removeConstraint",(PyCFunction) gPyRemoveConstraint,
- METH_VARARGS, gPyRemoveConstraint__doc__},
+ METH_VARARGS, (PY_METHODCHAR)gPyRemoveConstraint__doc__},
{"getAppliedImpulse",(PyCFunction) gPyGetAppliedImpulse,
- METH_VARARGS, gPyGetAppliedImpulse__doc__},
+ METH_VARARGS, (PY_METHODCHAR)gPyGetAppliedImpulse__doc__},
//sentinel
diff --git a/source/gameengine/Ketsji/KX_PyMath.h b/source/gameengine/Ketsji/KX_PyMath.h
index e1715c9275f..4e383e9b3d4 100644
--- a/source/gameengine/Ketsji/KX_PyMath.h
+++ b/source/gameengine/Ketsji/KX_PyMath.h
@@ -84,7 +84,10 @@ bool PyMatTo(PyObject* pymat, T& mat)
}
} else
noerror = false;
-
+
+ if (noerror==false)
+ PyErr_SetString(PyExc_TypeError, "could not be converted to a matrix (sequence of sequences)");
+
return noerror;
}
@@ -97,9 +100,13 @@ bool PyVecTo(PyObject* pyval, T& vec)
if (PySequence_Check(pyval))
{
unsigned int numitems = PySequence_Size(pyval);
- if (numitems != Size(vec))
+ if (numitems != Size(vec)) {
+ char err[128];
+ sprintf(err, "error setting vector, %d args, should be %d", numitems, Size(vec));
+ PyErr_SetString(PyExc_AttributeError, err);
return false;
-
+ }
+
for (unsigned int x = 0; x < numitems; x++)
{
PyObject *item = PySequence_GetItem(pyval, x); /* new ref */
@@ -107,7 +114,17 @@ bool PyVecTo(PyObject* pyval, T& vec)
Py_DECREF(item);
}
+ if (PyErr_Occurred()) {
+ PyErr_SetString(PyExc_AttributeError, "one or more of the items in the sequence was not a float");
+ return false;
+ }
+
return true;
+ } else
+ {
+ char err[128];
+ sprintf(err, "not a sequence type, expected a sequence of numbers size %d", Size(vec));
+ PyErr_SetString(PyExc_AttributeError, err);
}
return false;
diff --git a/source/gameengine/Ketsji/KX_PythonInit.cpp b/source/gameengine/Ketsji/KX_PythonInit.cpp
index 681548fcc06..7ac817488fe 100644
--- a/source/gameengine/Ketsji/KX_PythonInit.cpp
+++ b/source/gameengine/Ketsji/KX_PythonInit.cpp
@@ -28,24 +28,14 @@
* Initialize Python thingies.
*/
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
+#include "GL/glew.h"
-#ifdef WIN32
-#include <windows.h>
-#endif // WIN32
-#ifdef __APPLE__
-#define GL_GLEXT_LEGACY 1
-#include <OpenGL/gl.h>
-#include <OpenGL/glu.h>
-#else
-#include <GL/gl.h>
-#if defined(__sun__) && !defined(__sparc__)
-#include <mesa/glu.h>
+// directory header for py function getBlendFileList
+#include <stdlib.h>
+#ifndef WIN32
+ #include <dirent.h>
#else
-#include <GL/glu.h>
-#endif
+ #include "BLI_winstuff.h"
#endif
#ifdef WIN32
@@ -67,17 +57,28 @@
#include "BL_ActionActuator.h"
#include "RAS_IRasterizer.h"
#include "RAS_ICanvas.h"
+#include "RAS_BucketManager.h"
#include "MT_Vector3.h"
#include "MT_Point3.h"
#include "ListValue.h"
#include "KX_Scene.h"
#include "SND_DeviceManager.h"
-#include "RAS_OpenGLRasterizer/RAS_GLExtensionManager.h"
#include "BL_Shader.h"
#include "KX_PyMath.h"
+#include "PyObjectPlus.h"
+
+//XXX
+#if 0
+extern "C" {
+ #include "Mathutils.h" // Blender.Mathutils module copied here so the blenderlayer can use.
+}
+#endif
+
+#include "marshal.h" /* python header for loading/saving dicts */
+
#include "PHY_IPhysicsEnvironment.h"
// FIXME: Enable for access to blender python modules. This is disabled because
// python has dependencies on a lot of other modules and is a pain to link.
@@ -86,13 +87,20 @@
//#include "BPY_extern.h"
#endif
+#include "BKE_utildefines.h"
+#include "BKE_global.h"
+#include "BLI_blenlib.h"
+#include "GPU_material.h"
+
static void setSandbox(TPythonSecurityLevel level);
// 'local' copy of canvas ptr, for window height/width python scripts
static RAS_ICanvas* gp_Canvas = NULL;
static KX_Scene* gp_KetsjiScene = NULL;
+static KX_KetsjiEngine* gp_KetsjiEngine = NULL;
static RAS_IRasterizer* gp_Rasterizer = NULL;
+static char gp_GamePythonPath[FILE_MAXDIR + FILE_MAXFILE] = "";
void KX_RasterizerDrawDebugLine(const MT_Vector3& from,const MT_Vector3& to,const MT_Vector3& color)
{
@@ -115,36 +123,51 @@ void KX_RasterizerDrawDebugLine(const MT_Vector3& from,const MT_Vector3& to,cons
static PyObject* ErrorObject;
STR_String gPyGetRandomFloat_doc="getRandomFloat returns a random floating point value in the range [0..1)";
-static PyObject* gPyGetRandomFloat(PyObject*,
- PyObject*,
- PyObject*)
+static PyObject* gPyGetRandomFloat(PyObject*)
{
return PyFloat_FromDouble(MT_random());
}
-static PyObject* gPySetGravity(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPySetGravity(PyObject*, PyObject* args)
{
MT_Vector3 vec = MT_Vector3(0., 0., 0.);
- if (PyVecArgTo(args, vec))
- {
- if (gp_KetsjiScene)
- gp_KetsjiScene->SetGravity(vec);
-
- Py_Return;
- }
+ if (!PyVecArgTo(args, vec))
+ return NULL;
+
+ if (gp_KetsjiScene)
+ gp_KetsjiScene->SetGravity(vec);
- return NULL;
+ Py_RETURN_NONE;
+}
+
+static char gPyExpandPath_doc[] =
+"(path) - Converts a blender internal path into a proper file system path.\n\
+path - the string path to convert.\n\n\
+Use / as directory separator in path\n\
+You can use '//' at the start of the string to define a relative path;\n\
+Blender replaces that string by the directory of the startup .blend or runtime\n\
+file to make a full path name (doesn't change during the game, even if you load\n\
+other .blend).\n\
+The function also converts the directory separator to the local file system format.";
+
+static PyObject* gPyExpandPath(PyObject*, PyObject* args)
+{
+ char expanded[FILE_MAXDIR + FILE_MAXFILE];
+ char* filename;
+
+ if (!PyArg_ParseTuple(args,"s",&filename))
+ return NULL;
+
+ BLI_strncpy(expanded, filename, FILE_MAXDIR + FILE_MAXFILE);
+ BLI_convertstringcode(expanded, gp_GamePythonPath);
+ return PyString_FromString(expanded);
}
static bool usedsp = false;
// this gets a pointer to an array filled with floats
-static PyObject* gPyGetSpectrum(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPyGetSpectrum(PyObject*)
{
SND_IAudioDevice* audiodevice = SND_DeviceManager::Instance();
@@ -165,111 +188,145 @@ static PyObject* gPyGetSpectrum(PyObject*,
PyList_SetItem(resultlist, index, PyFloat_FromDouble(spectrum[index]));
}
}
+ else {
+ for (int index = 0; index < 512; index++)
+ {
+ PyList_SetItem(resultlist, index, PyFloat_FromDouble(0.0));
+ }
+ }
return resultlist;
}
-static PyObject* gPyStartDSP(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPyStartDSP(PyObject*, PyObject* args)
{
SND_IAudioDevice* audiodevice = SND_DeviceManager::Instance();
- if (audiodevice)
- {
- if (!usedsp)
- {
- audiodevice->StartUsingDSP();
- usedsp = true;
- Py_Return;
- }
+ if (!audiodevice) {
+ PyErr_SetString(PyExc_RuntimeError, "no audio device available");
+ return NULL;
}
- return NULL;
+
+ if (!usedsp) {
+ audiodevice->StartUsingDSP();
+ usedsp = true;
+ }
+
+ Py_RETURN_NONE;
}
-static PyObject* gPyStopDSP(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPyStopDSP(PyObject*, PyObject* args)
{
SND_IAudioDevice* audiodevice = SND_DeviceManager::Instance();
- if (audiodevice)
- {
- if (usedsp)
- {
- audiodevice->StopUsingDSP();
- usedsp = false;
- Py_Return;
- }
+ if (!audiodevice) {
+ PyErr_SetString(PyExc_RuntimeError, "no audio device available");
+ return NULL;
}
- return NULL;
+
+ if (usedsp) {
+ audiodevice->StopUsingDSP();
+ usedsp = true;
+ }
+
+ Py_RETURN_NONE;
}
-static PyObject* gPySetLogicTicRate(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPySetLogicTicRate(PyObject*, PyObject* args)
{
float ticrate;
- if (PyArg_ParseTuple(args, "f", &ticrate))
- {
- KX_KetsjiEngine::SetTicRate(ticrate);
- Py_Return;
- }
+ if (!PyArg_ParseTuple(args, "f", &ticrate))
+ return NULL;
- return NULL;
+ KX_KetsjiEngine::SetTicRate(ticrate);
+ Py_RETURN_NONE;
}
-static PyObject* gPyGetLogicTicRate(PyObject*, PyObject*, PyObject*)
+static PyObject* gPyGetLogicTicRate(PyObject*)
{
return PyFloat_FromDouble(KX_KetsjiEngine::GetTicRate());
}
-static PyObject* gPySetPhysicsTicRate(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPySetPhysicsTicRate(PyObject*, PyObject* args)
{
float ticrate;
- if (PyArg_ParseTuple(args, "f", &ticrate))
- {
-
- PHY_GetActiveEnvironment()->setFixedTimeStep(true,ticrate);
- Py_Return;
- }
+ if (!PyArg_ParseTuple(args, "f", &ticrate))
+ return NULL;
- return NULL;
+ PHY_GetActiveEnvironment()->setFixedTimeStep(true,ticrate);
+ Py_RETURN_NONE;
}
-static PyObject* gPySetPhysicsDebug(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPySetPhysicsDebug(PyObject*, PyObject* args)
{
int debugMode;
- if (PyArg_ParseTuple(args, "i", &debugMode))
- {
- PHY_GetActiveEnvironment()->setDebugMode(debugMode);
- Py_Return;
- }
+ if (!PyArg_ParseTuple(args, "i", &debugMode))
+ return NULL;
- return NULL;
+ PHY_GetActiveEnvironment()->setDebugMode(debugMode);
+ Py_RETURN_NONE;
}
-static PyObject* gPyGetPhysicsTicRate(PyObject*, PyObject*, PyObject*)
+static PyObject* gPyGetPhysicsTicRate(PyObject*)
{
return PyFloat_FromDouble(PHY_GetActiveEnvironment()->getFixedTimeStep());
}
+static PyObject* gPyGetAverageFrameRate(PyObject*)
+{
+ return PyFloat_FromDouble(KX_KetsjiEngine::GetAverageFrameRate());
+}
+
+static PyObject* gPyGetBlendFileList(PyObject*, PyObject* args)
+{
+ char cpath[sizeof(gp_GamePythonPath)];
+ char *searchpath = NULL;
+ PyObject* list, *value;
+
+ DIR *dp;
+ struct dirent *dirp;
+
+ if (!PyArg_ParseTuple(args, "|s", &searchpath))
+ return NULL;
+
+ list = PyList_New(0);
+
+ if (searchpath) {
+ BLI_strncpy(cpath, searchpath, FILE_MAXDIR + FILE_MAXFILE);
+ BLI_convertstringcode(cpath, gp_GamePythonPath);
+ } else {
+ /* Get the dir only */
+ BLI_split_dirfile_basic(gp_GamePythonPath, cpath, NULL);
+ }
+
+ if((dp = opendir(cpath)) == NULL) {
+ /* todo, show the errno, this shouldnt happen anyway if the blendfile is readable */
+ fprintf(stderr, "Could not read directoty (%s) failed, code %d (%s)\n", cpath, errno, strerror(errno));
+ return list;
+ }
+
+ while ((dirp = readdir(dp)) != NULL) {
+ if (BLI_testextensie(dirp->d_name, ".blend")) {
+ value = PyString_FromString(dirp->d_name);
+ PyList_Append(list, value);
+ Py_DECREF(value);
+ }
+ }
+
+ closedir(dp);
+ return list;
+}
+
static STR_String gPyGetCurrentScene_doc =
"getCurrentScene()\n"
"Gets a reference to the current scene.\n";
-static PyObject* gPyGetCurrentScene(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+static PyObject* gPyGetCurrentScene(PyObject* self)
{
Py_INCREF(gp_KetsjiScene);
return (PyObject*) gp_KetsjiScene;
@@ -278,17 +335,13 @@ static PyObject* gPyGetCurrentScene(PyObject* self,
static PyObject *pyPrintExt(PyObject *,PyObject *,PyObject *)
{
#define pprint(x) std::cout << x << std::endl;
- bgl::BL_EXTInfo ext = bgl::RAS_EXT_support;
bool count=0;
bool support=0;
pprint("Supported Extensions...");
-#ifdef GL_ARB_shader_objects
- pprint(" GL_ARB_shader_objects supported? "<< (ext._ARB_shader_objects?"yes.":"no."));
+ pprint(" GL_ARB_shader_objects supported? "<< (GLEW_ARB_shader_objects?"yes.":"no."));
count = 1;
-#endif
-#ifdef GL_ARB_vertex_shader
- support= ext._ARB_vertex_shader;
+ support= GLEW_ARB_vertex_shader;
pprint(" GL_ARB_vertex_shader supported? "<< (support?"yes.":"no."));
count = 1;
if(support){
@@ -307,9 +360,8 @@ static PyObject *pyPrintExt(PyObject *,PyObject *,PyObject *)
pprint(" Max combined texture units." << max);
pprint("");
}
-#endif
-#ifdef GL_ARB_fragment_shader
- support=ext._ARB_fragment_shader;
+
+ support=GLEW_ARB_fragment_shader;
pprint(" GL_ARB_fragment_shader supported? "<< (support?"yes.":"no."));
count = 1;
if(support){
@@ -319,9 +371,8 @@ static PyObject *pyPrintExt(PyObject *,PyObject *,PyObject *)
pprint(" Max uniform components." << max);
pprint("");
}
-#endif
-#ifdef GL_ARB_texture_cube_map
- support = ext._ARB_texture_cube_map;
+
+ support = GLEW_ARB_texture_cube_map;
pprint(" GL_ARB_texture_cube_map supported? "<< (support?"yes.":"no."));
count = 1;
if(support){
@@ -331,9 +382,8 @@ static PyObject *pyPrintExt(PyObject *,PyObject *,PyObject *)
pprint(" Max cubemap size." << size);
pprint("");
}
-#endif
-#ifdef GL_ARB_multitexture
- support = ext._ARB_multitexture;
+
+ support = GLEW_ARB_multitexture;
count = 1;
pprint(" GL_ARB_multitexture supported? "<< (support?"yes.":"no."));
if(support){
@@ -343,63 +393,52 @@ static PyObject *pyPrintExt(PyObject *,PyObject *,PyObject *)
pprint(" Max texture units available. " << units);
pprint("");
}
-#endif
-#ifdef GL_ARB_texture_env_combine
- pprint(" GL_ARB_texture_env_combine supported? "<< (ext._ARB_texture_env_combine?"yes.":"no."));
+
+ pprint(" GL_ARB_texture_env_combine supported? "<< (GLEW_ARB_texture_env_combine?"yes.":"no."));
count = 1;
-#endif
+
if(!count)
pprint("No extenstions are used in this build");
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
static struct PyMethodDef game_methods[] = {
+ {"expandPath", (PyCFunction)gPyExpandPath, METH_VARARGS, (PY_METHODCHAR)gPyExpandPath_doc},
{"getCurrentController",
(PyCFunction) SCA_PythonController::sPyGetCurrentController,
- METH_VARARGS, SCA_PythonController::sPyGetCurrentController__doc__},
+ METH_NOARGS, (PY_METHODCHAR)SCA_PythonController::sPyGetCurrentController__doc__},
{"getCurrentScene", (PyCFunction) gPyGetCurrentScene,
- METH_VARARGS, gPyGetCurrentScene_doc.Ptr()},
+ METH_NOARGS, (PY_METHODCHAR)gPyGetCurrentScene_doc.Ptr()},
{"addActiveActuator",(PyCFunction) SCA_PythonController::sPyAddActiveActuator,
- METH_VARARGS, SCA_PythonController::sPyAddActiveActuator__doc__},
+ METH_VARARGS, (PY_METHODCHAR)SCA_PythonController::sPyAddActiveActuator__doc__},
{"getRandomFloat",(PyCFunction) gPyGetRandomFloat,
- METH_VARARGS,gPyGetRandomFloat_doc.Ptr()},
- {"setGravity",(PyCFunction) gPySetGravity, METH_VARARGS,"set Gravitation"},
- {"getSpectrum",(PyCFunction) gPyGetSpectrum, METH_VARARGS,"get audio spectrum"},
- {"stopDSP",(PyCFunction) gPyStopDSP, METH_VARARGS,"stop using the audio dsp (for performance reasons)"},
- {"getLogicTicRate", (PyCFunction) gPyGetLogicTicRate, METH_VARARGS, "Gets the logic tic rate"},
- {"setLogicTicRate", (PyCFunction) gPySetLogicTicRate, METH_VARARGS, "Sets the logic tic rate"},
- {"getPhysicsTicRate", (PyCFunction) gPyGetPhysicsTicRate, METH_VARARGS, "Gets the physics tic rate"},
- {"setPhysicsTicRate", (PyCFunction) gPySetPhysicsTicRate, METH_VARARGS, "Sets the physics tic rate"},
- {"PrintGLInfo", (PyCFunction)pyPrintExt, METH_NOARGS, "Prints GL Extension Info"},
+ METH_NOARGS, (PY_METHODCHAR)gPyGetRandomFloat_doc.Ptr()},
+ {"setGravity",(PyCFunction) gPySetGravity, METH_VARARGS, (PY_METHODCHAR)"set Gravitation"},
+ {"getSpectrum",(PyCFunction) gPyGetSpectrum, METH_NOARGS, (PY_METHODCHAR)"get audio spectrum"},
+ {"stopDSP",(PyCFunction) gPyStopDSP, METH_VARARGS, (PY_METHODCHAR)"stop using the audio dsp (for performance reasons)"},
+ {"getLogicTicRate", (PyCFunction) gPyGetLogicTicRate, METH_NOARGS, (PY_METHODCHAR)"Gets the logic tic rate"},
+ {"setLogicTicRate", (PyCFunction) gPySetLogicTicRate, METH_VARARGS, (PY_METHODCHAR)"Sets the logic tic rate"},
+ {"getPhysicsTicRate", (PyCFunction) gPyGetPhysicsTicRate, METH_NOARGS, (PY_METHODCHAR)"Gets the physics tic rate"},
+ {"setPhysicsTicRate", (PyCFunction) gPySetPhysicsTicRate, METH_VARARGS, (PY_METHODCHAR)"Sets the physics tic rate"},
+ {"getAverageFrameRate", (PyCFunction) gPyGetAverageFrameRate, METH_NOARGS, (PY_METHODCHAR)"Gets the estimated average frame rate"},
+ {"getBlendFileList", (PyCFunction)gPyGetBlendFileList, METH_VARARGS, (PY_METHODCHAR)"Gets a list of blend files in the same directory as the current blend file"},
+ {"PrintGLInfo", (PyCFunction)pyPrintExt, METH_NOARGS, (PY_METHODCHAR)"Prints GL Extension Info"},
{NULL, (PyCFunction) NULL, 0, NULL }
};
-static PyObject* gPyGetWindowHeight(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPyGetWindowHeight(PyObject*, PyObject* args)
{
- int height = (gp_Canvas ? gp_Canvas->GetHeight() : 0);
-
- PyObject* heightval = PyInt_FromLong(height);
- return heightval;
+ return PyInt_FromLong((gp_Canvas ? gp_Canvas->GetHeight() : 0));
}
-static PyObject* gPyGetWindowWidth(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPyGetWindowWidth(PyObject*, PyObject* args)
{
-
-
- int width = (gp_Canvas ? gp_Canvas->GetWidth() : 0);
-
- PyObject* widthval = PyInt_FromLong(width);
- return widthval;
+ return PyInt_FromLong((gp_Canvas ? gp_Canvas->GetWidth() : 0));
}
@@ -407,264 +446,403 @@ static PyObject* gPyGetWindowWidth(PyObject*,
// temporarility visibility thing, will be moved to rasterizer/renderer later
bool gUseVisibilityTemp = false;
-static PyObject* gPyEnableVisibility(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPyEnableVisibility(PyObject*, PyObject* args)
{
int visible;
- if (PyArg_ParseTuple(args,"i",&visible))
- {
- gUseVisibilityTemp = (visible != 0);
- }
- else
- {
- Py_Return;
- }
- Py_Return;
+ if (!PyArg_ParseTuple(args,"i",&visible))
+ return NULL;
+
+ gUseVisibilityTemp = (visible != 0);
+ Py_RETURN_NONE;
}
-static PyObject* gPyShowMouse(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPyShowMouse(PyObject*, PyObject* args)
{
int visible;
- if (PyArg_ParseTuple(args,"i",&visible))
+ if (!PyArg_ParseTuple(args,"i",&visible))
+ return NULL;
+
+ if (visible)
{
- if (visible)
- {
- if (gp_Canvas)
- gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
- } else
- {
- if (gp_Canvas)
- gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
- }
+ if (gp_Canvas)
+ gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
+ } else
+ {
+ if (gp_Canvas)
+ gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
}
- Py_Return;
+ Py_RETURN_NONE;
}
-static PyObject* gPySetMousePosition(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPySetMousePosition(PyObject*, PyObject* args)
{
int x,y;
- if (PyArg_ParseTuple(args,"ii",&x,&y))
- {
- if (gp_Canvas)
- gp_Canvas->SetMousePosition(x,y);
- }
+ if (!PyArg_ParseTuple(args,"ii",&x,&y))
+ return NULL;
- Py_Return;
+ if (gp_Canvas)
+ gp_Canvas->SetMousePosition(x,y);
+
+ Py_RETURN_NONE;
}
-static PyObject* gPySetEyeSeparation(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPySetEyeSeparation(PyObject*, PyObject* args)
{
float sep;
- if (PyArg_ParseTuple(args, "f", &sep))
- {
- if (gp_Rasterizer)
- gp_Rasterizer->SetEyeSeparation(sep);
-
- Py_Return;
+ if (!PyArg_ParseTuple(args, "f", &sep))
+ return NULL;
+
+ if (!gp_Rasterizer) {
+ PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
+ return NULL;
}
- return NULL;
+ gp_Rasterizer->SetEyeSeparation(sep);
+
+ Py_RETURN_NONE;
}
static PyObject* gPyGetEyeSeparation(PyObject*, PyObject*, PyObject*)
{
- if (gp_Rasterizer)
- return PyFloat_FromDouble(gp_Rasterizer->GetEyeSeparation());
+ if (!gp_Rasterizer) {
+ PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
+ return NULL;
+ }
- return NULL;
+ return PyFloat_FromDouble(gp_Rasterizer->GetEyeSeparation());
}
-static PyObject* gPySetFocalLength(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPySetFocalLength(PyObject*, PyObject* args)
{
float focus;
- if (PyArg_ParseTuple(args, "f", &focus))
- {
- if (gp_Rasterizer)
- gp_Rasterizer->SetFocalLength(focus);
- Py_Return;
+ if (!PyArg_ParseTuple(args, "f", &focus))
+ return NULL;
+
+ if (!gp_Rasterizer) {
+ PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
+ return NULL;
}
+
+ gp_Rasterizer->SetFocalLength(focus);
- return NULL;
+ Py_RETURN_NONE;
}
static PyObject* gPyGetFocalLength(PyObject*, PyObject*, PyObject*)
{
- if (gp_Rasterizer)
- return PyFloat_FromDouble(gp_Rasterizer->GetFocalLength());
- return NULL;
+ if (!gp_Rasterizer) {
+ PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
+ return NULL;
+ }
+
+ return PyFloat_FromDouble(gp_Rasterizer->GetFocalLength());
+
+ Py_RETURN_NONE;
}
-static PyObject* gPySetBackgroundColor(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPySetBackgroundColor(PyObject*, PyObject* args)
{
MT_Vector4 vec = MT_Vector4(0., 0., 0.3, 0.);
- if (PyVecArgTo(args, vec))
+ if (!PyVecArgTo(args, vec))
+ return NULL;
+
+ if (gp_Canvas)
{
- if (gp_Canvas)
- {
- gp_Rasterizer->SetBackColor(vec[0], vec[1], vec[2], vec[3]);
- }
- Py_Return;
+ gp_Rasterizer->SetBackColor(vec[0], vec[1], vec[2], vec[3]);
}
-
- return NULL;
+ Py_RETURN_NONE;
}
-static PyObject* gPySetMistColor(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPySetMistColor(PyObject*, PyObject* args)
{
MT_Vector3 vec = MT_Vector3(0., 0., 0.);
- if (PyVecArgTo(args, vec))
- {
- if (gp_Rasterizer)
- {
- gp_Rasterizer->SetFogColor(vec[0], vec[1], vec[2]);
- }
- Py_Return;
- }
+ if (!PyVecArgTo(args, vec))
+ return NULL;
- return NULL;
+ if (!gp_Rasterizer) {
+ PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
+ return NULL;
+ }
+ gp_Rasterizer->SetFogColor(vec[0], vec[1], vec[2]);
+
+ Py_RETURN_NONE;
}
-static PyObject* gPySetMistStart(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPySetMistStart(PyObject*, PyObject* args)
{
float miststart;
- if (PyArg_ParseTuple(args,"f",&miststart))
- {
- if (gp_Rasterizer)
- {
- gp_Rasterizer->SetFogStart(miststart);
- }
+ if (!PyArg_ParseTuple(args,"f",&miststart))
+ return NULL;
+
+ if (!gp_Rasterizer) {
+ PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
+ return NULL;
}
- Py_Return;
+
+ gp_Rasterizer->SetFogStart(miststart);
+
+ Py_RETURN_NONE;
}
-static PyObject* gPySetMistEnd(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPySetMistEnd(PyObject*, PyObject* args)
{
float mistend;
- if (PyArg_ParseTuple(args,"f",&mistend))
- {
- if (gp_Rasterizer)
- {
- gp_Rasterizer->SetFogEnd(mistend);
- }
+ if (!PyArg_ParseTuple(args,"f",&mistend))
+ return NULL;
+
+ if (!gp_Rasterizer) {
+ PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
+ return NULL;
}
- Py_Return;
+
+ gp_Rasterizer->SetFogEnd(mistend);
+
+ Py_RETURN_NONE;
}
-static PyObject* gPySetAmbientColor(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPySetAmbientColor(PyObject*, PyObject* args)
{
MT_Vector3 vec = MT_Vector3(0., 0., 0.);
- if (PyVecArgTo(args, vec))
- {
- if (gp_Rasterizer)
- {
- gp_Rasterizer->SetAmbientColor(vec[0], vec[1], vec[2]);
- }
- Py_Return;
- }
+ if (!PyVecArgTo(args, vec))
+ return NULL;
- return NULL;
+ if (!gp_Rasterizer) {
+ PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
+ return NULL;
+ }
+ gp_Rasterizer->SetAmbientColor(vec[0], vec[1], vec[2]);
+
+ Py_RETURN_NONE;
}
-static PyObject* gPyMakeScreenshot(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPyMakeScreenshot(PyObject*, PyObject* args)
{
char* filename;
- if (PyArg_ParseTuple(args,"s",&filename))
+ if (!PyArg_ParseTuple(args,"s",&filename))
+ return NULL;
+
+ if (gp_Canvas)
{
- if (gp_Canvas)
- {
- gp_Canvas->MakeScreenShot(filename);
- }
+ gp_Canvas->MakeScreenShot(filename);
}
- Py_Return;
+
+ Py_RETURN_NONE;
}
-static PyObject* gPyEnableMotionBlur(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPyEnableMotionBlur(PyObject*, PyObject* args)
{
float motionblurvalue;
- if (PyArg_ParseTuple(args,"f",&motionblurvalue))
- {
- if(gp_Rasterizer)
- {
- gp_Rasterizer->EnableMotionBlur(motionblurvalue);
+ if (!PyArg_ParseTuple(args,"f",&motionblurvalue))
+ return NULL;
+
+ if (!gp_Rasterizer) {
+ PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
+ return NULL;
+ }
+
+ gp_Rasterizer->EnableMotionBlur(motionblurvalue);
+
+ Py_RETURN_NONE;
+}
+
+static PyObject* gPyDisableMotionBlur(PyObject*, PyObject* args)
+{
+ if (!gp_Rasterizer) {
+ PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
+ return NULL;
+ }
+
+ gp_Rasterizer->DisableMotionBlur();
+
+ Py_RETURN_NONE;
+}
+
+int getGLSLSettingFlag(char *setting)
+{
+ if(strcmp(setting, "lights") == 0)
+ return G_FILE_GLSL_NO_LIGHTS;
+ else if(strcmp(setting, "shaders") == 0)
+ return G_FILE_GLSL_NO_SHADERS;
+ else if(strcmp(setting, "shadows") == 0)
+ return G_FILE_GLSL_NO_SHADOWS;
+ else if(strcmp(setting, "ramps") == 0)
+ return G_FILE_GLSL_NO_RAMPS;
+ else if(strcmp(setting, "nodes") == 0)
+ return G_FILE_GLSL_NO_NODES;
+ else if(strcmp(setting, "extra_textures") == 0)
+ return G_FILE_GLSL_NO_EXTRA_TEX;
+ else
+ return -1;
+}
+
+static PyObject* gPySetGLSLMaterialSetting(PyObject*,
+ PyObject* args,
+ PyObject*)
+{
+ char *setting;
+ int enable, flag, fileflags;
+
+ if (!PyArg_ParseTuple(args,"si",&setting,&enable))
+ return NULL;
+
+ flag = getGLSLSettingFlag(setting);
+
+ if (flag==-1) {
+ PyErr_SetString(PyExc_ValueError, "glsl setting is not known");
+ return NULL;
+ }
+
+ fileflags = G.fileflags;
+
+ if (enable)
+ G.fileflags &= ~flag;
+ else
+ G.fileflags |= flag;
+
+ /* display lists and GLSL materials need to be remade */
+ if(G.fileflags != fileflags) {
+ if(gp_KetsjiEngine) {
+ KX_SceneList *scenes = gp_KetsjiEngine->CurrentScenes();
+ KX_SceneList::iterator it;
+
+ for(it=scenes->begin(); it!=scenes->end(); it++)
+ if((*it)->GetBucketManager())
+ (*it)->GetBucketManager()->ReleaseDisplayLists();
}
+
+ GPU_materials_free();
+ }
+
+ Py_RETURN_NONE;
+}
+
+static PyObject* gPyGetGLSLMaterialSetting(PyObject*,
+ PyObject* args,
+ PyObject*)
+{
+ char *setting;
+ int enabled = 0, flag;
+
+ if (!PyArg_ParseTuple(args,"s",&setting))
+ return NULL;
+
+ flag = getGLSLSettingFlag(setting);
+
+ if (flag==-1) {
+ PyErr_SetString(PyExc_ValueError, "glsl setting is not known");
+ return NULL;
}
- Py_Return;
+
+ enabled = ((G.fileflags & flag) != 0);
+ return PyInt_FromLong(enabled);
}
-static PyObject* gPyDisableMotionBlur(PyObject*,
+#define KX_TEXFACE_MATERIAL 0
+#define KX_BLENDER_MULTITEX_MATERIAL 1
+#define KX_BLENDER_GLSL_MATERIAL 2
+
+static PyObject* gPySetMaterialType(PyObject*,
PyObject* args,
PyObject*)
{
- if(gp_Rasterizer)
- {
- gp_Rasterizer->DisableMotionBlur();
+ int flag, type;
+
+ if (!PyArg_ParseTuple(args,"i",&type))
+ return NULL;
+
+ if(type == KX_BLENDER_GLSL_MATERIAL)
+ flag = G_FILE_GAME_MAT|G_FILE_GAME_MAT_GLSL;
+ else if(type == KX_BLENDER_MULTITEX_MATERIAL)
+ flag = G_FILE_GAME_MAT;
+ else if(type == KX_TEXFACE_MATERIAL)
+ flag = 0;
+ else {
+ PyErr_SetString(PyExc_ValueError, "material type is not known");
+ return NULL;
}
- Py_Return;
+
+ G.fileflags &= ~(G_FILE_GAME_MAT|G_FILE_GAME_MAT_GLSL);
+ G.fileflags |= flag;
+
+ Py_RETURN_NONE;
}
-STR_String gPyGetWindowHeight__doc__="getWindowHeight doc";
-STR_String gPyGetWindowWidth__doc__="getWindowWidth doc";
-STR_String gPyEnableVisibility__doc__="enableVisibility doc";
-STR_String gPyMakeScreenshot__doc__="make Screenshot doc";
-STR_String gPyShowMouse__doc__="showMouse(bool visible)";
-STR_String gPySetMousePosition__doc__="setMousePosition(int x,int y)";
+static PyObject* gPyGetMaterialType(PyObject*)
+{
+ int flag;
+
+ if(G.fileflags & (G_FILE_GAME_MAT|G_FILE_GAME_MAT_GLSL))
+ flag = KX_BLENDER_GLSL_MATERIAL;
+ else if(G.fileflags & G_FILE_GAME_MAT)
+ flag = KX_BLENDER_MULTITEX_MATERIAL;
+ else
+ flag = KX_TEXFACE_MATERIAL;
+
+ return PyInt_FromLong(flag);
+}
+
+static PyObject* gPyDrawLine(PyObject*, PyObject* args)
+{
+ PyObject* ob_from;
+ PyObject* ob_to;
+ PyObject* ob_color;
+
+ if (!gp_Rasterizer) {
+ PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
+ return NULL;
+ }
+
+ if (!PyArg_ParseTuple(args,"OOO",&ob_from,&ob_to,&ob_color))
+ return NULL;
+
+ MT_Vector3 from(0., 0., 0.);
+ MT_Vector3 to(0., 0., 0.);
+ MT_Vector3 color(0., 0., 0.);
+ if (!PyVecTo(ob_from, from))
+ return NULL;
+ if (!PyVecTo(ob_to, to))
+ return NULL;
+ if (!PyVecTo(ob_color, color))
+ return NULL;
+
+ gp_Rasterizer->DrawDebugLine(from,to,color);
+
+ Py_RETURN_NONE;
+}
static struct PyMethodDef rasterizer_methods[] = {
{"getWindowWidth",(PyCFunction) gPyGetWindowWidth,
- METH_VARARGS, gPyGetWindowWidth__doc__.Ptr()},
+ METH_VARARGS, "getWindowWidth doc"},
{"getWindowHeight",(PyCFunction) gPyGetWindowHeight,
- METH_VARARGS, gPyGetWindowHeight__doc__.Ptr()},
+ METH_VARARGS, "getWindowHeight doc"},
{"makeScreenshot",(PyCFunction)gPyMakeScreenshot,
- METH_VARARGS, gPyMakeScreenshot__doc__.Ptr()},
+ METH_VARARGS, "make Screenshot doc"},
{"enableVisibility",(PyCFunction) gPyEnableVisibility,
- METH_VARARGS, gPyEnableVisibility__doc__.Ptr()},
+ METH_VARARGS, "enableVisibility doc"},
{"showMouse",(PyCFunction) gPyShowMouse,
- METH_VARARGS, gPyShowMouse__doc__.Ptr()},
+ METH_VARARGS, "showMouse(bool visible)"},
{"setMousePosition",(PyCFunction) gPySetMousePosition,
- METH_VARARGS, gPySetMousePosition__doc__.Ptr()},
+ METH_VARARGS, "setMousePosition(int x,int y)"},
{"setBackgroundColor",(PyCFunction)gPySetBackgroundColor,METH_VARARGS,"set Background Color (rgb)"},
{"setAmbientColor",(PyCFunction)gPySetAmbientColor,METH_VARARGS,"set Ambient Color (rgb)"},
{"setMistColor",(PyCFunction)gPySetMistColor,METH_VARARGS,"set Mist Color (rgb)"},
@@ -678,11 +856,19 @@ static struct PyMethodDef rasterizer_methods[] = {
{"getEyeSeparation", (PyCFunction) gPyGetEyeSeparation, METH_VARARGS, "get the eye separation for stereo mode"},
{"setFocalLength", (PyCFunction) gPySetFocalLength, METH_VARARGS, "set the focal length for stereo mode"},
{"getFocalLength", (PyCFunction) gPyGetFocalLength, METH_VARARGS, "get the focal length for stereo mode"},
+ {"setMaterialMode",(PyCFunction) gPySetMaterialType,
+ METH_VARARGS, "set the material mode to use for OpenGL rendering"},
+ {"getMaterialMode",(PyCFunction) gPyGetMaterialType,
+ METH_NOARGS, "get the material mode being used for OpenGL rendering"},
+ {"setGLSLMaterialSetting",(PyCFunction) gPySetGLSLMaterialSetting,
+ METH_VARARGS, "set the state of a GLSL material setting"},
+ {"getGLSLMaterialSetting",(PyCFunction) gPyGetGLSLMaterialSetting,
+ METH_VARARGS, "get the state of a GLSL material setting"},
+ {"drawLine", (PyCFunction) gPyDrawLine,
+ METH_VARARGS, "draw a line on the screen"},
{ NULL, (PyCFunction) NULL, 0, NULL }
};
-
-
// Initialization function for the module (*must* be called initGameLogic)
static char GameLogic_module_documentation[] =
@@ -695,11 +881,12 @@ static char Rasterizer_module_documentation[] =
-PyObject* initGameLogic(KX_Scene* scene) // quick hack to get gravity hook
+PyObject* initGameLogic(KX_KetsjiEngine *engine, KX_Scene* scene) // quick hack to get gravity hook
{
PyObject* m;
PyObject* d;
+ gp_KetsjiEngine = engine;
gp_KetsjiScene = scene;
gUseVisibilityTemp=false;
@@ -711,10 +898,14 @@ PyObject* initGameLogic(KX_Scene* scene) // quick hack to get gravity hook
// Add some symbolic constants to the module
d = PyModule_GetDict(m);
+
+ // can be overwritten later for gameEngine instances that can load new blend files and re-initialize this module
+ // for now its safe to make sure it exists for other areas such as the web plugin
+ PyDict_SetItemString(d, "globalDict", PyDict_New());
ErrorObject = PyString_FromString("GameLogic.error");
PyDict_SetItemString(d, "error", ErrorObject);
-
+
// XXXX Add constants here
/* To use logic bricks, we need some sort of constants. Here, we associate */
/* constants and sumbolic names. Add them to dictionary d. */
@@ -737,6 +928,15 @@ PyObject* initGameLogic(KX_Scene* scene) // quick hack to get gravity hook
KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTX);
KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTY);
KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTZ);
+ KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPX);
+ KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPY);
+ KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPY);
+ KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNX);
+ KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNY);
+ KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNY);
+ KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIX);
+ KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIY);
+ KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIZ);
/* 4. Ipo actuator, simple part */
KX_MACRO_addTypesToDict(d, KX_IPOACT_PLAY, KX_IpoActuator::KX_ACT_IPO_PLAY);
@@ -803,37 +1003,75 @@ PyObject* initGameLogic(KX_Scene* scene) // quick hack to get gravity hook
KX_MACRO_addTypesToDict(d, CAM_POS, BL_Shader::CAM_POS);
KX_MACRO_addTypesToDict(d, CONSTANT_TIMER, BL_Shader::CONSTANT_TIMER);
+ /* 10 state actuator */
+ KX_MACRO_addTypesToDict(d, KX_STATE1, (1<<0));
+ KX_MACRO_addTypesToDict(d, KX_STATE2, (1<<1));
+ KX_MACRO_addTypesToDict(d, KX_STATE3, (1<<2));
+ KX_MACRO_addTypesToDict(d, KX_STATE4, (1<<3));
+ KX_MACRO_addTypesToDict(d, KX_STATE5, (1<<4));
+ KX_MACRO_addTypesToDict(d, KX_STATE6, (1<<5));
+ KX_MACRO_addTypesToDict(d, KX_STATE7, (1<<6));
+ KX_MACRO_addTypesToDict(d, KX_STATE8, (1<<7));
+ KX_MACRO_addTypesToDict(d, KX_STATE9, (1<<8));
+ KX_MACRO_addTypesToDict(d, KX_STATE10, (1<<9));
+ KX_MACRO_addTypesToDict(d, KX_STATE11, (1<<10));
+ KX_MACRO_addTypesToDict(d, KX_STATE12, (1<<11));
+ KX_MACRO_addTypesToDict(d, KX_STATE13, (1<<12));
+ KX_MACRO_addTypesToDict(d, KX_STATE14, (1<<13));
+ KX_MACRO_addTypesToDict(d, KX_STATE15, (1<<14));
+ KX_MACRO_addTypesToDict(d, KX_STATE16, (1<<15));
+ KX_MACRO_addTypesToDict(d, KX_STATE17, (1<<16));
+ KX_MACRO_addTypesToDict(d, KX_STATE18, (1<<17));
+ KX_MACRO_addTypesToDict(d, KX_STATE19, (1<<18));
+ KX_MACRO_addTypesToDict(d, KX_STATE20, (1<<19));
+ KX_MACRO_addTypesToDict(d, KX_STATE21, (1<<20));
+ KX_MACRO_addTypesToDict(d, KX_STATE22, (1<<21));
+ KX_MACRO_addTypesToDict(d, KX_STATE23, (1<<22));
+ KX_MACRO_addTypesToDict(d, KX_STATE24, (1<<23));
+ KX_MACRO_addTypesToDict(d, KX_STATE25, (1<<24));
+ KX_MACRO_addTypesToDict(d, KX_STATE26, (1<<25));
+ KX_MACRO_addTypesToDict(d, KX_STATE27, (1<<26));
+ KX_MACRO_addTypesToDict(d, KX_STATE28, (1<<27));
+ KX_MACRO_addTypesToDict(d, KX_STATE29, (1<<28));
+ KX_MACRO_addTypesToDict(d, KX_STATE30, (1<<29));
+
// Check for errors
if (PyErr_Occurred())
{
Py_FatalError("can't initialize module GameLogic");
}
- return d;
-}
-
-void dictionaryClearByHand(PyObject *dict)
-{
- // Clears the dictionary by hand:
- // This prevents, extra references to global variables
- // inside the GameLogic dictionary when the python interpreter is finalized.
- // which allows the scene to safely delete them :)
- // see: (space.c)->start_game
- if(dict) PyDict_Clear(dict);
+ return m;
}
-
// Python Sandbox code
// override builtin functions import() and open()
-PyObject *KXpy_open(PyObject *self, PyObject *args)
-{
+PyObject *KXpy_open(PyObject *self, PyObject *args) {
PyErr_SetString(PyExc_RuntimeError, "Sandbox: open() function disabled!\nGame Scripts should not use this function.");
return NULL;
}
+PyObject *KXpy_reload(PyObject *self, PyObject *args) {
+ PyErr_SetString(PyExc_RuntimeError, "Sandbox: reload() function disabled!\nGame Scripts should not use this function.");
+ return NULL;
+}
+
+PyObject *KXpy_file(PyObject *self, PyObject *args) {
+ PyErr_SetString(PyExc_RuntimeError, "Sandbox: file() function disabled!\nGame Scripts should not use this function.");
+ return NULL;
+}
+PyObject *KXpy_execfile(PyObject *self, PyObject *args) {
+ PyErr_SetString(PyExc_RuntimeError, "Sandbox: execfile() function disabled!\nGame Scripts should not use this function.");
+ return NULL;
+}
+
+PyObject *KXpy_compile(PyObject *self, PyObject *args) {
+ PyErr_SetString(PyExc_RuntimeError, "Sandbox: compile() function disabled!\nGame Scripts should not use this function.");
+ return NULL;
+}
PyObject *KXpy_import(PyObject *self, PyObject *args)
{
@@ -843,9 +1081,17 @@ PyObject *KXpy_import(PyObject *self, PyObject *args)
PyObject *fromlist = NULL;
PyObject *l, *m, *n;
+#if (PY_VERSION_HEX >= 0x02060000)
+ int dummy_val; /* what does this do?*/
+
+ if (!PyArg_ParseTuple(args, "s|OOOi:m_import",
+ &name, &globals, &locals, &fromlist, &dummy_val))
+ return NULL;
+#else
if (!PyArg_ParseTuple(args, "s|OOO:m_import",
&name, &globals, &locals, &fromlist))
return NULL;
+#endif
/* check for builtin modules */
m = PyImport_AddModule("sys");
@@ -859,7 +1105,7 @@ PyObject *KXpy_import(PyObject *self, PyObject *args)
/* quick hack for GamePython modules
TODO: register builtin modules properly by ExtendInittab */
if (!strcmp(name, "GameLogic") || !strcmp(name, "GameKeys") || !strcmp(name, "PhysicsConstraints") ||
- !strcmp(name, "Rasterizer")) {
+ !strcmp(name, "Rasterizer") || !strcmp(name, "Mathutils")) {
return PyImport_ImportModuleEx(name, globals, locals, fromlist);
}
@@ -869,40 +1115,67 @@ PyObject *KXpy_import(PyObject *self, PyObject *args)
}
+/* override python file type functions */
+#if 0
+static int
+file_init(PyObject *self, PyObject *args, PyObject *kwds)
+{
+ KXpy_file(NULL, NULL);
+ return -1;
+}
+static PyObject *
+file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
+{
+ return KXpy_file(NULL, NULL);
+}
+#endif
-static PyMethodDef meth_open[] = {
- { "open", KXpy_open, METH_VARARGS,
- "(disabled)"}
-};
-
-
-static PyMethodDef meth_import[] = {
- { "import", KXpy_import, METH_VARARGS,
- "our own import"}
-};
-
+static PyMethodDef meth_open[] = {{ "open", KXpy_open, METH_VARARGS, "(disabled)"}};
+static PyMethodDef meth_reload[] = {{ "reload", KXpy_reload, METH_VARARGS, "(disabled)"}};
+static PyMethodDef meth_file[] = {{ "file", KXpy_file, METH_VARARGS, "(disabled)"}};
+static PyMethodDef meth_execfile[] = {{ "execfile", KXpy_execfile, METH_VARARGS, "(disabled)"}};
+static PyMethodDef meth_compile[] = {{ "compile", KXpy_compile, METH_VARARGS, "(disabled)"}};
+static PyMethodDef meth_import[] = {{ "import", KXpy_import, METH_VARARGS, "our own import"}};
//static PyObject *g_oldopen = 0;
//static PyObject *g_oldimport = 0;
//static int g_security = 0;
-
void setSandbox(TPythonSecurityLevel level)
{
PyObject *m = PyImport_AddModule("__builtin__");
PyObject *d = PyModule_GetDict(m);
- PyObject *meth = PyCFunction_New(meth_open, NULL);
switch (level) {
case psl_Highest:
//if (!g_security) {
//g_oldopen = PyDict_GetItemString(d, "open");
- PyDict_SetItemString(d, "open", meth);
- meth = PyCFunction_New(meth_import, NULL);
- PyDict_SetItemString(d, "__import__", meth);
+
+ // functions we cant trust
+ PyDict_SetItemString(d, "open", PyCFunction_New(meth_open, NULL));
+ PyDict_SetItemString(d, "reload", PyCFunction_New(meth_reload, NULL));
+ PyDict_SetItemString(d, "file", PyCFunction_New(meth_file, NULL));
+ PyDict_SetItemString(d, "execfile", PyCFunction_New(meth_execfile, NULL));
+ PyDict_SetItemString(d, "compile", PyCFunction_New(meth_compile, NULL));
+
+ // our own import
+ PyDict_SetItemString(d, "__import__", PyCFunction_New(meth_import, NULL));
//g_security = level;
+
+ // Overiding file dosnt stop it being accessed if your sneaky
+ // f = [ t for t in (1).__class__.__mro__[-1].__subclasses__() if t.__name__ == 'file'][0]('/some_file.txt', 'w')
+ // f.write('...')
+ // so overwrite the file types functions. be very careful here still, since python uses python.
+ // ps - python devs frown deeply upon this.
+
+ /* this could mess up pythons internals, if we are serious about sandboxing
+ * issues like the one above need to be solved, possibly modify __subclasses__ is safer? */
+#if 0
+ PyFile_Type.tp_init = file_init;
+ PyFile_Type.tp_new = file_new;
+#endif
//}
break;
/*
@@ -985,6 +1258,11 @@ PyObject* initRasterizer(RAS_IRasterizer* rasty,RAS_ICanvas* canvas)
ErrorObject = PyString_FromString("Rasterizer.error");
PyDict_SetItemString(d, "error", ErrorObject);
+ /* needed for get/setMaterialType */
+ KX_MACRO_addTypesToDict(d, KX_TEXFACE_MATERIAL, KX_TEXFACE_MATERIAL);
+ KX_MACRO_addTypesToDict(d, KX_BLENDER_MULTITEX_MATERIAL, KX_BLENDER_MULTITEX_MATERIAL);
+ KX_MACRO_addTypesToDict(d, KX_BLENDER_GLSL_MATERIAL, KX_BLENDER_GLSL_MATERIAL);
+
// XXXX Add constants here
// Check for errors
@@ -1006,9 +1284,38 @@ static char GameKeys_module_documentation[] =
"This modules provides defines for key-codes"
;
+static char gPyEventToString_doc[] =
+"Take a valid event from the GameKeys module or Keyboard Sensor and return a name"
+;
+static PyObject* gPyEventToString(PyObject*, PyObject* value)
+{
+ PyObject* mod, *dict, *key, *val, *ret = NULL;
+ Py_ssize_t pos = 0;
+
+ mod = PyImport_ImportModule( "GameKeys" );
+ if (!mod)
+ return NULL;
+
+ dict = PyModule_GetDict(mod);
+
+ while (PyDict_Next(dict, &pos, &key, &val)) {
+ if (PyObject_Compare(value, val)==0) {
+ ret = key;
+ break;
+ }
+ }
+
+ PyErr_Clear(); // incase there was an error clearing
+ Py_DECREF(mod);
+ if (!ret) PyErr_SetString(PyExc_ValueError, "expected a valid int keyboard event");
+ else Py_INCREF(ret);
+
+ return ret;
+}
static struct PyMethodDef gamekeys_methods[] = {
+ {"EventToString", (PyCFunction)gPyEventToString, METH_O, (PY_METHODCHAR)gPyEventToString_doc},
{ NULL, (PyCFunction) NULL, 0, NULL }
};
@@ -1152,7 +1459,111 @@ PyObject* initGameKeys()
return d;
}
-void PHY_SetActiveScene(class KX_Scene* scene)
+PyObject* initMathutils()
+{
+ return NULL; //XXX Mathutils_Init("Mathutils"); // Use as a top level module in BGE
+}
+
+void KX_SetActiveScene(class KX_Scene* scene)
{
gp_KetsjiScene = scene;
}
+
+class KX_Scene* KX_GetActiveScene()
+{
+ return gp_KetsjiScene;
+}
+
+class KX_KetsjiEngine* KX_GetActiveEngine()
+{
+ return gp_KetsjiEngine;
+}
+
+// utility function for loading and saving the globalDict
+int saveGamePythonConfig( char **marshal_buffer)
+{
+ int marshal_length = 0;
+ PyObject* gameLogic = PyImport_ImportModule("GameLogic");
+ if (gameLogic) {
+ PyObject* pyGlobalDict = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module
+ if (pyGlobalDict) {
+#ifdef Py_MARSHAL_VERSION
+ PyObject* pyGlobalDictMarshal = PyMarshal_WriteObjectToString( pyGlobalDict, 2); // Py_MARSHAL_VERSION == 2 as of Py2.5
+#else
+ PyObject* pyGlobalDictMarshal = PyMarshal_WriteObjectToString( pyGlobalDict );
+#endif
+ if (pyGlobalDictMarshal) {
+ // for testing only
+ // PyObject_Print(pyGlobalDictMarshal, stderr, 0);
+
+ marshal_length= PyString_Size(pyGlobalDictMarshal);
+ *marshal_buffer = new char[marshal_length + 1];
+ memcpy(*marshal_buffer, PyString_AsString(pyGlobalDictMarshal), marshal_length);
+
+ Py_DECREF(pyGlobalDictMarshal);
+ } else {
+ printf("Error, GameLogic.globalDict could not be marshal'd\n");
+ }
+ } else {
+ printf("Error, GameLogic.globalDict was removed\n");
+ }
+ Py_DECREF(gameLogic);
+ } else {
+ PyErr_Clear();
+ printf("Error, GameLogic failed to import GameLogic.globalDict will be lost\n");
+ }
+ return marshal_length;
+}
+
+int loadGamePythonConfig(char *marshal_buffer, int marshal_length)
+{
+ /* Restore the dict */
+ if (marshal_buffer) {
+ PyObject* gameLogic = PyImport_ImportModule("GameLogic");
+
+ if (gameLogic) {
+ PyObject* pyGlobalDict = PyMarshal_ReadObjectFromString(marshal_buffer, marshal_length);
+ if (pyGlobalDict) {
+ PyObject* pyGlobalDict_orig = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module.
+ if (pyGlobalDict_orig) {
+ PyDict_Clear(pyGlobalDict_orig);
+ PyDict_Update(pyGlobalDict_orig, pyGlobalDict);
+ } else {
+ /* this should not happen, but cant find the original globalDict, just assign it then */
+ PyDict_SetItemString(PyModule_GetDict(gameLogic), "globalDict", pyGlobalDict); // Same as importing the module.
+ }
+ Py_DECREF(gameLogic);
+ Py_DECREF(pyGlobalDict);
+ return 1;
+ } else {
+ Py_DECREF(gameLogic);
+ PyErr_Clear();
+ printf("Error could not marshall string\n");
+ }
+ } else {
+ PyErr_Clear();
+ printf("Error, GameLogic failed to import GameLogic.globalDict will be lost\n");
+ }
+ }
+ return 0;
+}
+
+void pathGamePythonConfig( char *path )
+{
+ int len = strlen(gp_GamePythonPath);
+
+ BLI_strncpy(path, gp_GamePythonPath, sizeof(gp_GamePythonPath));
+
+ /* replace extension */
+ if (BLI_testextensie(path, ".blend")) {
+ strcpy(path+(len-6), ".bgeconf");
+ } else {
+ strcpy(path+len, ".bgeconf");
+ }
+}
+
+void setGamePythonPath(char *path)
+{
+ BLI_strncpy(gp_GamePythonPath, path, sizeof(gp_GamePythonPath));
+}
+
diff --git a/source/gameengine/Ketsji/KX_PythonInit.h b/source/gameengine/Ketsji/KX_PythonInit.h
index b2b66e70f5b..57ee0be9400 100644
--- a/source/gameengine/Ketsji/KX_PythonInit.h
+++ b/source/gameengine/Ketsji/KX_PythonInit.h
@@ -40,16 +40,27 @@ typedef enum {
extern bool gUseVisibilityTemp;
-PyObject* initGameLogic(class KX_Scene* ketsjiscene);
+PyObject* initGameLogic(class KX_KetsjiEngine *engine, class KX_Scene* ketsjiscene);
PyObject* initGameKeys();
PyObject* initRasterizer(class RAS_IRasterizer* rasty,class RAS_ICanvas* canvas);
PyObject* initGamePlayerPythonScripting(const STR_String& progname, TPythonSecurityLevel level);
+PyObject* initMathutils();
+PyObject* initVideoTexture(void);
void exitGamePlayerPythonScripting();
PyObject* initGamePythonScripting(const STR_String& progname, TPythonSecurityLevel level);
void exitGamePythonScripting();
-void dictionaryClearByHand(PyObject *dict);
-void PHY_SetActiveScene(class KX_Scene* scene);
+void setGamePythonPath(char *path);
+void pathGamePythonConfig( char *path );
+int saveGamePythonConfig( char **marshal_buffer);
+int loadGamePythonConfig(char *marshal_buffer, int marshal_length);
+
+class KX_KetsjiEngine;
+class KX_Scene;
+
+void KX_SetActiveScene(class KX_Scene* scene);
+class KX_Scene* KX_GetActiveScene();
+class KX_KetsjiEngine* KX_GetActiveEngine();
#include "MT_Vector3.h"
void KX_RasterizerDrawDebugLine(const MT_Vector3& from,const MT_Vector3& to,const MT_Vector3& color);
diff --git a/source/gameengine/Ketsji/KX_RadarSensor.cpp b/source/gameengine/Ketsji/KX_RadarSensor.cpp
index 66ff1e1e7ca..244e9b75d8e 100644
--- a/source/gameengine/Ketsji/KX_RadarSensor.cpp
+++ b/source/gameengine/Ketsji/KX_RadarSensor.cpp
@@ -71,7 +71,6 @@ KX_RadarSensor::KX_RadarSensor(SCA_EventManager* eventmgr,
//sumoObj->setClientObject(&m_client_info);
}
-
KX_RadarSensor::~KX_RadarSensor()
{
@@ -81,10 +80,7 @@ CValue* KX_RadarSensor::GetReplica()
{
KX_RadarSensor* replica = new KX_RadarSensor(*this);
replica->m_colliders = new CListValue();
- replica->m_bCollision = false;
- replica->m_bTriggered= false;
- replica->m_hitObject = NULL;
- replica->m_bLastTriggered = false;
+ replica->Init();
// this will copy properties and so on...
CValue::AddDataToReplica(replica);
@@ -93,6 +89,10 @@ CValue* KX_RadarSensor::GetReplica()
if (replica->m_physCtrl)
{
replica->m_physCtrl = replica->m_physCtrl->GetReplica();
+ if (replica->m_physCtrl)
+ {
+ replica->m_physCtrl->setNewClientInfo(replica->m_client_info);
+ }
}
//todo: make sure replication works fine!
@@ -124,27 +124,48 @@ void KX_RadarSensor::SynchronizeTransform()
// depends on the radar 'axis'
switch (m_axis)
{
- case 0: // X Axis
+ case 0: // +X Axis
{
MT_Quaternion rotquatje(MT_Vector3(0,0,1),MT_radians(90));
trans.rotate(rotquatje);
trans.translate(MT_Vector3 (0, -m_coneheight/2.0 ,0));
break;
};
- case 1: // Y Axis
+ case 1: // +Y Axis
{
MT_Quaternion rotquatje(MT_Vector3(1,0,0),MT_radians(-180));
trans.rotate(rotquatje);
trans.translate(MT_Vector3 (0, -m_coneheight/2.0 ,0));
break;
};
- case 2: // Z Axis
+ case 2: // +Z Axis
{
MT_Quaternion rotquatje(MT_Vector3(1,0,0),MT_radians(-90));
trans.rotate(rotquatje);
trans.translate(MT_Vector3 (0, -m_coneheight/2.0 ,0));
break;
};
+ case 3: // -X Axis
+ {
+ MT_Quaternion rotquatje(MT_Vector3(0,0,1),MT_radians(-90));
+ trans.rotate(rotquatje);
+ trans.translate(MT_Vector3 (0, -m_coneheight/2.0 ,0));
+ break;
+ };
+ case 4: // -Y Axis
+ {
+ //MT_Quaternion rotquatje(MT_Vector3(1,0,0),MT_radians(-180));
+ //trans.rotate(rotquatje);
+ trans.translate(MT_Vector3 (0, -m_coneheight/2.0 ,0));
+ break;
+ };
+ case 5: // -Z Axis
+ {
+ MT_Quaternion rotquatje(MT_Vector3(1,0,0),MT_radians(90));
+ trans.rotate(rotquatje);
+ trans.translate(MT_Vector3 (0, -m_coneheight/2.0 ,0));
+ break;
+ };
default:
{
}
@@ -155,8 +176,10 @@ void KX_RadarSensor::SynchronizeTransform()
if (m_physCtrl)
{
- m_physCtrl->setPosition(trans.getOrigin().x(),trans.getOrigin().y(),trans.getOrigin().z());
- m_physCtrl->setOrientation(trans.getRotation().x(),trans.getRotation().y(),trans.getRotation().z(),trans.getRotation().w());
+ MT_Quaternion orn = trans.getRotation();
+ MT_Point3 pos = trans.getOrigin();
+ m_physCtrl->setPosition(pos[0],pos[1],pos[2]);
+ m_physCtrl->setOrientation(orn[0],orn[1],orn[2],orn[3]);
m_physCtrl->calcXform();
}
@@ -198,11 +221,11 @@ PyParentObject KX_RadarSensor::Parents[] = {
PyMethodDef KX_RadarSensor::Methods[] = {
{"getConeOrigin", (PyCFunction) KX_RadarSensor::sPyGetConeOrigin,
- METH_VARARGS, GetConeOrigin_doc},
+ METH_VARARGS, (PY_METHODCHAR)GetConeOrigin_doc},
{"getConeTarget", (PyCFunction) KX_RadarSensor::sPyGetConeTarget,
- METH_VARARGS, GetConeTarget_doc},
+ METH_VARARGS, (PY_METHODCHAR)GetConeTarget_doc},
{"getConeHeight", (PyCFunction) KX_RadarSensor::sPyGetConeHeight,
- METH_VARARGS, GetConeHeight_doc},
+ METH_VARARGS, (PY_METHODCHAR)GetConeHeight_doc},
{NULL,NULL,NULL,NULL} //Sentinel
};
@@ -211,7 +234,7 @@ PyObject* KX_RadarSensor::_getattr(const STR_String& attr) {
}
/* getConeOrigin */
-char KX_RadarSensor::GetConeOrigin_doc[] =
+const char KX_RadarSensor::GetConeOrigin_doc[] =
"getConeOrigin()\n"
"\tReturns the origin of the cone with which to test. The origin\n"
"\tis in the middle of the cone.";
@@ -228,7 +251,7 @@ PyObject* KX_RadarSensor::PyGetConeOrigin(PyObject* self,
}
/* getConeOrigin */
-char KX_RadarSensor::GetConeTarget_doc[] =
+const char KX_RadarSensor::GetConeTarget_doc[] =
"getConeTarget()\n"
"\tReturns the center of the bottom face of the cone with which to test.\n";
PyObject* KX_RadarSensor::PyGetConeTarget(PyObject* self,
@@ -244,7 +267,7 @@ PyObject* KX_RadarSensor::PyGetConeTarget(PyObject* self,
}
/* getConeOrigin */
-char KX_RadarSensor::GetConeHeight_doc[] =
+const char KX_RadarSensor::GetConeHeight_doc[] =
"getConeHeight()\n"
"\tReturns the height of the cone with which to test.\n";
PyObject* KX_RadarSensor::PyGetConeHeight(PyObject* self,
diff --git a/source/gameengine/Ketsji/KX_RayCast.cpp b/source/gameengine/Ketsji/KX_RayCast.cpp
index 288a936e1b1..974d4b992a6 100644
--- a/source/gameengine/Ketsji/KX_RayCast.cpp
+++ b/source/gameengine/Ketsji/KX_RayCast.cpp
@@ -29,6 +29,7 @@
*/
#include <stdlib.h>
+#include <stdio.h>
#include "KX_RayCast.h"
@@ -39,7 +40,21 @@
#include "PHY_IPhysicsEnvironment.h"
#include "PHY_IPhysicsController.h"
-bool KX_RayCast::RayTest(KX_IPhysicsController* ignore_controller, PHY_IPhysicsEnvironment* physics_environment, const MT_Point3& _frompoint, const MT_Point3& topoint, MT_Point3& result_point, MT_Vector3& result_normal, const KX_RayCast& callback)
+KX_RayCast::KX_RayCast(KX_IPhysicsController* ignoreController, bool faceNormal)
+ :PHY_IRayCastFilterCallback(dynamic_cast<PHY_IPhysicsController*>(ignoreController), faceNormal)
+{
+}
+
+void KX_RayCast::reportHit(PHY_RayCastResult* result)
+{
+ m_hitFound = true;
+ m_hitPoint.setValue((const float*)result->m_hitPoint);
+ m_hitNormal.setValue((const float*)result->m_hitNormal);
+ m_hitMesh = result->m_meshObject;
+ m_hitPolygon = result->m_polygon;
+}
+
+bool KX_RayCast::RayTest(PHY_IPhysicsEnvironment* physics_environment, const MT_Point3& _frompoint, const MT_Point3& topoint, KX_RayCast& callback)
{
// Loops over all physics objects between frompoint and topoint,
// calling callback.RayHit for each one.
@@ -48,51 +63,52 @@ bool KX_RayCast::RayTest(KX_IPhysicsController* ignore_controller, PHY_IPhysicsE
//
// returns true if an object was found, false if not.
MT_Point3 frompoint(_frompoint);
- const MT_Vector3 todir( (topoint - frompoint).normalized() );
+ const MT_Vector3 todir( (topoint - frompoint).safe_normalized() );
+ MT_Point3 prevpoint(_frompoint+todir*(-1.f));
PHY_IPhysicsController* hit_controller;
- PHY__Vector3 phy_pos;
- PHY__Vector3 phy_normal;
- while((hit_controller = physics_environment->rayTest(dynamic_cast<PHY_IPhysicsController*>(ignore_controller),
+ while((hit_controller = physics_environment->rayTest(callback,
frompoint.x(),frompoint.y(),frompoint.z(),
- topoint.x(),topoint.y(),topoint.z(),
- phy_pos[0],phy_pos[1],phy_pos[2],
- phy_normal[0],phy_normal[1],phy_normal[2])))
+ topoint.x(),topoint.y(),topoint.z())) != NULL)
{
- result_point = MT_Point3(phy_pos);
- result_normal = MT_Vector3(phy_normal);
KX_ClientObjectInfo* info = static_cast<KX_ClientObjectInfo*>(hit_controller->getNewClientInfo());
if (!info)
{
printf("no info!\n");
MT_assert(info && "Physics controller with no client object info");
- return false;
+ break;
}
- if (callback.RayHit(info, result_point, result_normal))
- return true;
-
-
- // skip past the object and keep tracing
- /* We add 0.01 of fudge, so that if the margin && radius == 0., we don't endless loop. */
- MT_Scalar marg = 0.01 + hit_controller->GetMargin();
- marg += 2.f * hit_controller->GetMargin();
+ // The biggest danger to to endless loop, prevent this by checking that the
+ // hit point always progresses along the ray direction..
+ prevpoint -= callback.m_hitPoint;
+ if (prevpoint.length2() < MT_EPSILON)
+ break;
+
+ if (callback.RayHit(info))
+ // caller may decide to stop the loop and still cancel the hit
+ return callback.m_hitFound;
+
+ // Skip past the object and keep tracing.
+ // Note that retrieving in a single shot multiple hit points would be possible
+ // but it would require some change in Bullet.
+ prevpoint = callback.m_hitPoint;
+ /* We add 0.001 of fudge, so that if the margin && radius == 0., we don't endless loop. */
+ MT_Scalar marg = 0.001 + hit_controller->GetMargin();
+ marg *= 2.f;
/* Calculate the other side of this object */
- PHY__Vector3 hitpos;
- hit_controller->getPosition(hitpos);
- MT_Point3 hitObjPos(hitpos);
-
- MT_Vector3 hitvector = hitObjPos - result_point;
- if (hitvector.dot(hitvector) > MT_EPSILON)
- {
- hitvector.normalize();
- marg *= 2.*todir.dot(hitvector);
- }
- frompoint = result_point + marg * todir;
+ MT_Scalar h = MT_abs(todir.dot(callback.m_hitNormal));
+ if (h <= 0.01)
+ // the normal is almost orthogonal to the ray direction, cannot compute the other side
+ break;
+ marg /= h;
+ frompoint = callback.m_hitPoint + marg * todir;
+ // verify that we are not passed the to point
+ if ((topoint - frompoint).dot(todir) < 0.f)
+ break;
}
-
- return hit_controller;
+ return false;
}
diff --git a/source/gameengine/Ketsji/KX_RayCast.h b/source/gameengine/Ketsji/KX_RayCast.h
index 607dabd8afc..c3084c997a1 100644
--- a/source/gameengine/Ketsji/KX_RayCast.h
+++ b/source/gameengine/Ketsji/KX_RayCast.h
@@ -30,12 +30,14 @@
#ifndef __KX_RAYCAST_H__
#define __KX_RAYCAST_H__
-class MT_Point3;
-class MT_Vector3;
-class KX_IPhysicsController;
-class PHY_IPhysicsEnvironment;
+#include "PHY_IPhysicsEnvironment.h"
+#include "PHY_IPhysicsController.h"
+#include "MT_Point3.h"
+#include "MT_Vector3.h"
+class RAS_MeshObject;
struct KX_ClientObjectInfo;
+class KX_IPhysicsController;
/**
* Defines a function for doing a ray cast.
@@ -49,17 +51,27 @@ struct KX_ClientObjectInfo;
*
* Returns true if a client was accepted, false if nothing found.
*/
-class KX_RayCast
+class KX_RayCast : public PHY_IRayCastFilterCallback
{
-protected:
- KX_RayCast() {};
public:
+ bool m_hitFound;
+ MT_Point3 m_hitPoint;
+ MT_Vector3 m_hitNormal;
+ const RAS_MeshObject* m_hitMesh;
+ int m_hitPolygon;
+
+ KX_RayCast(KX_IPhysicsController* ignoreController, bool faceNormal);
virtual ~KX_RayCast() {}
+ /**
+ * The physic environment returns the ray casting result through this function
+ */
+ virtual void reportHit(PHY_RayCastResult* result);
+
/** ray test callback.
* either override this in your class, or use a callback wrapper.
*/
- virtual bool RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal) const = 0;
+ virtual bool RayHit(KX_ClientObjectInfo* client) = 0;
/**
* Callback wrapper.
@@ -71,13 +83,11 @@ public:
/// Public interface.
/// Implement bool RayHit in your class to receive ray callbacks.
- static bool RayTest(KX_IPhysicsController* physics_controller,
+ static bool RayTest(
PHY_IPhysicsEnvironment* physics_environment,
- const MT_Point3& _frompoint,
+ const MT_Point3& frompoint,
const MT_Point3& topoint,
- MT_Point3& result_point,
- MT_Vector3& result_normal,
- const KX_RayCast& callback);
+ KX_RayCast& callback);
};
@@ -86,18 +96,32 @@ template<class T> class KX_RayCast::Callback : public KX_RayCast
T *self;
void *data;
public:
- Callback(T *_self, void *_data = NULL)
- : self(_self),
+ Callback(T *_self, KX_IPhysicsController* controller=NULL, void *_data = NULL, bool faceNormal=false)
+ : KX_RayCast(controller, faceNormal),
+ self(_self),
data(_data)
{
}
~Callback() {}
-
- virtual bool RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal) const
+
+ virtual bool RayHit(KX_ClientObjectInfo* client)
{
- return self->RayHit(client, hit_point, hit_normal, data);
+ return self->RayHit(client, this, data);
}
+
+ virtual bool needBroadphaseRayCast(PHY_IPhysicsController* controller)
+ {
+ KX_ClientObjectInfo* info = static_cast<KX_ClientObjectInfo*>(controller->getNewClientInfo());
+
+ if (!info)
+ {
+ MT_assert(info && "Physics controller with no client object info");
+ return false;
+ }
+ return self->NeedRayCast(info);
+ }
+
};
diff --git a/source/gameengine/Ketsji/KX_RayEventManager.cpp b/source/gameengine/Ketsji/KX_RayEventManager.cpp
index 4101c6b547e..1af29151adf 100644
--- a/source/gameengine/Ketsji/KX_RayEventManager.cpp
+++ b/source/gameengine/Ketsji/KX_RayEventManager.cpp
@@ -44,14 +44,9 @@ using namespace std;
void KX_RayEventManager::NextFrame()
{
- for (vector<class SCA_ISensor*>::const_iterator i= m_sensors.begin();!(i==m_sensors.end());i++)
+ for (set<class SCA_ISensor*>::const_iterator i= m_sensors.begin();!(i==m_sensors.end());i++)
{
- SCA_ISensor *sensor = *i;
- sensor->Activate(m_logicmgr, NULL);
+ (*i)->Activate(m_logicmgr, NULL);
}
}
-void KX_RayEventManager::RegisterSensor(SCA_ISensor* sensor)
-{
- m_sensors.push_back(sensor);
-};
diff --git a/source/gameengine/Ketsji/KX_RayEventManager.h b/source/gameengine/Ketsji/KX_RayEventManager.h
index 3630f9682b9..b816d4d5250 100644
--- a/source/gameengine/Ketsji/KX_RayEventManager.h
+++ b/source/gameengine/Ketsji/KX_RayEventManager.h
@@ -45,7 +45,6 @@ public:
m_logicmgr(logicmgr)
{}
virtual void NextFrame();
- virtual void RegisterSensor(SCA_ISensor* sensor);
};
#endif //__KX_RAYEVENTMGR
diff --git a/source/gameengine/Ketsji/KX_RaySensor.cpp b/source/gameengine/Ketsji/KX_RaySensor.cpp
index 4ccb02d34ec..e24fb773eac 100644
--- a/source/gameengine/Ketsji/KX_RaySensor.cpp
+++ b/source/gameengine/Ketsji/KX_RaySensor.cpp
@@ -51,6 +51,7 @@ KX_RaySensor::KX_RaySensor(class SCA_EventManager* eventmgr,
SCA_IObject* gameobj,
const STR_String& propname,
bool bFindMaterial,
+ bool bXRay,
double distance,
int axis,
KX_Scene* ketsjiScene,
@@ -58,19 +59,23 @@ KX_RaySensor::KX_RaySensor(class SCA_EventManager* eventmgr,
: SCA_ISensor(gameobj,eventmgr, T),
m_propertyname(propname),
m_bFindMaterial(bFindMaterial),
+ m_bXRay(bXRay),
m_distance(distance),
m_scene(ketsjiScene),
- m_bTriggered(false),
- m_axis(axis),
- m_rayHit(false),
- m_hitObject(NULL)
+ m_axis(axis)
{
-
+ Init();
}
-
+void KX_RaySensor::Init()
+{
+ m_bTriggered = (m_invert)?true:false;
+ m_rayHit = false;
+ m_hitObject = NULL;
+ m_reset = true;
+}
KX_RaySensor::~KX_RaySensor()
{
@@ -81,9 +86,10 @@ KX_RaySensor::~KX_RaySensor()
CValue* KX_RaySensor::GetReplica()
{
- CValue* replica = new KX_RaySensor(*this);
+ KX_RaySensor* replica = new KX_RaySensor(*this);
// this will copy properties and so on...
CValue::AddDataToReplica(replica);
+ replica->Init();
return replica;
}
@@ -100,16 +106,10 @@ bool KX_RaySensor::IsPositiveTrigger()
return result;
}
-bool KX_RaySensor::RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data)
+bool KX_RaySensor::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data)
{
KX_GameObject* hitKXObj = client->m_gameobject;
-
- if (client->m_type > KX_ClientObjectInfo::ACTOR)
- {
- // false hit
- return false;
- }
bool bFound = false;
if (m_propertyname.Length() == 0)
@@ -135,20 +135,48 @@ bool KX_RaySensor::RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_
{
m_rayHit = true;
m_hitObject = hitKXObj;
- m_hitPosition = hit_point;
- m_hitNormal = hit_normal;
+ m_hitPosition = result->m_hitPoint;
+ m_hitNormal = result->m_hitNormal;
}
-
+ // no multi-hit search yet
return true;
-
}
-
+/* this function is used to pre-filter the object before casting the ray on them.
+ This is useful for "X-Ray" option when we want to see "through" unwanted object.
+ */
+bool KX_RaySensor::NeedRayCast(KX_ClientObjectInfo* client)
+{
+ if (client->m_type > KX_ClientObjectInfo::ACTOR)
+ {
+ // Unknown type of object, skip it.
+ // Should not occur as the sensor objects are filtered in RayTest()
+ printf("Invalid client type %d found ray casting\n", client->m_type);
+ return false;
+ }
+ if (m_bXRay && m_propertyname.Length() != 0)
+ {
+ if (m_bFindMaterial)
+ {
+ // not quite correct: an object may have multiple material
+ // should check all the material and not only the first one
+ if (!client->m_auxilary_info || (m_propertyname != ((char*)client->m_auxilary_info)))
+ return false;
+ }
+ else
+ {
+ if (client->m_gameobject->GetProperty(m_propertyname) == NULL)
+ return false;
+ }
+ }
+ return true;
+}
bool KX_RaySensor::Evaluate(CValue* event)
{
bool result = false;
+ bool reset = m_reset && m_level;
m_rayHit = false;
m_hitObject = NULL;
m_hitPosition = MT_Vector3(0,0,0);
@@ -160,6 +188,7 @@ bool KX_RaySensor::Evaluate(CValue* event)
MT_Matrix3x3 invmat = matje.inverse();
MT_Vector3 todir;
+ m_reset = false;
switch (m_axis)
{
case 1: // X
@@ -209,8 +238,6 @@ bool KX_RaySensor::Evaluate(CValue* event)
m_rayDirection = todir;
MT_Point3 topoint = frompoint + (m_distance) * todir;
- MT_Point3 resultpoint;
- MT_Vector3 resultnormal;
PHY_IPhysicsEnvironment* pe = m_scene->GetPhysicsEnvironment();
if (!pe)
@@ -232,7 +259,8 @@ bool KX_RaySensor::Evaluate(CValue* event)
PHY_IPhysicsEnvironment* physics_environment = this->m_scene->GetPhysicsEnvironment();
- result = KX_RayCast::RayTest(spc, physics_environment, frompoint, topoint, resultpoint, resultnormal, KX_RayCast::Callback<KX_RaySensor>(this));
+ KX_RayCast::Callback<KX_RaySensor> callback(this, spc);
+ KX_RayCast::RayTest(physics_environment, frompoint, topoint, callback);
/* now pass this result to some controller */
@@ -259,9 +287,15 @@ bool KX_RaySensor::Evaluate(CValue* event)
// notify logicsystem that ray JUST left the Object
result = true;
}
+ else
+ {
+ result = false;
+ }
}
-
+ if (reset)
+ // force an event
+ result = true;
return result;
}
@@ -301,14 +335,14 @@ PyParentObject KX_RaySensor::Parents[] = {
};
PyMethodDef KX_RaySensor::Methods[] = {
- {"getHitObject",(PyCFunction) KX_RaySensor::sPyGetHitObject,METH_VARARGS, GetHitObject_doc},
- {"getHitPosition",(PyCFunction) KX_RaySensor::sPyGetHitPosition,METH_VARARGS, GetHitPosition_doc},
- {"getHitNormal",(PyCFunction) KX_RaySensor::sPyGetHitNormal,METH_VARARGS, GetHitNormal_doc},
- {"getRayDirection",(PyCFunction) KX_RaySensor::sPyGetRayDirection,METH_VARARGS, GetRayDirection_doc},
+ {"getHitObject",(PyCFunction) KX_RaySensor::sPyGetHitObject,METH_VARARGS, (PY_METHODCHAR)GetHitObject_doc},
+ {"getHitPosition",(PyCFunction) KX_RaySensor::sPyGetHitPosition,METH_VARARGS, (PY_METHODCHAR)GetHitPosition_doc},
+ {"getHitNormal",(PyCFunction) KX_RaySensor::sPyGetHitNormal,METH_VARARGS, (PY_METHODCHAR)GetHitNormal_doc},
+ {"getRayDirection",(PyCFunction) KX_RaySensor::sPyGetRayDirection,METH_VARARGS, (PY_METHODCHAR)GetRayDirection_doc},
{NULL,NULL} //Sentinel
};
-char KX_RaySensor::GetHitObject_doc[] =
+const char KX_RaySensor::GetHitObject_doc[] =
"getHitObject()\n"
"\tReturns the name of the object that was hit by this ray.\n";
PyObject* KX_RaySensor::PyGetHitObject(PyObject* self,
@@ -323,7 +357,7 @@ PyObject* KX_RaySensor::PyGetHitObject(PyObject* self,
}
-char KX_RaySensor::GetHitPosition_doc[] =
+const char KX_RaySensor::GetHitPosition_doc[] =
"getHitPosition()\n"
"\tReturns the position (in worldcoordinates) where the object was hit by this ray.\n";
PyObject* KX_RaySensor::PyGetHitPosition(PyObject* self,
@@ -343,7 +377,7 @@ PyObject* KX_RaySensor::PyGetHitPosition(PyObject* self,
}
-char KX_RaySensor::GetRayDirection_doc[] =
+const char KX_RaySensor::GetRayDirection_doc[] =
"getRayDirection()\n"
"\tReturns the direction from the ray (in worldcoordinates) .\n";
PyObject* KX_RaySensor::PyGetRayDirection(PyObject* self,
@@ -363,7 +397,7 @@ PyObject* KX_RaySensor::PyGetRayDirection(PyObject* self,
}
-char KX_RaySensor::GetHitNormal_doc[] =
+const char KX_RaySensor::GetHitNormal_doc[] =
"getHitNormal()\n"
"\tReturns the normal (in worldcoordinates) of the object at the location where the object was hit by this ray.\n";
PyObject* KX_RaySensor::PyGetHitNormal(PyObject* self,
diff --git a/source/gameengine/Ketsji/KX_RaySensor.h b/source/gameengine/Ketsji/KX_RaySensor.h
index 8a317ffaa07..02a755fedc1 100644
--- a/source/gameengine/Ketsji/KX_RaySensor.h
+++ b/source/gameengine/Ketsji/KX_RaySensor.h
@@ -36,12 +36,14 @@
#include "MT_Point3.h"
struct KX_ClientObjectInfo;
+class KX_RayCast;
class KX_RaySensor : public SCA_ISensor
{
Py_Header;
STR_String m_propertyname;
bool m_bFindMaterial;
+ bool m_bXRay;
double m_distance;
class KX_Scene* m_scene;
bool m_bTriggered;
@@ -56,7 +58,8 @@ public:
KX_RaySensor(class SCA_EventManager* eventmgr,
SCA_IObject* gameobj,
const STR_String& propname,
- bool fFindMaterial,
+ bool bFindMaterial,
+ bool bXRay,
double distance,
int axis,
class KX_Scene* ketsjiScene,
@@ -66,8 +69,10 @@ public:
virtual bool Evaluate(CValue* event);
virtual bool IsPositiveTrigger();
+ virtual void Init();
- bool RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data);
+ bool RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data);
+ bool NeedRayCast(KX_ClientObjectInfo* client);
KX_PYMETHOD_DOC(KX_RaySensor,GetHitObject);
KX_PYMETHOD_DOC(KX_RaySensor,GetHitPosition);
diff --git a/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp b/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp
index b31fe16d05d..5777f54b799 100644
--- a/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp
+++ b/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp
@@ -39,6 +39,8 @@
#include "KX_GameObject.h"
#include "KX_IPhysicsController.h"
+#include "PyObjectPlus.h"
+
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
@@ -48,19 +50,28 @@
/* ------------------------------------------------------------------------- */
KX_SCA_AddObjectActuator::KX_SCA_AddObjectActuator(SCA_IObject *gameobj,
- CValue* original,
+ SCA_IObject *original,
int time,
SCA_IScene* scene,
const MT_Vector3& linvel,
- bool local,
+ bool linv_local,
+ const MT_Vector3& angvel,
+ bool angv_local,
PyTypeObject* T)
:
SCA_IActuator(gameobj, T),
m_OriginalObject(original),
m_scene(scene),
+
m_linear_velocity(linvel),
- m_localFlag(local)
+ m_localLinvFlag(linv_local),
+
+ m_angular_velocity(angvel),
+ m_localAngvFlag(angv_local)
{
+ if (m_OriginalObject)
+ m_OriginalObject->RegisterActuator(this);
+
m_lastCreatedObject = NULL;
m_timeProp = time;
}
@@ -69,6 +80,8 @@ KX_SCA_AddObjectActuator::KX_SCA_AddObjectActuator(SCA_IObject *gameobj,
KX_SCA_AddObjectActuator::~KX_SCA_AddObjectActuator()
{
+ if (m_OriginalObject)
+ m_OriginalObject->UnregisterActuator(this);
if (m_lastCreatedObject)
m_lastCreatedObject->Release();
}
@@ -108,12 +121,40 @@ CValue* KX_SCA_AddObjectActuator::GetReplica()
// this will copy properties and so on...
replica->ProcessReplica();
- replica->m_lastCreatedObject=NULL;
CValue::AddDataToReplica(replica);
return replica;
}
+void KX_SCA_AddObjectActuator::ProcessReplica()
+{
+ if (m_OriginalObject)
+ m_OriginalObject->RegisterActuator(this);
+ m_lastCreatedObject=NULL;
+ SCA_IActuator::ProcessReplica();
+}
+
+bool KX_SCA_AddObjectActuator::UnlinkObject(SCA_IObject* clientobj)
+{
+ if (clientobj == m_OriginalObject)
+ {
+ // this object is being deleted, we cannot continue to track it.
+ m_OriginalObject = NULL;
+ return true;
+ }
+ return false;
+}
+
+void KX_SCA_AddObjectActuator::Relink(GEN_Map<GEN_HashedPtr, void*> *obj_map)
+{
+ void **h_obj = (*obj_map)[m_OriginalObject];
+ if (h_obj) {
+ if (m_OriginalObject)
+ m_OriginalObject->UnregisterActuator(this);
+ m_OriginalObject = (SCA_IObject*)(*h_obj);
+ m_OriginalObject->RegisterActuator(this);
+ }
+}
/* ------------------------------------------------------------------------- */
@@ -147,14 +188,16 @@ PyParentObject KX_SCA_AddObjectActuator::Parents[] = {
NULL
};
PyMethodDef KX_SCA_AddObjectActuator::Methods[] = {
- {"setObject", (PyCFunction) KX_SCA_AddObjectActuator::sPySetObject, METH_VARARGS, SetObject_doc},
- {"setTime", (PyCFunction) KX_SCA_AddObjectActuator::sPySetTime, METH_VARARGS, SetTime_doc},
- {"getObject", (PyCFunction) KX_SCA_AddObjectActuator::sPyGetObject, METH_VARARGS, GetObject_doc},
- {"getTime", (PyCFunction) KX_SCA_AddObjectActuator::sPyGetTime, METH_VARARGS, GetTime_doc},
- {"getLinearVelocity", (PyCFunction) KX_SCA_AddObjectActuator::sPyGetLinearVelocity, METH_VARARGS, GetLinearVelocity_doc},
- {"setLinearVelocity", (PyCFunction) KX_SCA_AddObjectActuator::sPySetLinearVelocity, METH_VARARGS, SetLinearVelocity_doc},
- {"getLastCreatedObject", (PyCFunction) KX_SCA_AddObjectActuator::sPyGetLastCreatedObject, METH_VARARGS,"getLastCreatedObject() : get the object handle to the last created object\n"},
- {"instantAddObject", (PyCFunction) KX_SCA_AddObjectActuator::sPyInstantAddObject, METH_VARARGS,"instantAddObject() : immediately add object without delay\n"},
+ {"setObject", (PyCFunction) KX_SCA_AddObjectActuator::sPySetObject, METH_O, (PY_METHODCHAR)SetObject_doc},
+ {"setTime", (PyCFunction) KX_SCA_AddObjectActuator::sPySetTime, METH_O, (PY_METHODCHAR)SetTime_doc},
+ {"getObject", (PyCFunction) KX_SCA_AddObjectActuator::sPyGetObject, METH_VARARGS, (PY_METHODCHAR)GetObject_doc},
+ {"getTime", (PyCFunction) KX_SCA_AddObjectActuator::sPyGetTime, METH_NOARGS, (PY_METHODCHAR)GetTime_doc},
+ {"getLinearVelocity", (PyCFunction) KX_SCA_AddObjectActuator::sPyGetLinearVelocity, METH_NOARGS, (PY_METHODCHAR)GetLinearVelocity_doc},
+ {"setLinearVelocity", (PyCFunction) KX_SCA_AddObjectActuator::sPySetLinearVelocity, METH_VARARGS, (PY_METHODCHAR)SetLinearVelocity_doc},
+ {"getAngularVelocity", (PyCFunction) KX_SCA_AddObjectActuator::sPyGetAngularVelocity, METH_NOARGS, (PY_METHODCHAR)GetAngularVelocity_doc},
+ {"setAngularVelocity", (PyCFunction) KX_SCA_AddObjectActuator::sPySetAngularVelocity, METH_VARARGS, (PY_METHODCHAR)SetAngularVelocity_doc},
+ {"getLastCreatedObject", (PyCFunction) KX_SCA_AddObjectActuator::sPyGetLastCreatedObject, METH_NOARGS,"getLastCreatedObject() : get the object handle to the last created object\n"},
+ {"instantAddObject", (PyCFunction) KX_SCA_AddObjectActuator::sPyInstantAddObject, METH_NOARGS,"instantAddObject() : immediately add object without delay\n"},
{NULL,NULL} //Sentinel
};
@@ -166,114 +209,101 @@ PyObject* KX_SCA_AddObjectActuator::_getattr(const STR_String& attr)
}
/* 1. setObject */
-char KX_SCA_AddObjectActuator::SetObject_doc[] =
-"setObject(name)\n"
-"\t- name: string\n"
+const char KX_SCA_AddObjectActuator::SetObject_doc[] =
+"setObject(object)\n"
+"\t- object: KX_GameObject, string or None\n"
"\tSets the object that will be added. There has to be an object\n"
"\tof this name. If not, this function does nothing.\n";
-
-
-
-PyObject* KX_SCA_AddObjectActuator::PySetObject(PyObject* self,
- PyObject* args,
- PyObject* kwds)
-{
- PyObject* gameobj;
- if (PyArg_ParseTuple(args, "O!", &KX_GameObject::Type, &gameobj))
- {
- m_OriginalObject = (CValue*)gameobj;
- Py_Return;
- }
- PyErr_Clear();
+PyObject* KX_SCA_AddObjectActuator::PySetObject(PyObject* self, PyObject* value)
+{
+ KX_GameObject *gameobj;
- char* objectname;
- if (PyArg_ParseTuple(args, "s", &objectname))
- {
- m_OriginalObject= (CValue*)SCA_ILogicBrick::m_sCurrentLogicManager->GetGameObjectByName(STR_String(objectname));;
-
- Py_Return;
- }
+ if (!ConvertPythonToGameObject(value, &gameobj, true))
+ return NULL; // ConvertPythonToGameObject sets the error
+
+ if (m_OriginalObject != NULL)
+ m_OriginalObject->UnregisterActuator(this);
+
+ m_OriginalObject = (SCA_IObject*)gameobj;
+ if (m_OriginalObject)
+ m_OriginalObject->RegisterActuator(this);
- return NULL;
+ Py_RETURN_NONE;
}
/* 2. setTime */
-char KX_SCA_AddObjectActuator::SetTime_doc[] =
+const char KX_SCA_AddObjectActuator::SetTime_doc[] =
"setTime(duration)\n"
"\t- duration: integer\n"
"\tSets the lifetime of the object that will be added, in frames. \n"
"\tIf the duration is negative, it is set to 0.\n";
-PyObject* KX_SCA_AddObjectActuator::PySetTime(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_SCA_AddObjectActuator::PySetTime(PyObject* self, PyObject* value)
{
- int deltatime;
-
- if (!PyArg_ParseTuple(args, "i", &deltatime))
+ int deltatime = PyInt_AsLong(value);
+ if (deltatime==-1 && PyErr_Occurred()) {
+ PyErr_SetString(PyExc_TypeError, "expected an int");
return NULL;
+ }
m_timeProp = deltatime;
if (m_timeProp < 0) m_timeProp = 0;
- Py_Return;
+ Py_RETURN_NONE;
}
/* 3. getTime */
-char KX_SCA_AddObjectActuator::GetTime_doc[] =
+const char KX_SCA_AddObjectActuator::GetTime_doc[] =
"GetTime()\n"
"\tReturns the lifetime of the object that will be added.\n";
-PyObject* KX_SCA_AddObjectActuator::PyGetTime(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_SCA_AddObjectActuator::PyGetTime(PyObject* self)
{
return PyInt_FromLong(m_timeProp);
}
/* 4. getObject */
-char KX_SCA_AddObjectActuator::GetObject_doc[] =
-"getObject()\n"
+const char KX_SCA_AddObjectActuator::GetObject_doc[] =
+"getObject(name_only = 1)\n"
+"name_only - optional arg, when true will return the KX_GameObject rather then its name\n"
"\tReturns the name of the object that will be added.\n";
-
-
-
-PyObject* KX_SCA_AddObjectActuator::PyGetObject(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_SCA_AddObjectActuator::PyGetObject(PyObject* self, PyObject* args)
{
+ int ret_name_only = 1;
+ if (!PyArg_ParseTuple(args, "|i", &ret_name_only))
+ return NULL;
+
if (!m_OriginalObject)
- Py_Return;
-
- return PyString_FromString(m_OriginalObject->GetName());
+ Py_RETURN_NONE;
+
+ if (ret_name_only)
+ return PyString_FromString(m_OriginalObject->GetName());
+ else
+ return m_OriginalObject->AddRef();
}
/* 5. getLinearVelocity */
-char KX_SCA_AddObjectActuator::GetLinearVelocity_doc[] =
+const char KX_SCA_AddObjectActuator::GetLinearVelocity_doc[] =
"GetLinearVelocity()\n"
"\tReturns the linear velocity that will be assigned to \n"
"\tthe created object.\n";
-
-
-PyObject* KX_SCA_AddObjectActuator::PyGetLinearVelocity(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_SCA_AddObjectActuator::PyGetLinearVelocity(PyObject* self)
{
PyObject *retVal = PyList_New(3);
- PyList_SetItem(retVal, 0, PyFloat_FromDouble(m_linear_velocity[0]));
- PyList_SetItem(retVal, 1, PyFloat_FromDouble(m_linear_velocity[1]));
- PyList_SetItem(retVal, 2, PyFloat_FromDouble(m_linear_velocity[2]));
+ PyList_SET_ITEM(retVal, 0, PyFloat_FromDouble(m_linear_velocity[0]));
+ PyList_SET_ITEM(retVal, 1, PyFloat_FromDouble(m_linear_velocity[1]));
+ PyList_SET_ITEM(retVal, 2, PyFloat_FromDouble(m_linear_velocity[2]));
return retVal;
}
@@ -281,17 +311,15 @@ PyObject* KX_SCA_AddObjectActuator::PyGetLinearVelocity(PyObject* self,
/* 6. setLinearVelocity */
-char KX_SCA_AddObjectActuator::SetLinearVelocity_doc[] =
+const char KX_SCA_AddObjectActuator::SetLinearVelocity_doc[] =
"setLinearVelocity(vx, vy, vz)\n"
"\t- vx: float\n"
"\t- vy: float\n"
"\t- vz: float\n"
+"\t- local: bool\n"
"\tAssign this velocity to the created object. \n";
-
-PyObject* KX_SCA_AddObjectActuator::PySetLinearVelocity(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_SCA_AddObjectActuator::PySetLinearVelocity(PyObject* self, PyObject* args)
{
float vecArg[3];
@@ -299,7 +327,46 @@ PyObject* KX_SCA_AddObjectActuator::PySetLinearVelocity(PyObject* self,
return NULL;
m_linear_velocity.setValue(vecArg);
- Py_Return;
+ Py_RETURN_NONE;
+}
+
+/* 7. getAngularVelocity */
+const char KX_SCA_AddObjectActuator::GetAngularVelocity_doc[] =
+"GetAngularVelocity()\n"
+"\tReturns the angular velocity that will be assigned to \n"
+"\tthe created object.\n";
+
+PyObject* KX_SCA_AddObjectActuator::PyGetAngularVelocity(PyObject* self)
+{
+ PyObject *retVal = PyList_New(3);
+
+ PyList_SET_ITEM(retVal, 0, PyFloat_FromDouble(m_angular_velocity[0]));
+ PyList_SET_ITEM(retVal, 1, PyFloat_FromDouble(m_angular_velocity[1]));
+ PyList_SET_ITEM(retVal, 2, PyFloat_FromDouble(m_angular_velocity[2]));
+
+ return retVal;
+}
+
+
+
+/* 8. setAngularVelocity */
+const char KX_SCA_AddObjectActuator::SetAngularVelocity_doc[] =
+"setAngularVelocity(vx, vy, vz)\n"
+"\t- vx: float\n"
+"\t- vy: float\n"
+"\t- vz: float\n"
+"\t- local: bool\n"
+"\tAssign this angular velocity to the created object. \n";
+
+PyObject* KX_SCA_AddObjectActuator::PySetAngularVelocity(PyObject* self, PyObject* args)
+{
+
+ float vecArg[3];
+ if (!PyArg_ParseTuple(args, "fff", &vecArg[0], &vecArg[1], &vecArg[2]))
+ return NULL;
+
+ m_angular_velocity.setValue(vecArg);
+ Py_RETURN_NONE;
}
void KX_SCA_AddObjectActuator::InstantAddObject()
@@ -310,8 +377,9 @@ void KX_SCA_AddObjectActuator::InstantAddObject()
// Now it needs to be added to the current scene.
SCA_IObject* replica = m_scene->AddReplicaObject(m_OriginalObject,GetParent(),m_timeProp );
KX_GameObject * game_obj = static_cast<KX_GameObject *>(replica);
- game_obj->setLinearVelocity(m_linear_velocity,m_localFlag);
- game_obj->ResolveCombinedVelocities(m_linear_velocity, MT_Vector3(0., 0., 0.), m_localFlag, false);
+ game_obj->setLinearVelocity(m_linear_velocity,m_localLinvFlag);
+ game_obj->setAngularVelocity(m_angular_velocity,m_localAngvFlag);
+ game_obj->ResolveCombinedVelocities(m_linear_velocity, m_angular_velocity, m_localLinvFlag, m_localAngvFlag);
// keep a copy of the last object, to allow python scripters to change it
if (m_lastCreatedObject)
@@ -323,36 +391,37 @@ void KX_SCA_AddObjectActuator::InstantAddObject()
m_lastCreatedObject = replica;
m_lastCreatedObject->AddRef();
+ // finished using replica? then release it
+ replica->Release();
}
}
-PyObject* KX_SCA_AddObjectActuator::PyInstantAddObject(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_SCA_AddObjectActuator::PyInstantAddObject(PyObject* self)
{
InstantAddObject();
- Py_Return;
+ Py_RETURN_NONE;
}
/* 7. GetLastCreatedObject */
-char KX_SCA_AddObjectActuator::GetLastCreatedObject_doc[] =
+const char KX_SCA_AddObjectActuator::GetLastCreatedObject_doc[] =
"getLastCreatedObject()\n"
"\tReturn the last created object. \n";
-PyObject* KX_SCA_AddObjectActuator::PyGetLastCreatedObject(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_SCA_AddObjectActuator::PyGetLastCreatedObject(PyObject* self)
{
SCA_IObject* result = this->GetLastCreatedObject();
- if (result)
+
+ // if result->GetSGNode() is NULL
+ // it means the object has ended, The BGE python api crashes in many places if the object is returned.
+ if (result && (static_cast<KX_GameObject *>(result))->GetSGNode())
{
result->AddRef();
return result;
}
// don't return NULL to python anymore, it gives trouble in the scripts
- Py_Return;
+ Py_RETURN_NONE;
}
diff --git a/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h b/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h
index 2126a646303..278d4180284 100644
--- a/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h
+++ b/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h
@@ -53,16 +53,20 @@ class KX_SCA_AddObjectActuator : public SCA_IActuator
int m_timeProp;
/// Original object reference (object to replicate)
- CValue* m_OriginalObject;
+ SCA_IObject* m_OriginalObject;
/// Object will be added to the following scene
SCA_IScene* m_scene;
/// Linear velocity upon creation of the object.
MT_Vector3 m_linear_velocity;
+
+ /// Angular velocity upon creation of the object.
+ MT_Vector3 m_angular_velocity;
/// Apply the velocity locally
- bool m_localFlag;
+ bool m_localLinvFlag;
+ bool m_localAngvFlag;
SCA_IObject* m_lastCreatedObject;
@@ -75,11 +79,13 @@ public:
KX_SCA_AddObjectActuator(
SCA_IObject *gameobj,
- CValue* original,
+ SCA_IObject *original,
int time,
SCA_IScene* scene,
const MT_Vector3& linvel,
- bool local,
+ bool linv_local,
+ const MT_Vector3& angvel,
+ bool angv_local,
PyTypeObject* T=&Type
);
@@ -89,6 +95,15 @@ public:
GetReplica(
) ;
+ virtual void
+ ProcessReplica();
+
+ virtual bool
+ UnlinkObject(SCA_IObject* clientobj);
+
+ virtual void
+ Relink(GEN_Map<GEN_HashedPtr, void*> *obj_map);
+
virtual bool
Update();
@@ -104,21 +119,25 @@ public:
void InstantAddObject();
/* 1. setObject */
- KX_PYMETHOD_DOC(KX_SCA_AddObjectActuator,SetObject);
+ KX_PYMETHOD_DOC_O(KX_SCA_AddObjectActuator,SetObject);
/* 2. setTime */
- KX_PYMETHOD_DOC(KX_SCA_AddObjectActuator,SetTime);
+ KX_PYMETHOD_DOC_O(KX_SCA_AddObjectActuator,SetTime);
/* 3. getTime */
- KX_PYMETHOD_DOC(KX_SCA_AddObjectActuator,GetTime);
+ KX_PYMETHOD_DOC_NOARGS(KX_SCA_AddObjectActuator,GetTime);
/* 4. getObject */
- KX_PYMETHOD_DOC(KX_SCA_AddObjectActuator,GetObject);
+ KX_PYMETHOD_DOC_VARARGS(KX_SCA_AddObjectActuator,GetObject);
/* 5. getLinearVelocity */
- KX_PYMETHOD_DOC(KX_SCA_AddObjectActuator,GetLinearVelocity);
+ KX_PYMETHOD_DOC_NOARGS(KX_SCA_AddObjectActuator,GetLinearVelocity);
/* 6. setLinearVelocity */
- KX_PYMETHOD_DOC(KX_SCA_AddObjectActuator,SetLinearVelocity);
- /* 7. getLastCreatedObject */
- KX_PYMETHOD_DOC(KX_SCA_AddObjectActuator,GetLastCreatedObject);
- /* 8. instantAddObject*/
- KX_PYMETHOD_DOC(KX_SCA_AddObjectActuator,InstantAddObject);
+ KX_PYMETHOD_DOC_VARARGS(KX_SCA_AddObjectActuator,SetLinearVelocity);
+ /* 7. getAngularVelocity */
+ KX_PYMETHOD_DOC_NOARGS(KX_SCA_AddObjectActuator,GetAngularVelocity);
+ /* 8. setAngularVelocity */
+ KX_PYMETHOD_DOC_VARARGS(KX_SCA_AddObjectActuator,SetAngularVelocity);
+ /* 9. getLastCreatedObject */
+ KX_PYMETHOD_DOC_NOARGS(KX_SCA_AddObjectActuator,GetLastCreatedObject);
+ /* 10. instantAddObject*/
+ KX_PYMETHOD_DOC_NOARGS(KX_SCA_AddObjectActuator,InstantAddObject);
}; /* end of class KX_SCA_AddObjectActuator : public KX_EditObjectActuator */
diff --git a/source/gameengine/Ketsji/KX_SCA_DynamicActuator.cpp b/source/gameengine/Ketsji/KX_SCA_DynamicActuator.cpp
new file mode 100644
index 00000000000..d44ab477749
--- /dev/null
+++ b/source/gameengine/Ketsji/KX_SCA_DynamicActuator.cpp
@@ -0,0 +1,206 @@
+//
+// Adjust dynamics settins for this object
+//
+// $Id$
+//
+// ***** BEGIN GPL LICENSE BLOCK *****
+//
+// This program is free software; you can redistribute it and/or
+// modify it under the terms of the GNU General Public License
+// as published by the Free Software Foundation; either version 2
+// of the License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program; if not, write to the Free Software Foundation,
+// Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+//
+// The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+// All rights reserved.
+//
+// The Original Code is: all of this file.
+//
+// Contributor(s): none yet.
+//
+// ***** END GPL LICENSE BLOCK *****
+
+//
+// Previously existed as:
+
+// \source\gameengine\GameLogic\SCA_DynamicActuator.cpp
+
+// Please look here for revision history.
+
+#include "KX_SCA_DynamicActuator.h"
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/* ------------------------------------------------------------------------- */
+/* Python functions */
+/* ------------------------------------------------------------------------- */
+
+/* Integration hooks ------------------------------------------------------- */
+
+ PyTypeObject
+
+KX_SCA_DynamicActuator::
+
+Type = {
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0,
+ "KX_SCA_DynamicActuator",
+ sizeof(KX_SCA_DynamicActuator),
+ 0,
+ PyDestructor,
+ 0,
+ __getattr,
+ __setattr,
+ 0,
+ __repr,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+};
+
+PyParentObject KX_SCA_DynamicActuator::Parents[] = {
+ &KX_SCA_DynamicActuator::Type,
+ &SCA_IActuator::Type,
+ &SCA_ILogicBrick::Type,
+ &CValue::Type,
+ NULL
+};
+
+
+PyMethodDef KX_SCA_DynamicActuator::Methods[] = {
+ KX_PYMETHODTABLE(KX_SCA_DynamicActuator, setOperation),
+ KX_PYMETHODTABLE(KX_SCA_DynamicActuator, getOperation),
+ {NULL,NULL} //Sentinel
+};
+
+
+
+PyObject* KX_SCA_DynamicActuator::_getattr(const STR_String& attr)
+{
+ _getattr_up(SCA_IActuator);
+}
+
+
+
+/* 1. setOperation */
+KX_PYMETHODDEF_DOC(KX_SCA_DynamicActuator, setOperation,
+"setOperation(operation?)\n"
+"\t - operation? : type of dynamic operation\n"
+"\t 0 = restore dynamics\n"
+"\t 1 = disable dynamics\n"
+"\t 2 = enable rigid body\n"
+"\t 3 = disable rigid body\n"
+"Change the dynamic status of the parent object.\n")
+{
+ int dyn_operation;
+
+ if (!PyArg_ParseTuple(args, "i", &dyn_operation))
+ {
+ return NULL;
+ }
+ if (dyn_operation <0 || dyn_operation>3) {
+ PyErr_SetString(PyExc_IndexError, "Dynamic Actuator's setOperation() range must be between 0 and 3");
+ return NULL;
+ }
+ m_dyn_operation= dyn_operation;
+ Py_Return;
+}
+
+KX_PYMETHODDEF_DOC(KX_SCA_DynamicActuator, getOperation,
+"getOperation() -> integer\n"
+"Returns the operation type of this actuator.\n"
+)
+{
+ return PyInt_FromLong((long)m_dyn_operation);
+}
+
+
+/* ------------------------------------------------------------------------- */
+/* Native functions */
+/* ------------------------------------------------------------------------- */
+
+KX_SCA_DynamicActuator::KX_SCA_DynamicActuator(SCA_IObject *gameobj,
+ short dyn_operation,
+ PyTypeObject* T) :
+
+ SCA_IActuator(gameobj, T),
+ m_dyn_operation(dyn_operation)
+{
+} /* End of constructor */
+
+
+KX_SCA_DynamicActuator::~KX_SCA_DynamicActuator()
+{
+ // there's nothing to be done here, really....
+} /* end of destructor */
+
+
+
+bool KX_SCA_DynamicActuator::Update()
+{
+ // bool result = false; /*unused*/
+ KX_GameObject *obj = (KX_GameObject*) GetParent();
+ bool bNegativeEvent = IsNegativeEvent();
+ KX_IPhysicsController* controller;
+ RemoveAllEvents();
+
+ if (bNegativeEvent)
+ return false; // do nothing on negative events
+
+ if (!obj)
+ return false; // object not accessible, shouldnt happen
+ controller = obj->GetPhysicsController();
+ if (!controller)
+ return false; // no physic object
+
+ switch (m_dyn_operation)
+ {
+ case 0:
+ obj->RestoreDynamics();
+ break;
+ case 1:
+ obj->SuspendDynamics();
+ break;
+ case 2:
+ controller->setRigidBody(true);
+ break;
+ case 3:
+ controller->setRigidBody(false);
+ break;
+ }
+
+ return false;
+}
+
+
+
+CValue* KX_SCA_DynamicActuator::GetReplica()
+{
+ KX_SCA_DynamicActuator* replica =
+ new KX_SCA_DynamicActuator(*this);
+
+ if (replica == NULL)
+ return NULL;
+
+ replica->ProcessReplica();
+
+ // this will copy properties and so on...
+ CValue::AddDataToReplica(replica);
+
+ return replica;
+};
+
+
+/* eof */
diff --git a/source/gameengine/Ketsji/KX_SCA_DynamicActuator.h b/source/gameengine/Ketsji/KX_SCA_DynamicActuator.h
new file mode 100644
index 00000000000..b47c3a511d9
--- /dev/null
+++ b/source/gameengine/Ketsji/KX_SCA_DynamicActuator.h
@@ -0,0 +1,76 @@
+//
+// Add object to the game world on action of this actuator
+//
+// $Id$
+//
+// ***** BEGIN GPL LICENSE BLOCK *****
+//
+// This program is free software; you can redistribute it and/or
+// modify it under the terms of the GNU General Public License
+// as published by the Free Software Foundation; either version 2
+// of the License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program; if not, write to the Free Software Foundation,
+// Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+//
+// The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+// All rights reserved.
+//
+// The Original Code is: all of this file.
+//
+// Contributor(s): Campbell Barton
+//
+// ***** END GPL LICENSE BLOCK *****
+//
+
+#ifndef __KX_SCA_DYNAMICACTUATOR
+#define __KX_SCA_DYNAMICACTUATOR
+
+#include "SCA_IActuator.h"
+#include "SCA_PropertyActuator.h"
+#include "SCA_LogicManager.h"
+
+#include "KX_GameObject.h"
+#include "KX_IPhysicsController.h"
+
+class KX_SCA_DynamicActuator : public SCA_IActuator
+{
+ Py_Header;
+
+ // dynamics operation to apply to the game object
+ short m_dyn_operation;
+ public:
+ KX_SCA_DynamicActuator(
+ SCA_IObject* gameobj,
+ short dyn_operation,
+ PyTypeObject* T=&Type
+ );
+
+ ~KX_SCA_DynamicActuator(
+ );
+
+ CValue*
+ GetReplica(
+ );
+
+ virtual bool
+ Update();
+
+ virtual PyObject*
+ _getattr(
+ const STR_String& attr
+ );
+
+ /* 1. setOperation */
+ KX_PYMETHOD_DOC(KX_SCA_DynamicActuator,setOperation);
+ KX_PYMETHOD_DOC(KX_SCA_DynamicActuator,getOperation);
+
+};
+
+#endif
diff --git a/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp b/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp
index 630df2d21d9..261d9ec8f0c 100644
--- a/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp
+++ b/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp
@@ -37,6 +37,8 @@
#include "KX_SCA_ReplaceMeshActuator.h"
+#include "PyObjectPlus.h"
+
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
@@ -80,7 +82,7 @@ PyParentObject KX_SCA_ReplaceMeshActuator::Parents[] = {
PyMethodDef KX_SCA_ReplaceMeshActuator::Methods[] = {
- {"setMesh", (PyCFunction) KX_SCA_ReplaceMeshActuator::sPySetMesh, METH_VARARGS, SetMesh_doc},
+ {"setMesh", (PyCFunction) KX_SCA_ReplaceMeshActuator::sPySetMesh, METH_O, (PY_METHODCHAR)SetMesh_doc},
KX_PYMETHODTABLE(KX_SCA_ReplaceMeshActuator, instantReplaceMesh),
KX_PYMETHODTABLE(KX_SCA_ReplaceMeshActuator, getMesh),
@@ -97,30 +99,31 @@ PyObject* KX_SCA_ReplaceMeshActuator::_getattr(const STR_String& attr)
/* 1. setMesh */
-char KX_SCA_ReplaceMeshActuator::SetMesh_doc[] =
+const char KX_SCA_ReplaceMeshActuator::SetMesh_doc[] =
"setMesh(name)\n"
- "\t- name: string\n"
+ "\t- name: string or None\n"
"\tSet the mesh that will be substituted for the current one.\n";
-PyObject* KX_SCA_ReplaceMeshActuator::PySetMesh(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+PyObject* KX_SCA_ReplaceMeshActuator::PySetMesh(PyObject* self, PyObject* value)
{
- char* meshname;
-
- if (!PyArg_ParseTuple(args, "s", &meshname))
- {
- return NULL;
- }
-
- void* mesh = SCA_ILogicBrick::m_sCurrentLogicManager->GetMeshByName(STR_String(meshname));
-
- if (mesh) {
+ if (value == Py_None) {
+ m_mesh = NULL;
+ } else {
+ char* meshname = PyString_AsString(value);
+ if (!meshname) {
+ PyErr_SetString(PyExc_ValueError, "Expected the name of a mesh or None");
+ return NULL;
+ }
+ void* mesh = SCA_ILogicBrick::m_sCurrentLogicManager->GetMeshByName(STR_String(meshname));
+
+ if (mesh==NULL) {
+ PyErr_SetString(PyExc_ValueError, "The mesh name given does not exist");
+ return NULL;
+ }
m_mesh= (class RAS_MeshObject*)mesh;
- Py_Return;
}
- return NULL;
+ Py_RETURN_NONE;
}
KX_PYMETHODDEF_DOC(KX_SCA_ReplaceMeshActuator, getMesh,
@@ -129,7 +132,7 @@ KX_PYMETHODDEF_DOC(KX_SCA_ReplaceMeshActuator, getMesh,
)
{
if (!m_mesh)
- Py_Return;
+ Py_RETURN_NONE;
return PyString_FromString(const_cast<char *>(m_mesh->GetName().ReadPtr()));
}
@@ -139,7 +142,7 @@ KX_PYMETHODDEF_DOC(KX_SCA_ReplaceMeshActuator, instantReplaceMesh,
"instantReplaceMesh() : immediately replace mesh without delay\n")
{
InstantReplaceMesh();
- Py_Return;
+ Py_RETURN_NONE;
}
/* ------------------------------------------------------------------------- */
diff --git a/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h b/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h
index 5ba0a099b14..1da154cc222 100644
--- a/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h
+++ b/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h
@@ -76,7 +76,7 @@ class KX_SCA_ReplaceMeshActuator : public SCA_IActuator
void InstantReplaceMesh();
/* 1. setMesh */
- KX_PYMETHOD_DOC(KX_SCA_ReplaceMeshActuator,SetMesh);
+ KX_PYMETHOD_DOC_O(KX_SCA_ReplaceMeshActuator,SetMesh);
KX_PYMETHOD_DOC(KX_SCA_ReplaceMeshActuator,getMesh);
KX_PYMETHOD_DOC(KX_SCA_ReplaceMeshActuator,instantReplaceMesh);
diff --git a/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp b/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp
index f085ff435dc..d651373869a 100644
--- a/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp
+++ b/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp
@@ -78,7 +78,7 @@ UpdateChildCoordinates(
if (parent)
{
- const BL_ArmatureObject *armature = (const BL_ArmatureObject*)(parent->GetSGClientObject());
+ BL_ArmatureObject *armature = (BL_ArmatureObject*)(parent->GetSGClientObject());
if (armature)
{
MT_Matrix4x4 parent_matrix;
diff --git a/source/gameengine/Ketsji/KX_SG_NodeRelationships.h b/source/gameengine/Ketsji/KX_SG_NodeRelationships.h
index d83fb79ee25..faa650106c8 100644
--- a/source/gameengine/Ketsji/KX_SG_NodeRelationships.h
+++ b/source/gameengine/Ketsji/KX_SG_NodeRelationships.h
@@ -129,6 +129,12 @@ public :
~KX_VertexParentRelation(
);
+ bool
+ IsVertexRelation(
+ ) {
+ return true;
+ }
+
private :
KX_VertexParentRelation(
@@ -171,8 +177,23 @@ public :
NewCopy(
);
+ MT_Scalar
+ GetTimeOffset(
+ ) { return m_relax; }
+
+ void
+ SetTimeOffset(
+ MT_Scalar relaxation
+ ) { m_relax = relaxation; }
+
~KX_SlowParentRelation(
);
+
+ bool
+ IsSlowRelation(
+ ) {
+ return true;
+ }
private :
diff --git a/source/gameengine/Ketsji/KX_Scene.cpp b/source/gameengine/Ketsji/KX_Scene.cpp
index 7f7558b0ab7..caa71441b1d 100644
--- a/source/gameengine/Ketsji/KX_Scene.cpp
+++ b/source/gameengine/Ketsji/KX_Scene.cpp
@@ -32,10 +32,12 @@
#pragma warning (disable : 4786)
#endif //WIN32
+
#include "KX_Scene.h"
#include "MT_assert.h"
#include "KX_KetsjiEngine.h"
+#include "KX_BlenderMaterial.h"
#include "RAS_IPolygonMaterial.h"
#include "ListValue.h"
#include "SCA_LogicManager.h"
@@ -47,6 +49,7 @@
#include "SCA_KeyboardManager.h"
#include "SCA_MouseManager.h"
#include "SCA_PropertyEventManager.h"
+#include "SCA_ActuatorEventManager.h"
#include "KX_Camera.h"
#include "SCA_JoystickManager.h"
@@ -64,6 +67,9 @@
#include "SG_Controller.h"
#include "SG_IObject.h"
#include "SG_Tree.h"
+#include "DNA_group_types.h"
+#include "DNA_scene_types.h"
+#include "BKE_anim.h"
#include "KX_SG_NodeRelationships.h"
@@ -71,15 +77,26 @@
#include "NG_NetworkScene.h"
#include "PHY_IPhysicsEnvironment.h"
#include "KX_IPhysicsController.h"
+#include "KX_BlenderSceneConverter.h"
-#include "BL_SkinDeformer.h"
+#include "BL_ShapeDeformer.h"
#include "BL_DeformableGameObject.h"
+// to get USE_BULLET!
+#include "KX_ConvertPhysicsObject.h"
+
+#ifdef USE_BULLET
+#include "CcdPhysicsEnvironment.h"
+#include "CcdPhysicsController.h"
+#endif
void* KX_SceneReplicationFunc(SG_IObject* node,void* gameobj,void* scene)
{
KX_GameObject* replica = ((KX_Scene*)scene)->AddNodeReplicaObject(node,(KX_GameObject*)gameobj);
+ if(replica)
+ replica->Release();
+
return (void*)replica;
}
@@ -100,16 +117,19 @@ KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice,
class SCA_IInputDevice* mousedevice,
class NG_NetworkDeviceInterface *ndi,
class SND_IAudioDevice* adi,
- const STR_String& sceneName):
+ const STR_String& sceneName,
+ Scene *scene):
PyObjectPlus(&KX_Scene::Type),
m_keyboardmgr(NULL),
m_mousemgr(NULL),
+ m_sceneConverter(NULL),
m_physicsEnvironment(0),
m_sceneName(sceneName),
m_adi(adi),
m_networkDeviceInterface(ndi),
m_active_camera(NULL),
- m_ueberExecutionPriority(0)
+ m_ueberExecutionPriority(0),
+ m_blenderScene(scene)
{
m_suspendedtime = 0.0;
m_suspendeddelta = 0.0;
@@ -121,6 +141,7 @@ KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice,
m_objectlist = new CListValue();
m_parentlist = new CListValue();
m_lightlist= new CListValue();
+ m_inactivelist = new CListValue();
m_euthanasyobjects = new CListValue();
m_delayReleaseObjects = new CListValue();
@@ -132,22 +153,32 @@ KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice,
SCA_AlwaysEventManager* alwaysmgr = new SCA_AlwaysEventManager(m_logicmgr);
SCA_PropertyEventManager* propmgr = new SCA_PropertyEventManager(m_logicmgr);
+ SCA_ActuatorEventManager* actmgr = new SCA_ActuatorEventManager(m_logicmgr);
SCA_RandomEventManager* rndmgr = new SCA_RandomEventManager(m_logicmgr);
KX_RayEventManager* raymgr = new KX_RayEventManager(m_logicmgr);
KX_NetworkEventManager* netmgr = new KX_NetworkEventManager(m_logicmgr, ndi);
- SCA_JoystickManager *joymgr = new SCA_JoystickManager(m_logicmgr);
+
m_logicmgr->RegisterEventManager(alwaysmgr);
m_logicmgr->RegisterEventManager(propmgr);
+ m_logicmgr->RegisterEventManager(actmgr);
m_logicmgr->RegisterEventManager(m_keyboardmgr);
m_logicmgr->RegisterEventManager(m_mousemgr);
m_logicmgr->RegisterEventManager(m_timemgr);
m_logicmgr->RegisterEventManager(rndmgr);
m_logicmgr->RegisterEventManager(raymgr);
m_logicmgr->RegisterEventManager(netmgr);
- m_logicmgr->RegisterEventManager(joymgr);
+
+
+ SYS_SystemHandle hSystem = SYS_GetSystem();
+ bool nojoystick= SYS_GetCommandLineInt(hSystem,"nojoystick",0);
+ if (!nojoystick)
+ {
+ SCA_JoystickManager *joymgr = new SCA_JoystickManager(m_logicmgr);
+ m_logicmgr->RegisterEventManager(joymgr);
+ }
m_soundScene = new SND_Scene(adi);
MT_assert (m_networkDeviceInterface != NULL);
@@ -167,13 +198,14 @@ KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice,
KX_Scene::~KX_Scene()
{
-
-// int numobj = m_objectlist->GetCount();
+ // The release of debug properties used to be in SCA_IScene::~SCA_IScene
+ // It's still there but we remove all properties here otherwise some
+ // reference might be hanging and causing late release of objects
+ RemoveAllDebugProperties();
- //int numrootobjects = GetRootParentList()->GetCount();
- for (int i = 0; i < GetRootParentList()->GetCount(); i++)
+ while (GetRootParentList()->GetCount() > 0)
{
- KX_GameObject* parentobj = (KX_GameObject*) GetRootParentList()->GetValue(i);
+ KX_GameObject* parentobj = (KX_GameObject*) GetRootParentList()->GetValue(0);
this->RemoveObject(parentobj);
}
@@ -183,6 +215,9 @@ KX_Scene::~KX_Scene()
if (m_parentlist)
m_parentlist->Release();
+ if (m_inactivelist)
+ m_inactivelist->Release();
+
if (m_lightlist)
m_lightlist->Release();
@@ -210,13 +245,9 @@ KX_Scene::~KX_Scene()
{
delete m_bucketmanager;
}
-
//Py_DECREF(m_attrlist);
}
-
-
-
void KX_Scene::SetProjectionMatrix(MT_CmMatrix4x4& pmat)
{
m_projectionmat = pmat;
@@ -243,6 +274,11 @@ CListValue* KX_Scene::GetRootParentList()
return m_parentlist;
}
+CListValue* KX_Scene::GetInactiveList()
+{
+ return m_inactivelist;
+}
+
CListValue* KX_Scene::GetLightList()
@@ -263,7 +299,7 @@ SCA_TimeEventManager* KX_Scene::GetTimeEventManager()
-set<class KX_Camera*>* KX_Scene::GetCameras()
+list<class KX_Camera*>* KX_Scene::GetCameras()
{
return &m_cameras;
}
@@ -364,14 +400,26 @@ void KX_Scene::EnableZBufferClearing(bool isclearingZbuffer)
void KX_Scene::RemoveNodeDestructObject(class SG_IObject* node,class CValue* gameobj)
{
KX_GameObject* orgobj = (KX_GameObject*)gameobj;
- NewRemoveObject(orgobj);
-
+ if (NewRemoveObject(orgobj) != 0)
+ {
+ // object is not yet deleted (this can happen when it hangs in an add object actuator
+ // last object created reference. It's a bad situation, don't know how to fix it exactly
+ // The least I can do, is remove the reference to the node in the object as the node
+ // will in any case be deleted. This ensures that the object will not try to use the node
+ // when it is finally deleted (see KX_GameObject destructor)
+ orgobj->SetSGNode(NULL);
+ }
if (node)
delete node;
}
KX_GameObject* KX_Scene::AddNodeReplicaObject(class SG_IObject* node, class CValue* gameobj)
{
+ // for group duplication, limit the duplication of the hierarchy to the
+ // objects that are part of the group.
+ if (!IsObjectInGroup(gameobj))
+ return NULL;
+
KX_GameObject* orgobj = (KX_GameObject*)gameobj;
KX_GameObject* newobj = (KX_GameObject*)orgobj->GetReplica();
m_map_gameobject_to_replica.insert(orgobj, newobj);
@@ -415,8 +463,8 @@ KX_GameObject* KX_Scene::AddNodeReplicaObject(class SG_IObject* node, class CVal
replicanode->SetSGClientObject(newobj);
// this is the list of object that are send to the graphics pipeline
- m_objectlist->Add(newobj);
- newobj->Bucketize();
+ m_objectlist->Add(newobj->AddRef());
+ newobj->AddMeshUser();
// logic cannot be replicated, until the whole hierarchy is replicated.
m_logicHierarchicalGameObjects.push_back(newobj);
@@ -449,6 +497,11 @@ KX_GameObject* KX_Scene::AddNodeReplicaObject(class SG_IObject* node, class CVal
// hierarchy that's because first ALL bricks must exist in the new
// replica of the hierarchy in order to make cross-links work properly
// !
+// It is VERY important that the order of sensors and actuators in
+// the replicated object is preserved: it is is used to reconnect the logic.
+// This method is more robust then using the bricks name in case of complex
+// group replication. The replication of logic bricks is done in
+// SCA_IObject::ReParentLogic(), make sure it preserves the order of the bricks.
void KX_Scene::ReplicateLogic(KX_GameObject* newobj)
{
// also relink the controller to sensors/actuators
@@ -471,37 +524,38 @@ void KX_Scene::ReplicateLogic(KX_GameObject* newobj)
for (vector<SCA_ISensor*>::iterator its = linkedsensors.begin();!(its==linkedsensors.end());its++)
{
SCA_ISensor* oldsensor = (*its);
- STR_String name = oldsensor->GetName();
- //find this name in the list
- SCA_ISensor* newsensor = newobj->FindSensor(name);
+ SCA_IObject* oldsensorobj = oldsensor->GetParent();
+ SCA_IObject* newsensorobj = NULL;
- if (newsensor)
+ // the original owner of the sensor has been replicated?
+ void **h_obj = m_map_gameobject_to_replica[oldsensorobj];
+ if (h_obj)
+ newsensorobj = (SCA_IObject*)(*h_obj);
+ if (!newsensorobj)
{
- // relink this newsensor to the controller
- m_logicmgr->RegisterToSensor(cont,newsensor);
+ // no, then the sensor points outside the hierachy, keep it the same
+ if (m_objectlist->SearchValue(oldsensorobj))
+ // only replicate links that points to active objects
+ m_logicmgr->RegisterToSensor(cont,oldsensor);
}
else
{
- // it can be linked somewhere in the hierarchy or...
- for (vector<KX_GameObject*>::iterator git = m_logicHierarchicalGameObjects.begin();
- !(git==m_logicHierarchicalGameObjects.end());++git)
- {
- newsensor = (*git)->FindSensor(name);
- if (newsensor)
- break;
- }
+ // yes, then the new sensor has the same position
+ SCA_SensorList& sensorlist = oldsensorobj->GetSensors();
+ SCA_SensorList::iterator sit;
+ SCA_ISensor* newsensor = NULL;
+ int sensorpos;
- if (newsensor)
- {
- // relink this newsensor to the controller somewhere else within this
- // hierarchy
- m_logicmgr->RegisterToSensor(cont,newsensor);
- }
- else
+ for (sensorpos=0, sit=sensorlist.begin(); sit!=sensorlist.end(); sit++, sensorpos++)
{
- // must be an external sensor, so...
- m_logicmgr->RegisterToSensor(cont,oldsensor);
+ if ((*sit) == oldsensor)
+ {
+ newsensor = newsensorobj->GetSensors().at(sensorpos);
+ break;
+ }
}
+ assert(newsensor != NULL);
+ m_logicmgr->RegisterToSensor(cont,newsensor);
}
}
@@ -509,43 +563,189 @@ void KX_Scene::ReplicateLogic(KX_GameObject* newobj)
for (vector<SCA_IActuator*>::iterator ita = linkedactuators.begin();!(ita==linkedactuators.end());ita++)
{
SCA_IActuator* oldactuator = (*ita);
- STR_String name = oldactuator->GetName();
- //find this name in the list
- SCA_IActuator* newactuator = newobj->FindActuator(name);
- if (newactuator)
+ SCA_IObject* oldactuatorobj = oldactuator->GetParent();
+ SCA_IObject* newactuatorobj = NULL;
+
+ // the original owner of the sensor has been replicated?
+ void **h_obj = m_map_gameobject_to_replica[oldactuatorobj];
+ if (h_obj)
+ newactuatorobj = (SCA_IObject*)(*h_obj);
+
+ if (!newactuatorobj)
{
- // relink this newsensor to the controller
- m_logicmgr->RegisterToActuator(cont,newactuator);
- newactuator->SetUeberExecutePriority(m_ueberExecutionPriority);
+ // no, then the sensor points outside the hierachy, keep it the same
+ if (m_objectlist->SearchValue(oldactuatorobj))
+ // only replicate links that points to active objects
+ m_logicmgr->RegisterToActuator(cont,oldactuator);
}
else
{
- // it can be linked somewhere in the hierarchy or...
- for (vector<KX_GameObject*>::iterator git = m_logicHierarchicalGameObjects.begin();
- !(git==m_logicHierarchicalGameObjects.end());++git)
- {
- newactuator= (*git)->FindActuator(name);
- if (newactuator)
- break;
- }
+ // yes, then the new sensor has the same position
+ SCA_ActuatorList& actuatorlist = oldactuatorobj->GetActuators();
+ SCA_ActuatorList::iterator ait;
+ SCA_IActuator* newactuator = NULL;
+ int actuatorpos;
- if (newactuator)
+ for (actuatorpos=0, ait=actuatorlist.begin(); ait!=actuatorlist.end(); ait++, actuatorpos++)
{
- // relink this actuator to the controller somewhere else within this
- // hierarchy
- m_logicmgr->RegisterToActuator(cont,newactuator);
- newactuator->SetUeberExecutePriority(m_ueberExecutionPriority);
- }
- else
- {
- // must be an external actuator, so...
- m_logicmgr->RegisterToActuator(cont,oldactuator);
+ if ((*ait) == oldactuator)
+ {
+ newactuator = newactuatorobj->GetActuators().at(actuatorpos);
+ break;
+ }
}
+ assert(newactuator != NULL);
+ m_logicmgr->RegisterToActuator(cont,newactuator);
+ newactuator->SetUeberExecutePriority(m_ueberExecutionPriority);
}
}
}
+ // ready to set initial state
+ newobj->ResetState();
}
+void KX_Scene::DupliGroupRecurse(CValue* obj, int level)
+{
+ KX_GameObject* groupobj = (KX_GameObject*) obj;
+ KX_GameObject* replica;
+ KX_GameObject* gameobj;
+ Object* blgroupobj = groupobj->GetBlenderObject();
+ Group* group;
+ GroupObject *go;
+ vector<KX_GameObject*> duplilist;
+
+ if (!groupobj->GetSGNode() ||
+ !groupobj->IsDupliGroup() ||
+ level>MAX_DUPLI_RECUR)
+ return;
+
+ // we will add one group at a time
+ m_logicHierarchicalGameObjects.clear();
+ m_map_gameobject_to_replica.clear();
+ m_ueberExecutionPriority++;
+ // for groups will do something special:
+ // we will force the creation of objects to those in the group only
+ // Again, this is match what Blender is doing (it doesn't care of parent relationship)
+ m_groupGameObjects.clear();
+
+ group = blgroupobj->dup_group;
+ for(go=(GroupObject*)group->gobject.first; go; go=(GroupObject*)go->next)
+ {
+ Object* blenderobj = go->ob;
+ if (blgroupobj == blenderobj)
+ // this check is also in group_duplilist()
+ continue;
+
+ gameobj = (KX_GameObject*)m_logicmgr->FindGameObjByBlendObj(blenderobj);
+ if (gameobj == NULL)
+ {
+ // this object has not been converted!!!
+ // Should not happen as dupli group are created automatically
+ continue;
+ }
+
+ gameobj->SetBlenderGroupObject(blgroupobj);
+
+ if ((blenderobj->lay & group->layer)==0)
+ {
+ // object is not visible in the 3D view, will not be instantiated
+ continue;
+ }
+ m_groupGameObjects.insert(gameobj);
+ }
+
+ set<CValue*>::iterator oit;
+ for (oit=m_groupGameObjects.begin(); oit != m_groupGameObjects.end(); oit++)
+ {
+ gameobj = (KX_GameObject*)(*oit);
+
+ KX_GameObject *parent = gameobj->GetParent();
+ if (parent != NULL)
+ {
+ parent->Release(); // GetParent() increased the refcount
+
+ // this object is not a top parent. Either it is the child of another
+ // object in the group and it will be added automatically when the parent
+ // is added. Or it is the child of an object outside the group and the group
+ // is inconsistent, skip it anyway
+ continue;
+ }
+ replica = (KX_GameObject*) AddNodeReplicaObject(NULL,gameobj);
+ // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
+ m_parentlist->Add(replica->AddRef());
+
+ // recurse replication into children nodes
+ NodeList& children = gameobj->GetSGNode()->GetSGChildren();
+
+ replica->GetSGNode()->ClearSGChildren();
+ for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
+ {
+ SG_Node* orgnode = (*childit);
+ SG_Node* childreplicanode = orgnode->GetSGReplica();
+ if (childreplicanode)
+ replica->GetSGNode()->AddChild(childreplicanode);
+ }
+ // don't replicate logic now: we assume that the objects in the group can have
+ // logic relationship, even outside parent relationship
+ // In order to match 3D view, the position of groupobj is used as a
+ // transformation matrix instead of the new position. This means that
+ // the group reference point is 0,0,0
+
+ // get the rootnode's scale
+ MT_Vector3 newscale = groupobj->NodeGetWorldScaling();
+ // set the replica's relative scale with the rootnode's scale
+ replica->NodeSetRelativeScale(newscale);
+
+ MT_Matrix3x3 newori = groupobj->NodeGetWorldOrientation() * gameobj->NodeGetWorldOrientation();
+ replica->NodeSetLocalOrientation(newori);
+
+ MT_Point3 newpos = groupobj->NodeGetWorldPosition() +
+ newscale*(groupobj->NodeGetWorldOrientation() * gameobj->NodeGetWorldPosition());
+ replica->NodeSetLocalPosition(newpos);
+
+ replica->GetSGNode()->UpdateWorldData(0);
+ replica->GetSGNode()->SetBBox(gameobj->GetSGNode()->BBox());
+ replica->GetSGNode()->SetRadius(gameobj->GetSGNode()->Radius());
+ // done with replica
+ replica->Release();
+ }
+
+ // the logic must be replicated first because we need
+ // the new logic bricks before relinking
+ vector<KX_GameObject*>::iterator git;
+ for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
+ {
+ (*git)->ReParentLogic();
+ }
+
+ // relink any pointers as necessary, sort of a temporary solution
+ for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
+ {
+ // this will also relink the actuator to objects within the hierarchy
+ (*git)->Relink(&m_map_gameobject_to_replica);
+ // add the object in the layer of the parent
+ (*git)->SetLayer(groupobj->GetLayer());
+ }
+
+ // replicate crosslinks etc. between logic bricks
+ for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
+ {
+ ReplicateLogic((*git));
+ }
+
+ // now look if object in the hierarchy have dupli group and recurse
+ for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
+ {
+ if ((*git) != groupobj && (*git)->IsDupliGroup())
+ // can't instantiate group immediately as it destroys m_logicHierarchicalGameObjects
+ duplilist.push_back((*git));
+ }
+
+ for (git = duplilist.begin(); !(git == duplilist.end()); ++git)
+ {
+ DupliGroupRecurse((*git), level+1);
+ }
+}
SCA_IObject* KX_Scene::AddReplicaObject(class CValue* originalobject,
@@ -555,6 +755,7 @@ SCA_IObject* KX_Scene::AddReplicaObject(class CValue* originalobject,
m_logicHierarchicalGameObjects.clear();
m_map_gameobject_to_replica.clear();
+ m_groupGameObjects.clear();
// todo: place a timebomb in the object, for temporarily objects :)
// lifespan of zero means 'this object lives forever'
@@ -571,7 +772,9 @@ SCA_IObject* KX_Scene::AddReplicaObject(class CValue* originalobject,
// add a timebomb to this object
// for now, convert between so called frames and realtime
m_tempObjectList->Add(replica->AddRef());
- replica->SetProperty("::timebomb",new CFloatValue(lifespan*0.02));
+ CValue *fval = new CFloatValue(lifespan*0.02);
+ replica->SetProperty("::timebomb",fval);
+ fval->Release();
}
// add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
@@ -586,22 +789,26 @@ SCA_IObject* KX_Scene::AddReplicaObject(class CValue* originalobject,
{
SG_Node* orgnode = (*childit);
SG_Node* childreplicanode = orgnode->GetSGReplica();
- replica->GetSGNode()->AddChild(childreplicanode);
+ if (childreplicanode)
+ replica->GetSGNode()->AddChild(childreplicanode);
}
- // relink any pointers as necessary, sort of a temporary solution
+ // now replicate logic
vector<KX_GameObject*>::iterator git;
for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
{
- (*git)->Relink(&m_map_gameobject_to_replica);
+ (*git)->ReParentLogic();
}
-
- // now replicate logic
+
+ // relink any pointers as necessary, sort of a temporary solution
for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
{
- (*git)->ReParentLogic();
+ // this will also relink the actuators in the hierarchy
+ (*git)->Relink(&m_map_gameobject_to_replica);
+ // add the object in the layer of the parent
+ (*git)->SetLayer(parentobj->GetLayer());
}
-
+
// replicate crosslinks etc. between logic bricks
for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
{
@@ -620,21 +827,24 @@ SCA_IObject* KX_Scene::AddReplicaObject(class CValue* originalobject,
// set the replica's relative scale with the rootnode's scale
replica->NodeSetRelativeScale(newscale);
- if (replica->GetPhysicsController())
- {
- replica->GetPhysicsController()->setPosition(newpos);
- replica->GetPhysicsController()->setOrientation(newori.getRotation());
- replica->GetPhysicsController()->setScaling(newscale);
- }
-
- // here we want to set the relative scale: the rootnode's scale will override all other
- // scalings, so lets better prepare for it
-
-
replica->GetSGNode()->UpdateWorldData(0);
replica->GetSGNode()->SetBBox(originalobj->GetSGNode()->BBox());
replica->GetSGNode()->SetRadius(originalobj->GetSGNode()->Radius());
-
+ // check if there are objects with dupligroup in the hierarchy
+ vector<KX_GameObject*> duplilist;
+ for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
+ {
+ if ((*git)->IsDupliGroup())
+ {
+ // separate list as m_logicHierarchicalGameObjects is also used by DupliGroupRecurse()
+ duplilist.push_back(*git);
+ }
+ }
+ for (git = duplilist.begin();!(git==duplilist.end());++git)
+ {
+ DupliGroupRecurse(*git, 0);
+ }
+ // don't release replica here because we are returning it, not done with it...
return replica;
}
@@ -654,7 +864,8 @@ void KX_Scene::RemoveObject(class CValue* gameobj)
// recursively destruct
node->Destruct();
}
- newobj->SetSGNode(0);
+ //no need to do that: the object is destroyed and memory released
+ //newobj->SetSGNode(0);
}
void KX_Scene::DelayedReleaseObject(CValue* gameobj)
@@ -674,10 +885,17 @@ void KX_Scene::DelayedRemoveObject(class CValue* gameobj)
-void KX_Scene::NewRemoveObject(class CValue* gameobj)
+int KX_Scene::NewRemoveObject(class CValue* gameobj)
{
+ int ret;
KX_GameObject* newobj = (KX_GameObject*) gameobj;
+ // keep the blender->game object association up to date
+ // note that all the replicas of an object will have the same
+ // blender object, that's why we need to check the game object
+ // as only the deletion of the original object must be recorded
+ m_logicmgr->UnregisterGameObj(newobj->GetBlenderObject(), gameobj);
+
//todo: look at this
//GetPhysicsEnvironment()->RemovePhysicsController(gameobj->getPhysicsController());
@@ -694,8 +912,7 @@ void KX_Scene::NewRemoveObject(class CValue* gameobj)
for (SCA_ControllerList::iterator itc = controllers.begin();
!(itc==controllers.end());itc++)
{
- (*itc)->UnlinkAllSensors();
- (*itc)->UnlinkAllActuators();
+ m_logicmgr->RemoveController(*itc);
}
SCA_ActuatorList& actuators = newobj->GetActuators();
@@ -704,6 +921,7 @@ void KX_Scene::NewRemoveObject(class CValue* gameobj)
{
m_logicmgr->RemoveDestroyedActuator(*ita);
}
+ // the sensors/controllers/actuators must also be released, this is done in ~SCA_IObject
// now remove the timer properties from the time manager
int numprops = newobj->GetPropertyCount();
@@ -718,113 +936,138 @@ void KX_Scene::NewRemoveObject(class CValue* gameobj)
}
newobj->RemoveMeshes();
+ ret = 1;
+ if (m_lightlist->RemoveValue(newobj)) // TODO - use newobj->IsLight() test when its merged in from apricot. - Campbell
+ ret = newobj->Release();
if (m_objectlist->RemoveValue(newobj))
- newobj->Release();
+ ret = newobj->Release();
if (m_tempObjectList->RemoveValue(newobj))
- newobj->Release();
+ ret = newobj->Release();
if (m_parentlist->RemoveValue(newobj))
- newobj->Release();
+ ret = newobj->Release();
+ if (m_inactivelist->RemoveValue(newobj))
+ ret = newobj->Release();
if (m_euthanasyobjects->RemoveValue(newobj))
- newobj->Release();
+ ret = newobj->Release();
if (newobj == m_active_camera)
{
- m_active_camera->Release();
+ //no AddRef done on m_active_camera so no Release
+ //m_active_camera->Release();
m_active_camera = NULL;
}
+
+ // in case this is a camera
+ m_cameras.remove((KX_Camera*)newobj);
+
+ if (m_sceneConverter)
+ m_sceneConverter->UnregisterGameObject(newobj);
+ // return value will be 0 if the object is actually deleted (all reference gone)
+ return ret;
}
-void KX_Scene::ReplaceMesh(class CValue* gameobj,void* meshobj)
+void KX_Scene::ReplaceMesh(class CValue* obj,void* meshobj)
{
- KX_GameObject* newobj = static_cast<KX_GameObject*>(gameobj);
+ KX_GameObject* gameobj = static_cast<KX_GameObject*>(obj);
RAS_MeshObject* mesh = static_cast<RAS_MeshObject*>(meshobj);
- const STR_String origMeshName = newobj->GetMesh(0)->GetName();
-
- if( !newobj || !mesh )
+ if(!gameobj || !mesh)
{
std::cout << "warning: invalid object, mesh will not be replaced" << std::endl;
return;
}
- newobj->RemoveMeshes();
- newobj->AddMesh(mesh);
-
- bool isDeformer = (newobj->m_isDeformable && mesh->m_class == 1);
- if(isDeformer)
- {
- /* FindBlendObjByGameObj() can return 0...
- In the case of 0 here,
- the replicated object that is calling this function
- is some how not in the map. (which is strange because it's added)
- So we will search the map by the first mesh name
- to try to locate it there. If its still not found
- spit some message rather than crash
- */
- Object* blendobj = static_cast<struct Object*>(m_logicmgr->FindBlendObjByGameObj(newobj));
- Object* oldblendobj = static_cast<struct Object*>(m_logicmgr->FindBlendObjByGameMeshName(mesh->GetName()));
+ gameobj->RemoveMeshes();
+ gameobj->AddMesh(mesh);
- bool parSkin = blendobj && blendobj->parent && blendobj->parent->type == OB_ARMATURE && blendobj->partype==PARSKEL;
- bool releaseParent = true;
- KX_GameObject* parentobj = newobj->GetParent();
-
-
- // lookup by mesh name if blendobj is 0
- if( !blendobj && parentobj )
+ if (gameobj->m_isDeformable)
+ {
+ BL_DeformableGameObject* newobj = static_cast<BL_DeformableGameObject*>( gameobj );
+
+ if (newobj->GetDeformer())
{
- blendobj = static_cast<struct Object*>(m_logicmgr->FindBlendObjByGameMeshName(origMeshName));
-
- // replace the mesh on the parent armature
- if( blendobj )
- parSkin = parentobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE;
-
- // can't do it
- else
- std::cout << "warning: child object for " << parentobj->GetName().ReadPtr()
- << " not found, and can't create!" << std::endl;
+ delete newobj->GetDeformer();
+ newobj->SetDeformer(NULL);
}
- if( blendobj && oldblendobj )
+ if (mesh->IsDeformed())
{
- isDeformer = (static_cast<Mesh*>(blendobj->data)->dvert != 0);
- BL_DeformableGameObject* deformIter =0;
-
- // armature parent
- if( parSkin && isDeformer )
+ // we must create a new deformer but which one?
+ KX_GameObject* parentobj = newobj->GetParent();
+ // this always return the original game object (also for replicate)
+ Object* blendobj = newobj->GetBlenderObject();
+ // object that owns the new mesh
+ Object* oldblendobj = static_cast<struct Object*>(m_logicmgr->FindBlendObjByGameMeshName(mesh->GetName()));
+ Mesh* blendmesh = mesh->GetMesh();
+
+ bool bHasShapeKey = blendmesh->key != NULL && blendmesh->key->type==KEY_RELATIVE;
+ bool bHasDvert = blendmesh->dvert != NULL;
+ bool bHasArmature =
+ parentobj && // current parent is armature
+ parentobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE &&
+ oldblendobj && // needed for mesh deform
+ blendobj->parent && // original object had armature (not sure this test is needed)
+ blendobj->parent->type == OB_ARMATURE &&
+ blendobj->partype==PARSKEL &&
+ blendmesh->dvert!=NULL; // mesh has vertex group
+ bool releaseParent = true;
+
+ if (bHasShapeKey)
+ {
+ BL_ShapeDeformer* shapeDeformer;
+ if (bHasArmature)
+ {
+ shapeDeformer = new BL_ShapeDeformer(
+ newobj,
+ oldblendobj, blendobj,
+ static_cast<BL_SkinMeshObject*>(mesh),
+ true,
+ static_cast<BL_ArmatureObject*>( parentobj )
+ );
+ releaseParent= false;
+ shapeDeformer->LoadShapeDrivers(blendobj->parent);
+ }
+ else
+ {
+ shapeDeformer = new BL_ShapeDeformer(
+ newobj,
+ oldblendobj, blendobj,
+ static_cast<BL_SkinMeshObject*>(mesh),
+ false,
+ NULL
+ );
+ }
+ newobj->SetDeformer( shapeDeformer);
+ }
+ else if (bHasArmature)
{
- deformIter = static_cast<BL_DeformableGameObject*>( newobj );
- delete deformIter->m_pDeformer;
-
BL_SkinDeformer* skinDeformer = new BL_SkinDeformer(
+ newobj,
oldblendobj, blendobj,
static_cast<BL_SkinMeshObject*>(mesh),
true,
static_cast<BL_ArmatureObject*>( parentobj )
);
releaseParent= false;
- deformIter->m_pDeformer = skinDeformer;
+ newobj->SetDeformer(skinDeformer);
}
-
- // normal deformer
- if( !parSkin && isDeformer)
+ else if (bHasDvert)
{
- deformIter = static_cast<BL_DeformableGameObject*>( newobj );
- delete deformIter->m_pDeformer;
-
BL_MeshDeformer* meshdeformer = new BL_MeshDeformer(
- oldblendobj, static_cast<BL_SkinMeshObject*>(mesh)
+ newobj, oldblendobj, static_cast<BL_SkinMeshObject*>(mesh)
);
-
- deformIter->m_pDeformer = meshdeformer;
+ newobj->SetDeformer(meshdeformer);
}
+
+ // release parent reference if its not being used
+ if( releaseParent && parentobj)
+ parentobj->Release();
}
- // release parent reference if its not being used
- if( releaseParent && parentobj)
- parentobj->Release();
}
- newobj->Bucketize();
+
+ gameobj->AddMeshUser();
}
@@ -847,7 +1090,7 @@ MT_CmMatrix4x4& KX_Scene::GetProjectionMatrix()
KX_Camera* KX_Scene::FindCamera(KX_Camera* cam)
{
- set<KX_Camera*>::iterator it = m_cameras.begin();
+ list<KX_Camera*>::iterator it = m_cameras.begin();
while ( (it != m_cameras.end())
&& ((*it) != cam) ) {
@@ -860,7 +1103,7 @@ KX_Camera* KX_Scene::FindCamera(KX_Camera* cam)
KX_Camera* KX_Scene::FindCamera(STR_String& name)
{
- set<KX_Camera*>::iterator it = m_cameras.begin();
+ list<KX_Camera*>::iterator it = m_cameras.begin();
while ( (it != m_cameras.end())
&& ((*it)->GetName() != name) ) {
@@ -872,9 +1115,11 @@ KX_Camera* KX_Scene::FindCamera(STR_String& name)
void KX_Scene::AddCamera(KX_Camera* cam)
{
- m_cameras.insert(cam);
+ if (!FindCamera(cam))
+ m_cameras.push_back(cam);
}
+
KX_Camera* KX_Scene::GetActiveCamera()
{
// NULL if not defined
@@ -893,6 +1138,17 @@ void KX_Scene::SetActiveCamera(KX_Camera* cam)
m_active_camera = cam;
}
+void KX_Scene::SetCameraOnTop(KX_Camera* cam)
+{
+ if (!FindCamera(cam)){
+ // adding is always done at the back, so that's all that needs to be done
+ AddCamera(cam);
+ if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
+ } else {
+ m_cameras.remove(cam);
+ m_cameras.push_back(cam);
+ }
+}
void KX_Scene::UpdateMeshTransformations()
@@ -906,12 +1162,13 @@ void KX_Scene::UpdateMeshTransformations()
}
}
-void KX_Scene::MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty, KX_Camera* cam)
+void KX_Scene::MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty, KX_Camera* cam, int layer)
{
int intersect = KX_Camera::INTERSECT;
KX_GameObject *gameobj = node->Client()?(KX_GameObject*) node->Client()->GetSGClientObject():NULL;
- bool dotest = (gameobj && gameobj->GetVisible()) || node->Left() || node->Right();
-
+ bool visible = (gameobj && gameobj->GetVisible() && (!layer || (gameobj->GetLayer() & layer)));
+ bool dotest = visible || node->Left() || node->Right();
+
/* If the camera is inside the box, assume intersect. */
if (dotest && !node->inside( cam->NodeGetWorldPosition()))
{
@@ -935,19 +1192,19 @@ void KX_Scene::MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty, KX_Camera* cam
break;
case KX_Camera::INTERSECT:
if (gameobj)
- MarkVisible(rasty, gameobj,cam);
+ MarkVisible(rasty, gameobj, cam, layer);
if (node->Left())
- MarkVisible(node->Left(), rasty,cam);
+ MarkVisible(node->Left(), rasty, cam, layer);
if (node->Right())
- MarkVisible(node->Right(), rasty,cam);
+ MarkVisible(node->Right(), rasty, cam, layer);
break;
case KX_Camera::INSIDE:
- MarkSubTreeVisible(node, rasty, true,cam);
+ MarkSubTreeVisible(node, rasty, true, cam, layer);
break;
}
}
-void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible,KX_Camera* cam)
+void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible, KX_Camera* cam, int layer)
{
if (node->Client())
{
@@ -957,29 +1214,35 @@ void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool vi
if (visible)
{
int nummeshes = gameobj->GetMeshCount();
- MT_Transform t( cam->GetWorldToCamera() * gameobj->GetSGNode()->GetWorldTransform());
-
+ // this adds the vertices to the display list
for (int m=0;m<nummeshes;m++)
- {
- // this adds the vertices to the display list
- (gameobj->GetMesh(m))->SchedulePolygons(t, rasty->GetDrawingMode());
- }
+ (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
}
- gameobj->MarkVisible(visible);
+
+ gameobj->SetCulled(!visible);
+ gameobj->UpdateBuckets(false);
}
}
if (node->Left())
- MarkSubTreeVisible(node->Left(), rasty, visible,cam);
+ MarkSubTreeVisible(node->Left(), rasty, visible, cam, layer);
if (node->Right())
- MarkSubTreeVisible(node->Right(), rasty, visible,cam);
+ MarkSubTreeVisible(node->Right(), rasty, visible, cam, layer);
}
-void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj,KX_Camera* cam)
+void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj,KX_Camera* cam,int layer)
{
// User (Python/Actuator) has forced object invisible...
- if (!gameobj->GetVisible())
+ if (!gameobj->GetSGNode() || !gameobj->GetVisible())
+ return;
+
+ // Shadow lamp layers
+ if(layer && !(gameobj->GetLayer() & layer)) {
+ gameobj->SetCulled(true);
+ gameobj->UpdateBuckets(false);
return;
+ }
+
// If Frustum culling is off, the object is always visible.
bool vis = !cam->GetFrustumCulling();
@@ -1014,35 +1277,36 @@ void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj,KX_Cam
if (vis)
{
int nummeshes = gameobj->GetMeshCount();
- MT_Transform t(cam->GetWorldToCamera() * gameobj->GetSGNode()->GetWorldTransform());
for (int m=0;m<nummeshes;m++)
{
// this adds the vertices to the display list
- (gameobj->GetMesh(m))->SchedulePolygons(t, rasty->GetDrawingMode());
+ (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
}
// Visibility/ non-visibility are marked
// elsewhere now.
- gameobj->MarkVisible();
+ gameobj->SetCulled(false);
+ gameobj->UpdateBuckets(false);
} else {
- gameobj->MarkVisible(false);
+ gameobj->SetCulled(true);
+ gameobj->UpdateBuckets(false);
}
}
-void KX_Scene::CalculateVisibleMeshes(RAS_IRasterizer* rasty,KX_Camera* cam)
+void KX_Scene::CalculateVisibleMeshes(RAS_IRasterizer* rasty,KX_Camera* cam, int layer)
{
// FIXME: When tree is operational
#if 1
// do this incrementally in the future
for (int i = 0; i < m_objectlist->GetCount(); i++)
{
- MarkVisible(rasty, static_cast<KX_GameObject*>(m_objectlist->GetValue(i)), cam);
+ MarkVisible(rasty, static_cast<KX_GameObject*>(m_objectlist->GetValue(i)), cam, layer);
}
#else
if (cam->GetFrustumCulling())
- MarkVisible(m_objecttree, rasty, cam);
+ MarkVisible(m_objecttree, rasty, cam, layer);
else
- MarkSubTreeVisible(m_objecttree, rasty, true, cam);
+ MarkSubTreeVisible(m_objecttree, rasty, true, cam, layer);
#endif
}
@@ -1096,6 +1360,8 @@ void KX_Scene::LogicEndFrame()
for (i = numobj - 1; i >= 0; i--)
{
KX_GameObject* gameobj = (KX_GameObject*)m_euthanasyobjects->GetValue(i);
+ // KX_Scene::RemoveObject will also remove the object from this list
+ // that's why we start from the end
this->RemoveObject(gameobj);
}
@@ -1103,11 +1369,11 @@ void KX_Scene::LogicEndFrame()
for (i = numobj-1;i>=0;i--)
{
KX_GameObject* gameobj = (KX_GameObject*)m_delayReleaseObjects->GetValue(i);
- m_delayReleaseObjects->RemoveValue(gameobj);
-
+ // This list is not for object removal, but just object release
+ gameobj->Release();
}
-
-
+ // empty the list as we have removed all references
+ m_delayReleaseObjects->Resize(0);
}
@@ -1128,9 +1394,9 @@ void KX_Scene::UpdateParents(double curtime)
-RAS_MaterialBucket* KX_Scene::FindBucket(class RAS_IPolyMaterial* polymat)
+RAS_MaterialBucket* KX_Scene::FindBucket(class RAS_IPolyMaterial* polymat, bool &bucketCreated)
{
- return m_bucketmanager->RAS_BucketManagerFindBucket(polymat);
+ return m_bucketmanager->FindBucket(polymat, bucketCreated);
}
@@ -1140,10 +1406,9 @@ void KX_Scene::RenderBuckets(const MT_Transform & cameratransform,
class RAS_IRenderTools* rendertools)
{
m_bucketmanager->Renderbuckets(cameratransform,rasty,rendertools);
+ KX_BlenderMaterial::EndFrame();
}
-
-
void KX_Scene::UpdateObjectActivity(void)
{
if (m_activity_culling) {
@@ -1212,6 +1477,11 @@ void KX_Scene::SetNodeTree(SG_Tree* root)
m_objecttree = root;
}
+void KX_Scene::SetSceneConverter(class KX_BlenderSceneConverter* sceneConverter)
+{
+ m_sceneConverter = sceneConverter;
+}
+
void KX_Scene::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* physEnv)
{
m_physicsEnvironment = physEnv;
diff --git a/source/gameengine/Ketsji/KX_Scene.h b/source/gameengine/Ketsji/KX_Scene.h
index dbe04a18e0f..5f7e1167e27 100644
--- a/source/gameengine/Ketsji/KX_Scene.h
+++ b/source/gameengine/Ketsji/KX_Scene.h
@@ -36,6 +36,7 @@
#include <vector>
#include <set>
+#include <list>
#include "GEN_Map.h"
#include "GEN_HashedPtr.h"
@@ -53,6 +54,7 @@
*/
struct SM_MaterialProps;
struct SM_ShapeProps;
+struct Scene;
class GEN_HashedPtr;
class CListValue;
@@ -81,6 +83,8 @@ class RAS_IPolyMaterial;
class RAS_IRasterizer;
class RAS_IRenderTools;
class SCA_JoystickManager;
+class btCollisionShape;
+class KX_BlenderSceneConverter;
/**
* The KX_Scene holds all data for an independent scene. It relates
* KX_Objects to the specific objects in the modules.
@@ -107,6 +111,7 @@ protected:
CListValue* m_objectlist;
CListValue* m_parentlist; // all 'root' parents
CListValue* m_lightlist;
+ CListValue* m_inactivelist; // all objects that are not in the active layer
/**
* The tree of objects in the scene.
@@ -116,8 +121,7 @@ protected:
/**
* The set of cameras for this scene
*/
- set<class KX_Camera*> m_cameras;
-
+ list<class KX_Camera*> m_cameras;
/**
* Various SCA managers used by the scene
*/
@@ -126,10 +130,12 @@ protected:
SCA_MouseManager* m_mousemgr;
SCA_TimeEventManager* m_timemgr;
+ // Scene converter where many scene entities are registered
+ // Used to deregister objects that are deleted
+ class KX_BlenderSceneConverter* m_sceneConverter;
/**
* physics engine abstraction
*/
-
//e_PhysicsEngine m_physicsEngine; //who needs this ?
class PHY_IPhysicsEnvironment* m_physicsEnvironment;
@@ -206,6 +212,16 @@ protected:
*/
std::vector<KX_GameObject*> m_logicHierarchicalGameObjects;
+ /**
+ * This temporary variable will contain the list of
+ * object that can be added during group instantiation.
+ * objects outside this list will not be added (can
+ * happen with children that are outside the group).
+ * Used in AddReplicaObject. If the list is empty, it
+ * means don't care.
+ */
+ std::set<CValue*> m_groupGameObjects;
+
/**
* Pointer to system variable passed in in constructor
* only used in constructor so we do not need to keep it
@@ -250,9 +266,9 @@ protected:
/**
* Visibility testing functions.
*/
- void MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty, KX_Camera*cam);
- void MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible, KX_Camera*cam);
- void MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj, KX_Camera*cam);
+ void MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty, KX_Camera*cam,int layer=0);
+ void MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible, KX_Camera*cam,int layer=0);
+ void MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj, KX_Camera*cam, int layer=0);
double m_suspendedtime;
double m_suspendeddelta;
@@ -262,18 +278,21 @@ protected:
*/
PyObject* m_attrlist;
+ struct Scene* m_blenderScene;
+
public:
KX_Scene(class SCA_IInputDevice* keyboarddevice,
class SCA_IInputDevice* mousedevice,
class NG_NetworkDeviceInterface* ndi,
class SND_IAudioDevice* adi,
- const STR_String& scenename );
+ const STR_String& scenename,
+ struct Scene* scene);
virtual
~KX_Scene();
RAS_BucketManager* GetBucketManager();
- RAS_MaterialBucket* FindBucket(RAS_IPolyMaterial* polymat);
+ RAS_MaterialBucket* FindBucket(RAS_IPolyMaterial* polymat, bool &bucketCreated);
void RenderBuckets(const MT_Transform& cameratransform,
RAS_IRasterizer* rasty,
RAS_IRenderTools* rendertools);
@@ -281,6 +300,12 @@ public:
* Update all transforms according to the scenegraph.
*/
void UpdateParents(double curtime);
+ void DupliGroupRecurse(CValue* gameobj, int level);
+ bool IsObjectInGroup(CValue* gameobj)
+ {
+ return (m_groupGameObjects.empty() ||
+ m_groupGameObjects.find(gameobj) != m_groupGameObjects.end());
+ }
SCA_IObject* AddReplicaObject(CValue* gameobj,
CValue* locationobj,
int lifespan=0);
@@ -293,7 +318,7 @@ public:
void DelayedReleaseObject(CValue* gameobj);
- void NewRemoveObject(CValue* gameobj);
+ int NewRemoveObject(CValue* gameobj);
void ReplaceMesh(CValue* gameobj,
void* meshobj);
/**
@@ -312,6 +337,10 @@ public:
);
CListValue*
+ GetInactiveList(
+ );
+
+ CListValue*
GetRootParentList(
);
@@ -327,7 +356,7 @@ public:
GetTimeEventManager(
);
- set<class KX_Camera*>*
+ list<class KX_Camera*>*
GetCameras(
);
@@ -365,6 +394,15 @@ public:
class KX_Camera*
);
+ /**
+ * Move this camera to the end of the list so that it is rendered last.
+ * If the camera is not on the list, it will be added
+ */
+ void
+ SetCameraOnTop(
+ class KX_Camera*
+ );
+
/** Return the viewmatrix as used by the last frame. */
MT_CmMatrix4x4&
GetViewMatrix(
@@ -459,7 +497,7 @@ public:
void SetNetworkScene(NG_NetworkScene *newScene);
void SetWorldInfo(class KX_WorldInfo* wi);
KX_WorldInfo* GetWorldInfo();
- void CalculateVisibleMeshes(RAS_IRasterizer* rasty, KX_Camera *cam);
+ void CalculateVisibleMeshes(RAS_IRasterizer* rasty, KX_Camera *cam, int layer=0);
void UpdateMeshTransformations();
KX_Camera* GetpCamera();
SND_Scene* GetSoundScene();
@@ -493,6 +531,8 @@ public:
bool IsClearingZBuffer();
void EnableZBufferClearing(bool isclearingZbuffer);
+ void SetSceneConverter(class KX_BlenderSceneConverter* sceneConverter);
+
class PHY_IPhysicsEnvironment* GetPhysicsEnvironment()
{
return m_physicsEnvironment;
@@ -546,6 +586,10 @@ public:
* was running and not suspended) and the "curtime"
*/
double getSuspendedDelta();
+ /**
+ * Returns the Blender scene this was made from
+ */
+ struct Scene *GetBlenderScene() { return m_blenderScene; }
};
typedef std::vector<KX_Scene*> KX_SceneList;
diff --git a/source/gameengine/Ketsji/KX_SceneActuator.cpp b/source/gameengine/Ketsji/KX_SceneActuator.cpp
index ce357cd708a..35484699b17 100644
--- a/source/gameengine/Ketsji/KX_SceneActuator.cpp
+++ b/source/gameengine/Ketsji/KX_SceneActuator.cpp
@@ -58,13 +58,16 @@ KX_SceneActuator::KX_SceneActuator(SCA_IObject *gameobj,
m_KetsjiEngine=ketsjiEngine;
m_camera = camera;
m_nextSceneName = nextSceneName;
+ if (m_camera)
+ m_camera->RegisterActuator(this);
} /* End of constructor */
KX_SceneActuator::~KX_SceneActuator()
{
- // there's nothing to be done here, really....
+ if (m_camera)
+ m_camera->UnregisterActuator(this);
} /* end of destructor */
@@ -79,6 +82,34 @@ CValue* KX_SceneActuator::GetReplica()
return replica;
}
+void KX_SceneActuator::ProcessReplica()
+{
+ if (m_camera)
+ m_camera->RegisterActuator(this);
+ SCA_IActuator::ProcessReplica();
+}
+
+bool KX_SceneActuator::UnlinkObject(SCA_IObject* clientobj)
+{
+ if (clientobj == (SCA_IObject*)m_camera)
+ {
+ // this object is being deleted, we cannot continue to track it.
+ m_camera = NULL;
+ return true;
+ }
+ return false;
+}
+
+void KX_SceneActuator::Relink(GEN_Map<GEN_HashedPtr, void*> *obj_map)
+{
+ void **h_obj = (*obj_map)[m_camera];
+ if (h_obj) {
+ if (m_camera)
+ m_camera->UnregisterActuator(this);
+ m_camera = (KX_Camera*)(*h_obj);
+ m_camera->RegisterActuator(this);
+ }
+}
bool KX_SceneActuator::Update()
@@ -102,6 +133,15 @@ bool KX_SceneActuator::Update()
{
m_scene->SetActiveCamera(m_camera);
}
+ else
+ {
+ // if no camera is set and the parent object is a camera, use it as the camera
+ SCA_IObject* parent = GetParent();
+ if (parent->isA(&KX_Camera::Type))
+ {
+ m_scene->SetActiveCamera((KX_Camera*)parent);
+ }
+ }
break;
default:
break;
@@ -219,12 +259,12 @@ PyParentObject KX_SceneActuator::Parents[] =
PyMethodDef KX_SceneActuator::Methods[] =
{
- {"setUseRestart", (PyCFunction) KX_SceneActuator::sPySetUseRestart, METH_VARARGS, SetUseRestart_doc},
- {"setScene", (PyCFunction) KX_SceneActuator::sPySetScene, METH_VARARGS, SetScene_doc},
- {"setCamera", (PyCFunction) KX_SceneActuator::sPySetCamera, METH_VARARGS, SetCamera_doc},
- {"getUseRestart", (PyCFunction) KX_SceneActuator::sPyGetUseRestart, METH_VARARGS, GetUseRestart_doc},
- {"getScene", (PyCFunction) KX_SceneActuator::sPyGetScene, METH_VARARGS, GetScene_doc},
- {"getCamera", (PyCFunction) KX_SceneActuator::sPyGetCamera, METH_VARARGS, GetCamera_doc},
+ {"setUseRestart", (PyCFunction) KX_SceneActuator::sPySetUseRestart, METH_VARARGS, (PY_METHODCHAR)SetUseRestart_doc},
+ {"setScene", (PyCFunction) KX_SceneActuator::sPySetScene, METH_VARARGS, (PY_METHODCHAR)SetScene_doc},
+ {"setCamera", (PyCFunction) KX_SceneActuator::sPySetCamera, METH_VARARGS, (PY_METHODCHAR)SetCamera_doc},
+ {"getUseRestart", (PyCFunction) KX_SceneActuator::sPyGetUseRestart, METH_VARARGS, (PY_METHODCHAR)GetUseRestart_doc},
+ {"getScene", (PyCFunction) KX_SceneActuator::sPyGetScene, METH_VARARGS, (PY_METHODCHAR)GetScene_doc},
+ {"getCamera", (PyCFunction) KX_SceneActuator::sPyGetCamera, METH_VARARGS, (PY_METHODCHAR)GetCamera_doc},
{NULL,NULL} //Sentinel
};
@@ -238,7 +278,7 @@ PyObject* KX_SceneActuator::_getattr(const STR_String& attr)
/* 2. setUseRestart--------------------------------------------------------- */
-char KX_SceneActuator::SetUseRestart_doc[] =
+const char KX_SceneActuator::SetUseRestart_doc[] =
"setUseRestart(flag)\n"
"\t- flag: 0 or 1.\n"
"\tSet flag to 1 to restart the scene.\n" ;
@@ -261,7 +301,7 @@ PyObject* KX_SceneActuator::PySetUseRestart(PyObject* self,
/* 3. getUseRestart: */
-char KX_SceneActuator::GetUseRestart_doc[] =
+const char KX_SceneActuator::GetUseRestart_doc[] =
"getUseRestart()\n"
"\tReturn whether the scene will be restarted.\n" ;
PyObject* KX_SceneActuator::PyGetUseRestart(PyObject* self,
@@ -274,7 +314,7 @@ PyObject* KX_SceneActuator::PyGetUseRestart(PyObject* self,
/* 4. set scene------------------------------------------------------------- */
-char KX_SceneActuator::SetScene_doc[] =
+const char KX_SceneActuator::SetScene_doc[] =
"setScene(scene)\n"
"\t- scene: string\n"
"\tSet the name of scene the actuator will switch to.\n" ;
@@ -299,7 +339,7 @@ PyObject* KX_SceneActuator::PySetScene(PyObject* self,
/* 5. getScene: */
-char KX_SceneActuator::GetScene_doc[] =
+const char KX_SceneActuator::GetScene_doc[] =
"getScene()\n"
"\tReturn the name of the scene the actuator wants to switch to.\n" ;
PyObject* KX_SceneActuator::PyGetScene(PyObject* self,
@@ -312,7 +352,7 @@ PyObject* KX_SceneActuator::PyGetScene(PyObject* self,
/* 6. set camera------------------------------------------------------------ */
-char KX_SceneActuator::SetCamera_doc[] =
+const char KX_SceneActuator::SetCamera_doc[] =
"setCamera(camera)\n"
"\t- camera: string\n"
"\tSet the camera to switch to.\n" ;
@@ -323,7 +363,11 @@ PyObject* KX_SceneActuator::PySetCamera(PyObject* self,
PyObject *cam;
if (PyArg_ParseTuple(args, "O!", &KX_Camera::Type, &cam))
{
+ if (m_camera)
+ m_camera->UnregisterActuator(this);
m_camera = (KX_Camera*) cam;
+ if (m_camera)
+ m_camera->RegisterActuator(this);
Py_Return;
}
PyErr_Clear();
@@ -336,7 +380,13 @@ PyObject* KX_SceneActuator::PySetCamera(PyObject* self,
}
KX_Camera *camOb = FindCamera(camName);
- if (camOb) m_camera = camOb;
+ if (camOb)
+ {
+ if (m_camera)
+ m_camera->UnregisterActuator(this);
+ m_camera = camOb;
+ m_camera->RegisterActuator(this);
+ }
Py_Return;
}
@@ -344,7 +394,7 @@ PyObject* KX_SceneActuator::PySetCamera(PyObject* self,
/* 7. getCamera: */
-char KX_SceneActuator::GetCamera_doc[] =
+const char KX_SceneActuator::GetCamera_doc[] =
"getCamera()\n"
"\tReturn the name of the camera to switch to.\n" ;
PyObject* KX_SceneActuator::PyGetCamera(PyObject* self,
diff --git a/source/gameengine/Ketsji/KX_SceneActuator.h b/source/gameengine/Ketsji/KX_SceneActuator.h
index cfc79b93f8e..55aaf629d7c 100644
--- a/source/gameengine/Ketsji/KX_SceneActuator.h
+++ b/source/gameengine/Ketsji/KX_SceneActuator.h
@@ -82,6 +82,9 @@ class KX_SceneActuator : public SCA_IActuator
virtual ~KX_SceneActuator();
virtual CValue* GetReplica();
+ virtual void ProcessReplica();
+ virtual bool UnlinkObject(SCA_IObject* clientobj);
+ virtual void Relink(GEN_Map<GEN_HashedPtr, void*> *obj_map);
virtual bool Update();
diff --git a/source/gameengine/Ketsji/KX_SoundActuator.cpp b/source/gameengine/Ketsji/KX_SoundActuator.cpp
index 949156571a7..afa5af3bc04 100644
--- a/source/gameengine/Ketsji/KX_SoundActuator.cpp
+++ b/source/gameengine/Ketsji/KX_SoundActuator.cpp
@@ -69,11 +69,11 @@ KX_SoundActuator::KX_SoundActuator(SCA_IObject* gameobj,
KX_SoundActuator::~KX_SoundActuator()
{
- //m_soundScene->RemoveObject(this->m_soundObject);
- //(this->m_soundObject)->DeleteWhenFinished();
- m_soundScene->RemoveActiveObject(m_soundObject);
-// m_soundScene->DeleteObjectWhenFinished(m_soundObject);
- m_soundScene->DeleteObject(m_soundObject);
+ if (m_soundObject)
+ {
+ m_soundScene->RemoveActiveObject(m_soundObject);
+ m_soundScene->DeleteObject(m_soundObject);
+ }
}
@@ -82,9 +82,12 @@ CValue* KX_SoundActuator::GetReplica()
{
KX_SoundActuator* replica = new KX_SoundActuator(*this);
replica->ProcessReplica();
- SND_SoundObject* soundobj = new SND_SoundObject(*m_soundObject);
- replica->setSoundObject(soundobj);
- m_soundScene->AddObject(soundobj);
+ if (m_soundObject)
+ {
+ SND_SoundObject* soundobj = new SND_SoundObject(*m_soundObject);
+ replica->setSoundObject(soundobj);
+ m_soundScene->AddObject(soundobj);
+ }
// this will copy properties and so on...
CValue::AddDataToReplica(replica);
@@ -104,6 +107,12 @@ bool KX_SoundActuator::Update(double curtime, bool frame)
RemoveAllEvents();
+ if (!m_soundObject)
+ return false;
+
+ // actual audio device playing state
+ bool isplaying = (m_soundObject->GetPlaystate() != SND_STOPPED) ? true : false;
+
if (m_pino)
{
bNegativeEvent = true;
@@ -113,30 +122,40 @@ bool KX_SoundActuator::Update(double curtime, bool frame)
if (bNegativeEvent)
{
// here must be a check if it is still playing
- m_isplaying = false;
-
- switch (m_type)
+ if (m_isplaying && isplaying)
{
- case KX_SOUNDACT_PLAYSTOP:
- case KX_SOUNDACT_LOOPSTOP:
- case KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP:
- {
- m_soundScene->RemoveActiveObject(m_soundObject);
- break;
- }
- case KX_SOUNDACT_PLAYEND:
+ switch (m_type)
{
- m_soundObject->SetPlaystate(SND_MUST_STOP_WHEN_FINISHED);
+ case KX_SOUNDACT_PLAYSTOP:
+ case KX_SOUNDACT_LOOPSTOP:
+ case KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP:
+ {
+ m_soundScene->RemoveActiveObject(m_soundObject);
+ break;
+ }
+ case KX_SOUNDACT_PLAYEND:
+ {
+ m_soundObject->SetPlaystate(SND_MUST_STOP_WHEN_FINISHED);
+ break;
+ }
+ case KX_SOUNDACT_LOOPEND:
+ case KX_SOUNDACT_LOOPBIDIRECTIONAL:
+ {
+ m_soundObject->SetLoopMode(SND_LOOP_OFF);
+ m_soundObject->SetPlaystate(SND_MUST_STOP_WHEN_FINISHED);
+ break;
+ }
+ default:
+ // implement me !!
break;
}
- default:
- // implement me !!
- break;
}
+ // remember that we tried to stop the actuator
+ m_isplaying = false;
}
else
{
- if (m_soundObject && !m_isplaying)
+ if (!m_isplaying)
{
switch (m_type)
{
@@ -173,8 +192,10 @@ bool KX_SoundActuator::Update(double curtime, bool frame)
}
}
}
+ // verify that the sound is still playing
+ isplaying = (m_soundObject->GetPlaystate() != SND_STOPPED) ? true : false;
- if (m_isplaying)
+ if (isplaying)
{
m_soundObject->SetPosition(((KX_GameObject*)this->GetParent())->NodeGetWorldPosition());
m_soundObject->SetVelocity(((KX_GameObject*)this->GetParent())->GetLinearVelocity());
@@ -183,14 +204,15 @@ bool KX_SoundActuator::Update(double curtime, bool frame)
}
else
{
+ m_isplaying = false;
result = false;
}
-
+ /*
if (result && (m_soundObject->IsLifeSpanOver(curtime)) && ((m_type == KX_SOUNDACT_PLAYEND) || (m_type == KX_SOUNDACT_PLAYSTOP)))
{
m_pino = true;
}
-
+ */
return result;
}
@@ -287,11 +309,16 @@ PyObject* KX_SoundActuator::PySetFilename(PyObject* self, PyObject* args, PyObje
PyObject* KX_SoundActuator::PyGetFilename(PyObject* self, PyObject* args, PyObject* kwds)
{
+ if (!m_soundObject)
+ {
+ return PyString_FromString("");
+ }
STR_String objectname = m_soundObject->GetObjectName();
char* name = objectname.Ptr();
if (!name) {
- Py_Return; /* internal error */
+ PyErr_SetString(PyExc_RuntimeError, "Unable to get sound filename");
+ return NULL;
} else
return PyString_FromString(name);
}
@@ -300,7 +327,11 @@ PyObject* KX_SoundActuator::PyGetFilename(PyObject* self, PyObject* args, PyObje
PyObject* KX_SoundActuator::PyStartSound(PyObject* self, PyObject* args, PyObject* kwds)
{
- m_soundObject->StartSound();
+ if (m_soundObject)
+ // This has no effect if the actuator is not active.
+ // To start the sound you must activate the actuator.
+ // This function is to restart the sound.
+ m_soundObject->StartSound();
Py_Return;
}
@@ -308,7 +339,9 @@ PyObject* KX_SoundActuator::PyStartSound(PyObject* self, PyObject* args, PyObjec
PyObject* KX_SoundActuator::PyPauseSound(PyObject* self, PyObject* args, PyObject* kwds)
{
- m_soundObject->PauseSound();
+ if (m_soundObject)
+ // unfortunately, openal does not implement pause correctly, it is equivalent to a stop
+ m_soundObject->PauseSound();
Py_Return;
}
@@ -316,7 +349,8 @@ PyObject* KX_SoundActuator::PyPauseSound(PyObject* self, PyObject* args, PyObjec
PyObject* KX_SoundActuator::PyStopSound(PyObject* self, PyObject* args, PyObject* kwds)
{
- m_soundObject->StopSound();
+ if (m_soundObject)
+ m_soundObject->StopSound();
Py_Return;
}
@@ -328,7 +362,8 @@ PyObject* KX_SoundActuator::PySetGain(PyObject* self, PyObject* args, PyObject*
if (!PyArg_ParseTuple(args, "f", &gain))
return NULL;
- m_soundObject->SetGain(gain);
+ if (m_soundObject)
+ m_soundObject->SetGain(gain);
Py_Return;
}
@@ -337,7 +372,7 @@ PyObject* KX_SoundActuator::PySetGain(PyObject* self, PyObject* args, PyObject*
PyObject* KX_SoundActuator::PyGetGain(PyObject* self, PyObject* args, PyObject* kwds)
{
- float gain = m_soundObject->GetGain();
+ float gain = (m_soundObject) ? m_soundObject->GetGain() : 1.0f;
PyObject* result = PyFloat_FromDouble(gain);
return result;
@@ -351,7 +386,8 @@ PyObject* KX_SoundActuator::PySetPitch(PyObject* self, PyObject* args, PyObject*
if (!PyArg_ParseTuple(args, "f", &pitch))
return NULL;
- m_soundObject->SetPitch(pitch);
+ if (m_soundObject)
+ m_soundObject->SetPitch(pitch);
Py_Return;
}
@@ -360,7 +396,7 @@ PyObject* KX_SoundActuator::PySetPitch(PyObject* self, PyObject* args, PyObject*
PyObject* KX_SoundActuator::PyGetPitch(PyObject* self, PyObject* args, PyObject* kwds)
{
- float pitch = m_soundObject->GetPitch();
+ float pitch = (m_soundObject) ? m_soundObject->GetPitch() : 1.0;
PyObject* result = PyFloat_FromDouble(pitch);
return result;
@@ -374,7 +410,8 @@ PyObject* KX_SoundActuator::PySetRollOffFactor(PyObject* self, PyObject* args, P
if (!PyArg_ParseTuple(args, "f", &rollofffactor))
return NULL;
- m_soundObject->SetRollOffFactor(rollofffactor);
+ if (m_soundObject)
+ m_soundObject->SetRollOffFactor(rollofffactor);
Py_Return;
}
@@ -383,7 +420,7 @@ PyObject* KX_SoundActuator::PySetRollOffFactor(PyObject* self, PyObject* args, P
PyObject* KX_SoundActuator::PyGetRollOffFactor(PyObject* self, PyObject* args, PyObject* kwds)
{
- float rollofffactor = m_soundObject->GetRollOffFactor();
+ float rollofffactor = (m_soundObject) ? m_soundObject->GetRollOffFactor() : 1.0;
PyObject* result = PyFloat_FromDouble(rollofffactor);
return result;
@@ -397,7 +434,8 @@ PyObject* KX_SoundActuator::PySetLooping(PyObject* self, PyObject* args, PyObjec
if (!PyArg_ParseTuple(args, "i", &looping))
return NULL;
- m_soundObject->SetLoopMode(looping);
+ if (m_soundObject)
+ m_soundObject->SetLoopMode(looping);
Py_Return;
}
@@ -406,7 +444,7 @@ PyObject* KX_SoundActuator::PySetLooping(PyObject* self, PyObject* args, PyObjec
PyObject* KX_SoundActuator::PyGetLooping(PyObject* self, PyObject* args, PyObject* kwds)
{
- int looping = m_soundObject->GetLoopMode();
+ int looping = (m_soundObject) ? m_soundObject->GetLoopMode() : SND_LOOP_OFF;
PyObject* result = PyInt_FromLong(looping);
return result;
@@ -424,7 +462,8 @@ PyObject* KX_SoundActuator::PySetPosition(PyObject* self, PyObject* args, PyObje
if (!PyArg_ParseTuple(args, "fff", &pos[0], &pos[1], &pos[2]))
return NULL;
- m_soundObject->SetPosition(pos);
+ if (m_soundObject)
+ m_soundObject->SetPosition(pos);
Py_Return;
}
@@ -441,7 +480,8 @@ PyObject* KX_SoundActuator::PySetVelocity(PyObject* self, PyObject* args, PyObje
if (!PyArg_ParseTuple(args, "fff", &vel[0], &vel[1], &vel[2]))
return NULL;
- m_soundObject->SetVelocity(vel);
+ if (m_soundObject)
+ m_soundObject->SetVelocity(vel);
Py_Return;
}
@@ -464,7 +504,8 @@ PyObject* KX_SoundActuator::PySetOrientation(PyObject* self, PyObject* args, PyO
if (!PyArg_ParseTuple(args, "fffffffff", &ori[0][0], &ori[0][1], &ori[0][2], &ori[1][0], &ori[1][1], &ori[1][2], &ori[2][0], &ori[2][1], &ori[2][2]))
return NULL;
- m_soundObject->SetOrientation(ori);
+ if (m_soundObject)
+ m_soundObject->SetOrientation(ori);
Py_Return;
}
diff --git a/source/gameengine/Ketsji/KX_StateActuator.cpp b/source/gameengine/Ketsji/KX_StateActuator.cpp
new file mode 100644
index 00000000000..e360c4bac1f
--- /dev/null
+++ b/source/gameengine/Ketsji/KX_StateActuator.cpp
@@ -0,0 +1,207 @@
+/*
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ * Actuator to toggle visibility/invisibility of objects
+ */
+
+#include "KX_StateActuator.h"
+#include "KX_GameObject.h"
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+KX_StateActuator::KX_StateActuator(
+ SCA_IObject* gameobj,
+ int operation,
+ unsigned int mask,
+ PyTypeObject* T
+ )
+ : SCA_IActuator(gameobj,T),
+ m_operation(operation),
+ m_mask(mask)
+{
+ // intentionally empty
+}
+
+KX_StateActuator::~KX_StateActuator(
+ void
+ )
+{
+ // intentionally empty
+}
+
+CValue*
+KX_StateActuator::GetReplica(
+ void
+ )
+{
+ KX_StateActuator* replica = new KX_StateActuator(*this);
+ replica->ProcessReplica();
+ // this will copy properties and so on...
+ CValue::AddDataToReplica(replica);
+ return replica;
+}
+
+bool
+KX_StateActuator::Update()
+{
+ bool bNegativeEvent = IsNegativeEvent();
+ unsigned int objMask;
+
+ RemoveAllEvents();
+ if (bNegativeEvent) return false;
+
+ KX_GameObject *obj = (KX_GameObject*) GetParent();
+
+ objMask = obj->GetState();
+ switch (m_operation)
+ {
+ case OP_CPY:
+ objMask = m_mask;
+ break;
+ case OP_SET:
+ objMask |= m_mask;
+ break;
+ case OP_CLR:
+ objMask &= ~m_mask;
+ break;
+ case OP_NEG:
+ objMask ^= m_mask;
+ break;
+ default:
+ // unsupported operation, no nothing
+ return false;
+ }
+ obj->SetState(objMask);
+ return false;
+}
+
+/* ------------------------------------------------------------------------- */
+/* Python functions */
+/* ------------------------------------------------------------------------- */
+
+
+
+/* Integration hooks ------------------------------------------------------- */
+PyTypeObject
+KX_StateActuator::Type = {
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0,
+ "KX_StateActuator",
+ sizeof(KX_StateActuator),
+ 0,
+ PyDestructor,
+ 0,
+ __getattr,
+ __setattr,
+ 0, //&MyPyCompare,
+ __repr,
+ 0, //&cvalue_as_number,
+ 0,
+ 0,
+ 0,
+ 0
+};
+
+PyParentObject
+KX_StateActuator::Parents[] = {
+ &KX_StateActuator::Type,
+ &SCA_IActuator::Type,
+ &SCA_ILogicBrick::Type,
+ &CValue::Type,
+ NULL
+};
+
+PyMethodDef
+KX_StateActuator::Methods[] = {
+ {"setOperation", (PyCFunction) KX_StateActuator::sPySetOperation,
+ METH_VARARGS, (PY_METHODCHAR)SetOperation_doc},
+ {"setMask", (PyCFunction) KX_StateActuator::sPySetMask,
+ METH_VARARGS, (PY_METHODCHAR)SetMask_doc},
+ {NULL,NULL} //Sentinel
+};
+
+PyObject*
+KX_StateActuator::_getattr(
+ const STR_String& attr
+ )
+{
+ _getattr_up(SCA_IActuator);
+};
+
+
+
+/* set operation ---------------------------------------------------------- */
+const char
+KX_StateActuator::SetOperation_doc[] =
+"setOperation(op)\n"
+"\t - op : bit operation (0=Copy, 1=Set, 2=Clear, 3=Negate)"
+"\tSet the type of bit operation to be applied on object state mask.\n"
+"\tUse setMask() to specify the bits that will be modified.\n";
+PyObject*
+
+KX_StateActuator::PySetOperation(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ int oper;
+
+ if(!PyArg_ParseTuple(args, "i", &oper)) {
+ return NULL;
+ }
+
+ m_operation = oper;
+
+ Py_Return;
+}
+
+/* set mask ---------------------------------------------------------- */
+const char
+KX_StateActuator::SetMask_doc[] =
+"setMask(mask)\n"
+"\t - mask : bits that will be modified"
+"\tSet the value that defines the bits that will be modified by the operation.\n"
+"\tThe bits that are 1 in the value will be updated in the object state,\n"
+"\tthe bits that are 0 are will be left unmodified expect for the Copy operation\n"
+"\twhich copies the value to the object state.\n";
+PyObject*
+
+KX_StateActuator::PySetMask(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ int mask;
+
+ if(!PyArg_ParseTuple(args, "i", &mask)) {
+ return NULL;
+ }
+
+ m_mask = mask;
+
+ Py_Return;
+}
+
+
diff --git a/source/gameengine/Ketsji/KX_StateActuator.h b/source/gameengine/Ketsji/KX_StateActuator.h
new file mode 100644
index 00000000000..8698e51b2c1
--- /dev/null
+++ b/source/gameengine/Ketsji/KX_StateActuator.h
@@ -0,0 +1,83 @@
+/*
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ * Actuator to toggle visibility/invisibility of objects
+ */
+
+#ifndef __KX_STATEACTUATOR
+#define __KX_STATEACTUATOR
+
+#include "SCA_IActuator.h"
+
+class KX_StateActuator : public SCA_IActuator
+{
+ Py_Header;
+
+ /** Make visible? */
+ enum {
+ OP_CPY = 0,
+ OP_SET,
+ OP_CLR,
+ OP_NEG
+ };
+ int m_operation;
+ unsigned int m_mask;
+
+ public:
+
+ KX_StateActuator(
+ SCA_IObject* gameobj,
+ int operation,
+ unsigned int mask,
+ PyTypeObject* T=&Type
+ );
+
+ virtual
+ ~KX_StateActuator(
+ void
+ );
+
+ virtual CValue*
+ GetReplica(
+ void
+ );
+
+ virtual bool
+ Update();
+
+ /* --------------------------------------------------------------------- */
+ /* Python interface ---------------------------------------------------- */
+ /* --------------------------------------------------------------------- */
+
+ virtual PyObject* _getattr(const STR_String& attr);
+ //KX_PYMETHOD_DOC
+ KX_PYMETHOD_DOC(KX_StateActuator,SetOperation);
+ KX_PYMETHOD_DOC(KX_StateActuator,SetMask);
+};
+
+#endif
+
diff --git a/source/gameengine/Ketsji/KX_SumoPhysicsController.cpp b/source/gameengine/Ketsji/KX_SumoPhysicsController.cpp
index 6ea5461dbaa..c842ca1ee14 100644
--- a/source/gameengine/Ketsji/KX_SumoPhysicsController.cpp
+++ b/source/gameengine/Ketsji/KX_SumoPhysicsController.cpp
@@ -101,7 +101,7 @@ void KX_SumoPhysicsController::SetSumoTransform(bool nondynaonly)
}
-void KX_SumoPhysicsController::SuspendDynamics()
+void KX_SumoPhysicsController::SuspendDynamics(bool)
{
SumoPhysicsController::SuspendDynamics();
}
@@ -170,8 +170,9 @@ void KX_SumoPhysicsController::setMargin(float collisionMargin)
}
-void KX_SumoPhysicsController::setOrientation(const MT_Quaternion& orn)
+void KX_SumoPhysicsController::setOrientation(const MT_Matrix3x3& rot)
{
+ MT_Quaternion orn = rot.getRotation();
SumoPhysicsController::setOrientation(
orn[0],orn[1],orn[2],orn[3]);
@@ -204,6 +205,11 @@ MT_Scalar KX_SumoPhysicsController::GetMass()
return SumoPhysicsController::getMass();
}
+MT_Scalar KX_SumoPhysicsController::GetRadius()
+{
+ return SumoPhysicsController::GetRadius();
+}
+
MT_Vector3 KX_SumoPhysicsController::getReactionForce()
{
float force[3];
diff --git a/source/gameengine/Ketsji/KX_SumoPhysicsController.h b/source/gameengine/Ketsji/KX_SumoPhysicsController.h
index 868465c8f10..abe48d99043 100644
--- a/source/gameengine/Ketsji/KX_SumoPhysicsController.h
+++ b/source/gameengine/Ketsji/KX_SumoPhysicsController.h
@@ -68,20 +68,23 @@ public:
void ApplyTorque(const MT_Vector3& torque,bool local);
void ApplyForce(const MT_Vector3& force,bool local);
MT_Vector3 GetLinearVelocity();
+ MT_Vector3 GetAngularVelocity() // to keep compiler happy
+ { return MT_Vector3(0.0,0.0,0.0); }
MT_Vector3 GetVelocity(const MT_Point3& pos);
void SetAngularVelocity(const MT_Vector3& ang_vel,bool local);
void SetLinearVelocity(const MT_Vector3& lin_vel,bool local);
void resolveCombinedVelocities(float linvelX,float linvelY,float linvelZ,float angVelX,float angVelY,float angVelZ);
- void SuspendDynamics();
+ void SuspendDynamics(bool);
void RestoreDynamics();
virtual void getOrientation(MT_Quaternion& orn);
- virtual void setOrientation(const MT_Quaternion& orn);
+ virtual void setOrientation(const MT_Matrix3x3& orn);
virtual void setPosition(const MT_Point3& pos);
virtual void setScaling(const MT_Vector3& scaling);
virtual MT_Scalar GetMass();
+ virtual MT_Scalar GetRadius();
virtual MT_Vector3 getReactionForce();
virtual void setRigidBody(bool rigid);
diff --git a/source/gameengine/Ketsji/KX_TouchEventManager.cpp b/source/gameengine/Ketsji/KX_TouchEventManager.cpp
index 2da899c62cb..48d4cf59a2b 100644
--- a/source/gameengine/Ketsji/KX_TouchEventManager.cpp
+++ b/source/gameengine/Ketsji/KX_TouchEventManager.cpp
@@ -51,6 +51,7 @@ KX_TouchEventManager::KX_TouchEventManager(class SCA_LogicManager* logicmgr,
m_physEnv->addTouchCallback(PHY_OBJECT_RESPONSE, KX_TouchEventManager::newCollisionResponse, this);
m_physEnv->addTouchCallback(PHY_SENSOR_RESPONSE, KX_TouchEventManager::newCollisionResponse, this);
+ m_physEnv->addTouchCallback(PHY_BROADPH_RESPONSE, KX_TouchEventManager::newBroadphaseResponse, this);
}
@@ -76,19 +77,47 @@ bool KX_TouchEventManager::newCollisionResponse(void *client_data,
return false;
}
+bool KX_TouchEventManager::newBroadphaseResponse(void *client_data,
+ void *object1,
+ void *object2,
+ const PHY_CollData *coll_data)
+{
+ PHY_IPhysicsController* ctrl = static_cast<PHY_IPhysicsController*>(object1);
+ KX_ClientObjectInfo* info = (ctrl) ? static_cast<KX_ClientObjectInfo*>(ctrl->getNewClientInfo()) : NULL;
+ // This call back should only be called for controllers of Near and Radar sensor
+ if (info &&
+ info->m_sensors.size() == 1 &&
+ (info->m_type == KX_ClientObjectInfo::NEAR ||
+ info->m_type == KX_ClientObjectInfo::RADAR))
+ {
+ // only one sensor for this type of object
+ KX_TouchSensor* touchsensor = static_cast<KX_TouchSensor*>(*info->m_sensors.begin());
+ return touchsensor->BroadPhaseFilterCollision(object1,object2);
+ }
+ return true;
+}
+
void KX_TouchEventManager::RegisterSensor(SCA_ISensor* sensor)
{
KX_TouchSensor* touchsensor = static_cast<KX_TouchSensor*>(sensor);
- m_sensors.push_back(touchsensor);
+ if (m_sensors.insert(touchsensor).second)
+ // the sensor was effectively inserted, register it
+ touchsensor->RegisterSumo(this);
+}
- touchsensor->RegisterSumo(this);
+void KX_TouchEventManager::RemoveSensor(SCA_ISensor* sensor)
+{
+ KX_TouchSensor* touchsensor = static_cast<KX_TouchSensor*>(sensor);
+ if (m_sensors.erase(touchsensor))
+ // the sensor was effectively removed, unregister it
+ touchsensor->UnregisterSumo(this);
}
void KX_TouchEventManager::EndFrame()
{
- vector<SCA_ISensor*>::iterator it;
+ set<SCA_ISensor*>::iterator it;
for ( it = m_sensors.begin();
!(it==m_sensors.end());it++)
{
@@ -103,7 +132,7 @@ void KX_TouchEventManager::NextFrame()
{
if (m_sensors.size() > 0)
{
- vector<SCA_ISensor*>::iterator it;
+ set<SCA_ISensor*>::iterator it;
for (it = m_sensors.begin();!(it==m_sensors.end());++it)
static_cast<KX_TouchSensor*>(*it)->SynchronizeTransform();
@@ -116,14 +145,18 @@ void KX_TouchEventManager::NextFrame()
// KX_GameObject* gameOb1 = ctrl1->getClientInfo();
KX_ClientObjectInfo *client_info = static_cast<KX_ClientObjectInfo *>(ctrl1->getNewClientInfo());
-
list<SCA_ISensor*>::iterator sit;
- for ( sit = client_info->m_sensors.begin(); sit != client_info->m_sensors.end(); ++sit)
- static_cast<KX_TouchSensor*>(*sit)->NewHandleCollision((*cit).first, (*cit).second, NULL);
-
+ if (client_info) {
+ for ( sit = client_info->m_sensors.begin(); sit != client_info->m_sensors.end(); ++sit) {
+ static_cast<KX_TouchSensor*>(*sit)->NewHandleCollision((*cit).first, (*cit).second, NULL);
+ }
+ }
client_info = static_cast<KX_ClientObjectInfo *>((*cit).second->getNewClientInfo());
- for ( sit = client_info->m_sensors.begin(); sit != client_info->m_sensors.end(); ++sit)
- static_cast<KX_TouchSensor*>(*sit)->NewHandleCollision((*cit).second, (*cit).first, NULL);
+ if (client_info) {
+ for ( sit = client_info->m_sensors.begin(); sit != client_info->m_sensors.end(); ++sit) {
+ static_cast<KX_TouchSensor*>(*sit)->NewHandleCollision((*cit).second, (*cit).first, NULL);
+ }
+ }
}
m_newCollisions.clear();
@@ -132,20 +165,3 @@ void KX_TouchEventManager::NextFrame()
(*it)->Activate(m_logicmgr,NULL);
}
}
-
-
-
-void KX_TouchEventManager::RemoveSensor(class SCA_ISensor* sensor)
-{
- std::vector<SCA_ISensor*>::iterator i =
- std::find(m_sensors.begin(), m_sensors.end(), sensor);
- if (!(i == m_sensors.end()))
- {
- std::swap(*i, m_sensors.back());
- m_sensors.pop_back();
- }
-
- // remove the sensor forever :)
- SCA_EventManager::RemoveSensor(sensor);
-}
-
diff --git a/source/gameengine/Ketsji/KX_TouchEventManager.h b/source/gameengine/Ketsji/KX_TouchEventManager.h
index d15128284da..cc77bccfc31 100644
--- a/source/gameengine/Ketsji/KX_TouchEventManager.h
+++ b/source/gameengine/Ketsji/KX_TouchEventManager.h
@@ -53,7 +53,12 @@ class KX_TouchEventManager : public SCA_EventManager
void *object1,
void *object2,
const PHY_CollData *coll_data);
-
+
+ static bool newBroadphaseResponse(void *client_data,
+ void *object1,
+ void *object2,
+ const PHY_CollData *coll_data);
+
virtual bool NewHandleCollision(void* obj1,void* obj2,
const PHY_CollData * coll_data);
@@ -66,8 +71,8 @@ public:
PHY_IPhysicsEnvironment* physEnv);
virtual void NextFrame();
virtual void EndFrame();
- virtual void RemoveSensor(class SCA_ISensor* sensor);
virtual void RegisterSensor(SCA_ISensor* sensor);
+ virtual void RemoveSensor(SCA_ISensor* sensor);
SCA_LogicManager* GetLogicManager() { return m_logicmgr;}
PHY_IPhysicsEnvironment *GetPhysicsEnvironment() { return m_physEnv; }
diff --git a/source/gameengine/Ketsji/KX_TouchSensor.cpp b/source/gameengine/Ketsji/KX_TouchSensor.cpp
index 62e400a7049..1935a0bde39 100644
--- a/source/gameengine/Ketsji/KX_TouchSensor.cpp
+++ b/source/gameengine/Ketsji/KX_TouchSensor.cpp
@@ -48,30 +48,30 @@
void KX_TouchSensor::SynchronizeTransform()
{
-
- if (m_physCtrl)
- {
-
- KX_GameObject* parent = ((KX_GameObject*)GetParent());
- MT_Vector3 pos = parent->NodeGetWorldPosition();
- MT_Quaternion orn = parent->NodeGetWorldOrientation().getRotation();
- m_physCtrl->setPosition(pos.x(),pos.y(),pos.z());
- m_physCtrl->setOrientation(orn.x(),orn.y(),orn.z(),orn.w());
- m_physCtrl->calcXform();
- }
-
+ // the touch sensor does not require any synchronization: it uses
+ // the same physical object which is already synchronized by Blender
}
void KX_TouchSensor::EndFrame() {
m_colliders->ReleaseAndRemoveAll();
+ m_hitObject = NULL;
m_bTriggered = false;
}
+void KX_TouchSensor::UnregisterToManager()
+{
+ // before unregistering the sensor, make sure we release all references
+ EndFrame();
+ m_eventmgr->RemoveSensor(this);
+}
+
bool KX_TouchSensor::Evaluate(CValue* event)
{
bool result = false;
+ bool reset = m_reset && m_level;
+ m_reset = false;
if (m_bTriggered != m_bLastTriggered)
{
m_bLastTriggered = m_bTriggered;
@@ -79,7 +79,9 @@ bool KX_TouchSensor::Evaluate(CValue* event)
m_hitObject = NULL;
result = true;
}
-
+ if (reset)
+ // force an event
+ result = true;
return result;
}
@@ -87,18 +89,14 @@ KX_TouchSensor::KX_TouchSensor(SCA_EventManager* eventmgr,KX_GameObject* gameobj
:SCA_ISensor(gameobj,eventmgr,T),
m_touchedpropname(touchedpropname),
m_bFindMaterial(bFindMaterial),
-m_eventmgr(eventmgr),
+m_eventmgr(eventmgr)
/*m_sumoObj(sumoObj),*/
-m_bCollision(false),
-m_bTriggered(false),
-m_bLastTriggered(false)
{
// KX_TouchEventManager* touchmgr = (KX_TouchEventManager*) eventmgr;
// m_resptable = touchmgr->GetResponseTable();
// m_solidHandle = m_sumoObj->getObjectHandle();
- m_hitObject = NULL;
m_colliders = new CListValue();
KX_ClientObjectInfo *client_info = gameobj->getClientInfo();
@@ -108,8 +106,17 @@ m_bLastTriggered(false)
m_physCtrl = dynamic_cast<PHY_IPhysicsController*>(gameobj->GetPhysicsController());
MT_assert( !gameobj->GetPhysicsController() || m_physCtrl );
+ Init();
}
+void KX_TouchSensor::Init()
+{
+ m_bCollision = false;
+ m_bTriggered = false;
+ m_bLastTriggered = (m_invert)?true:false;
+ m_hitObject = NULL;
+ m_reset = true;
+}
KX_TouchSensor::~KX_TouchSensor()
{
@@ -121,10 +128,7 @@ CValue* KX_TouchSensor::GetReplica()
{
KX_TouchSensor* replica = new KX_TouchSensor(*this);
replica->m_colliders = new CListValue();
- replica->m_bCollision = false;
- replica->m_bTriggered= false;
- replica->m_hitObject = NULL;
- replica->m_bLastTriggered = false;
+ replica->Init();
// this will copy properties and so on...
CValue::AddDataToReplica(replica);
return replica;
@@ -157,6 +161,14 @@ void KX_TouchSensor::RegisterSumo(KX_TouchEventManager *touchman)
}
}
+void KX_TouchSensor::UnregisterSumo(KX_TouchEventManager* touchman)
+{
+ if (m_physCtrl)
+ {
+ touchman->GetPhysicsEnvironment()->removeCollisionCallback(m_physCtrl);
+ }
+}
+
bool KX_TouchSensor::NewHandleCollision(void*object1,void*object2,const PHY_CollData* colldata)
{
// KX_TouchEventManager* toucheventmgr = (KX_TouchEventManager*)m_eventmgr;
@@ -172,7 +184,10 @@ bool KX_TouchSensor::NewHandleCollision(void*object1,void*object2,const PHY_Coll
client_info->m_gameobject :
NULL);
- if (gameobj && (gameobj != parent) && client_info->isActor())
+ // add the same check as in SCA_ISensor::Activate(),
+ // we don't want to record collision when the sensor is not active.
+ if (m_links && !m_suspended &&
+ gameobj && (gameobj != parent) && client_info->isActor())
{
if (!m_colliders->SearchValue(gameobj))
m_colliders->Add(gameobj->AddRef());
@@ -236,13 +251,13 @@ PyParentObject KX_TouchSensor::Parents[] = {
PyMethodDef KX_TouchSensor::Methods[] = {
{"setProperty",
- (PyCFunction) KX_TouchSensor::sPySetProperty, METH_VARARGS, SetProperty_doc},
+ (PyCFunction) KX_TouchSensor::sPySetProperty, METH_VARARGS, (PY_METHODCHAR)SetProperty_doc},
{"getProperty",
- (PyCFunction) KX_TouchSensor::sPyGetProperty, METH_VARARGS, GetProperty_doc},
+ (PyCFunction) KX_TouchSensor::sPyGetProperty, METH_VARARGS, (PY_METHODCHAR)GetProperty_doc},
{"getHitObject",
- (PyCFunction) KX_TouchSensor::sPyGetHitObject, METH_VARARGS, GetHitObject_doc},
+ (PyCFunction) KX_TouchSensor::sPyGetHitObject, METH_VARARGS, (PY_METHODCHAR)GetHitObject_doc},
{"getHitObjectList",
- (PyCFunction) KX_TouchSensor::sPyGetHitObjectList, METH_VARARGS, GetHitObjectList_doc},
+ (PyCFunction) KX_TouchSensor::sPyGetHitObjectList, METH_VARARGS, (PY_METHODCHAR)GetHitObjectList_doc},
{NULL,NULL} //Sentinel
};
@@ -253,7 +268,7 @@ PyObject* KX_TouchSensor::_getattr(const STR_String& attr) {
/* Python API */
/* 1. setProperty */
-char KX_TouchSensor::SetProperty_doc[] =
+const char KX_TouchSensor::SetProperty_doc[] =
"setProperty(name)\n"
"\t- name: string\n"
"\tSet the property or material to collide with. Use\n"
@@ -271,15 +286,15 @@ PyObject* KX_TouchSensor::PySetProperty(PyObject* self,
if (!prop->IsError()) {
m_touchedpropname = nameArg;
- prop->Release();
} else {
; /* not found ... */
}
+ prop->Release();
Py_Return;
}
/* 2. getProperty */
-char KX_TouchSensor::GetProperty_doc[] =
+const char KX_TouchSensor::GetProperty_doc[] =
"getProperty(name)\n"
"\tReturns the property or material to collide with. Use\n"
"\tgetTouchMaterial() to find out whether this sensor\n"
@@ -290,7 +305,7 @@ PyObject* KX_TouchSensor::PyGetProperty(PyObject* self,
return PyString_FromString(m_touchedpropname);
}
-char KX_TouchSensor::GetHitObject_doc[] =
+const char KX_TouchSensor::GetHitObject_doc[] =
"getHitObject()\n"
;
PyObject* KX_TouchSensor::PyGetHitObject(PyObject* self,
@@ -306,7 +321,7 @@ PyObject* KX_TouchSensor::PyGetHitObject(PyObject* self,
Py_Return;
}
-char KX_TouchSensor::GetHitObjectList_doc[] =
+const char KX_TouchSensor::GetHitObjectList_doc[] =
"getHitObjectList()\n"
"\tReturn a list of the objects this object collided with,\n"
"\tbut only those matching the property/material condition.\n";
@@ -348,8 +363,8 @@ PyObject* KX_TouchSensor::PyGetHitObjectList(PyObject* self,
CValue* val = m_colliders->GetValue(i)->FindIdentifier(m_touchedpropname);
if (!val->IsError()) {
newList->Add(m_colliders->GetValue(i)->AddRef());
- val->Release();
}
+ val->Release();
}
i++;
@@ -360,7 +375,7 @@ PyObject* KX_TouchSensor::PyGetHitObjectList(PyObject* self,
}
/* 5. getTouchMaterial */
-char KX_TouchSensor::GetTouchMaterial_doc[] =
+const char KX_TouchSensor::GetTouchMaterial_doc[] =
"getTouchMaterial()\n"
"\tReturns KX_TRUE if this sensor looks for a specific material,\n"
"\tKX_FALSE if it looks for a specific property.\n" ;
@@ -372,7 +387,7 @@ PyObject* KX_TouchSensor::PyGetTouchMaterial(PyObject* self,
}
/* 6. setTouchMaterial */
-char KX_TouchSensor::SetTouchMaterial_doc[] =
+const char KX_TouchSensor::SetTouchMaterial_doc[] =
"setTouchMaterial(flag)\n"
"\t- flag: KX_TRUE or KX_FALSE.\n"
"\tSet flag to KX_TRUE to switch on positive pulse mode,\n"
diff --git a/source/gameengine/Ketsji/KX_TouchSensor.h b/source/gameengine/Ketsji/KX_TouchSensor.h
index dd869fa69c9..8fbb1c676ba 100644
--- a/source/gameengine/Ketsji/KX_TouchSensor.h
+++ b/source/gameengine/Ketsji/KX_TouchSensor.h
@@ -54,8 +54,6 @@ protected:
class SCA_EventManager* m_eventmgr;
class PHY_IPhysicsController* m_physCtrl;
- class PHY_ResponseTable* m_responstTable;
- class PHY_PhysicsController* m_responsObject;
bool m_bCollision;
bool m_bTriggered;
@@ -74,16 +72,23 @@ public:
virtual CValue* GetReplica();
virtual void SynchronizeTransform();
virtual bool Evaluate(CValue* event);
+ virtual void Init();
virtual void ReParent(SCA_IObject* parent);
virtual void RegisterSumo(KX_TouchEventManager* touchman);
+ virtual void UnregisterSumo(KX_TouchEventManager* touchman);
+ virtual void UnregisterToManager();
// virtual DT_Bool HandleCollision(void* obj1,void* obj2,
// const DT_CollData * coll_data);
virtual bool NewHandleCollision(void*obj1,void*obj2,const PHY_CollData* colldata);
- PHY_PhysicsController* GetPhysicsController() { return m_responsObject;}
+ // Allows to do pre-filtering and save computation time
+ // obj1 = sensor physical controller, obj2 = physical controller of second object
+ // return value = true if collision should be checked on pair of object
+ virtual bool BroadPhaseFilterCollision(void*obj1,void*obj2) { return true; }
+
virtual bool IsPositiveTrigger() {
diff --git a/source/gameengine/Ketsji/KX_TrackToActuator.cpp b/source/gameengine/Ketsji/KX_TrackToActuator.cpp
index dc637bf0837..acc4a6ab5d7 100644
--- a/source/gameengine/Ketsji/KX_TrackToActuator.cpp
+++ b/source/gameengine/Ketsji/KX_TrackToActuator.cpp
@@ -42,6 +42,8 @@
#include <iostream>
#include "KX_GameObject.h"
+#include "PyObjectPlus.h"
+
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
@@ -69,12 +71,19 @@ KX_TrackToActuator::KX_TrackToActuator(SCA_IObject *gameobj,
m_upflag = upflag;
m_parentobj = 0;
- if (m_object){
- KX_GameObject* curobj = (KX_GameObject*) GetParent();
+ if (m_object)
+ m_object->RegisterActuator(this);
- m_parentobj = curobj->GetParent(); // check if the object is parented
- if (m_parentobj) { // if so, store the initial local rotation
- m_parentlocalmat = m_parentobj->GetSGNode()->GetLocalOrientation();
+ if (gameobj->isA(&KX_GameObject::Type))
+ {
+ // if the object is vertex parented, don't check parent orientation as the link is broken
+ if (!((KX_GameObject*)gameobj)->IsVertexParent()){
+ m_parentobj = ((KX_GameObject*)gameobj)->GetParent(); // check if the object is parented
+ if (m_parentobj) {
+ // if so, store the initial local rotation
+ // this is needed to revert the effect of the parent inverse node (TBC)
+ m_parentlocalmat = m_parentobj->GetSGNode()->GetLocalOrientation();
+ }
}
}
@@ -139,19 +148,19 @@ void compatible_eulFast(float *eul, float *oldrot)
{
float dx, dy, dz;
- /* verschillen van ong 360 graden corrigeren */
+ /* angular difference of 360 degrees */
dx= eul[0] - oldrot[0];
dy= eul[1] - oldrot[1];
dz= eul[2] - oldrot[2];
- if( fabs(dx) > 5.1) {
+ if( fabs(dx) > MT_PI) {
if(dx > 0.0) eul[0] -= MT_2_PI; else eul[0]+= MT_2_PI;
}
- if( fabs(dy) > 5.1) {
+ if( fabs(dy) > MT_PI) {
if(dy > 0.0) eul[1] -= MT_2_PI; else eul[1]+= MT_2_PI;
}
- if( fabs(dz) > 5.1 ) {
+ if( fabs(dz) > MT_PI ) {
if(dz > 0.0) eul[2] -= MT_2_PI; else eul[2]+= MT_2_PI;
}
}
@@ -176,10 +185,53 @@ MT_Matrix3x3 matrix3x3_interpol(MT_Matrix3x3 oldmat, MT_Matrix3x3 mat, int m_tim
KX_TrackToActuator::~KX_TrackToActuator()
-{
- // there's nothing to be done here, really....
+{
+ if (m_object)
+ m_object->UnregisterActuator(this);
+ if (m_parentobj)
+ m_parentobj->Release();
} /* end of destructor */
+void KX_TrackToActuator::ProcessReplica()
+{
+ // the replica is tracking the same object => register it
+ if (m_object)
+ m_object->RegisterActuator(this);
+ if (m_parentobj)
+ m_parentobj->AddRef();
+ SCA_IActuator::ProcessReplica();
+}
+
+
+bool KX_TrackToActuator::UnlinkObject(SCA_IObject* clientobj)
+{
+ if (clientobj == m_object)
+ {
+ // this object is being deleted, we cannot continue to track it.
+ m_object = NULL;
+ return true;
+ }
+ return false;
+}
+
+void KX_TrackToActuator::Relink(GEN_Map<GEN_HashedPtr, void*> *obj_map)
+{
+ void **h_obj = (*obj_map)[m_object];
+ if (h_obj) {
+ if (m_object)
+ m_object->UnregisterActuator(this);
+ m_object = (SCA_IObject*)(*h_obj);
+ m_object->RegisterActuator(this);
+ }
+
+ void **h_parobj = (*obj_map)[m_parentobj];
+ if (h_parobj) {
+ if (m_parentobj)
+ m_parentobj->Release();
+ m_parentobj= (KX_GameObject*)(*h_parobj);
+ m_parentobj->AddRef();
+ }
+}
bool KX_TrackToActuator::Update(double curtime, bool frame)
@@ -196,7 +248,8 @@ bool KX_TrackToActuator::Update(double curtime, bool frame)
{
KX_GameObject* curobj = (KX_GameObject*) GetParent();
MT_Vector3 dir = ((KX_GameObject*)m_object)->NodeGetWorldPosition() - curobj->NodeGetWorldPosition();
- dir.normalize();
+ if (dir.length2())
+ dir.normalize();
MT_Vector3 up(0,0,1);
@@ -222,12 +275,12 @@ bool KX_TrackToActuator::Update(double curtime, bool frame)
#endif
if (m_allow3D)
{
- up = (up - up.dot(dir) * dir).normalized();
+ up = (up - up.dot(dir) * dir).safe_normalized();
}
else
{
- dir = (dir - up.dot(dir)*up).normalized();
+ dir = (dir - up.dot(dir)*up).safe_normalized();
}
MT_Vector3 left;
@@ -238,8 +291,8 @@ bool KX_TrackToActuator::Update(double curtime, bool frame)
case 0: // TRACK X
{
// (1.0 , 0.0 , 0.0 ) x direction is forward, z (0.0 , 0.0 , 1.0 ) up
- left = dir.normalized();
- dir = (left.cross(up)).normalized();
+ left = dir.safe_normalized();
+ dir = (left.cross(up)).safe_normalized();
mat.setValue (
left[0], dir[0],up[0],
left[1], dir[1],up[1],
@@ -251,7 +304,7 @@ bool KX_TrackToActuator::Update(double curtime, bool frame)
case 1: // TRACK Y
{
// (0.0 , 1.0 , 0.0 ) y direction is forward, z (0.0 , 0.0 , 1.0 ) up
- left = (dir.cross(up)).normalized();
+ left = (dir.cross(up)).safe_normalized();
mat.setValue (
left[0], dir[0],up[0],
left[1], dir[1],up[1],
@@ -263,10 +316,10 @@ bool KX_TrackToActuator::Update(double curtime, bool frame)
case 2: // track Z
{
- left = up.normalized();
- up = dir.normalized();
+ left = up.safe_normalized();
+ up = dir.safe_normalized();
dir = left;
- left = (dir.cross(up)).normalized();
+ left = (dir.cross(up)).safe_normalized();
mat.setValue (
left[0], dir[0],up[0],
left[1], dir[1],up[1],
@@ -278,8 +331,8 @@ bool KX_TrackToActuator::Update(double curtime, bool frame)
case 3: // TRACK -X
{
// (1.0 , 0.0 , 0.0 ) x direction is forward, z (0.0 , 0.0 , 1.0 ) up
- left = -dir.normalized();
- dir = -(left.cross(up)).normalized();
+ left = -dir.safe_normalized();
+ dir = -(left.cross(up)).safe_normalized();
mat.setValue (
left[0], dir[0],up[0],
left[1], dir[1],up[1],
@@ -291,7 +344,7 @@ bool KX_TrackToActuator::Update(double curtime, bool frame)
case 4: // TRACK -Y
{
// (0.0 , -1.0 , 0.0 ) -y direction is forward, z (0.0 , 0.0 , 1.0 ) up
- left = (-dir.cross(up)).normalized();
+ left = (-dir.cross(up)).safe_normalized();
mat.setValue (
left[0], -dir[0],up[0],
left[1], -dir[1],up[1],
@@ -301,10 +354,10 @@ bool KX_TrackToActuator::Update(double curtime, bool frame)
}
case 5: // track -Z
{
- left = up.normalized();
- up = -dir.normalized();
+ left = up.safe_normalized();
+ up = -dir.safe_normalized();
dir = left;
- left = (dir.cross(up)).normalized();
+ left = (dir.cross(up)).safe_normalized();
mat.setValue (
left[0], dir[0],up[0],
left[1], dir[1],up[1],
@@ -317,8 +370,8 @@ bool KX_TrackToActuator::Update(double curtime, bool frame)
default:
{
// (1.0 , 0.0 , 0.0 ) -x direction is forward, z (0.0 , 0.0 , 1.0 ) up
- left = -dir.normalized();
- dir = -(left.cross(up)).normalized();
+ left = -dir.safe_normalized();
+ dir = -(left.cross(up)).safe_normalized();
mat.setValue (
left[0], dir[0],up[0],
left[1], dir[1],up[1],
@@ -403,12 +456,12 @@ PyParentObject KX_TrackToActuator::Parents[] = {
PyMethodDef KX_TrackToActuator::Methods[] = {
- {"setObject", (PyCFunction) KX_TrackToActuator::sPySetObject, METH_VARARGS, SetObject_doc},
- {"getObject", (PyCFunction) KX_TrackToActuator::sPyGetObject, METH_VARARGS, GetObject_doc},
- {"setTime", (PyCFunction) KX_TrackToActuator::sPySetTime, METH_VARARGS, SetTime_doc},
- {"getTime", (PyCFunction) KX_TrackToActuator::sPyGetTime, METH_VARARGS, GetTime_doc},
- {"setUse3D", (PyCFunction) KX_TrackToActuator::sPySetUse3D, METH_VARARGS, SetUse3D_doc},
- {"getUse3D", (PyCFunction) KX_TrackToActuator::sPyGetUse3D, METH_VARARGS, GetUse3D_doc},
+ {"setObject", (PyCFunction) KX_TrackToActuator::sPySetObject, METH_O, (PY_METHODCHAR)SetObject_doc},
+ {"getObject", (PyCFunction) KX_TrackToActuator::sPyGetObject, METH_VARARGS, (PY_METHODCHAR)GetObject_doc},
+ {"setTime", (PyCFunction) KX_TrackToActuator::sPySetTime, METH_VARARGS, (PY_METHODCHAR)SetTime_doc},
+ {"getTime", (PyCFunction) KX_TrackToActuator::sPyGetTime, METH_VARARGS, (PY_METHODCHAR)GetTime_doc},
+ {"setUse3D", (PyCFunction) KX_TrackToActuator::sPySetUse3D, METH_VARARGS, (PY_METHODCHAR)SetUse3D_doc},
+ {"getUse3D", (PyCFunction) KX_TrackToActuator::sPyGetUse3D, METH_VARARGS, (PY_METHODCHAR)GetUse3D_doc},
{NULL,NULL} //Sentinel
};
@@ -422,49 +475,53 @@ PyObject* KX_TrackToActuator::_getattr(const STR_String& attr)
/* 1. setObject */
-char KX_TrackToActuator::SetObject_doc[] =
+const char KX_TrackToActuator::SetObject_doc[] =
"setObject(object)\n"
-"\t- object: string\n"
+"\t- object: KX_GameObject, string or None\n"
"\tSet the object to track with the parent of this actuator.\n";
-PyObject* KX_TrackToActuator::PySetObject(PyObject* self, PyObject* args, PyObject* kwds) {
- PyObject* gameobj;
- if (PyArg_ParseTuple(args, "O!", &KX_GameObject::Type, &gameobj))
- {
- m_object = (SCA_IObject*)gameobj;
-
- Py_Return;
- }
- PyErr_Clear();
+PyObject* KX_TrackToActuator::PySetObject(PyObject* self, PyObject* value)
+{
+ KX_GameObject *gameobj;
- char* objectname;
- if (PyArg_ParseTuple(args, "s", &objectname))
- {
- m_object= static_cast<SCA_IObject*>(SCA_ILogicBrick::m_sCurrentLogicManager->GetGameObjectByName(STR_String(objectname)));
-
- Py_Return;
- }
+ if (!ConvertPythonToGameObject(value, &gameobj, true))
+ return NULL; // ConvertPythonToGameObject sets the error
+
+ if (m_object != NULL)
+ m_object->UnregisterActuator(this);
+
+ m_object = (SCA_IObject*)gameobj;
+ if (m_object)
+ m_object->RegisterActuator(this);
- return NULL;
+ Py_RETURN_NONE;
}
/* 2. getObject */
-char KX_TrackToActuator::GetObject_doc[] =
-"getObject()\n"
-"\tReturns the object to track with the parent of this actuator.\n";
-PyObject* KX_TrackToActuator::PyGetObject(PyObject* self, PyObject* args, PyObject* kwds)
+const char KX_TrackToActuator::GetObject_doc[] =
+"getObject(name_only = 1)\n"
+"name_only - optional arg, when true will return the KX_GameObject rather then its name\n"
+"\tReturns the object to track with the parent of this actuator\n";
+PyObject* KX_TrackToActuator::PyGetObject(PyObject* self, PyObject* args)
{
+ int ret_name_only = 1;
+ if (!PyArg_ParseTuple(args, "|i", &ret_name_only))
+ return NULL;
+
if (!m_object)
- Py_Return;
-
- return PyString_FromString(m_object->GetName());
+ Py_RETURN_NONE;
+
+ if (ret_name_only)
+ return PyString_FromString(m_object->GetName());
+ else
+ return m_object->AddRef();
}
/* 3. setTime */
-char KX_TrackToActuator::SetTime_doc[] =
+const char KX_TrackToActuator::SetTime_doc[] =
"setTime(time)\n"
"\t- time: integer\n"
"\tSet the time in frames with which to delay the tracking motion.\n";
@@ -485,7 +542,7 @@ PyObject* KX_TrackToActuator::PySetTime(PyObject* self, PyObject* args, PyObject
/* 4.getTime */
-char KX_TrackToActuator::GetTime_doc[] =
+const char KX_TrackToActuator::GetTime_doc[] =
"getTime()\n"
"\t- time: integer\n"
"\tReturn the time in frames with which the tracking motion is delayed.\n";
@@ -497,7 +554,7 @@ PyObject* KX_TrackToActuator::PyGetTime(PyObject* self, PyObject* args, PyObject
/* 5. getUse3D */
-char KX_TrackToActuator::GetUse3D_doc[] =
+const char KX_TrackToActuator::GetUse3D_doc[] =
"getUse3D()\n"
"\tReturns 1 if the motion is allowed to extend in the z-direction.\n";
PyObject* KX_TrackToActuator::PyGetUse3D(PyObject* self, PyObject* args, PyObject* kwds)
@@ -508,7 +565,7 @@ PyObject* KX_TrackToActuator::PyGetUse3D(PyObject* self, PyObject* args, PyObjec
/* 6. setUse3D */
-char KX_TrackToActuator::SetUse3D_doc[] =
+const char KX_TrackToActuator::SetUse3D_doc[] =
"setUse3D(value)\n"
"\t- value: 0 or 1\n"
"\tSet to 1 to allow the tracking motion to extend in the z-direction,\n"
diff --git a/source/gameengine/Ketsji/KX_TrackToActuator.h b/source/gameengine/Ketsji/KX_TrackToActuator.h
index 944eaadf025..445132a6094 100644
--- a/source/gameengine/Ketsji/KX_TrackToActuator.h
+++ b/source/gameengine/Ketsji/KX_TrackToActuator.h
@@ -66,15 +66,18 @@ class KX_TrackToActuator : public SCA_IActuator
return replica;
};
+ virtual void ProcessReplica();
+ virtual bool UnlinkObject(SCA_IObject* clientobj);
+ virtual void Relink(GEN_Map<GEN_HashedPtr, void*> *obj_map);
virtual bool Update(double curtime, bool frame);
/* Python part */
virtual PyObject* _getattr(const STR_String& attr);
/* 1. setObject */
- KX_PYMETHOD_DOC(KX_TrackToActuator,SetObject);
+ KX_PYMETHOD_DOC_O(KX_TrackToActuator,SetObject);
/* 2. getObject */
- KX_PYMETHOD_DOC(KX_TrackToActuator,GetObject);
+ KX_PYMETHOD_DOC_VARARGS(KX_TrackToActuator,GetObject);
/* 3. setTime */
KX_PYMETHOD_DOC(KX_TrackToActuator,SetTime);
/* 4. getTime */
diff --git a/source/gameengine/Ketsji/KX_VehicleWrapper.cpp b/source/gameengine/Ketsji/KX_VehicleWrapper.cpp
index fba2ecc223b..028f96f6c5b 100644
--- a/source/gameengine/Ketsji/KX_VehicleWrapper.cpp
+++ b/source/gameengine/Ketsji/KX_VehicleWrapper.cpp
@@ -1,6 +1,8 @@
#include <Python.h>
+#include "PyObjectPlus.h"
+
#include "KX_VehicleWrapper.h"
#include "PHY_IPhysicsEnvironment.h"
#include "PHY_IVehicle.h"
@@ -47,30 +49,34 @@ PyObject* KX_VehicleWrapper::PyAddWheel(PyObject* self,
if (PyArg_ParseTuple(args,"OOOOffi",&wheelGameObject,&pylistPos,&pylistDir,&pylistAxleDir,&suspensionRestLength,&wheelRadius,&hasSteering))
{
KX_GameObject* gameOb = (KX_GameObject*) wheelGameObject;
+
+ if (gameOb->GetSGNode())
+ {
+ PHY_IMotionState* motionState = new KX_MotionState(gameOb->GetSGNode());
+
+ MT_Vector3 attachPos,attachDir,attachAxle;
+ PyVecTo(pylistPos,attachPos);
+ PyVecTo(pylistDir,attachDir);
+ PyVecTo(pylistAxleDir,attachAxle);
+ PHY__Vector3 aPos,aDir,aAxle;
+ aPos[0] = attachPos[0];
+ aPos[1] = attachPos[1];
+ aPos[2] = attachPos[2];
+ aDir[0] = attachDir[0];
+ aDir[1] = attachDir[1];
+ aDir[2] = attachDir[2];
+ aAxle[0] = -attachAxle[0];//someone reverse some conventions inside Bullet (axle winding)
+ aAxle[1] = -attachAxle[1];
+ aAxle[2] = -attachAxle[2];
+
+ printf("attempt for addWheel: suspensionRestLength%f wheelRadius %f, hasSteering:%d\n",suspensionRestLength,wheelRadius,hasSteering);
+ m_vehicle->AddWheel(motionState,aPos,aDir,aAxle,suspensionRestLength,wheelRadius,hasSteering);
+ }
- PHY_IMotionState* motionState = new KX_MotionState(gameOb->GetSGNode());
-
- MT_Vector3 attachPos,attachDir,attachAxle;
- PyVecTo(pylistPos,attachPos);
- PyVecTo(pylistDir,attachDir);
- PyVecTo(pylistAxleDir,attachAxle);
- PHY__Vector3 aPos,aDir,aAxle;
- aPos[0] = attachPos[0];
- aPos[1] = attachPos[1];
- aPos[2] = attachPos[2];
- aDir[0] = attachDir[0];
- aDir[1] = attachDir[1];
- aDir[2] = attachDir[2];
- aAxle[0] = -attachAxle[0];//someone reverse some conventions inside Bullet (axle winding)
- aAxle[1] = -attachAxle[1];
- aAxle[2] = -attachAxle[2];
-
- printf("attempt for addWheel: suspensionRestLength%f wheelRadius %f, hasSteering:%d\n",suspensionRestLength,wheelRadius,hasSteering);
- m_vehicle->AddWheel(motionState,aPos,aDir,aAxle,suspensionRestLength,wheelRadius,hasSteering);
-
+ } else {
+ return NULL;
}
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
@@ -90,8 +96,7 @@ PyObject* KX_VehicleWrapper::PyGetWheelPosition(PyObject* self,
MT_Vector3 pos(position[0],position[1],position[2]);
return PyObjectFrom(pos);
}
- Py_INCREF(Py_None);
- return Py_None;
+ return NULL;
}
PyObject* KX_VehicleWrapper::PyGetWheelRotation(PyObject* self,
@@ -103,8 +108,7 @@ PyObject* KX_VehicleWrapper::PyGetWheelRotation(PyObject* self,
{
return PyFloat_FromDouble(m_vehicle->GetWheelRotation(wheelIndex));
}
- Py_INCREF(Py_None);
- return Py_None;
+ return NULL;
}
PyObject* KX_VehicleWrapper::PyGetWheelOrientationQuaternion(PyObject* self,
@@ -120,8 +124,7 @@ PyObject* KX_VehicleWrapper::PyGetWheelOrientationQuaternion(PyObject* self,
MT_Matrix3x3 ornmat(quatorn);
return PyObjectFrom(ornmat);
}
- Py_INCREF(Py_None);
- return Py_None;
+ return NULL;
}
@@ -155,8 +158,10 @@ PyObject* KX_VehicleWrapper::PyApplyEngineForce(PyObject* self,
force *= -1.f;//someone reverse some conventions inside Bullet (axle winding)
m_vehicle->ApplyEngineForce(force,wheelIndex);
}
- Py_INCREF(Py_None);
- return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
PyObject* KX_VehicleWrapper::PySetTyreFriction(PyObject* self,
@@ -170,8 +175,10 @@ PyObject* KX_VehicleWrapper::PySetTyreFriction(PyObject* self,
{
m_vehicle->SetWheelFriction(wheelFriction,wheelIndex);
}
- Py_INCREF(Py_None);
- return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
PyObject* KX_VehicleWrapper::PySetSuspensionStiffness(PyObject* self,
@@ -185,8 +192,10 @@ PyObject* KX_VehicleWrapper::PySetSuspensionStiffness(PyObject* self,
{
m_vehicle->SetSuspensionStiffness(suspensionStiffness,wheelIndex);
}
- Py_INCREF(Py_None);
- return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
PyObject* KX_VehicleWrapper::PySetSuspensionDamping(PyObject* self,
@@ -199,9 +208,10 @@ PyObject* KX_VehicleWrapper::PySetSuspensionDamping(PyObject* self,
if (PyArg_ParseTuple(args,"fi",&suspensionDamping,&wheelIndex))
{
m_vehicle->SetSuspensionDamping(suspensionDamping,wheelIndex);
+ } else {
+ return NULL;
}
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
PyObject* KX_VehicleWrapper::PySetSuspensionCompression(PyObject* self,
@@ -214,9 +224,10 @@ PyObject* KX_VehicleWrapper::PySetSuspensionCompression(PyObject* self,
if (PyArg_ParseTuple(args,"fi",&suspensionCompression,&wheelIndex))
{
m_vehicle->SetSuspensionCompression(suspensionCompression,wheelIndex);
+ } else {
+ return NULL;
}
- Py_INCREF(Py_None);
- return Py_None;
+ Py_RETURN_NONE;
}
PyObject* KX_VehicleWrapper::PySetRollInfluence(PyObject* self,
@@ -230,8 +241,10 @@ PyObject* KX_VehicleWrapper::PySetRollInfluence(PyObject* self,
{
m_vehicle->SetRollInfluence(rollInfluence,wheelIndex);
}
- Py_INCREF(Py_None);
- return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
@@ -246,8 +259,10 @@ PyObject* KX_VehicleWrapper::PyApplyBraking(PyObject* self,
{
m_vehicle->ApplyBraking(braking,wheelIndex);
}
- Py_INCREF(Py_None);
- return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
@@ -264,8 +279,10 @@ PyObject* KX_VehicleWrapper::PySetSteeringValue(PyObject* self,
{
m_vehicle->SetSteeringValue(steeringValue,wheelIndex);
}
- Py_INCREF(Py_None);
- return Py_None;
+ else {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
diff --git a/source/gameengine/Ketsji/KX_VertexProxy.cpp b/source/gameengine/Ketsji/KX_VertexProxy.cpp
index 5cec65dff1c..25205714308 100644
--- a/source/gameengine/Ketsji/KX_VertexProxy.cpp
+++ b/source/gameengine/Ketsji/KX_VertexProxy.cpp
@@ -82,7 +82,7 @@ PyObject*
KX_VertexProxy::_getattr(const STR_String& attr)
{
if (attr == "XYZ")
- return PyObjectFrom(MT_Vector3(m_vertex->getLocalXYZ()));
+ return PyObjectFrom(MT_Vector3(m_vertex->getXYZ()));
if (attr == "UV")
return PyObjectFrom(MT_Point2(m_vertex->getUV1()));
@@ -102,11 +102,11 @@ KX_VertexProxy::_getattr(const STR_String& attr)
// pos
if (attr == "x")
- return PyFloat_FromDouble(m_vertex->getLocalXYZ()[0]);
+ return PyFloat_FromDouble(m_vertex->getXYZ()[0]);
if (attr == "y")
- return PyFloat_FromDouble(m_vertex->getLocalXYZ()[1]);
+ return PyFloat_FromDouble(m_vertex->getXYZ()[1]);
if (attr == "z")
- return PyFloat_FromDouble(m_vertex->getLocalXYZ()[2]);
+ return PyFloat_FromDouble(m_vertex->getXYZ()[2]);
// Col
if (attr == "r")
@@ -184,7 +184,7 @@ int KX_VertexProxy::_setattr(const STR_String& attr, PyObject *pyvalue)
{
float val = PyFloat_AsDouble(pyvalue);
// pos
- MT_Point3 pos(m_vertex->getLocalXYZ());
+ MT_Point3 pos(m_vertex->getXYZ());
if (attr == "x")
{
pos.x() = val;
@@ -312,7 +312,7 @@ PyObject* KX_VertexProxy::PyGetXYZ(PyObject*,
PyObject*,
PyObject*)
{
- return PyObjectFrom(MT_Point3(m_vertex->getLocalXYZ()));
+ return PyObjectFrom(MT_Point3(m_vertex->getXYZ()));
}
PyObject* KX_VertexProxy::PySetXYZ(PyObject*,
@@ -426,7 +426,7 @@ PyObject* KX_VertexProxy::PySetUV2(PyObject*,
{
if (PyVecTo(list, vec))
{
- m_vertex->SetFlag((m_vertex->getFlag()|TV_2NDUV));
+ m_vertex->SetFlag((m_vertex->getFlag()|RAS_TexVert::SECOND_UV));
m_vertex->SetUnit(unit);
m_vertex->SetUV2(vec);
m_mesh->SetMeshModified(true);
diff --git a/source/gameengine/Ketsji/KX_VisibilityActuator.cpp b/source/gameengine/Ketsji/KX_VisibilityActuator.cpp
index b4693a7a7db..4b0db5a7953 100644
--- a/source/gameengine/Ketsji/KX_VisibilityActuator.cpp
+++ b/source/gameengine/Ketsji/KX_VisibilityActuator.cpp
@@ -38,10 +38,12 @@
KX_VisibilityActuator::KX_VisibilityActuator(
SCA_IObject* gameobj,
bool visible,
+ bool recursive,
PyTypeObject* T
)
: SCA_IActuator(gameobj,T),
- m_visible(visible)
+ m_visible(visible),
+ m_recursive(recursive)
{
// intentionally empty
}
@@ -75,10 +77,10 @@ KX_VisibilityActuator::Update()
KX_GameObject *obj = (KX_GameObject*) GetParent();
- obj->SetVisible(m_visible);
- obj->MarkVisible();
+ obj->SetVisible(m_visible, m_recursive);
+ obj->UpdateBuckets(m_recursive);
- return true;
+ return false;
}
/* ------------------------------------------------------------------------- */
@@ -120,7 +122,7 @@ KX_VisibilityActuator::Parents[] = {
PyMethodDef
KX_VisibilityActuator::Methods[] = {
{"set", (PyCFunction) KX_VisibilityActuator::sPySetVisible,
- METH_VARARGS, SetVisible_doc},
+ METH_VARARGS, (PY_METHODCHAR)SetVisible_doc},
{NULL,NULL} //Sentinel
};
@@ -135,7 +137,7 @@ KX_VisibilityActuator::_getattr(
/* set visibility ---------------------------------------------------------- */
-char
+const char
KX_VisibilityActuator::SetVisible_doc[] =
"setVisible(visible?)\n"
"\t - visible? : Make the object visible? (KX_TRUE, KX_FALSE)"
diff --git a/source/gameengine/Ketsji/KX_VisibilityActuator.h b/source/gameengine/Ketsji/KX_VisibilityActuator.h
index 9b4753033fb..d1b85ab998c 100644
--- a/source/gameengine/Ketsji/KX_VisibilityActuator.h
+++ b/source/gameengine/Ketsji/KX_VisibilityActuator.h
@@ -39,12 +39,14 @@ class KX_VisibilityActuator : public SCA_IActuator
/** Make visible? */
bool m_visible;
+ bool m_recursive;
public:
KX_VisibilityActuator(
SCA_IObject* gameobj,
bool visible,
+ bool recursive,
PyTypeObject* T=&Type
);
diff --git a/source/gameengine/Ketsji/Makefile b/source/gameengine/Ketsji/Makefile
index fe226f22635..bdc0b335b02 100644
--- a/source/gameengine/Ketsji/Makefile
+++ b/source/gameengine/Ketsji/Makefile
@@ -35,9 +35,13 @@ include nan_compile.mk
CCFLAGS += $(LEVEL_1_CPP_WARNINGS)
+CPPFLAGS += $(NAN_SDLCFLAGS)
CPPFLAGS += $(OGL_CPPFLAGS)
+CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(OPENGL_HEADERS)
-CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION) -I../../blender/python
+CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION)
+CPPFLAGS += -I../../blender/python
+CPPFLAGS += -I../../blender/python/api2_2x
CPPFLAGS += -I$(NAN_STRING)/include
CPPFLAGS += -I$(NAN_SOUNDSYSTEM)/include
CPPFLAGS += -I$(NAN_FUZZICS)/include -I$(NAN_SUMO) -I$(NAN_MOTO)/include
@@ -60,6 +64,7 @@ CPPFLAGS += -I../../blender/blenlib
CPPFLAGS += -I../../blender/editors/include
CPPFLAGS += -I../../blender/makesdna
CPPFLAGS += -I../../blender/imbuf
+CPPFLAGS += -I../../blender/gpu
CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include
###########################
diff --git a/source/gameengine/Ketsji/SConscript b/source/gameengine/Ketsji/SConscript
index f9f7920d244..7d2cfb403c0 100644
--- a/source/gameengine/Ketsji/SConscript
+++ b/source/gameengine/Ketsji/SConscript
@@ -5,7 +5,22 @@ Import ('env')
sources = env.Glob('*.cpp')
-incs = '. #source/kernel/gen_system #intern/string #intern/guardedalloc'
+#XXX
+# Mathutils C files.
+#sources.extend([\
+# '#source/blender/python/api2_2x/Mathutils.c',\
+# '#source/blender/python/api2_2x/constant.c',\
+# '#source/blender/python/api2_2x/euler.c',\
+# '#source/blender/python/api2_2x/gen_utils.c',\
+# '#source/blender/python/api2_2x/matrix.c',\
+# '#source/blender/python/api2_2x/point.c',\
+# '#source/blender/python/api2_2x/quat.c',\
+# '#source/blender/python/api2_2x/vector.c',\
+#])
+
+incs = '. #source/blender/python/api2_2x' # Only for Mathutils! - no other deps
+
+incs += ' #source/kernel/gen_system #intern/string #intern/guardedalloc'
incs += ' #source/gameengine/Rasterizer/RAS_OpenGLRasterizer #intern/bmfont'
incs += ' #intern/SoundSystem #intern/SoundSystem/include #intern/SoundSystem/openal'
incs += ' #intern/SoundSystem/dummy #intern/SoundSystem/intern #source/gameengine/Converter'
@@ -18,7 +33,7 @@ incs += ' #source/gameengine/SceneGraph #source/gameengine/Physics/common #sourc
incs += ' #source/gameengine/Physics/BlOde #source/gameengine/Physics/Dummy'
incs += ' #source/gameengine/Physics/Sumo #source/gameengine/Physics/Sumo/include'
incs += ' #source/gameengine/Physics/Sumo/Fuzzics/include #source/gameengine/Network/LoopBackNetwork'
-incs += ' #source/blender/misc #source/blender/blenloader'
+incs += ' #source/blender/misc #source/blender/blenloader #extern/glew/include #source/blender/gpu'
cflags = []
if env['OURPLATFORM'] == 'win32-vc':
@@ -27,8 +42,10 @@ if env['OURPLATFORM'] == 'win32-vc':
incs += ' ' + env['BF_SOLID_INC']
incs += ' ' + env['BF_PYTHON_INC']
-incs += ' ' + env['BF_SDL_INC']
incs += ' ' + env['BF_BULLET_INC']
incs += ' ' + env['BF_OPENGL_INC']
+if env['WITH_BF_SDL']:
+ incs += ' ' + env['BF_SDL_INC']
+
env.BlenderLib ( 'bf_ketsji', sources, Split(incs), [], libtype=['game','player'], priority=[25, 60], compileflags = cflags )
diff --git a/source/gameengine/Makefile b/source/gameengine/Makefile
index 1d3bc8c2058..51bc0f7d39f 100644
--- a/source/gameengine/Makefile
+++ b/source/gameengine/Makefile
@@ -35,7 +35,7 @@ DIR = $(OCGDIR)/gameengine
DIRS = BlenderRoutines
DIRS += Converter
DIRS += Expressions GameLogic Ketsji Rasterizer SceneGraph
-DIRS += Network Physics
+DIRS += Network Physics VideoTexture
ifeq ($(WITH_BF_BLENDERGAMEENGINE),true)
DIRS += GamePlayer
diff --git a/source/gameengine/Physics/BlOde/OdePhysicsController.h b/source/gameengine/Physics/BlOde/OdePhysicsController.h
index d3eb443ed3a..925f5b6686a 100644
--- a/source/gameengine/Physics/BlOde/OdePhysicsController.h
+++ b/source/gameengine/Physics/BlOde/OdePhysicsController.h
@@ -111,6 +111,8 @@ public:
virtual void calcXform(){}
virtual void SetMargin(float margin) {}
virtual float GetMargin() const {return 0.f;}
+ virtual float GetRadius() const {return 0.f;}
+ virtual void SetRadius(float margin) {}
// clientinfo for raycasts for example
virtual void* getNewClientInfo() { return m_clientInfo;}
diff --git a/source/gameengine/Physics/BlOde/OdePhysicsEnvironment.cpp b/source/gameengine/Physics/BlOde/OdePhysicsEnvironment.cpp
index a04560aaf09..2e8ee31058f 100644
--- a/source/gameengine/Physics/BlOde/OdePhysicsEnvironment.cpp
+++ b/source/gameengine/Physics/BlOde/OdePhysicsEnvironment.cpp
@@ -198,7 +198,7 @@ int ODEPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl
}
-void ODEPhysicsEnvironment::removeConstraint(int constraintid)
+void ODEPhysicsEnvironment::removeConstraint(void *constraintid)
{
if (constraintid)
{
@@ -206,8 +206,7 @@ void ODEPhysicsEnvironment::removeConstraint(int constraintid)
}
}
-PHY_IPhysicsController* ODEPhysicsEnvironment::rayTest(PHY_IPhysicsController* ignoreClient,float fromX,float fromY,float fromZ, float toX,float toY,float toZ,
- float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ)
+PHY_IPhysicsController* ODEPhysicsEnvironment::rayTest(PHY_IRayCastFilterCallback &filterCallback,float fromX,float fromY,float fromZ, float toX,float toY,float toZ)
{
//m_OdeWorld
diff --git a/source/gameengine/Physics/BlOde/OdePhysicsEnvironment.h b/source/gameengine/Physics/BlOde/OdePhysicsEnvironment.h
index ec1b7702ffd..dcc87d614c0 100644
--- a/source/gameengine/Physics/BlOde/OdePhysicsEnvironment.h
+++ b/source/gameengine/Physics/BlOde/OdePhysicsEnvironment.h
@@ -54,8 +54,7 @@ public:
float axisX,float axisY,float axisZ);
virtual void removeConstraint(void * constraintid);
- virtual PHY_IPhysicsController* rayTest(PHY_IPhysicsController* ignoreClient,float fromX,float fromY,float fromZ, float toX,float toY,float toZ,
- float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ);
+ virtual PHY_IPhysicsController* rayTest(PHY_IRayCastFilterCallback &filterCallback,float fromX,float fromY,float fromZ, float toX,float toY,float toZ);
//gamelogic callbacks
@@ -65,6 +64,7 @@ public:
{
}
virtual void requestCollisionCallback(PHY_IPhysicsController* ctrl) {}
+ virtual void removeCollisionCallback(PHY_IPhysicsController* ctrl) {}
virtual PHY_IPhysicsController* CreateSphereController(float radius,const PHY__Vector3& position) {return 0;}
virtual PHY_IPhysicsController* CreateConeController(float coneradius,float coneheight) { return 0;}
diff --git a/source/gameengine/Physics/BlOde/SConscript b/source/gameengine/Physics/BlOde/SConscript
index 0ffeb1dad62..90e949d2d86 100644
--- a/source/gameengine/Physics/BlOde/SConscript
+++ b/source/gameengine/Physics/BlOde/SConscript
@@ -5,11 +5,11 @@ Import ('library_env')
phy_ode_env = library_env.Copy ()
source_files = ['OdePhysicsController.cpp',
- 'OdePhysicsEnvironment.cpp']
+ 'OdePhysicsEnvironment.cpp']
phy_ode_env.Append (CPPPATH=['.',
- '../common',
- ])
+ '../common',
+ ])
phy_ode_env.Append (CPPPATH=user_options_dict['ODE_INCLUDE'])
phy_ode_env.Library (target='#'+user_options_dict['BUILD_DIR']+'/lib/PHY_Ode', source=source_files)
diff --git a/source/gameengine/Physics/Bullet/CMakeLists.txt b/source/gameengine/Physics/Bullet/CMakeLists.txt
index b610fd1bbb0..6c733786caf 100644
--- a/source/gameengine/Physics/Bullet/CMakeLists.txt
+++ b/source/gameengine/Physics/Bullet/CMakeLists.txt
@@ -30,6 +30,10 @@ SET(INC
.
../common
../../../../extern/bullet2/src
+ ../../../../intern/moto/include
+ ../../../kernel/gen_system
+ ../../../../intern/string
+ ../../Rasterizer
)
BLENDERLIB(bf_bullet "${SRC}" "${INC}")
diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp b/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp
index 5a45ce020cc..c9c30c1b450 100644
--- a/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp
+++ b/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp
@@ -15,10 +15,18 @@ subject to the following restrictions:
#include "CcdPhysicsController.h"
#include "btBulletDynamicsCommon.h"
-
+#include "BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h"
#include "PHY_IMotionState.h"
#include "CcdPhysicsEnvironment.h"
+#include "RAS_MeshObject.h"
+#include "BulletSoftBody/btSoftBody.h"
+#include "BulletSoftBody//btSoftBodyInternals.h"
+#include "BulletSoftBody/btSoftBodyHelpers.h"
+#include "LinearMath/btConvexHull.h"
+#include "BulletCollision/Gimpact/btGImpactShape.h"
+
+#include "BulletSoftBody/btSoftRigidDynamicsWorld.h"
class BP_Proxy;
@@ -36,24 +44,40 @@ float gAngularSleepingTreshold = 1.0f;
btVector3 startVel(0,0,0);//-10000);
+
CcdPhysicsController::CcdPhysicsController (const CcdConstructionInfo& ci)
:m_cci(ci)
{
+ m_prototypeTransformInitialized = false;
+ m_softbodyMappingDone = false;
m_collisionDelay = 0;
m_newClientInfo = 0;
-
+ m_registerCount = 0;
+ m_softBodyTransformInitialized = false;
+ m_parentCtrl = 0;
+ // copy pointers locally to allow smart release
m_MotionState = ci.m_MotionState;
+ m_collisionShape = ci.m_collisionShape;
+ // apply scaling before creating rigid body
+ m_collisionShape->setLocalScaling(m_cci.m_scaling);
+ if (m_cci.m_mass)
+ m_collisionShape->calculateLocalInertia(m_cci.m_mass, m_cci.m_localInertiaTensor);
+ // shape info is shared, increment ref count
+ m_shapeInfo = ci.m_shapeInfo;
+ if (m_shapeInfo)
+ m_shapeInfo->AddRef();
+
m_bulletMotionState = 0;
CreateRigidbody();
-
- #ifdef WIN32
- if (m_body->getInvMass())
- m_body->setLinearVelocity(startVel);
- #endif
+///???
+#ifdef WIN32
+ if (GetRigidBody() && !GetRigidBody()->isStaticObject())
+ GetRigidBody()->setLinearVelocity(startVel);
+#endif
}
@@ -105,34 +129,395 @@ public:
};
-void CcdPhysicsController::CreateRigidbody()
+btRigidBody* CcdPhysicsController::GetRigidBody()
+{
+ return btRigidBody::upcast(m_object);
+}
+btCollisionObject* CcdPhysicsController::GetCollisionObject()
+{
+ return m_object;
+}
+btSoftBody* CcdPhysicsController::GetSoftBody()
{
+ return btSoftBody::upcast(m_object);
+}
+
+#include "BulletSoftBody/btSoftBodyHelpers.h"
+
- btTransform trans = GetTransformFromMotionState(m_MotionState);
+void CcdPhysicsController::CreateRigidbody()
+{
+
+ //btTransform trans = GetTransformFromMotionState(m_MotionState);
m_bulletMotionState = new BlenderBulletMotionState(m_MotionState);
- m_body = new btRigidBody(m_cci.m_mass,
- m_bulletMotionState,
- m_cci.m_collisionShape,
- m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor,
- m_cci.m_linearDamping,m_cci.m_angularDamping,
- m_cci.m_friction,m_cci.m_restitution);
+ ///either create a btCollisionObject, btRigidBody or btSoftBody
+
+ //create a collision object
+
+ int shapeType = m_cci.m_collisionShape ? m_cci.m_collisionShape->getShapeType() : 0;
+
+ //disable soft body until first sneak preview is ready
+ if (m_cci.m_bSoft && m_cci.m_collisionShape &&
+ (shapeType == CONVEX_HULL_SHAPE_PROXYTYPE)|
+ (shapeType == TRIANGLE_MESH_SHAPE_PROXYTYPE) |
+ (shapeType == SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE))
+ {
+ btRigidBody::btRigidBodyConstructionInfo rbci(m_cci.m_mass,m_bulletMotionState,m_collisionShape,m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor);
+ rbci.m_linearDamping = m_cci.m_linearDamping;
+ rbci.m_angularDamping = m_cci.m_angularDamping;
+ rbci.m_friction = m_cci.m_friction;
+ rbci.m_restitution = m_cci.m_restitution;
+
+
+ int nodecount = 0;
+
+ int numtriangles = 1;
+
+ btVector3 p(0,0,0);// = getOrigin();
+ btScalar h = 1.f;
+
+ btSoftRigidDynamicsWorld* softDynaWorld = (btSoftRigidDynamicsWorld*)m_cci.m_physicsEnv->getDynamicsWorld();
+
+ PHY__Vector3 grav;
+ grav[0] = softDynaWorld->getGravity().getX();
+ grav[1] = softDynaWorld->getGravity().getY();
+ grav[2] = softDynaWorld->getGravity().getZ();
+ softDynaWorld->getWorldInfo().m_gravity.setValue(grav[0],grav[1],grav[2]); //??
+
+
+ //btSoftBody* psb=btSoftBodyHelpers::CreateRope(sbi, btVector3(-10,0,i*0.25),btVector3(10,0,i*0.25), 16,1+2);
+
+ btSoftBody* psb = 0;
+
+ if (m_cci.m_collisionShape->getShapeType() == CONVEX_HULL_SHAPE_PROXYTYPE)
+ {
+ btConvexHullShape* convexHull = (btConvexHullShape* )m_cci.m_collisionShape;
+
+ //psb = btSoftBodyHelpers::CreateFromConvexHull(sbi,&transformedVertices[0],convexHull->getNumPoints());
+
+ {
+ int nvertices = convexHull->getNumPoints();
+ const btVector3* vertices = convexHull->getPoints();
+ btSoftBodyWorldInfo& worldInfo = softDynaWorld->getWorldInfo();
+
+ HullDesc hdsc(QF_TRIANGLES,nvertices,vertices);
+ HullResult hres;
+ HullLibrary hlib;/*??*/
+ hdsc.mMaxVertices=nvertices;
+ hlib.CreateConvexHull(hdsc,hres);
+
+ psb=new btSoftBody(&worldInfo,(int)hres.mNumOutputVertices,
+ &hres.m_OutputVertices[0],0);
+ for(int i=0;i<(int)hres.mNumFaces;++i)
+ {
+ const int idx[]={ hres.m_Indices[i*3+0],
+ hres.m_Indices[i*3+1],
+ hres.m_Indices[i*3+2]};
+ if(idx[0]<idx[1]) psb->appendLink( idx[0],idx[1]);
+ if(idx[1]<idx[2]) psb->appendLink( idx[1],idx[2]);
+ if(idx[2]<idx[0]) psb->appendLink( idx[2],idx[0]);
+ psb->appendFace(idx[0],idx[1],idx[2]);
+ }
+
+
+
+ hlib.ReleaseResult(hres);
+
+
+ }
+
+
+
+
+
+
+ } else
+ {
+
+ btSoftBodyWorldInfo& sbi= softDynaWorld->getWorldInfo();
+
+ if (m_cci.m_collisionShape->getShapeType() ==SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE)
+ {
+ btScaledBvhTriangleMeshShape* scaledtrimeshshape = (btScaledBvhTriangleMeshShape*) m_cci.m_collisionShape;
+ btBvhTriangleMeshShape* trimeshshape = scaledtrimeshshape->getChildShape();
+
+ ///only deal with meshes that have 1 sub part/component, for now
+ if (trimeshshape->getMeshInterface()->getNumSubParts()==1)
+ {
+ unsigned char* vertexBase;
+ PHY_ScalarType vertexType;
+ int numverts;
+ int vertexstride;
+ unsigned char* indexbase;
+ int indexstride;
+ int numtris;
+ PHY_ScalarType indexType;
+ trimeshshape->getMeshInterface()->getLockedVertexIndexBase(&vertexBase,numverts,vertexType,vertexstride,&indexbase,indexstride,numtris,indexType);
+
+ psb = btSoftBodyHelpers::CreateFromTriMesh(sbi,(const btScalar*)vertexBase,(const int*)indexbase,numtris);
+ }
+ } else
+ {
+ btBvhTriangleMeshShape* trimeshshape = (btBvhTriangleMeshShape*) m_cci.m_collisionShape;
+ ///only deal with meshes that have 1 sub part/component, for now
+ if (trimeshshape->getMeshInterface()->getNumSubParts()==1)
+ {
+ unsigned char* vertexBase;
+ PHY_ScalarType vertexType;
+ int numverts;
+ int vertexstride;
+ unsigned char* indexbase;
+ int indexstride;
+ int numtris;
+ PHY_ScalarType indexType;
+ trimeshshape->getMeshInterface()->getLockedVertexIndexBase(&vertexBase,numverts,vertexType,vertexstride,&indexbase,indexstride,numtris,indexType);
+
+ psb = btSoftBodyHelpers::CreateFromTriMesh(sbi,(const btScalar*)vertexBase,(const int*)indexbase,numtris);
+ }
+
+
+ //psb = btSoftBodyHelpers::CreateFromTriMesh(sbi,&pts[0].getX(),triangles,numtriangles);
+ }
+
+ }
+
+ m_object = psb;
+
+ //psb->m_cfg.collisions = btSoftBody::fCollision::SDF_RS;//btSoftBody::fCollision::CL_SS+ btSoftBody::fCollision::CL_RS;
+
+ //psb->m_cfg.collisions = btSoftBody::fCollision::SDF_RS + btSoftBody::fCollision::VF_SS;//CL_SS;
+
+
+ //btSoftBody::Material* pm=psb->appendMaterial();
+ btSoftBody::Material* pm=psb->m_materials[0];
+ pm->m_kLST = m_cci.m_soft_linStiff;
+ pm->m_kAST = m_cci.m_soft_angStiff;
+ pm->m_kVST = m_cci.m_soft_volume;
+ psb->m_cfg.collisions = 0;
+
+ if (m_cci.m_soft_collisionflags & CCD_BSB_COL_CL_RS)
+ {
+ psb->m_cfg.collisions += btSoftBody::fCollision::CL_RS;
+ } else
+ {
+ psb->m_cfg.collisions += btSoftBody::fCollision::SDF_RS;
+ }
+ if (m_cci.m_soft_collisionflags & CCD_BSB_COL_CL_SS)
+ {
+ psb->m_cfg.collisions += btSoftBody::fCollision::CL_SS;
+ } else
+ {
+ psb->m_cfg.collisions += btSoftBody::fCollision::VF_SS;
+ }
+
+
+ psb->m_cfg.kSRHR_CL = m_cci.m_soft_kSRHR_CL; /* Soft vs rigid hardness [0,1] (cluster only) */
+ psb->m_cfg.kSKHR_CL = m_cci.m_soft_kSKHR_CL; /* Soft vs kinetic hardness [0,1] (cluster only) */
+ psb->m_cfg.kSSHR_CL = m_cci.m_soft_kSSHR_CL; /* Soft vs soft hardness [0,1] (cluster only) */
+ psb->m_cfg.kSR_SPLT_CL = m_cci.m_soft_kSR_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
+
+ psb->m_cfg.kSK_SPLT_CL = m_cci.m_soft_kSK_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
+ psb->m_cfg.kSS_SPLT_CL = m_cci.m_soft_kSS_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
+ psb->m_cfg.kVCF = m_cci.m_soft_kVCF; /* Velocities correction factor (Baumgarte) */
+ psb->m_cfg.kDP = m_cci.m_soft_kDP; /* Damping coefficient [0,1] */
+
+ psb->m_cfg.kDG = m_cci.m_soft_kDG; /* Drag coefficient [0,+inf] */
+ psb->m_cfg.kLF = m_cci.m_soft_kLF; /* Lift coefficient [0,+inf] */
+ psb->m_cfg.kPR = m_cci.m_soft_kPR; /* Pressure coefficient [-inf,+inf] */
+ psb->m_cfg.kVC = m_cci.m_soft_kVC; /* Volume conversation coefficient [0,+inf] */
+
+ psb->m_cfg.kDF = m_cci.m_soft_kDF; /* Dynamic friction coefficient [0,1] */
+ psb->m_cfg.kMT = m_cci.m_soft_kMT; /* Pose matching coefficient [0,1] */
+ psb->m_cfg.kCHR = m_cci.m_soft_kCHR; /* Rigid contacts hardness [0,1] */
+ psb->m_cfg.kKHR = m_cci.m_soft_kKHR; /* Kinetic contacts hardness [0,1] */
+
+ psb->m_cfg.kSHR = m_cci.m_soft_kSHR; /* Soft contacts hardness [0,1] */
+ psb->m_cfg.kAHR = m_cci.m_soft_kAHR; /* Anchors hardness [0,1] */
+
+
+
+ if (m_cci.m_gamesoftFlag & CCD_BSB_BENDING_CONSTRAINTS)//OB_SB_GOAL)
+ {
+ psb->generateBendingConstraints(2,pm);
+ }
+
+ psb->m_cfg.piterations = m_cci.m_soft_piterations;
+ psb->m_cfg.viterations = m_cci.m_soft_viterations;
+ psb->m_cfg.diterations = m_cci.m_soft_diterations;
+ psb->m_cfg.citerations = m_cci.m_soft_citerations;
+
+ if (m_cci.m_gamesoftFlag & CCD_BSB_SHAPE_MATCHING)//OB_SB_GOAL)
+ {
+ psb->setPose(false,true);//
+ } else
+ {
+ psb->setPose(true,false);
+ }
+
+
+
+ psb->randomizeConstraints();
+ if (m_cci.m_soft_collisionflags & (CCD_BSB_COL_CL_RS+CCD_BSB_COL_CL_SS))
+ {
+ psb->generateClusters(m_cci.m_soft_numclusteriterations);
+ }
+
+// psb->activate();
+// psb->setActivationState(1);
+// psb->setDeactivationTime(1.f);
+
+ //psb->m_materials[0]->m_kLST = 0.1+(i/(btScalar)(n-1))*0.9;
+ psb->setTotalMass(m_cci.m_mass);
+
+ psb->setCollisionFlags(0);
+
+ ///create a mapping between graphics mesh vertices and soft body vertices
+ {
+ RAS_MeshObject* rasMesh= GetShapeInfo()->GetMesh();
+
+ if (rasMesh && !m_softbodyMappingDone)
+ {
+
+ //printf("apply\n");
+ RAS_MeshSlot::iterator it;
+ RAS_MeshMaterial *mmat;
+ RAS_MeshSlot *slot;
+ size_t i;
+
+ //for each material
+ for (int m=0;m<rasMesh->NumMaterials();m++)
+ {
+ // The vertex cache can only be updated for this deformer:
+ // Duplicated objects with more than one ploymaterial (=multiple mesh slot per object)
+ // share the same mesh (=the same cache). As the rendering is done per polymaterial
+ // cycling through the objects, the entire mesh cache cannot be updated in one shot.
+ mmat = rasMesh->GetMeshMaterial(m);
+
+ slot = mmat->m_baseslot;
+ for(slot->begin(it); !slot->end(it); slot->next(it))
+ {
+ int index = 0;
+ for(i=it.startvertex; i<it.endvertex; i++,index++)
+ {
+ RAS_TexVert* vertex = &it.vertex[i];
+
+
+ //search closest index, and store it in vertex
+ vertex->setSoftBodyIndex(0);
+ btScalar maxDistSqr = 1e30;
+ btSoftBody::tNodeArray& nodes(psb->m_nodes);
+ btVector3 xyz = btVector3(vertex->getXYZ()[0],vertex->getXYZ()[1],vertex->getXYZ()[2]);
+ for (int n=0;n<nodes.size();n++)
+ {
+ btScalar distSqr = (nodes[n].m_x - xyz).length2();
+ if (distSqr<maxDistSqr)
+ {
+ maxDistSqr = distSqr;
+
+ vertex->setSoftBodyIndex(n);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ m_softbodyMappingDone = true;
+
+
+
+
+
+
+// m_object->setCollisionShape(rbci.m_collisionShape);
+ btTransform startTrans;
+
+ if (rbci.m_motionState)
+ {
+ rbci.m_motionState->getWorldTransform(startTrans);
+ } else
+ {
+ startTrans = rbci.m_startWorldTransform;
+ }
+ //startTrans.setIdentity();
+
+ //m_object->setWorldTransform(startTrans);
+ //m_object->setInterpolationWorldTransform(startTrans);
+ m_MotionState->setWorldPosition(startTrans.getOrigin().getX(),startTrans.getOrigin().getY(),startTrans.getOrigin().getZ());
+ m_MotionState->setWorldOrientation(0,0,0,1);
+
+ if (!m_prototypeTransformInitialized)
+ {
+ m_prototypeTransformInitialized = true;
+ m_softBodyTransformInitialized = true;
+ GetSoftBody()->transform(startTrans);
+ }
+
+// btVector3 wp = m_softBody->getWorldTransform().getOrigin();
+// MT_Point3 center(wp.getX(),wp.getY(),wp.getZ());
+// m_gameobj->NodeSetWorldPosition(center);
+
+
+ } else
+ {
+ btRigidBody::btRigidBodyConstructionInfo rbci(m_cci.m_mass,m_bulletMotionState,m_collisionShape,m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor);
+ rbci.m_linearDamping = m_cci.m_linearDamping;
+ rbci.m_angularDamping = m_cci.m_angularDamping;
+ rbci.m_friction = m_cci.m_friction;
+ rbci.m_restitution = m_cci.m_restitution;
+ m_object = new btRigidBody(rbci);
+ }
+
//
// init the rigidbody properly
//
//setMassProps this also sets collisionFlags
//convert collision flags!
+ //special case: a near/radar sensor controller should not be defined static or it will
+ //generate loads of static-static collision messages on the console
+ if ((m_cci.m_collisionFilterGroup & CcdConstructionInfo::SensorFilter) != 0)
+ {
+ // reset the flags that have been set so far
+ GetCollisionObject()->setCollisionFlags(0);
+ }
+ GetCollisionObject()->setCollisionFlags(m_object->getCollisionFlags() | m_cci.m_collisionFlags);
+ btRigidBody* body = GetRigidBody();
- m_body->setCollisionFlags(m_body->getCollisionFlags() | m_cci.m_collisionFlags);
-
- m_body->setGravity( m_cci.m_gravity);
- m_body->setDamping(m_cci.m_linearDamping, m_cci.m_angularDamping);
+ if (body)
+ {
+ body->setGravity( m_cci.m_gravity);
+ body->setDamping(m_cci.m_linearDamping, m_cci.m_angularDamping);
+ if (!m_cci.m_bRigid)
+ {
+ body->setAngularFactor(0.f);
+ }
+ }
+ if (m_object && m_cci.m_do_anisotropic)
+ {
+ m_object->setAnisotropicFriction(m_cci.m_anisotropicFriction);
+ }
+
+}
+
+static void DeleteBulletShape(btCollisionShape* shape)
+{
+ if (shape->getShapeType() == TRIANGLE_MESH_SHAPE_PROXYTYPE)
+ {
+ // shapes based on meshes use an interface that contains the vertices.
+ btTriangleMeshShape* meshShape = static_cast<btTriangleMeshShape*>(shape);
+ btStridingMeshInterface* meshInterface = meshShape->getMeshInterface();
+ if (meshInterface)
+ delete meshInterface;
+ }
+ delete shape;
}
CcdPhysicsController::~CcdPhysicsController()
@@ -141,12 +526,35 @@ CcdPhysicsController::~CcdPhysicsController()
if (m_cci.m_physicsEnv)
m_cci.m_physicsEnv->removeCcdPhysicsController(this);
- delete m_MotionState;
+ if (m_MotionState)
+ delete m_MotionState;
if (m_bulletMotionState)
delete m_bulletMotionState;
- delete m_body;
+ delete m_object;
+
+ if (m_collisionShape)
+ {
+ // collision shape is always unique to the controller, can delete it here
+ if (m_collisionShape->isCompound())
+ {
+ // bullet does not delete the child shape, must do it here
+ btCompoundShape* compoundShape = (btCompoundShape*)m_collisionShape;
+ int numChild = compoundShape->getNumChildShapes();
+ for (int i=numChild-1 ; i >= 0; i--)
+ {
+ btCollisionShape* childShape = compoundShape->getChildShape(i);
+ DeleteBulletShape(childShape);
+ }
+ }
+ DeleteBulletShape(m_collisionShape);
+ }
+ if (m_shapeInfo)
+ {
+ m_shapeInfo->Release();
+ }
}
+
/**
SynchronizeMotionStates ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
*/
@@ -154,12 +562,26 @@ bool CcdPhysicsController::SynchronizeMotionStates(float time)
{
//sync non-static to motionstate, and static from motionstate (todo: add kinematic etc.)
- if (!m_body->isStaticObject())
+ btSoftBody* sb = GetSoftBody();
+ if (sb)
{
- const btVector3& worldPos = m_body->getCenterOfMassPosition();
+ btVector3 aabbMin,aabbMax;
+ sb->getAabb(aabbMin,aabbMax);
+ btVector3 worldPos = (aabbMax+aabbMin)*0.5f;
+ m_MotionState->setWorldPosition(worldPos[0],worldPos[1],worldPos[2]);
+ m_MotionState->calculateWorldTransformations();
+ return true;
+ }
+
+ btRigidBody* body = GetRigidBody();
+
+ if (body && !body->isStaticObject())
+ {
+
+ const btVector3& worldPos = body->getCenterOfMassPosition();
m_MotionState->setWorldPosition(worldPos[0],worldPos[1],worldPos[2]);
- const btQuaternion& worldquat = m_body->getOrientation();
+ const btQuaternion& worldquat = body->getOrientation();
m_MotionState->setWorldOrientation(worldquat[0],worldquat[1],worldquat[2],worldquat[3]);
m_MotionState->calculateWorldTransformations();
@@ -178,7 +600,7 @@ bool CcdPhysicsController::SynchronizeMotionStates(float time)
btTransform oldTrans = m_body->getCenterOfMassTransform();
btTransform newTrans(worldquat,worldPos);
- m_body->setCenterOfMassTransform(newTrans);
+ SetCenterOfMassTransform(newTrans);
//need to keep track of previous position for friction effects...
m_MotionState->calculateWorldTransformations();
@@ -206,13 +628,41 @@ void CcdPhysicsController::WriteDynamicsToMotionState()
// controller replication
void CcdPhysicsController::PostProcessReplica(class PHY_IMotionState* motionstate,class PHY_IPhysicsController* parentctrl)
{
+
+ m_softBodyTransformInitialized=false;
m_MotionState = motionstate;
+ m_registerCount = 0;
+ m_collisionShape = NULL;
-
+ // always create a new shape to avoid scaling bug
+ if (m_shapeInfo)
+ {
+ m_shapeInfo->AddRef();
+ m_collisionShape = m_shapeInfo->CreateBulletShape();
- m_body = 0;
+ if (m_collisionShape)
+ {
+ // new shape has no scaling, apply initial scaling
+ m_collisionShape->setMargin(m_cci.m_margin);
+ m_collisionShape->setLocalScaling(m_cci.m_scaling);
+
+ if (m_cci.m_mass)
+ m_collisionShape->calculateLocalInertia(m_cci.m_mass, m_cci.m_localInertiaTensor);
+ }
+ }
+
+ m_object = 0;
CreateRigidbody();
-
+
+ btRigidBody* body = GetRigidBody();
+
+ if (body)
+ {
+ if (m_cci.m_mass)
+ {
+ body->setMassProps(m_cci.m_mass, m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor);
+ }
+ }
m_cci.m_physicsEnv->addCcdPhysicsController(this);
@@ -248,60 +698,95 @@ void CcdPhysicsController::PostProcessReplica(class PHY_IMotionState* motionsta
}
+
+void CcdPhysicsController::SetCenterOfMassTransform(btTransform& xform)
+{
+ btRigidBody* body = GetRigidBody();
+ if (body)
+ {
+ body->setCenterOfMassTransform(xform);
+ } else
+ {
+ //either collision object or soft body?
+ if (GetSoftBody())
+ {
+
+ } else
+ {
+
+ if (m_object->isStaticOrKinematicObject())
+ {
+ m_object->setInterpolationWorldTransform(m_object->getWorldTransform());
+ } else
+ {
+ m_object->setInterpolationWorldTransform(xform);
+ }
+ if (body)
+ {
+ body->setInterpolationLinearVelocity(body->getLinearVelocity());
+ body->setInterpolationAngularVelocity(body->getAngularVelocity());
+ body->updateInertiaTensor();
+ }
+ m_object->setWorldTransform(xform);
+ }
+ }
+}
+
// kinematic methods
void CcdPhysicsController::RelativeTranslate(float dlocX,float dlocY,float dlocZ,bool local)
{
- if (m_body)
+ if (m_object)
{
- m_body->activate(true);
- if (m_body->isStaticObject())
+ m_object->activate(true);
+ if (m_object->isStaticObject())
{
- m_body->setCollisionFlags(m_body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
}
+ btRigidBody* body = GetRigidBody();
btVector3 dloc(dlocX,dlocY,dlocZ);
- btTransform xform = m_body->getCenterOfMassTransform();
-
+ btTransform xform = m_object->getWorldTransform();
+
if (local)
{
dloc = xform.getBasis()*dloc;
}
xform.setOrigin(xform.getOrigin() + dloc);
- m_body->setCenterOfMassTransform(xform);
+ SetCenterOfMassTransform(xform);
}
}
void CcdPhysicsController::RelativeRotate(const float rotval[9],bool local)
{
- if (m_body )
+ if (m_object)
{
- m_body->activate(true);
- if (m_body->isStaticObject())
+ m_object->activate(true);
+ if (m_object->isStaticObject())
{
- m_body->setCollisionFlags(m_body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
}
- btMatrix3x3 drotmat( rotval[0],rotval[1],rotval[2],
- rotval[4],rotval[5],rotval[6],
- rotval[8],rotval[9],rotval[10]);
+ btMatrix3x3 drotmat( rotval[0],rotval[4],rotval[8],
+ rotval[1],rotval[5],rotval[9],
+ rotval[2],rotval[6],rotval[10]);
btMatrix3x3 currentOrn;
GetWorldOrientation(currentOrn);
- btTransform xform = m_body->getCenterOfMassTransform();
-
+ btTransform xform = m_object->getWorldTransform();
+
xform.setBasis(xform.getBasis()*(local ?
drotmat : (currentOrn.inverse() * drotmat * currentOrn)));
- m_body->setCenterOfMassTransform(xform);
+ SetCenterOfMassTransform(xform);
}
-
}
+
void CcdPhysicsController::GetWorldOrientation(btMatrix3x3& mat)
{
float orn[4];
@@ -312,7 +797,7 @@ void CcdPhysicsController::GetWorldOrientation(btMatrix3x3& mat)
void CcdPhysicsController::getOrientation(float &quatImag0,float &quatImag1,float &quatImag2,float &quatReal)
{
- btQuaternion q = m_body->getCenterOfMassTransform().getRotation();
+ btQuaternion q = m_object->getWorldTransform().getRotation();
quatImag0 = q[0];
quatImag1 = q[1];
quatImag2 = q[2];
@@ -320,33 +805,75 @@ void CcdPhysicsController::getOrientation(float &quatImag0,float &quatImag1,flo
}
void CcdPhysicsController::setOrientation(float quatImag0,float quatImag1,float quatImag2,float quatReal)
{
- m_body->activate(true);
- if (m_body->isStaticObject())
+ if (m_object)
{
- m_body->setCollisionFlags(m_body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ m_object->activate(true);
+ if (m_object->isStaticObject())
+ {
+ m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ }
+ // not required
+ //m_MotionState->setWorldOrientation(quatImag0,quatImag1,quatImag2,quatReal);
+ btTransform xform = m_object->getWorldTransform();
+ xform.setRotation(btQuaternion(quatImag0,quatImag1,quatImag2,quatReal));
+ SetCenterOfMassTransform(xform);
+ // not required
+ //m_bulletMotionState->setWorldTransform(xform);
+
+
+
}
- m_MotionState->setWorldOrientation(quatImag0,quatImag1,quatImag2,quatReal);
- btTransform xform = m_body->getCenterOfMassTransform();
- xform.setRotation(btQuaternion(quatImag0,quatImag1,quatImag2,quatReal));
- m_body->setCenterOfMassTransform(xform);
- m_bulletMotionState->setWorldTransform(xform);
+}
+
+void CcdPhysicsController::setWorldOrientation(const btMatrix3x3& orn)
+{
+ if (m_object)
+ {
+ m_object->activate(true);
+ if (m_object->isStaticObject())
+ {
+ m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ }
+ // not required
+ //m_MotionState->setWorldOrientation(quatImag0,quatImag1,quatImag2,quatReal);
+ btTransform xform = m_object->getWorldTransform();
+ xform.setBasis(orn);
+ SetCenterOfMassTransform(xform);
+ // not required
+ //m_bulletMotionState->setWorldTransform(xform);
+ //only once!
+ if (!m_softBodyTransformInitialized && GetSoftBody())
+ {
+ m_softbodyStartTrans.setBasis(orn);
+ xform.setOrigin(m_softbodyStartTrans.getOrigin());
+ GetSoftBody()->transform(xform);
+ m_softBodyTransformInitialized = true;
+ }
+
+ }
}
void CcdPhysicsController::setPosition(float posX,float posY,float posZ)
{
- m_body->activate(true);
- if (m_body->isStaticObject())
+ if (m_object)
{
- m_body->setCollisionFlags(m_body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ m_object->activate(true);
+ if (m_object->isStaticObject())
+ {
+ m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ }
+ // not required, this function is only used to update the physic controller
+ //m_MotionState->setWorldPosition(posX,posY,posZ);
+ btTransform xform = m_object->getWorldTransform();
+ xform.setOrigin(btVector3(posX,posY,posZ));
+ SetCenterOfMassTransform(xform);
+ if (!m_softBodyTransformInitialized)
+ m_softbodyStartTrans.setOrigin(xform.getOrigin());
+ // not required
+ //m_bulletMotionState->setWorldTransform(xform);
}
-
- m_MotionState->setWorldPosition(posX,posY,posZ);
- btTransform xform = m_body->getCenterOfMassTransform();
- xform.setOrigin(btVector3(posX,posY,posZ));
- m_body->setCenterOfMassTransform(xform);
- m_bulletMotionState->setWorldTransform(xform);
}
@@ -356,7 +883,7 @@ void CcdPhysicsController::resolveCombinedVelocities(float linvelX,float linvel
void CcdPhysicsController::getPosition(PHY__Vector3& pos) const
{
- const btTransform& xform = m_body->getCenterOfMassTransform();
+ const btTransform& xform = m_object->getWorldTransform();
pos[0] = xform.getOrigin().x();
pos[1] = xform.getOrigin().y();
pos[2] = xform.getOrigin().z();
@@ -370,15 +897,16 @@ void CcdPhysicsController::setScaling(float scaleX,float scaleY,float scaleZ)
{
m_cci.m_scaling = btVector3(scaleX,scaleY,scaleZ);
- if (m_body && m_body->getCollisionShape())
+ if (m_object && m_object->getCollisionShape())
{
- m_body->getCollisionShape()->setLocalScaling(m_cci.m_scaling);
+ m_object->getCollisionShape()->setLocalScaling(m_cci.m_scaling);
//printf("no inertia recalc for fixed objects with mass=0\n");
- if (m_cci.m_mass)
+ btRigidBody* body = GetRigidBody();
+ if (body && m_cci.m_mass)
{
- m_body->getCollisionShape()->calculateLocalInertia(m_cci.m_mass, m_cci.m_localInertiaTensor);
- m_body->setMassProps(m_cci.m_mass, m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor);
+ body->getCollisionShape()->calculateLocalInertia(m_cci.m_mass, m_cci.m_localInertiaTensor);
+ body->setMassProps(m_cci.m_mass, m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor);
}
}
@@ -389,51 +917,81 @@ void CcdPhysicsController::setScaling(float scaleX,float scaleY,float scaleZ)
void CcdPhysicsController::ApplyTorque(float torqueX,float torqueY,float torqueZ,bool local)
{
btVector3 torque(torqueX,torqueY,torqueZ);
- btTransform xform = m_body->getCenterOfMassTransform();
- if (torque.length2() > (SIMD_EPSILON*SIMD_EPSILON))
- {
- m_body->activate();
- }
- if (local)
+ btTransform xform = m_object->getWorldTransform();
+
+
+ if (m_object && torque.length2() > (SIMD_EPSILON*SIMD_EPSILON))
{
- torque = xform.getBasis()*torque;
+ btRigidBody* body = GetRigidBody();
+ m_object->activate();
+ if (m_object->isStaticObject())
+ {
+ m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ }
+ if (local)
+ {
+ torque = xform.getBasis()*torque;
+ }
+ if (body)
+ body->applyTorque(torque);
}
- m_body->applyTorque(torque);
}
void CcdPhysicsController::ApplyForce(float forceX,float forceY,float forceZ,bool local)
{
btVector3 force(forceX,forceY,forceZ);
- if (force.length2() > (SIMD_EPSILON*SIMD_EPSILON))
- {
- m_body->activate();
- }
-
- btTransform xform = m_body->getCenterOfMassTransform();
- if (local)
+ if (m_object && force.length2() > (SIMD_EPSILON*SIMD_EPSILON))
{
- force = xform.getBasis()*force;
+ m_object->activate();
+ if (m_object->isStaticObject())
+ {
+ m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ }
+
+ {
+ btTransform xform = m_object->getWorldTransform();
+
+ if (local)
+ {
+ force = xform.getBasis()*force;
+ }
+ btRigidBody* body = GetRigidBody();
+ if (body)
+ body->applyCentralForce(force);
+ btSoftBody* soft = GetSoftBody();
+ if (soft)
+ {
+ // the force is applied on each node, must reduce it in the same extend
+ if (soft->m_nodes.size() > 0)
+ force /= soft->m_nodes.size();
+ soft->addForce(force);
+ }
+ }
}
- m_body->applyCentralForce(force);
}
void CcdPhysicsController::SetAngularVelocity(float ang_velX,float ang_velY,float ang_velZ,bool local)
{
btVector3 angvel(ang_velX,ang_velY,ang_velZ);
- if (angvel.length2() > (SIMD_EPSILON*SIMD_EPSILON))
- {
- m_body->activate(true);
- }
-
+ if (m_object && angvel.length2() > (SIMD_EPSILON*SIMD_EPSILON))
{
- btTransform xform = m_body->getCenterOfMassTransform();
- if (local)
+ m_object->activate(true);
+ if (m_object->isStaticObject())
{
- angvel = xform.getBasis()*angvel;
- }
+ m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ } else
+ {
+ btTransform xform = m_object->getWorldTransform();
+ if (local)
+ {
+ angvel = xform.getBasis()*angvel;
+ }
+ btRigidBody* body = GetRigidBody();
+ if (body)
+ body->setAngularVelocity(angvel);
- m_body->setAngularVelocity(angvel);
+ }
}
}
@@ -441,33 +999,53 @@ void CcdPhysicsController::SetLinearVelocity(float lin_velX,float lin_velY,floa
{
btVector3 linVel(lin_velX,lin_velY,lin_velZ);
- if (linVel.length2() > (SIMD_EPSILON*SIMD_EPSILON))
- {
- m_body->activate(true);
- }
-
+ if (m_object/* && linVel.length2() > (SIMD_EPSILON*SIMD_EPSILON)*/)
{
- btTransform xform = m_body->getCenterOfMassTransform();
- if (local)
+ m_object->activate(true);
+ if (m_object->isStaticObject())
{
- linVel = xform.getBasis()*linVel;
+ m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ return;
+ }
+
+ btSoftBody* soft = GetSoftBody();
+ if (soft)
+ {
+ if (local)
+ {
+ linVel = m_softbodyStartTrans.getBasis()*linVel;
+ }
+ soft->setVelocity(linVel);
+ } else
+ {
+ btTransform xform = m_object->getWorldTransform();
+ if (local)
+ {
+ linVel = xform.getBasis()*linVel;
+ }
+ btRigidBody* body = GetRigidBody();
+ if (body)
+ body->setLinearVelocity(linVel);
}
- m_body->setLinearVelocity(linVel);
}
}
void CcdPhysicsController::applyImpulse(float attachX,float attachY,float attachZ, float impulseX,float impulseY,float impulseZ)
{
btVector3 impulse(impulseX,impulseY,impulseZ);
- if (impulse.length2() > (SIMD_EPSILON*SIMD_EPSILON))
+ if (m_object && impulse.length2() > (SIMD_EPSILON*SIMD_EPSILON))
{
- m_body->activate();
+ m_object->activate();
+ if (m_object->isStaticObject())
+ {
+ m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ }
btVector3 pos(attachX,attachY,attachZ);
-
- m_body->activate();
-
- m_body->applyImpulse(impulse,pos);
+ btRigidBody* body = GetRigidBody();
+ if (body)
+ body->applyImpulse(impulse,pos);
+
}
}
@@ -477,29 +1055,55 @@ void CcdPhysicsController::SetActive(bool active)
// reading out information from physics
void CcdPhysicsController::GetLinearVelocity(float& linvX,float& linvY,float& linvZ)
{
- const btVector3& linvel = this->m_body->getLinearVelocity();
- linvX = linvel.x();
- linvY = linvel.y();
- linvZ = linvel.z();
+ btRigidBody* body = GetRigidBody();
+ if (body)
+ {
+ const btVector3& linvel = body->getLinearVelocity();
+ linvX = linvel.x();
+ linvY = linvel.y();
+ linvZ = linvel.z();
+ } else
+ {
+ linvX = 0.f;
+ linvY = 0.f;
+ linvZ = 0.f;
+ }
}
void CcdPhysicsController::GetAngularVelocity(float& angVelX,float& angVelY,float& angVelZ)
{
- const btVector3& angvel= m_body->getAngularVelocity();
- angVelX = angvel.x();
- angVelY = angvel.y();
- angVelZ = angvel.z();
+ btRigidBody* body = GetRigidBody();
+ if (body)
+ {
+ const btVector3& angvel= body->getAngularVelocity();
+ angVelX = angvel.x();
+ angVelY = angvel.y();
+ angVelZ = angvel.z();
+ } else
+ {
+ angVelX = 0.f;
+ angVelY = 0.f;
+ angVelZ = 0.f;
+ }
}
void CcdPhysicsController::GetVelocity(const float posX,const float posY,const float posZ,float& linvX,float& linvY,float& linvZ)
{
btVector3 pos(posX,posY,posZ);
- btVector3 rel_pos = pos-m_body->getCenterOfMassPosition();
- btVector3 linvel = m_body->getVelocityInLocalPoint(rel_pos);
- linvX = linvel.x();
- linvY = linvel.y();
- linvZ = linvel.z();
+ btRigidBody* body = GetRigidBody();
+ if (body)
+ {
+ btVector3 linvel = body->getVelocityInLocalPoint(pos);
+ linvX = linvel.x();
+ linvY = linvel.y();
+ linvZ = linvel.z();
+ } else
+ {
+ linvX = 0.f;
+ linvY = 0.f;
+ linvZ = 0.f;
+ }
}
void CcdPhysicsController::getReactionForce(float& forceX,float& forceY,float& forceZ)
{
@@ -510,11 +1114,15 @@ void CcdPhysicsController::setRigidBody(bool rigid)
{
if (!rigid)
{
- //fake it for now
- btVector3 inertia = m_body->getInvInertiaDiagLocal();
- inertia[1] = 0.f;
- m_body->setInvInertiaDiagLocal(inertia);
- m_body->updateInertiaTensor();
+ btRigidBody* body = GetRigidBody();
+ if (body)
+ {
+ //fake it for now
+ btVector3 inertia = body->getInvInertiaDiagLocal();
+ inertia[1] = 0.f;
+ body->setInvInertiaDiagLocal(inertia);
+ body->updateInertiaTensor();
+ }
}
}
@@ -531,40 +1139,52 @@ void CcdPhysicsController::setNewClientInfo(void* clientinfo)
void CcdPhysicsController::UpdateDeactivation(float timeStep)
{
- m_body->updateDeactivation( timeStep);
+ btRigidBody* body = GetRigidBody();
+ if (body)
+ {
+ body->updateDeactivation( timeStep);
+ }
}
bool CcdPhysicsController::wantsSleeping()
{
-
- return m_body->wantsSleeping();
+ btRigidBody* body = GetRigidBody();
+ if (body)
+ {
+ return body->wantsSleeping();
+ }
+ //check it out
+ return true;
}
PHY_IPhysicsController* CcdPhysicsController::GetReplica()
{
- //very experimental, shape sharing is not implemented yet.
- //just support btSphereShape/ConeShape for now
-
+ // This is used only to replicate Near and Radar sensor controllers
+ // The replication of object physics controller is done in KX_BulletPhysicsController::GetReplica()
CcdConstructionInfo cinfo = m_cci;
- if (cinfo.m_collisionShape)
+ if (m_shapeInfo)
+ {
+ // This situation does not normally happen
+ cinfo.m_collisionShape = m_shapeInfo->CreateBulletShape();
+ }
+ else if (m_collisionShape)
{
- switch (cinfo.m_collisionShape->getShapeType())
+ switch (m_collisionShape->getShapeType())
{
case SPHERE_SHAPE_PROXYTYPE:
{
- btSphereShape* orgShape = (btSphereShape*)cinfo.m_collisionShape;
+ btSphereShape* orgShape = (btSphereShape*)m_collisionShape;
cinfo.m_collisionShape = new btSphereShape(*orgShape);
break;
}
- case CONE_SHAPE_PROXYTYPE:
+ case CONE_SHAPE_PROXYTYPE:
{
- btConeShape* orgShape = (btConeShape*)cinfo.m_collisionShape;
+ btConeShape* orgShape = (btConeShape*)m_collisionShape;
cinfo.m_collisionShape = new btConeShape(*orgShape);
break;
}
-
default:
{
return 0;
@@ -573,6 +1193,7 @@ PHY_IPhysicsController* CcdPhysicsController::GetReplica()
}
cinfo.m_MotionState = new DefaultMotionState();
+ cinfo.m_shapeInfo = m_shapeInfo;
CcdPhysicsController* replica = new CcdPhysicsController(cinfo);
return replica;
@@ -634,3 +1255,273 @@ void DefaultMotionState::calculateWorldTransformations()
}
+// Shape constructor
+std::map<RAS_MeshObject*, CcdShapeConstructionInfo*> CcdShapeConstructionInfo::m_meshShapeMap;
+
+CcdShapeConstructionInfo* CcdShapeConstructionInfo::FindMesh(RAS_MeshObject* mesh, bool polytope)
+{
+ if (polytope)
+ // not yet supported
+ return NULL;
+
+ std::map<RAS_MeshObject*,CcdShapeConstructionInfo*>::const_iterator mit = m_meshShapeMap.find(mesh);
+ if (mit != m_meshShapeMap.end())
+ return mit->second;
+ return NULL;
+}
+
+bool CcdShapeConstructionInfo::SetMesh(RAS_MeshObject* meshobj, bool polytope,bool useGimpact)
+{
+ m_useGimpact = useGimpact;
+
+ // assume no shape information
+ // no support for dynamic change of shape yet
+ assert(m_meshObject == NULL);
+ m_shapeType = PHY_SHAPE_NONE;
+ m_vertexArray.clear();
+ m_polygonIndexArray.clear();
+ m_meshObject = NULL;
+
+ if (!meshobj)
+ return false;
+
+ // Mesh has no polygons!
+ int numpolys = meshobj->NumPolygons();
+ if (!numpolys)
+ {
+ return false;
+ }
+
+ // check that we have at least one colliding polygon
+ int numvalidpolys = 0;
+
+ for (int p=0; p<numpolys; p++)
+ {
+ RAS_Polygon* poly = meshobj->GetPolygon(p);
+
+ // only add polygons that have the collisionflag set
+ if (poly->IsCollider())
+ {
+ numvalidpolys++;
+ break;
+ }
+ }
+
+ // No collision polygons
+ if (numvalidpolys < 1)
+ return false;
+
+ m_shapeType = (polytope) ? PHY_SHAPE_POLYTOPE : PHY_SHAPE_MESH;
+
+ numvalidpolys = 0;
+
+ for (int p2=0; p2<numpolys; p2++)
+ {
+ RAS_Polygon* poly = meshobj->GetPolygon(p2);
+
+ // only add polygons that have the collisionflag set
+ if (poly->IsCollider())
+ {
+ //Bullet can raycast any shape, so
+ if (polytope)
+ {
+ for (int i=0;i<poly->VertexCount();i++)
+ {
+ const float* vtx = poly->GetVertex(i)->getXYZ();
+ btPoint3 point(vtx[0],vtx[1],vtx[2]);
+ //avoid duplicates (could better directly use vertex offsets, rather than a vertex compare)
+ bool found = false;
+ for (int j=0;j<m_vertexArray.size();j++)
+ {
+ if (m_vertexArray[j]==point)
+ {
+ found = true;
+ break;
+ }
+ }
+ if (!found)
+ m_vertexArray.push_back(point);
+
+ numvalidpolys++;
+ }
+ } else
+ {
+ {
+ const float* vtx = poly->GetVertex(2)->getXYZ();
+ btPoint3 vertex0(vtx[0],vtx[1],vtx[2]);
+
+ vtx = poly->GetVertex(1)->getXYZ();
+ btPoint3 vertex1(vtx[0],vtx[1],vtx[2]);
+
+ vtx = poly->GetVertex(0)->getXYZ();
+ btPoint3 vertex2(vtx[0],vtx[1],vtx[2]);
+
+ m_vertexArray.push_back(vertex0);
+ m_vertexArray.push_back(vertex1);
+ m_vertexArray.push_back(vertex2);
+ m_polygonIndexArray.push_back(p2);
+ numvalidpolys++;
+ }
+ if (poly->VertexCount() == 4)
+ {
+ const float* vtx = poly->GetVertex(3)->getXYZ();
+ btPoint3 vertex0(vtx[0],vtx[1],vtx[2]);
+
+ vtx = poly->GetVertex(2)->getXYZ();
+ btPoint3 vertex1(vtx[0],vtx[1],vtx[2]);
+
+ vtx = poly->GetVertex(0)->getXYZ();
+ btPoint3 vertex2(vtx[0],vtx[1],vtx[2]);
+
+ m_vertexArray.push_back(vertex0);
+ m_vertexArray.push_back(vertex1);
+ m_vertexArray.push_back(vertex2);
+ m_polygonIndexArray.push_back(p2);
+ numvalidpolys++;
+ }
+ }
+ }
+ }
+
+ if (!numvalidpolys)
+ {
+ // should not happen
+ m_shapeType = PHY_SHAPE_NONE;
+ return false;
+ }
+ m_meshObject = meshobj;
+ if (!polytope)
+ {
+ // triangle shape can be shared, store the mesh object in the map
+ m_meshShapeMap.insert(std::pair<RAS_MeshObject*,CcdShapeConstructionInfo*>(meshobj,this));
+ }
+ return true;
+}
+
+btCollisionShape* CcdShapeConstructionInfo::CreateBulletShape()
+{
+ btCollisionShape* collisionShape = 0;
+ btTriangleMeshShape* concaveShape = 0;
+ btTriangleMesh* collisionMeshData = 0;
+ btCompoundShape* compoundShape = 0;
+ CcdShapeConstructionInfo* nextShapeInfo;
+
+ switch (m_shapeType)
+ {
+ case PHY_SHAPE_NONE:
+ break;
+
+ case PHY_SHAPE_BOX:
+ collisionShape = new btBoxShape(m_halfExtend);
+ break;
+
+ case PHY_SHAPE_SPHERE:
+ collisionShape = new btSphereShape(m_radius);
+ break;
+
+ case PHY_SHAPE_CYLINDER:
+ collisionShape = new btCylinderShapeZ(m_halfExtend);
+ break;
+
+ case PHY_SHAPE_CONE:
+ collisionShape = new btConeShapeZ(m_radius, m_height);
+ break;
+
+ case PHY_SHAPE_POLYTOPE:
+ collisionShape = new btConvexHullShape(&m_vertexArray.begin()->getX(), m_vertexArray.size());
+ break;
+
+ case PHY_SHAPE_MESH:
+ // Let's use the latest btScaledBvhTriangleMeshShape: it allows true sharing of
+ // triangle mesh information between duplicates => drastic performance increase when
+ // duplicating complex mesh objects.
+ // BUT it causes a small performance decrease when sharing is not required:
+ // 9 multiplications/additions and one function call for each triangle that passes the mid phase filtering
+ // One possible optimization is to use directly the btBvhTriangleMeshShape when the scale is 1,1,1
+ // and btScaledBvhTriangleMeshShape otherwise.
+ if (m_useGimpact)
+ {
+ collisionMeshData = new btTriangleMesh();
+
+
+ // m_vertexArray is necessarily a multiple of 3
+ for (std::vector<btPoint3>::iterator it=m_vertexArray.begin(); it != m_vertexArray.end(); )
+ {
+ collisionMeshData->addTriangle(*it++,*it++,*it++);
+ }
+ btGImpactMeshShape* gimpactShape = new btGImpactMeshShape(collisionMeshData);
+
+ collisionShape = gimpactShape;
+ gimpactShape->updateBound();
+
+ } else
+ {
+ if (!m_unscaledShape)
+ {
+ collisionMeshData = new btTriangleMesh(true,false);
+ collisionMeshData->m_weldingThreshold = m_weldingThreshold;
+
+ // m_vertexArray is necessarily a multiple of 3
+ for (std::vector<btPoint3>::iterator it=m_vertexArray.begin(); it != m_vertexArray.end(); )
+ {
+ collisionMeshData->addTriangle(*it++,*it++,*it++);
+ }
+ // this shape will be shared and not deleted until shapeInfo is deleted
+ m_unscaledShape = new btBvhTriangleMeshShape( collisionMeshData, true );
+ m_unscaledShape->recalcLocalAabb();
+ }
+ collisionShape = new btScaledBvhTriangleMeshShape(m_unscaledShape, btVector3(1.0f,1.0f,1.0f));
+ }
+ break;
+
+ case PHY_SHAPE_COMPOUND:
+ if (m_shapeArray.size() > 0)
+ {
+ compoundShape = new btCompoundShape();
+ for (std::vector<CcdShapeConstructionInfo*>::iterator sit = m_shapeArray.begin();
+ sit != m_shapeArray.end();
+ sit++)
+ {
+ collisionShape = (*sit)->CreateBulletShape();
+ if (collisionShape)
+ {
+ collisionShape->setLocalScaling((*sit)->m_childScale);
+ compoundShape->addChildShape((*sit)->m_childTrans, collisionShape);
+ }
+ }
+ collisionShape = compoundShape;
+ }
+ }
+ return collisionShape;
+}
+
+void CcdShapeConstructionInfo::AddShape(CcdShapeConstructionInfo* shapeInfo)
+{
+ m_shapeArray.push_back(shapeInfo);
+}
+
+CcdShapeConstructionInfo::~CcdShapeConstructionInfo()
+{
+ for (std::vector<CcdShapeConstructionInfo*>::iterator sit = m_shapeArray.begin();
+ sit != m_shapeArray.end();
+ sit++)
+ {
+ (*sit)->Release();
+ }
+ m_shapeArray.clear();
+ if (m_unscaledShape)
+ {
+ DeleteBulletShape(m_unscaledShape);
+ }
+ m_vertexArray.clear();
+ if (m_shapeType == PHY_SHAPE_MESH && m_meshObject != NULL)
+ {
+ std::map<RAS_MeshObject*,CcdShapeConstructionInfo*>::iterator mit = m_meshShapeMap.find(m_meshObject);
+ if (mit != m_meshShapeMap.end() && mit->second == this)
+ {
+ m_meshShapeMap.erase(mit);
+ }
+ }
+}
+
+
diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsController.h b/source/gameengine/Physics/Bullet/CcdPhysicsController.h
index 11fef56401f..054ec91122a 100644
--- a/source/gameengine/Physics/Bullet/CcdPhysicsController.h
+++ b/source/gameengine/Physics/Bullet/CcdPhysicsController.h
@@ -17,11 +17,15 @@ subject to the following restrictions:
#ifndef BULLET2_PHYSICSCONTROLLER_H
#define BULLET2_PHYSICSCONTROLLER_H
+#include <vector>
+#include <map>
+
#include "PHY_IPhysicsController.h"
/// PHY_IPhysicsController is the abstract simplified Interface to a physical object.
/// It contains the IMotionState and IDeformableMesh Interfaces.
#include "btBulletDynamicsCommon.h"
+#include "LinearMath/btTransform.h"
#include "PHY_IMotionState.h"
@@ -31,8 +35,119 @@ extern float gAngularSleepingTreshold;
extern bool gDisableDeactivation;
class CcdPhysicsEnvironment;
class btMotionState;
+class RAS_MeshObject;
+class btCollisionShape;
+
+
+#define CCD_BSB_SHAPE_MATCHING 2
+#define CCD_BSB_BENDING_CONSTRAINTS 8
+#define CCD_BSB_AERO_VPOINT 16 /* aero model, Vertex normals are oriented toward velocity*/
+#define CCD_BSB_AERO_VTWOSIDE 32 /* aero model, Vertex normals are flipped to match velocity */
+
+/* BulletSoftBody.collisionflags */
+#define CCD_BSB_COL_SDF_RS 2 /* SDF based rigid vs soft */
+#define CCD_BSB_COL_CL_RS 4 /* Cluster based rigid vs soft */
+#define CCD_BSB_COL_CL_SS 8 /* Cluster based soft vs soft */
+#define CCD_BSB_COL_VF_SS 16 /* Vertex/Face based soft vs soft */
+
+
+
+// Shape contructor
+// It contains all the information needed to create a simple bullet shape at runtime
+class CcdShapeConstructionInfo
+{
+public:
+
+
+ static CcdShapeConstructionInfo* FindMesh(RAS_MeshObject* mesh, bool polytope);
+
+ CcdShapeConstructionInfo() :
+ m_shapeType(PHY_SHAPE_NONE),
+ m_radius(1.0),
+ m_height(1.0),
+ m_halfExtend(0.f,0.f,0.f),
+ m_childScale(1.0f,1.0f,1.0f),
+ m_refCount(1),
+ m_meshObject(NULL),
+ m_unscaledShape(NULL),
+ m_useGimpact(false),
+ m_weldingThreshold(0.f)
+ {
+ m_childTrans.setIdentity();
+ }
+
+ ~CcdShapeConstructionInfo();
+
+ CcdShapeConstructionInfo* AddRef()
+ {
+ m_refCount++;
+ return this;
+ }
+ int Release()
+ {
+ if (--m_refCount > 0)
+ return m_refCount;
+ delete this;
+ return 0;
+ }
+ void AddShape(CcdShapeConstructionInfo* shapeInfo);
+
+ btTriangleMeshShape* GetMeshShape(void)
+ {
+ return m_unscaledShape;
+ }
+ CcdShapeConstructionInfo* GetChildShape(int i)
+ {
+ if (i < 0 || i >= m_shapeArray.size())
+ return NULL;
+
+ return m_shapeArray.at(i);
+ }
+
+ bool SetMesh(RAS_MeshObject* mesh, bool polytope,bool useGimpact);
+ RAS_MeshObject* GetMesh(void)
+ {
+ return m_meshObject;
+ }
+
+ btCollisionShape* CreateBulletShape();
+
+ // member variables
+ PHY_ShapeType m_shapeType;
+ btScalar m_radius;
+ btScalar m_height;
+ btVector3 m_halfExtend;
+ btTransform m_childTrans;
+ btVector3 m_childScale;
+ std::vector<btPoint3> m_vertexArray; // Contains both vertex array for polytope shape and
+ // triangle array for concave mesh shape.
+ // In this case a triangle is made of 3 consecutive points
+ std::vector<int> m_polygonIndexArray; // Contains the array of polygon index in the
+ // original mesh that correspond to shape triangles.
+ // only set for concave mesh shape.
+
+ void setVertexWeldingThreshold(float threshold)
+ {
+ m_weldingThreshold = threshold;
+ }
+ float getVertexWeldingThreshold() const
+ {
+ return m_weldingThreshold;
+ }
+protected:
+ static std::map<RAS_MeshObject*, CcdShapeConstructionInfo*> m_meshShapeMap;
+ int m_refCount; // this class is shared between replicas
+ // keep track of users so that we can release it
+ RAS_MeshObject* m_meshObject; // Keep a pointer to the original mesh
+ btBvhTriangleMeshShape* m_unscaledShape;// holds the shared unscale BVH mesh shape,
+ // the actual shape is of type btScaledBvhTriangleMeshShape
+ std::vector<CcdShapeConstructionInfo*> m_shapeArray; // for compound shapes
+ bool m_useGimpact; //use gimpact for concave dynamic/moving collision detection
+ float m_weldingThreshold; //welding closeby vertices together can improve softbody stability etc.
+
+};
struct CcdConstructionInfo
{
@@ -46,24 +161,34 @@ struct CcdConstructionInfo
StaticFilter = 2,
KinematicFilter = 4,
DebrisFilter = 8,
- AllFilter = DefaultFilter | StaticFilter | KinematicFilter | DebrisFilter,
+ SensorFilter = 16,
+ AllFilter = DefaultFilter | StaticFilter | KinematicFilter | DebrisFilter | SensorFilter,
};
CcdConstructionInfo()
- : m_gravity(0,0,0),
+ : m_localInertiaTensor(1.f, 1.f, 1.f),
+ m_gravity(0,0,0),
m_scaling(1.f,1.f,1.f),
m_mass(0.f),
m_restitution(0.1f),
m_friction(0.5f),
m_linearDamping(0.1f),
m_angularDamping(0.1f),
+ m_margin(0.06f),
+ m_gamesoftFlag(0),
m_collisionFlags(0),
+ m_bRigid(false),
+ m_bSoft(false),
m_collisionFilterGroup(DefaultFilter),
m_collisionFilterMask(AllFilter),
+ m_collisionShape(0),
m_MotionState(0),
+ m_shapeInfo(0),
m_physicsEnv(0),
- m_inertiaFactor(1.f)
+ m_inertiaFactor(1.f),
+ m_do_anisotropic(false),
+ m_anisotropicFriction(1.f,1.f,1.f)
{
}
@@ -75,7 +200,50 @@ struct CcdConstructionInfo
btScalar m_friction;
btScalar m_linearDamping;
btScalar m_angularDamping;
+ btScalar m_margin;
+
+ ////////////////////
+ int m_gamesoftFlag;
+ float m_soft_linStiff; /* linear stiffness 0..1 */
+ float m_soft_angStiff; /* angular stiffness 0..1 */
+ float m_soft_volume; /* volume preservation 0..1 */
+
+ int m_soft_viterations; /* Velocities solver iterations */
+ int m_soft_piterations; /* Positions solver iterations */
+ int m_soft_diterations; /* Drift solver iterations */
+ int m_soft_citerations; /* Cluster solver iterations */
+
+ float m_soft_kSRHR_CL; /* Soft vs rigid hardness [0,1] (cluster only) */
+ float m_soft_kSKHR_CL; /* Soft vs kinetic hardness [0,1] (cluster only) */
+ float m_soft_kSSHR_CL; /* Soft vs soft hardness [0,1] (cluster only) */
+ float m_soft_kSR_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
+
+ float m_soft_kSK_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
+ float m_soft_kSS_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
+ float m_soft_kVCF; /* Velocities correction factor (Baumgarte) */
+ float m_soft_kDP; /* Damping coefficient [0,1] */
+
+ float m_soft_kDG; /* Drag coefficient [0,+inf] */
+ float m_soft_kLF; /* Lift coefficient [0,+inf] */
+ float m_soft_kPR; /* Pressure coefficient [-inf,+inf] */
+ float m_soft_kVC; /* Volume conversation coefficient [0,+inf] */
+
+ float m_soft_kDF; /* Dynamic friction coefficient [0,1] */
+ float m_soft_kMT; /* Pose matching coefficient [0,1] */
+ float m_soft_kCHR; /* Rigid contacts hardness [0,1] */
+ float m_soft_kKHR; /* Kinetic contacts hardness [0,1] */
+
+ float m_soft_kSHR; /* Soft contacts hardness [0,1] */
+ float m_soft_kAHR; /* Anchors hardness [0,1] */
+ int m_soft_collisionflags; /* Vertex/Face or Signed Distance Field(SDF) or Clusters, Soft versus Soft or Rigid */
+ int m_soft_numclusteriterations; /* number of iterations to refine collision clusters*/
+///////////////////
+
+
+
int m_collisionFlags;
+ bool m_bRigid;
+ bool m_bSoft;
///optional use of collision group/mask:
///only collision with object goups that match the collision mask.
@@ -85,32 +253,73 @@ struct CcdConstructionInfo
short int m_collisionFilterGroup;
short int m_collisionFilterMask;
-
- btCollisionShape* m_collisionShape;
- class PHY_IMotionState* m_MotionState;
+ ///these pointers are used as argument passing for the CcdPhysicsController constructor
+ ///and not anymore after that
+ class btCollisionShape* m_collisionShape;
+ class PHY_IMotionState* m_MotionState;
+ class CcdShapeConstructionInfo* m_shapeInfo;
CcdPhysicsEnvironment* m_physicsEnv; //needed for self-replication
float m_inertiaFactor;//tweak the inertia (hooked up to Blender 'formfactor'
+ bool m_do_anisotropic;
+ btVector3 m_anisotropicFriction;
+
+ bool m_do_fh; ///< Should the object have a linear Fh spring?
+ bool m_do_rot_fh; ///< Should the object have an angular Fh spring?
+ btScalar m_fh_spring; ///< Spring constant (both linear and angular)
+ btScalar m_fh_damping; ///< Damping factor (linear and angular) in range [0, 1]
+ btScalar m_fh_distance; ///< The range above the surface where Fh is active.
+ bool m_fh_normal; ///< Should the object slide off slopes?
+ float m_radius;//for fh backwards compatibility
+
};
class btRigidBody;
+class btCollisionObject;
+class btSoftBody;
///CcdPhysicsController is a physics object that supports continuous collision detection and time of impact based physics resolution.
class CcdPhysicsController : public PHY_IPhysicsController
{
- btRigidBody* m_body;
- class PHY_IMotionState* m_MotionState;
+
+ btCollisionObject* m_object;
+
+
+ class PHY_IMotionState* m_MotionState;
btMotionState* m_bulletMotionState;
+ class btCollisionShape* m_collisionShape;
+ class CcdShapeConstructionInfo* m_shapeInfo;
+ friend class CcdPhysicsEnvironment; // needed when updating the controller
+
+ //some book keeping for replication
+ bool m_softbodyMappingDone;
+ bool m_softBodyTransformInitialized;
+ bool m_prototypeTransformInitialized;
+ btTransform m_softbodyStartTrans;
- void* m_newClientInfo;
+ void* m_newClientInfo;
+ int m_registerCount; // needed when multiple sensors use the same controller
CcdConstructionInfo m_cci;//needed for replication
+
+ CcdPhysicsController* m_parentCtrl;
+
void GetWorldOrientation(btMatrix3x3& mat);
void CreateRigidbody();
+ bool Register() {
+ return (m_registerCount++ == 0) ? true : false;
+ }
+ bool Unregister() {
+ return (--m_registerCount == 0) ? true : false;
+ }
+
+ protected:
+ void setWorldOrientation(const btMatrix3x3& mat);
+
public:
int m_collisionDelay;
@@ -120,11 +329,24 @@ class CcdPhysicsController : public PHY_IPhysicsController
virtual ~CcdPhysicsController();
+ CcdConstructionInfo& getConstructionInfo()
+ {
+ return m_cci;
+ }
+ const CcdConstructionInfo& getConstructionInfo() const
+ {
+ return m_cci;
+ }
+
- btRigidBody* GetRigidBody() { return m_body;}
+ btRigidBody* GetRigidBody();
+ btCollisionObject* GetCollisionObject();
+ btSoftBody* GetSoftBody();
+
+ CcdShapeConstructionInfo* GetShapeInfo() { return m_shapeInfo; }
btCollisionShape* GetCollisionShape() {
- return m_body->getCollisionShape();
+ return m_object->getCollisionShape();
}
////////////////////////////////////
// PHY_IPhysicsController interface
@@ -190,16 +412,38 @@ class CcdPhysicsController : public PHY_IPhysicsController
return m_cci.m_collisionFilterMask;
}
-
virtual void calcXform() {} ;
- virtual void SetMargin(float margin) {};
- virtual float GetMargin() const {return 0.f;};
+ virtual void SetMargin(float margin)
+ {
+ if (m_collisionShape)
+ m_collisionShape->setMargin(btScalar(margin));
+ }
+ virtual float GetMargin() const
+ {
+ return (m_collisionShape) ? m_collisionShape->getMargin() : 0.f;
+ }
+ virtual float GetRadius() const
+ {
+ // this is not the actual shape radius, it's only used for Fh support
+ return m_cci.m_radius;
+ }
+ virtual void SetRadius(float margin)
+ {
+ if (m_collisionShape && m_collisionShape->getShapeType() == SPHERE_SHAPE_PROXYTYPE)
+ {
+ btSphereShape* sphereShape = static_cast<btSphereShape*>(m_collisionShape);
+ sphereShape->setUnscaledRadius(margin);
+ }
+ m_cci.m_radius = margin;
+ }
bool wantsSleeping();
void UpdateDeactivation(float timeStep);
+ void SetCenterOfMassTransform(btTransform& xform);
+
static btTransform GetTransformFromMotionState(PHY_IMotionState* motionState);
void setAabb(const btVector3& aabbMin,const btVector3& aabbMax);
@@ -215,7 +459,28 @@ class CcdPhysicsController : public PHY_IPhysicsController
return m_MotionState;
}
+ class CcdPhysicsEnvironment* GetPhysicsEnvironment()
+ {
+ return m_cci.m_physicsEnv;
+ }
+ void setParentCtrl(CcdPhysicsController* parentCtrl)
+ {
+ m_parentCtrl = parentCtrl;
+ }
+
+ CcdPhysicsController* getParentCtrl()
+ {
+ return m_parentCtrl;
+ }
+
+ const CcdPhysicsController* getParentCtrl() const
+ {
+ return m_parentCtrl;
+ }
+
+
+
};
diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp b/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp
index 99c3e5f77c7..4fe35630784 100644
--- a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp
+++ b/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp
@@ -23,6 +23,9 @@ subject to the following restrictions:
#include "btBulletDynamicsCommon.h"
#include "LinearMath/btIDebugDraw.h"
#include "BulletCollision/CollisionDispatch/btSimulationIslandManager.h"
+#include "BulletSoftBody/btSoftRigidDynamicsWorld.h"
+#include "BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.h"
+#include "BulletCollision/Gimpact/btGImpactCollisionAlgorithm.h"
//profiling/timings
#include "LinearMath/btQuickprof.h"
@@ -30,6 +33,7 @@ subject to the following restrictions:
#include "PHY_IMotionState.h"
+#define CCD_CONSTRAINT_DISABLE_LINKED_COLLISION 0x80
bool useIslands = true;
@@ -53,6 +57,7 @@ void DrawRasterizerLine(const float* from,const float* to,int color);
#include <stdio.h>
+#include <string.h> // for memset
#ifdef NEW_BULLET_VEHICLE_SUPPORT
class WrapperVehicle : public PHY_IVehicle
@@ -251,6 +256,22 @@ public:
};
#endif //NEW_BULLET_VEHICLE_SUPPORT
+class CcdOverlapFilterCallBack : public btOverlapFilterCallback
+{
+private:
+ class CcdPhysicsEnvironment* m_physEnv;
+public:
+ CcdOverlapFilterCallBack(CcdPhysicsEnvironment* env) :
+ m_physEnv(env)
+ {
+ }
+ virtual ~CcdOverlapFilterCallBack()
+ {
+ }
+ // return true when pairs need collision
+ virtual bool needBroadphaseCollision(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) const;
+};
+
void CcdPhysicsEnvironment::setDebugDrawer(btIDebugDraw* debugDrawer)
{
@@ -302,33 +323,40 @@ m_numTimeSubSteps(1),
m_ccdMode(0),
m_solverType(-1),
m_profileTimings(0),
-m_enableSatCollisionDetection(false)
+m_enableSatCollisionDetection(false),
+m_solver(NULL),
+m_ownPairCache(NULL),
+m_ownDispatcher(NULL),
+m_filterCallback(NULL)
{
for (int i=0;i<PHY_NUM_RESPONSE;i++)
{
m_triggerCallbacks[i] = 0;
}
- if (!dispatcher)
- dispatcher = new btCollisionDispatcher();
+// m_collisionConfiguration = new btDefaultCollisionConfiguration();
+ m_collisionConfiguration = new btSoftBodyRigidBodyCollisionConfiguration();
- if(!pairCache)
+ if (!dispatcher)
{
-
- //todo: calculate/let user specify this world sizes
- btVector3 worldMin(-10000,-10000,-10000);
- btVector3 worldMax(10000,10000,10000);
-
- pairCache = new btAxisSweep3(worldMin,worldMax);
-
- //broadphase = new btSimpleBroadphase();
+ btCollisionDispatcher* disp = new btCollisionDispatcher(m_collisionConfiguration);
+ dispatcher = disp;
+ btGImpactCollisionAlgorithm::registerAlgorithm(disp);
+ m_ownDispatcher = dispatcher;
}
+ //m_broadphase = new btAxisSweep3(btVector3(-1000,-1000,-1000),btVector3(1000,1000,1000));
+ //m_broadphase = new btSimpleBroadphase();
+ m_broadphase = new btDbvtBroadphase();
+
+ m_filterCallback = new CcdOverlapFilterCallBack(this);
+ m_broadphase->getOverlappingPairCache()->setOverlapFilterCallback(m_filterCallback);
setSolverType(1);//issues with quickstep and memory allocations
+// m_dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,m_broadphase,m_solver,m_collisionConfiguration);
+ m_dynamicsWorld = new btSoftRigidDynamicsWorld(dispatcher,m_broadphase,m_solver,m_collisionConfiguration);
- m_dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,pairCache,new btSequentialImpulseConstraintSolver());
m_debugDrawer = 0;
m_gravity = btVector3(0.f,-10.f,0.f);
m_dynamicsWorld->setGravity(m_gravity);
@@ -339,23 +367,42 @@ m_enableSatCollisionDetection(false)
void CcdPhysicsEnvironment::addCcdPhysicsController(CcdPhysicsController* ctrl)
{
btRigidBody* body = ctrl->GetRigidBody();
+ btCollisionObject* obj = ctrl->GetCollisionObject();
//this m_userPointer is just used for triggers, see CallbackTriggers
- body->setUserPointer(ctrl);
+ obj->setUserPointer(ctrl);
+ if (body)
+ body->setGravity( m_gravity );
- body->setGravity( m_gravity );
- m_controllers.push_back(ctrl);
+ m_controllers.insert(ctrl);
- m_dynamicsWorld->addRigidBody(body);
- if (body->isStaticOrKinematicObject())
+ if (body)
+ {
+ //use explicit group/filter for finer control over collision in bullet => near/radar sensor
+ m_dynamicsWorld->addRigidBody(body, ctrl->GetCollisionFilterGroup(), ctrl->GetCollisionFilterMask());
+ } else
+ {
+ if (ctrl->GetSoftBody())
+ {
+ btSoftBody* softBody = ctrl->GetSoftBody();
+ m_dynamicsWorld->addSoftBody(softBody);
+ } else
+ {
+ if (obj->getCollisionShape())
+ {
+ m_dynamicsWorld->addCollisionObject(obj,ctrl->GetCollisionFilterGroup(), ctrl->GetCollisionFilterMask());
+ }
+ }
+ }
+ if (obj->isStaticOrKinematicObject())
{
- body->setActivationState(ISLAND_SLEEPING);
+ obj->setActivationState(ISLAND_SLEEPING);
}
//CollisionObject(body,ctrl->GetCollisionFilterGroup(),ctrl->GetCollisionFilterMask());
- assert(body->getBroadphaseHandle());
+ assert(obj->getBroadphaseHandle());
btBroadphaseInterface* scene = getBroadphase();
@@ -364,7 +411,7 @@ void CcdPhysicsEnvironment::addCcdPhysicsController(CcdPhysicsController* ctrl)
assert(shapeinterface);
- const btTransform& t = ctrl->GetRigidBody()->getCenterOfMassTransform();
+ const btTransform& t = ctrl->GetCollisionObject()->getWorldTransform();
btPoint3 minAabb,maxAabb;
@@ -376,69 +423,123 @@ void CcdPhysicsEnvironment::addCcdPhysicsController(CcdPhysicsController* ctrl)
//extent it with the motion
- btVector3 linMotion = body->getLinearVelocity()*timeStep;
-
- float maxAabbx = maxAabb.getX();
- float maxAabby = maxAabb.getY();
- float maxAabbz = maxAabb.getZ();
- float minAabbx = minAabb.getX();
- float minAabby = minAabb.getY();
- float minAabbz = minAabb.getZ();
-
- if (linMotion.x() > 0.f)
- maxAabbx += linMotion.x();
- else
- minAabbx += linMotion.x();
- if (linMotion.y() > 0.f)
- maxAabby += linMotion.y();
- else
- minAabby += linMotion.y();
- if (linMotion.z() > 0.f)
- maxAabbz += linMotion.z();
- else
- minAabbz += linMotion.z();
-
-
- minAabb = btVector3(minAabbx,minAabby,minAabbz);
- maxAabb = btVector3(maxAabbx,maxAabby,maxAabbz);
-
+ if (body)
+ {
+ btVector3 linMotion = body->getLinearVelocity()*timeStep;
+
+ float maxAabbx = maxAabb.getX();
+ float maxAabby = maxAabb.getY();
+ float maxAabbz = maxAabb.getZ();
+ float minAabbx = minAabb.getX();
+ float minAabby = minAabb.getY();
+ float minAabbz = minAabb.getZ();
+
+ if (linMotion.x() > 0.f)
+ maxAabbx += linMotion.x();
+ else
+ minAabbx += linMotion.x();
+ if (linMotion.y() > 0.f)
+ maxAabby += linMotion.y();
+ else
+ minAabby += linMotion.y();
+ if (linMotion.z() > 0.f)
+ maxAabbz += linMotion.z();
+ else
+ minAabbz += linMotion.z();
+
+
+ minAabb = btVector3(minAabbx,minAabby,minAabbz);
+ maxAabb = btVector3(maxAabbx,maxAabby,maxAabbz);
+ }
}
+
+
void CcdPhysicsEnvironment::removeCcdPhysicsController(CcdPhysicsController* ctrl)
{
-
//also remove constraint
-
-
-
- m_dynamicsWorld->removeRigidBody(ctrl->GetRigidBody());
-
-
+ btRigidBody* body = ctrl->GetRigidBody();
+ if (body)
+ {
+ m_dynamicsWorld->removeRigidBody(ctrl->GetRigidBody());
+ } else
{
- std::vector<CcdPhysicsController*>::iterator i =
- std::find(m_controllers.begin(), m_controllers.end(), ctrl);
- if (!(i == m_controllers.end()))
+ //if a softbody
+ if (ctrl->GetSoftBody())
{
- std::swap(*i, m_controllers.back());
- m_controllers.pop_back();
+ m_dynamicsWorld->removeSoftBody(ctrl->GetSoftBody());
+ } else
+ {
+ m_dynamicsWorld->removeCollisionObject(ctrl->GetCollisionObject());
}
}
+ m_controllers.erase(ctrl);
+
+ if (ctrl->m_registerCount != 0)
+ printf("Warning: removing controller with non-zero m_registerCount: %d\n", ctrl->m_registerCount);
//remove it from the triggers
+ m_triggerControllers.erase(ctrl);
+}
+
+void CcdPhysicsEnvironment::updateCcdPhysicsController(CcdPhysicsController* ctrl, btScalar newMass, int newCollisionFlags, short int newCollisionGroup, short int newCollisionMask)
+{
+ // this function is used when the collisionning group of a controller is changed
+ // remove and add the collistioning object
+ btRigidBody* body = ctrl->GetRigidBody();
+ btCollisionObject* obj = ctrl->GetCollisionObject();
+ if (obj)
{
- std::vector<CcdPhysicsController*>::iterator i =
- std::find(m_triggerControllers.begin(), m_triggerControllers.end(), ctrl);
- if (!(i == m_triggerControllers.end()))
+ btVector3 inertia(0.0,0.0,0.0);
+ m_dynamicsWorld->removeCollisionObject(obj);
+ obj->setCollisionFlags(newCollisionFlags);
+ if (body)
{
- std::swap(*i, m_triggerControllers.back());
- m_triggerControllers.pop_back();
+ if (newMass)
+ body->getCollisionShape()->calculateLocalInertia(newMass, inertia);
+ body->setMassProps(newMass, inertia);
}
+ m_dynamicsWorld->addCollisionObject(obj, newCollisionGroup, newCollisionMask);
}
+ // to avoid nasty interaction, we must update the property of the controller as well
+ ctrl->m_cci.m_mass = newMass;
+ ctrl->m_cci.m_collisionFilterGroup = newCollisionGroup;
+ ctrl->m_cci.m_collisionFilterMask = newCollisionMask;
+ ctrl->m_cci.m_collisionFlags = newCollisionFlags;
+}
+void CcdPhysicsEnvironment::enableCcdPhysicsController(CcdPhysicsController* ctrl)
+{
+ if (m_controllers.insert(ctrl).second)
+ {
+ btCollisionObject* obj = ctrl->GetCollisionObject();
+ obj->setUserPointer(ctrl);
+ m_dynamicsWorld->addCollisionObject(obj,
+ ctrl->GetCollisionFilterGroup(), ctrl->GetCollisionFilterMask());
+ }
+}
+void CcdPhysicsEnvironment::disableCcdPhysicsController(CcdPhysicsController* ctrl)
+{
+ if (m_controllers.erase(ctrl))
+ {
+ btRigidBody* body = ctrl->GetRigidBody();
+ if (body)
+ {
+ m_dynamicsWorld->removeRigidBody(body);
+ } else
+ {
+ if (ctrl->GetSoftBody())
+ {
+ } else
+ {
+ m_dynamicsWorld->removeCollisionObject(body);
+ }
+ }
+ }
}
@@ -450,25 +551,31 @@ void CcdPhysicsEnvironment::beginFrame()
bool CcdPhysicsEnvironment::proceedDeltaTime(double curTime,float timeStep)
{
+ std::set<CcdPhysicsController*>::iterator it;
+ int i;
- int i,numCtrl = GetNumControllers();
- for (i=0;i<numCtrl;i++)
+ for (it=m_controllers.begin(); it!=m_controllers.end(); it++)
{
- CcdPhysicsController* ctrl = GetPhysicsController(i);
- ctrl->SynchronizeMotionStates(timeStep);
+ (*it)->SynchronizeMotionStates(timeStep);
}
+ processFhSprings(curTime,timeStep);
+
float subStep = timeStep / float(m_numTimeSubSteps);
for (i=0;i<m_numTimeSubSteps;i++)
{
- m_dynamicsWorld->stepSimulation(subStep,0);//perform always a full simulation step
+// m_dynamicsWorld->stepSimulation(subStep,20,1./240.);//perform always a full simulation step
+ m_dynamicsWorld->stepSimulation(subStep,0);//perform always a full simulation step
}
- numCtrl = GetNumControllers();
- for (i=0;i<numCtrl;i++)
+ for (it=m_controllers.begin(); it!=m_controllers.end(); it++)
{
- CcdPhysicsController* ctrl = GetPhysicsController(i);
- ctrl->SynchronizeMotionStates(timeStep);
+ (*it)->SynchronizeMotionStates(timeStep);
+ }
+
+ for (it=m_controllers.begin(); it!=m_controllers.end(); it++)
+ {
+ (*it)->SynchronizeMotionStates(timeStep);
}
for (i=0;i<m_wrapperVehicles.size();i++)
@@ -477,11 +584,181 @@ bool CcdPhysicsEnvironment::proceedDeltaTime(double curTime,float timeStep)
veh->SyncWheels();
}
+ if (m_dynamicsWorld->getDebugDrawer() && m_dynamicsWorld->getDebugDrawer()->getDebugMode() >0)
+ m_dynamicsWorld->debugDrawWorld();
+
+
CallbackTriggers();
return true;
}
+class ClosestRayResultCallbackNotMe : public btCollisionWorld::ClosestRayResultCallback
+{
+ btCollisionObject* m_owner;
+ btCollisionObject* m_parent;
+
+public:
+ ClosestRayResultCallbackNotMe(const btVector3& rayFromWorld,const btVector3& rayToWorld,btCollisionObject* owner,btCollisionObject* parent)
+ :btCollisionWorld::ClosestRayResultCallback(rayFromWorld,rayToWorld),
+ m_owner(owner)
+ {
+
+ }
+
+ virtual bool needsCollision(btBroadphaseProxy* proxy0) const
+ {
+ //don't collide with self
+ if (proxy0->m_clientObject == m_owner)
+ return false;
+
+ if (proxy0->m_clientObject == m_parent)
+ return false;
+
+ return btCollisionWorld::ClosestRayResultCallback::needsCollision(proxy0);
+ }
+
+};
+
+void CcdPhysicsEnvironment::processFhSprings(double curTime,float timeStep)
+{
+ std::set<CcdPhysicsController*>::iterator it;
+
+ for (it=m_controllers.begin(); it!=m_controllers.end(); it++)
+ {
+ CcdPhysicsController* ctrl = (*it);
+ btRigidBody* body = ctrl->GetRigidBody();
+
+ if (body && (ctrl->getConstructionInfo().m_do_fh || ctrl->getConstructionInfo().m_do_rot_fh))
+ {
+ //printf("has Fh or RotFh\n");
+ //re-implement SM_FhObject.cpp using btCollisionWorld::rayTest and info from ctrl->getConstructionInfo()
+ //send a ray from {0.0, 0.0, 0.0} towards {0.0, 0.0, -10.0}, in local coordinates
+
+
+ CcdPhysicsController* parentCtrl = ctrl->getParentCtrl();
+ btRigidBody* parentBody = parentCtrl?parentCtrl->GetRigidBody() : 0;
+ btRigidBody* cl_object = parentBody ? parentBody : body;
+
+ if (body->isStaticOrKinematicObject())
+ continue;
+
+ btVector3 rayDirLocal(0,0,-10);
+
+ //m_dynamicsWorld
+ //ctrl->GetRigidBody();
+ btVector3 rayFromWorld = body->getCenterOfMassPosition();
+ //btVector3 rayToWorld = rayFromWorld + body->getCenterOfMassTransform().getBasis() * rayDirLocal;
+ //ray always points down the z axis in world space...
+ btVector3 rayToWorld = rayFromWorld + rayDirLocal;
+
+ ClosestRayResultCallbackNotMe resultCallback(rayFromWorld,rayToWorld,body,parentBody);
+
+ m_dynamicsWorld->rayTest(rayFromWorld,rayToWorld,resultCallback);
+ if (resultCallback.hasHit())
+ {
+ //we hit this one: resultCallback.m_collisionObject;
+ CcdPhysicsController* controller = static_cast<CcdPhysicsController*>(resultCallback.m_collisionObject->getUserPointer());
+
+ if (controller)
+ {
+ if (controller->getConstructionInfo().m_fh_distance < SIMD_EPSILON)
+ continue;
+
+ btRigidBody* hit_object = controller->GetRigidBody();
+ if (!hit_object)
+ continue;
+
+ CcdConstructionInfo& hitObjShapeProps = controller->getConstructionInfo();
+
+ float distance = resultCallback.m_closestHitFraction*rayDirLocal.length()-ctrl->getConstructionInfo().m_radius;
+ if (distance >= hitObjShapeProps.m_fh_distance)
+ continue;
+
+
+
+ //btVector3 ray_dir = cl_object->getCenterOfMassTransform().getBasis()* rayDirLocal.normalized();
+ btVector3 ray_dir = rayDirLocal.normalized();
+ btVector3 normal = resultCallback.m_hitNormalWorld;
+ normal.normalize();
+
+
+ if (ctrl->getConstructionInfo().m_do_fh)
+ {
+ btVector3 lspot = cl_object->getCenterOfMassPosition()
+ + rayDirLocal * resultCallback.m_closestHitFraction;
+
+
+
+
+ lspot -= hit_object->getCenterOfMassPosition();
+ btVector3 rel_vel = cl_object->getLinearVelocity() - hit_object->getVelocityInLocalPoint(lspot);
+ btScalar rel_vel_ray = ray_dir.dot(rel_vel);
+ btScalar spring_extent = 1.0 - distance / hitObjShapeProps.m_fh_distance;
+
+ btScalar i_spring = spring_extent * hitObjShapeProps.m_fh_spring;
+ btScalar i_damp = rel_vel_ray * hitObjShapeProps.m_fh_damping;
+
+ cl_object->setLinearVelocity(cl_object->getLinearVelocity() + (-(i_spring + i_damp) * ray_dir));
+ if (hitObjShapeProps.m_fh_normal)
+ {
+ cl_object->setLinearVelocity(cl_object->getLinearVelocity()+(i_spring + i_damp) *(normal - normal.dot(ray_dir) * ray_dir));
+ }
+
+ btVector3 lateral = rel_vel - rel_vel_ray * ray_dir;
+
+
+ if (ctrl->getConstructionInfo().m_do_anisotropic) {
+ //Bullet basis contains no scaling/shear etc.
+ const btMatrix3x3& lcs = cl_object->getCenterOfMassTransform().getBasis();
+ btVector3 loc_lateral = lateral * lcs;
+ const btVector3& friction_scaling = cl_object->getAnisotropicFriction();
+ loc_lateral *= friction_scaling;
+ lateral = lcs * loc_lateral;
+ }
+
+ btScalar rel_vel_lateral = lateral.length();
+
+ if (rel_vel_lateral > SIMD_EPSILON) {
+ btScalar friction_factor = hit_object->getFriction();//cl_object->getFriction();
+
+ btScalar max_friction = friction_factor * btMax(btScalar(0.0), i_spring);
+
+ btScalar rel_mom_lateral = rel_vel_lateral / cl_object->getInvMass();
+
+ btVector3 friction = (rel_mom_lateral > max_friction) ?
+ -lateral * (max_friction / rel_vel_lateral) :
+ -lateral;
+
+ cl_object->applyCentralImpulse(friction);
+ }
+ }
+
+
+ if (ctrl->getConstructionInfo().m_do_rot_fh) {
+ btVector3 up2 = cl_object->getWorldTransform().getBasis().getColumn(2);
+
+ btVector3 t_spring = up2.cross(normal) * hitObjShapeProps.m_fh_spring;
+ btVector3 ang_vel = cl_object->getAngularVelocity();
+
+ // only rotations that tilt relative to the normal are damped
+ ang_vel -= ang_vel.dot(normal) * normal;
+
+ btVector3 t_damp = ang_vel * hitObjShapeProps.m_fh_damping;
+
+ cl_object->setAngularVelocity(cl_object->getAngularVelocity() + (t_spring - t_damp));
+ }
+
+ }
+
+
+ }
+
+
+ }
+ }
+
+}
void CcdPhysicsEnvironment::setDebugMode(int debugMode)
{
@@ -537,7 +814,7 @@ void CcdPhysicsEnvironment::setSolverDamping(float damping)
void CcdPhysicsEnvironment::setLinearAirDamping(float damping)
{
- gLinearAirDamping = damping;
+ //gLinearAirDamping = damping;
}
void CcdPhysicsEnvironment::setUseEpa(bool epa)
@@ -556,7 +833,7 @@ void CcdPhysicsEnvironment::setSolverType(int solverType)
{
m_solver = new btSequentialImpulseConstraintSolver();
-
+// ((btSequentialImpulseConstraintSolver*)m_solver)->setSolverMode(btSequentialImpulseConstraintSolver::SOLVER_USE_WARMSTARTING | btSequentialImpulseConstraintSolver::SOLVER_RANDMIZE_ORDER);
break;
}
}
@@ -577,7 +854,13 @@ void CcdPhysicsEnvironment::setSolverType(int solverType)
-
+void CcdPhysicsEnvironment::getGravity(PHY__Vector3& grav)
+{
+ const btVector3& gravity = m_dynamicsWorld->getGravity();
+ grav[0] = gravity.getX();
+ grav[1] = gravity.getY();
+ grav[2] = gravity.getZ();
+}
void CcdPhysicsEnvironment::setGravity(float x,float y,float z)
@@ -600,13 +883,16 @@ int CcdPhysicsEnvironment::createUniversalD6Constraint(
const btVector3& linearMinLimits,
const btVector3& linearMaxLimits,
const btVector3& angularMinLimits,
- const btVector3& angularMaxLimits
+ const btVector3& angularMaxLimits,int flags
)
{
+ bool disableCollisionBetweenLinkedBodies = (0!=(flags & CCD_CONSTRAINT_DISABLE_LINKED_COLLISION));
+
//we could either add some logic to recognize ball-socket and hinge, or let that up to the user
//perhaps some warning or hint that hinge/ball-socket is more efficient?
+
btGeneric6DofConstraint* genericConstraint = 0;
CcdPhysicsController* ctrl0 = (CcdPhysicsController*) ctrlRef;
CcdPhysicsController* ctrl1 = (CcdPhysicsController*) ctrlOther;
@@ -618,9 +904,10 @@ int CcdPhysicsEnvironment::createUniversalD6Constraint(
{
+ bool useReferenceFrameA = true;
genericConstraint = new btGeneric6DofConstraint(
*rb0,*rb1,
- frameInA,frameInB);
+ frameInA,frameInB,useReferenceFrameA);
genericConstraint->setLinearLowerLimit(linearMinLimits);
genericConstraint->setLinearUpperLimit(linearMaxLimits);
genericConstraint->setAngularLowerLimit(angularMinLimits);
@@ -635,7 +922,7 @@ int CcdPhysicsEnvironment::createUniversalD6Constraint(
if (genericConstraint)
{
// m_constraints.push_back(genericConstraint);
- m_dynamicsWorld->addConstraint(genericConstraint);
+ m_dynamicsWorld->addConstraint(genericConstraint,disableCollisionBetweenLinkedBodies);
genericConstraint->setUserConstraintId(gConstraintUid++);
genericConstraint->setUserConstraintType(PHY_GENERIC_6DOF_CONSTRAINT);
@@ -668,35 +955,54 @@ void CcdPhysicsEnvironment::removeConstraint(int constraintId)
struct FilterClosestRayResultCallback : public btCollisionWorld::ClosestRayResultCallback
{
- PHY_IPhysicsController* m_ignoreClient;
+ PHY_IRayCastFilterCallback& m_phyRayFilter;
+ const btCollisionShape* m_hitTriangleShape;
+ int m_hitTriangleIndex;
- FilterClosestRayResultCallback (PHY_IPhysicsController* ignoreClient,const btVector3& rayFrom,const btVector3& rayTo)
+ FilterClosestRayResultCallback (PHY_IRayCastFilterCallback& phyRayFilter,const btVector3& rayFrom,const btVector3& rayTo)
: btCollisionWorld::ClosestRayResultCallback(rayFrom,rayTo),
- m_ignoreClient(ignoreClient)
+ m_phyRayFilter(phyRayFilter),
+ m_hitTriangleShape(NULL),
+ m_hitTriangleIndex(0)
{
-
}
virtual ~FilterClosestRayResultCallback()
{
}
- virtual float AddSingleResult( btCollisionWorld::LocalRayResult& rayResult)
+ virtual bool needsCollision(btBroadphaseProxy* proxy0) const
+ {
+ if (!(proxy0->m_collisionFilterGroup & m_collisionFilterMask))
+ return false;
+ if (!(m_collisionFilterGroup & proxy0->m_collisionFilterMask))
+ return false;
+ btCollisionObject* object = (btCollisionObject*)proxy0->m_clientObject;
+ CcdPhysicsController* phyCtrl = static_cast<CcdPhysicsController*>(object->getUserPointer());
+ if (phyCtrl == m_phyRayFilter.m_ignoreController)
+ return false;
+ return m_phyRayFilter.needBroadphaseRayCast(phyCtrl);
+ }
+
+ virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult,bool normalInWorldSpace)
{
CcdPhysicsController* curHit = static_cast<CcdPhysicsController*>(rayResult.m_collisionObject->getUserPointer());
- //ignore client...
- if (curHit != m_ignoreClient)
- {
- //if valid
- return ClosestRayResultCallback::AddSingleResult(rayResult);
+ // save shape information as ClosestRayResultCallback::AddSingleResult() does not do it
+ if (rayResult.m_localShapeInfo)
+ {
+ m_hitTriangleShape = rayResult.m_collisionObject->getCollisionShape();
+ m_hitTriangleIndex = rayResult.m_localShapeInfo->m_triangleIndex;
+ } else
+ {
+ m_hitTriangleShape = NULL;
+ m_hitTriangleIndex = 0;
}
- return m_closestHitFraction;
+ return ClosestRayResultCallback::addSingleResult(rayResult,normalInWorldSpace);
}
};
-PHY_IPhysicsController* CcdPhysicsEnvironment::rayTest(PHY_IPhysicsController* ignoreClient, float fromX,float fromY,float fromZ, float toX,float toY,float toZ,
- float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ)
+PHY_IPhysicsController* CcdPhysicsEnvironment::rayTest(PHY_IRayCastFilterCallback &filterCallback, float fromX,float fromY,float fromZ, float toX,float toY,float toZ)
{
@@ -710,19 +1016,101 @@ PHY_IPhysicsController* CcdPhysicsEnvironment::rayTest(PHY_IPhysicsController* i
//Either Ray Cast with or without filtering
//btCollisionWorld::ClosestRayResultCallback rayCallback(rayFrom,rayTo);
- FilterClosestRayResultCallback rayCallback(ignoreClient,rayFrom,rayTo);
+ FilterClosestRayResultCallback rayCallback(filterCallback,rayFrom,rayTo);
+
+ PHY_RayCastResult result;
+ memset(&result, 0, sizeof(result));
- PHY_IPhysicsController* nearestHit = 0;
+ // don't collision with sensor object
+ rayCallback.m_collisionFilterMask = CcdConstructionInfo::AllFilter ^ CcdConstructionInfo::SensorFilter;
+ //, ,filterCallback.m_faceNormal);
m_dynamicsWorld->rayTest(rayFrom,rayTo,rayCallback);
- if (rayCallback.HasHit())
+ if (rayCallback.hasHit())
{
- nearestHit = static_cast<CcdPhysicsController*>(rayCallback.m_collisionObject->getUserPointer());
- hitX = rayCallback.m_hitPointWorld.getX();
- hitY = rayCallback.m_hitPointWorld.getY();
- hitZ = rayCallback.m_hitPointWorld.getZ();
+ CcdPhysicsController* controller = static_cast<CcdPhysicsController*>(rayCallback.m_collisionObject->getUserPointer());
+ result.m_controller = controller;
+ result.m_hitPoint[0] = rayCallback.m_hitPointWorld.getX();
+ result.m_hitPoint[1] = rayCallback.m_hitPointWorld.getY();
+ result.m_hitPoint[2] = rayCallback.m_hitPointWorld.getZ();
+
+ if (rayCallback.m_hitTriangleShape != NULL)
+ {
+ // identify the mesh polygon
+ CcdShapeConstructionInfo* shapeInfo = controller->m_shapeInfo;
+ if (shapeInfo)
+ {
+ btCollisionShape* shape = controller->GetCollisionObject()->getCollisionShape();
+ if (shape->isCompound())
+ {
+ btCompoundShape* compoundShape = (btCompoundShape*)shape;
+ CcdShapeConstructionInfo* compoundShapeInfo = shapeInfo;
+ // need to search which sub-shape has been hit
+ for (int i=0; i<compoundShape->getNumChildShapes(); i++)
+ {
+ shapeInfo = compoundShapeInfo->GetChildShape(i);
+ shape=compoundShape->getChildShape(i);
+ if (shape == rayCallback.m_hitTriangleShape)
+ break;
+ }
+ }
+ if (shape == rayCallback.m_hitTriangleShape &&
+ rayCallback.m_hitTriangleIndex < shapeInfo->m_polygonIndexArray.size())
+ {
+ result.m_meshObject = shapeInfo->GetMesh();
+ result.m_polygon = shapeInfo->m_polygonIndexArray.at(rayCallback.m_hitTriangleIndex);
+ // Bullet returns the normal from "outside".
+ // If the user requests the real normal, compute it now
+ if (filterCallback.m_faceNormal)
+ {
+ // mesh shapes are shared and stored in the shapeInfo
+ btTriangleMeshShape* triangleShape = shapeInfo->GetMeshShape();
+ if (triangleShape)
+ {
+ // this code is copied from Bullet
+ btVector3 triangle[3];
+ const unsigned char *vertexbase;
+ int numverts;
+ PHY_ScalarType type;
+ int stride;
+ const unsigned char *indexbase;
+ int indexstride;
+ int numfaces;
+ PHY_ScalarType indicestype;
+ btStridingMeshInterface* meshInterface = triangleShape->getMeshInterface();
+
+ meshInterface->getLockedReadOnlyVertexIndexBase(
+ &vertexbase,
+ numverts,
+ type,
+ stride,
+ &indexbase,
+ indexstride,
+ numfaces,
+ indicestype,
+ 0);
+
+ unsigned int* gfxbase = (unsigned int*)(indexbase+rayCallback.m_hitTriangleIndex*indexstride);
+ const btVector3& meshScaling = shape->getLocalScaling();
+ for (int j=2;j>=0;j--)
+ {
+ int graphicsindex = indicestype==PHY_SHORT?((unsigned short*)gfxbase)[j]:gfxbase[j];
+
+ btScalar* graphicsbase = (btScalar*)(vertexbase+graphicsindex*stride);
+
+ triangle[j] = btVector3(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),graphicsbase[2]*meshScaling.getZ());
+ }
+ meshInterface->unLockReadOnlyVertexBase(0);
+ btVector3 triangleNormal;
+ triangleNormal = (triangle[1]-triangle[0]).cross(triangle[2]-triangle[0]);
+ rayCallback.m_hitNormalWorld = rayCallback.m_collisionObject->getWorldTransform().getBasis()*triangleNormal;
+ }
+ }
+ }
+ }
+ }
if (rayCallback.m_hitNormalWorld.length2() > (SIMD_EPSILON*SIMD_EPSILON))
{
rayCallback.m_hitNormalWorld.normalize();
@@ -730,14 +1118,14 @@ PHY_IPhysicsController* CcdPhysicsEnvironment::rayTest(PHY_IPhysicsController* i
{
rayCallback.m_hitNormalWorld.setValue(1,0,0);
}
- normalX = rayCallback.m_hitNormalWorld.getX();
- normalY = rayCallback.m_hitNormalWorld.getY();
- normalZ = rayCallback.m_hitNormalWorld.getZ();
-
+ result.m_hitNormal[0] = rayCallback.m_hitNormalWorld.getX();
+ result.m_hitNormal[1] = rayCallback.m_hitNormalWorld.getY();
+ result.m_hitNormal[2] = rayCallback.m_hitNormalWorld.getZ();
+ filterCallback.reportHit(&result);
}
- return nearestHit;
+ return result.m_controller;
}
@@ -760,6 +1148,13 @@ btBroadphaseInterface* CcdPhysicsEnvironment::getBroadphase()
return m_dynamicsWorld->getBroadphase();
}
+btDispatcher* CcdPhysicsEnvironment::getDispatcher()
+{
+ return m_dynamicsWorld->getDispatcher();
+}
+
+
+
@@ -778,22 +1173,27 @@ CcdPhysicsEnvironment::~CcdPhysicsEnvironment()
delete m_dynamicsWorld;
+ if (NULL != m_ownPairCache)
+ delete m_ownPairCache;
-}
-
+ if (NULL != m_ownDispatcher)
+ delete m_ownDispatcher;
-int CcdPhysicsEnvironment::GetNumControllers()
-{
- return m_controllers.size();
-}
+ if (NULL != m_solver)
+ delete m_solver;
+ if (NULL != m_debugDrawer)
+ delete m_debugDrawer;
-CcdPhysicsController* CcdPhysicsEnvironment::GetPhysicsController( int index)
-{
- return m_controllers[index];
-}
+ if (NULL != m_filterCallback)
+ delete m_filterCallback;
+ if (NULL != m_collisionConfiguration)
+ delete m_collisionConfiguration;
+ if (NULL != m_broadphase)
+ delete m_broadphase;
+}
void CcdPhysicsEnvironment::setConstraintParam(int constraintId,int param,float value0,float value1)
@@ -805,7 +1205,7 @@ void CcdPhysicsEnvironment::setConstraintParam(int constraintId,int param,float
{
//param = 1..12, min0,max0,min1,max1...min6,max6
btGeneric6DofConstraint* genCons = (btGeneric6DofConstraint*)typedConstraint;
- genCons->SetLimit(param,value0,value1);
+ genCons->setLimit(param,value0,value1);
break;
};
default:
@@ -835,15 +1235,18 @@ void CcdPhysicsEnvironment::addSensor(PHY_IPhysicsController* ctrl)
{
CcdPhysicsController* ctrl1 = (CcdPhysicsController* )ctrl;
- std::vector<CcdPhysicsController*>::iterator i =
- std::find(m_controllers.begin(), m_controllers.end(), ctrl);
- if ((i == m_controllers.end()))
- {
- addCcdPhysicsController(ctrl1);
- }
+ // addSensor() is a "light" function for bullet because it is used
+ // dynamically when the sensor is activated. Use enableCcdPhysicsController() instead
+ //if (m_controllers.insert(ctrl1).second)
+ //{
+ // addCcdPhysicsController(ctrl1);
+ //}
+ enableCcdPhysicsController(ctrl1);
+
+ //Collision filter/mask is now set at the time of the creation of the controller
//force collision detection with everything, including static objects (might hurt performance!)
- ctrl1->GetRigidBody()->getBroadphaseHandle()->m_collisionFilterMask = btBroadphaseProxy::AllFilter;
- ctrl1->GetRigidBody()->getBroadphaseHandle()->m_collisionFilterGroup = btBroadphaseProxy::AllFilter;
+ //ctrl1->GetRigidBody()->getBroadphaseHandle()->m_collisionFilterMask = btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::SensorTrigger;
+ //ctrl1->GetRigidBody()->getBroadphaseHandle()->m_collisionFilterGroup = btBroadphaseProxy::SensorTrigger;
//todo: make this 'sensor'!
requestCollisionCallback(ctrl);
@@ -852,21 +1255,19 @@ void CcdPhysicsEnvironment::addSensor(PHY_IPhysicsController* ctrl)
void CcdPhysicsEnvironment::removeCollisionCallback(PHY_IPhysicsController* ctrl)
{
- std::vector<CcdPhysicsController*>::iterator i =
- std::find(m_triggerControllers.begin(), m_triggerControllers.end(), ctrl);
- if (!(i == m_triggerControllers.end()))
- {
- std::swap(*i, m_triggerControllers.back());
- m_triggerControllers.pop_back();
- }
+ CcdPhysicsController* ccdCtrl = (CcdPhysicsController*)ctrl;
+ if (ccdCtrl->Unregister())
+ m_triggerControllers.erase(ccdCtrl);
}
void CcdPhysicsEnvironment::removeSensor(PHY_IPhysicsController* ctrl)
{
removeCollisionCallback(ctrl);
- //printf("removeSensor\n");
+
+ disableCcdPhysicsController((CcdPhysicsController*)ctrl);
}
+
void CcdPhysicsEnvironment::addTouchCallback(int response_class, PHY_ResponseCallback callback, void *user)
{
/* printf("addTouchCallback\n(response class = %i)\n",response_class);
@@ -903,11 +1304,10 @@ void CcdPhysicsEnvironment::requestCollisionCallback(PHY_IPhysicsController* ctr
{
CcdPhysicsController* ccdCtrl = static_cast<CcdPhysicsController*>(ctrl);
- //printf("requestCollisionCallback\n");
- m_triggerControllers.push_back(ccdCtrl);
+ if (ccdCtrl->Register())
+ m_triggerControllers.insert(ccdCtrl);
}
-
void CcdPhysicsEnvironment::CallbackTriggers()
{
@@ -916,13 +1316,16 @@ void CcdPhysicsEnvironment::CallbackTriggers()
if (m_triggerCallbacks[PHY_OBJECT_RESPONSE] || (m_debugDrawer && (m_debugDrawer->getDebugMode() & btIDebugDraw::DBG_DrawContactPoints)))
{
//walk over all overlapping pairs, and if one of the involved bodies is registered for trigger callback, perform callback
- int numManifolds = m_dynamicsWorld->getDispatcher()->getNumManifolds();
+ btDispatcher* dispatcher = m_dynamicsWorld->getDispatcher();
+ int numManifolds = dispatcher->getNumManifolds();
for (int i=0;i<numManifolds;i++)
{
- btPersistentManifold* manifold = m_dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
+ btPersistentManifold* manifold = dispatcher->getManifoldByIndexInternal(i);
int numContacts = manifold->getNumContacts();
if (numContacts)
{
+ btRigidBody* rb0 = static_cast<btRigidBody*>(manifold->getBody0());
+ btRigidBody* rb1 = static_cast<btRigidBody*>(manifold->getBody1());
if (m_debugDrawer && (m_debugDrawer->getDebugMode() & btIDebugDraw::DBG_DrawContactPoints))
{
for (int j=0;j<numContacts;j++)
@@ -933,18 +1336,17 @@ void CcdPhysicsEnvironment::CallbackTriggers()
m_debugDrawer->drawContactPoint(cp.m_positionWorldOnB,cp.m_normalWorldOnB,cp.getDistance(),cp.getLifeTime(),color);
}
}
- btRigidBody* obj0 = static_cast<btRigidBody* >(manifold->getBody0());
- btRigidBody* obj1 = static_cast<btRigidBody* >(manifold->getBody1());
+ btRigidBody* obj0 = rb0;
+ btRigidBody* obj1 = rb1;
//m_internalOwner is set in 'addPhysicsController'
CcdPhysicsController* ctrl0 = static_cast<CcdPhysicsController*>(obj0->getUserPointer());
CcdPhysicsController* ctrl1 = static_cast<CcdPhysicsController*>(obj1->getUserPointer());
- std::vector<CcdPhysicsController*>::iterator i =
- std::find(m_triggerControllers.begin(), m_triggerControllers.end(), ctrl0);
+ std::set<CcdPhysicsController*>::const_iterator i = m_triggerControllers.find(ctrl0);
if (i == m_triggerControllers.end())
{
- i = std::find(m_triggerControllers.begin(), m_triggerControllers.end(), ctrl1);
+ i = m_triggerControllers.find(ctrl1);
}
if (!(i == m_triggerControllers.end()))
@@ -952,6 +1354,15 @@ void CcdPhysicsEnvironment::CallbackTriggers()
m_triggerCallbacks[PHY_OBJECT_RESPONSE](m_triggerCallbacksUserPtrs[PHY_OBJECT_RESPONSE],
ctrl0,ctrl1,0);
}
+ // Bullet does not refresh the manifold contact point for object without contact response
+ // may need to remove this when a newer Bullet version is integrated
+ if (!dispatcher->needsResponse(rb0, rb1))
+ {
+ // Refresh algorithm fails sometimes when there is penetration
+ // (usuall the case with ghost and sensor objects)
+ // Let's just clear the manifold, in any case, it is recomputed on each frame.
+ manifold->clearManifold(); //refreshContactPoints(rb0->getCenterOfMassTransform(),rb1->getCenterOfMassTransform());
+ }
}
}
@@ -962,9 +1373,47 @@ void CcdPhysicsEnvironment::CallbackTriggers()
}
-
-
-
+// This call back is called before a pair is added in the cache
+// Handy to remove objects that must be ignored by sensors
+bool CcdOverlapFilterCallBack::needBroadphaseCollision(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) const
+{
+ btCollisionObject *colObj0, *colObj1;
+ CcdPhysicsController *sensorCtrl, *objCtrl;
+ bool collides;
+ // first check the filters
+ collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0;
+ collides = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);
+ if (!collides)
+ return false;
+
+ // additional check for sensor object
+ if (proxy0->m_collisionFilterGroup & btBroadphaseProxy::SensorTrigger)
+ {
+ // this is a sensor object, the other one can't be a sensor object because
+ // they exclude each other in the above test
+ assert(!(proxy1->m_collisionFilterGroup & btBroadphaseProxy::SensorTrigger));
+ colObj0 = (btCollisionObject*)proxy0->m_clientObject;
+ colObj1 = (btCollisionObject*)proxy1->m_clientObject;
+ }
+ else if (proxy1->m_collisionFilterGroup & btBroadphaseProxy::SensorTrigger)
+ {
+ colObj0 = (btCollisionObject*)proxy1->m_clientObject;
+ colObj1 = (btCollisionObject*)proxy0->m_clientObject;
+ }
+ else
+ {
+ return true;
+ }
+ if (!colObj0 || !colObj1)
+ return false;
+ sensorCtrl = static_cast<CcdPhysicsController*>(colObj0->getUserPointer());
+ objCtrl = static_cast<CcdPhysicsController*>(colObj1->getUserPointer());
+ if (m_physEnv->m_triggerCallbacks[PHY_BROADPH_RESPONSE])
+ {
+ return m_physEnv->m_triggerCallbacks[PHY_BROADPH_RESPONSE](m_physEnv->m_triggerCallbacksUserPtrs[PHY_BROADPH_RESPONSE], sensorCtrl, objCtrl, 0);
+ }
+ return true;
+}
#ifdef NEW_BULLET_VEHICLE_SUPPORT
@@ -998,29 +1447,58 @@ PHY_IPhysicsController* CcdPhysicsEnvironment::CreateSphereController(float radi
{
CcdConstructionInfo cinfo;
+ // memory leak! The shape is not deleted by Bullet and we cannot add it to the KX_Scene.m_shapes list
cinfo.m_collisionShape = new btSphereShape(radius);
cinfo.m_MotionState = 0;
cinfo.m_physicsEnv = this;
- cinfo.m_collisionFlags |= btCollisionObject::CF_NO_CONTACT_RESPONSE | btCollisionObject::CF_KINEMATIC_OBJECT;
+ // declare this object as Dyamic rather then static!!
+ // The reason as it is designed to detect all type of object, including static object
+ // It would cause static-static message to be printed on the console otherwise
+ cinfo.m_collisionFlags |= btCollisionObject::CF_NO_CONTACT_RESPONSE/* | btCollisionObject::CF_KINEMATIC_OBJECT*/;
DefaultMotionState* motionState = new DefaultMotionState();
cinfo.m_MotionState = motionState;
+ // we will add later the possibility to select the filter from option
+ cinfo.m_collisionFilterMask = CcdConstructionInfo::AllFilter ^ CcdConstructionInfo::SensorFilter;
+ cinfo.m_collisionFilterGroup = CcdConstructionInfo::SensorFilter;
motionState->m_worldTransform.setIdentity();
motionState->m_worldTransform.setOrigin(btVector3(position[0],position[1],position[2]));
CcdPhysicsController* sphereController = new CcdPhysicsController(cinfo);
-
return sphereController;
}
+int findClosestNode(btSoftBody* sb,const btVector3& worldPoint);
+int findClosestNode(btSoftBody* sb,const btVector3& worldPoint)
+{
+ int node = -1;
+
+ btSoftBody::tNodeArray& nodes(sb->m_nodes);
+ float maxDistSqr = 1e30f;
+
+ for (int n=0;n<nodes.size();n++)
+ {
+ btScalar distSqr = (nodes[n].m_x - worldPoint).length2();
+ if (distSqr<maxDistSqr)
+ {
+ maxDistSqr = distSqr;
+ node = n;
+ }
+ }
+ return node;
+}
+
int CcdPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl0,class PHY_IPhysicsController* ctrl1,PHY_ConstraintType type,
float pivotX,float pivotY,float pivotZ,
float axisX,float axisY,float axisZ,
float axis1X,float axis1Y,float axis1Z,
- float axis2X,float axis2Y,float axis2Z
+ float axis2X,float axis2Y,float axis2Z,int flags
)
{
+ bool disableCollisionBetweenLinkedBodies = (0!=(flags & CCD_CONSTRAINT_DISABLE_LINKED_COLLISION));
+
+
CcdPhysicsController* c0 = (CcdPhysicsController*)ctrl0;
CcdPhysicsController* c1 = (CcdPhysicsController*)ctrl1;
@@ -1028,14 +1506,166 @@ int CcdPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl
btRigidBody* rb0 = c0 ? c0->GetRigidBody() : 0;
btRigidBody* rb1 = c1 ? c1->GetRigidBody() : 0;
+
+
+
bool rb0static = rb0 ? rb0->isStaticOrKinematicObject() : true;
bool rb1static = rb1 ? rb1->isStaticOrKinematicObject() : true;
+
+ btCollisionObject* colObj0 = c0->GetCollisionObject();
+ if (!colObj0)
+ {
+ return 0;
+ }
+
+ btVector3 pivotInA(pivotX,pivotY,pivotZ);
+
+ //it might be a soft body, let's try
+ btSoftBody* sb0 = c0 ? c0->GetSoftBody() : 0;
+ btSoftBody* sb1 = c1 ? c1->GetSoftBody() : 0;
+ if (sb0 && sb1)
+ {
+ //not between two soft bodies?
+ return 0;
+ }
+
+ if (sb0)
+ {
+ //either cluster or node attach, let's find closest node first
+ //the soft body doesn't have a 'real' world transform, so get its initial world transform for now
+ btVector3 pivotPointSoftWorld = sb0->m_initialWorldTransform(pivotInA);
+ int node=findClosestNode(sb0,pivotPointSoftWorld);
+ if (node >=0)
+ {
+ bool clusterconstaint = false;
+/*
+ switch (type)
+ {
+ case PHY_LINEHINGE_CONSTRAINT:
+ {
+ if (sb0->clusterCount() && rb1)
+ {
+ btSoftBody::LJoint::Specs ls;
+ ls.erp=0.5f;
+ ls.position=sb0->clusterCom(0);
+ sb0->appendLinearJoint(ls,rb1);
+ clusterconstaint = true;
+ break;
+ }
+ }
+ case PHY_GENERIC_6DOF_CONSTRAINT:
+ {
+ if (sb0->clusterCount() && rb1)
+ {
+ btSoftBody::AJoint::Specs as;
+ as.erp = 1;
+ as.cfm = 1;
+ as.axis.setValue(axisX,axisY,axisZ);
+ sb0->appendAngularJoint(as,rb1);
+ clusterconstaint = true;
+ break;
+ }
+
+ break;
+ }
+ default:
+ {
+
+ }
+ };
+ */
+
+ if (!clusterconstaint)
+ {
+ if (rb1)
+ {
+ sb0->appendAnchor(node,rb1,disableCollisionBetweenLinkedBodies);
+ } else
+ {
+ sb0->setMass(node,0.f);
+ }
+ }
+
+
+ }
+ return 0;//can't remove soft body anchors yet
+ }
+
+ if (sb1)
+ {
+ btVector3 pivotPointAWorld = colObj0->getWorldTransform()(pivotInA);
+ int node=findClosestNode(sb1,pivotPointAWorld);
+ if (node >=0)
+ {
+ bool clusterconstaint = false;
+
+ /*
+ switch (type)
+ {
+ case PHY_LINEHINGE_CONSTRAINT:
+ {
+ if (sb1->clusterCount() && rb0)
+ {
+ btSoftBody::LJoint::Specs ls;
+ ls.erp=0.5f;
+ ls.position=sb1->clusterCom(0);
+ sb1->appendLinearJoint(ls,rb0);
+ clusterconstaint = true;
+ break;
+ }
+ }
+ case PHY_GENERIC_6DOF_CONSTRAINT:
+ {
+ if (sb1->clusterCount() && rb0)
+ {
+ btSoftBody::AJoint::Specs as;
+ as.erp = 1;
+ as.cfm = 1;
+ as.axis.setValue(axisX,axisY,axisZ);
+ sb1->appendAngularJoint(as,rb0);
+ clusterconstaint = true;
+ break;
+ }
+
+ break;
+ }
+ default:
+ {
+
+
+ }
+ };*/
+
+
+ if (!clusterconstaint)
+ {
+ if (rb0)
+ {
+ sb1->appendAnchor(node,rb0,disableCollisionBetweenLinkedBodies);
+ } else
+ {
+ sb1->setMass(node,0.f);
+ }
+ }
+
+
+ }
+ return 0;//can't remove soft body anchors yet
+ }
+
if (rb0static && rb1static)
+ {
+
return 0;
+ }
+
- btVector3 pivotInA(pivotX,pivotY,pivotZ);
+ if (!rb0)
+ return 0;
+
+
btVector3 pivotInB = rb1 ? rb1->getCenterOfMassTransform().inverse()(rb0->getCenterOfMassTransform()(pivotInA)) :
rb0->getCenterOfMassTransform() * pivotInA;
btVector3 axisInA(axisX,axisY,axisZ);
@@ -1060,7 +1690,7 @@ int CcdPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl
pivotInA);
}
- m_dynamicsWorld->addConstraint(p2p);
+ m_dynamicsWorld->addConstraint(p2p,disableCollisionBetweenLinkedBodies);
// m_constraints.push_back(p2p);
p2p->setUserConstraintId(gConstraintUid++);
@@ -1096,10 +1726,11 @@ int CcdPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl
btTransform globalFrameA = rb0->getCenterOfMassTransform() * frameInA;
frameInB = inv * globalFrameA;
-
+ bool useReferenceFrameA = true;
+
genericConstraint = new btGeneric6DofConstraint(
*rb0,*rb1,
- frameInA,frameInB);
+ frameInA,frameInB,useReferenceFrameA);
} else
@@ -1120,15 +1751,16 @@ int CcdPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl
///frameInB in worldspace
frameInB = rb0->getCenterOfMassTransform() * frameInA;
+ bool useReferenceFrameA = true;
genericConstraint = new btGeneric6DofConstraint(
*rb0,s_fixedObject2,
- frameInA,frameInB);
+ frameInA,frameInB,useReferenceFrameA);
}
if (genericConstraint)
{
//m_constraints.push_back(genericConstraint);
- m_dynamicsWorld->addConstraint(genericConstraint);
+ m_dynamicsWorld->addConstraint(genericConstraint,disableCollisionBetweenLinkedBodies);
genericConstraint->setUserConstraintId(gConstraintUid++);
genericConstraint->setUserConstraintType(type);
//64 bit systems can't cast pointer to int. could use size_t instead.
@@ -1194,7 +1826,7 @@ int CcdPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl
if (coneTwistContraint)
{
//m_constraints.push_back(genericConstraint);
- m_dynamicsWorld->addConstraint(coneTwistContraint);
+ m_dynamicsWorld->addConstraint(coneTwistContraint,disableCollisionBetweenLinkedBodies);
coneTwistContraint->setUserConstraintId(gConstraintUid++);
coneTwistContraint->setUserConstraintType(type);
//64 bit systems can't cast pointer to int. could use size_t instead.
@@ -1233,7 +1865,7 @@ int CcdPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl
hinge->setAngularOnly(angularOnly);
//m_constraints.push_back(hinge);
- m_dynamicsWorld->addConstraint(hinge);
+ m_dynamicsWorld->addConstraint(hinge,disableCollisionBetweenLinkedBodies);
hinge->setUserConstraintId(gConstraintUid++);
hinge->setUserConstraintType(type);
//64 bit systems can't cast pointer to int. could use size_t instead.
@@ -1275,12 +1907,19 @@ int CcdPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl
PHY_IPhysicsController* CcdPhysicsEnvironment::CreateConeController(float coneradius,float coneheight)
{
CcdConstructionInfo cinfo;
+
+ // we don't need a CcdShapeConstructionInfo for this shape:
+ // it is simple enough for the standard copy constructor (see CcdPhysicsController::GetReplica)
cinfo.m_collisionShape = new btConeShape(coneradius,coneheight);
cinfo.m_MotionState = 0;
cinfo.m_physicsEnv = this;
cinfo.m_collisionFlags |= btCollisionObject::CF_NO_CONTACT_RESPONSE;
DefaultMotionState* motionState = new DefaultMotionState();
cinfo.m_MotionState = motionState;
+
+ // we will add later the possibility to select the filter from option
+ cinfo.m_collisionFilterMask = CcdConstructionInfo::AllFilter ^ CcdConstructionInfo::SensorFilter;
+ cinfo.m_collisionFilterGroup = CcdConstructionInfo::SensorFilter;
motionState->m_worldTransform.setIdentity();
// motionState->m_worldTransform.setOrigin(btVector3(position[0],position[1],position[2]));
diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h b/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h
index 66a6ed59c17..74384dd8cf2 100644
--- a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h
+++ b/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h
@@ -18,6 +18,7 @@ subject to the following restrictions:
#include "PHY_IPhysicsEnvironment.h"
#include <vector>
+#include <set>
class CcdPhysicsController;
#include "LinearMath/btVector3.h"
#include "LinearMath/btTransform.h"
@@ -42,6 +43,7 @@ class btBroadphaseInterface;
class btOverlappingPairCache;
class btIDebugDraw;
class PHY_IVehicle;
+class CcdOverlapFilterCallBack;
/// CcdPhysicsEnvironment is an experimental mainloop for physics simulation using optional continuous collision detection.
/// Physics Environment takes care of stepping the simulation and is a container for physics entities.
@@ -49,12 +51,15 @@ class PHY_IVehicle;
/// A derived class may be able to 'construct' entities by loading and/or converting
class CcdPhysicsEnvironment : public PHY_IPhysicsEnvironment
{
+ friend class CcdOverlapFilterCallBack;
btVector3 m_gravity;
-
-
protected:
btIDebugDraw* m_debugDrawer;
+
+ class btDefaultCollisionConfiguration* m_collisionConfiguration;
+ class btBroadphaseInterface* m_broadphase;
+
//solver iterations
int m_numIterations;
@@ -69,6 +74,7 @@ protected:
btContactSolverInfo m_solverInfo;
+ void processFhSprings(double curTime,float timeStep);
public:
CcdPhysicsEnvironment(btDispatcher* dispatcher=0, btOverlappingPairCache* pairCache=0);
@@ -114,12 +120,14 @@ protected:
virtual void setDebugMode(int debugMode);
virtual void setGravity(float x,float y,float z);
+ virtual void getGravity(PHY__Vector3& grav);
+
virtual int createConstraint(class PHY_IPhysicsController* ctrl,class PHY_IPhysicsController* ctrl2,PHY_ConstraintType type,
float pivotX,float pivotY,float pivotZ,
float axisX,float axisY,float axisZ,
float axis1X=0,float axis1Y=0,float axis1Z=0,
- float axis2X=0,float axis2Y=0,float axis2Z=0
+ float axis2X=0,float axis2Y=0,float axis2Z=0,int flag=0
);
@@ -131,7 +139,7 @@ protected:
const btVector3& linearMinLimits,
const btVector3& linearMaxLimits,
const btVector3& angularMinLimits,
- const btVector3& angularMaxLimits
+ const btVector3& angularMaxLimits,int flags
);
virtual void setConstraintParam(int constraintId,int param,float value,float value1);
@@ -156,8 +164,7 @@ protected:
btTypedConstraint* getConstraintById(int constraintId);
- virtual PHY_IPhysicsController* rayTest(PHY_IPhysicsController* ignoreClient, float fromX,float fromY,float fromZ, float toX,float toY,float toZ,
- float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ);
+ virtual PHY_IPhysicsController* rayTest(PHY_IRayCastFilterCallback &filterCallback, float fromX,float fromY,float fromZ, float toX,float toY,float toZ);
//Methods for gamelogic collision/physics callbacks
@@ -166,7 +173,7 @@ protected:
virtual void addTouchCallback(int response_class, PHY_ResponseCallback callback, void *user);
virtual void requestCollisionCallback(PHY_IPhysicsController* ctrl);
virtual void removeCollisionCallback(PHY_IPhysicsController* ctrl);
-
+ //These two methods are used *solely* to create controllers for Near/Radar sensor! Don't use for anything else
virtual PHY_IPhysicsController* CreateSphereController(float radius,const PHY__Vector3& position);
virtual PHY_IPhysicsController* CreateConeController(float coneradius,float coneheight);
@@ -183,10 +190,15 @@ protected:
void removeCcdPhysicsController(CcdPhysicsController* ctrl);
+ void updateCcdPhysicsController(CcdPhysicsController* ctrl, btScalar newMass, int newCollisionFlags, short int newCollisionGroup, short int newCollisionMask);
+
+ void disableCcdPhysicsController(CcdPhysicsController* ctrl);
+
+ void enableCcdPhysicsController(CcdPhysicsController* ctrl);
+
btBroadphaseInterface* getBroadphase();
-
-
+ btDispatcher* getDispatcher();
bool IsSatCollisionDetectionEnabled() const
@@ -200,18 +212,15 @@ protected:
}
- int GetNumControllers();
-
- CcdPhysicsController* GetPhysicsController( int index);
-
-
-
const btPersistentManifold* GetManifold(int index) const;
void SyncMotionStates(float timeStep);
-
+ class btSoftRigidDynamicsWorld* getDynamicsWorld()
+ {
+ return m_dynamicsWorld;
+ }
class btConstraintSolver* GetConstraintSolver();
@@ -220,19 +229,31 @@ protected:
- std::vector<CcdPhysicsController*> m_controllers;
+ std::set<CcdPhysicsController*> m_controllers;
- std::vector<CcdPhysicsController*> m_triggerControllers;
+ std::set<CcdPhysicsController*> m_triggerControllers;
PHY_ResponseCallback m_triggerCallbacks[PHY_NUM_RESPONSE];
void* m_triggerCallbacksUserPtrs[PHY_NUM_RESPONSE];
std::vector<WrapperVehicle*> m_wrapperVehicles;
- class btDynamicsWorld* m_dynamicsWorld;
+ //use explicit btSoftRigidDynamicsWorld/btDiscreteDynamicsWorld* so that we have access to
+ //btDiscreteDynamicsWorld::addRigidBody(body,filter,group)
+ //so that we can set the body collision filter/group at the time of creation
+ //and not afterwards (breaks the collision system for radar/near sensor)
+ //Ideally we would like to have access to this function from the btDynamicsWorld interface
+ //class btDynamicsWorld* m_dynamicsWorld;
+ class btSoftRigidDynamicsWorld* m_dynamicsWorld;
class btConstraintSolver* m_solver;
+ class btOverlappingPairCache* m_ownPairCache;
+
+ class CcdOverlapFilterCallBack* m_filterCallback;
+
+ class btDispatcher* m_ownDispatcher;
+
bool m_scalingPropagated;
diff --git a/source/gameengine/Physics/Bullet/Makefile b/source/gameengine/Physics/Bullet/Makefile
index 49259d0a67c..d5570e75833 100644
--- a/source/gameengine/Physics/Bullet/Makefile
+++ b/source/gameengine/Physics/Bullet/Makefile
@@ -37,5 +37,10 @@ CCFLAGS += $(LEVEL_1_CPP_WARNINGS)
CPPFLAGS += -I$(NAN_BULLET2)/include
CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include
+CPPFLAGS += -I$(NAN_STRING)/include
+CPPFLAGS += -I$(NAN_MOTO)/include
+CPPFLAGS += -I../../../kernel/gen_system
CPPFLAGS += -I../../Physics/common
CPPFLAGS += -I../../Physics/Dummy
+CPPFLAGS += -I../../Rasterizer
+
diff --git a/source/gameengine/Physics/Bullet/SConscript b/source/gameengine/Physics/Bullet/SConscript
index 04abca6e4a5..138ae493013 100644
--- a/source/gameengine/Physics/Bullet/SConscript
+++ b/source/gameengine/Physics/Bullet/SConscript
@@ -3,13 +3,13 @@ Import ('env')
sources = 'CcdPhysicsEnvironment.cpp CcdPhysicsController.cpp'
-incs = '. ../common'
+incs = '. ../common #source/kernel/gen_system #intern/string #intern/moto/include #source/gameengine/Rasterizer'
incs += ' ' + env['BF_BULLET_INC']
cflags = []
if env['OURPLATFORM']=='win32-vc':
- cflags.append('/GR')
- cflags.append('/O2')
+ cflags.append('/GR')
+ cflags.append('/O2')
env.BlenderLib ( 'bf_bullet', Split(sources), Split(incs), [], libtype=['game','player'], priority=[15,80] )
diff --git a/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.cpp b/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.cpp
index f512d44c9f2..ba196b5cf55 100644
--- a/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.cpp
+++ b/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.cpp
@@ -92,8 +92,7 @@ void DummyPhysicsEnvironment::setGravity(float x,float y,float z)
int DummyPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl,class PHY_IPhysicsController* ctrl2,PHY_ConstraintType type,
float pivotX,float pivotY,float pivotZ,float axisX,float axisY,float axisZ,
float axis1X,float axis1Y,float axis1Z,
- float axis2X,float axis2Y,float axis2Z
-
+ float axis2X,float axis2Y,float axis2Z,int flag
)
{
@@ -109,8 +108,7 @@ void DummyPhysicsEnvironment::removeConstraint(int constraintid)
}
}
-PHY_IPhysicsController* DummyPhysicsEnvironment::rayTest(PHY_IPhysicsController* ignoreClient,float fromX,float fromY,float fromZ, float toX,float toY,float toZ,
- float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ)
+PHY_IPhysicsController* DummyPhysicsEnvironment::rayTest(PHY_IRayCastFilterCallback &filterCallback,float fromX,float fromY,float fromZ, float toX,float toY,float toZ)
{
//collision detection / raytesting
return NULL;
diff --git a/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h b/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h
index f0761618e4e..a92b1e7f4a6 100644
--- a/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h
+++ b/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h
@@ -58,7 +58,7 @@ public:
float pivotX,float pivotY,float pivotZ,
float axisX,float axisY,float axisZ,
float axis1X=0,float axis1Y=0,float axis1Z=0,
- float axis2X=0,float axis2Y=0,float axis2Z=0
+ float axis2X=0,float axis2Y=0,float axis2Z=0,int flag=0
);
virtual void removeConstraint(int constraintid);
@@ -69,8 +69,7 @@ public:
return 0;
}
- virtual PHY_IPhysicsController* rayTest(PHY_IPhysicsController* ignoreClient, float fromX,float fromY,float fromZ, float toX,float toY,float toZ,
- float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ);
+ virtual PHY_IPhysicsController* rayTest(PHY_IRayCastFilterCallback &filterCallback, float fromX,float fromY,float fromZ, float toX,float toY,float toZ);
//gamelogic callbacks
@@ -80,6 +79,7 @@ public:
{
}
virtual void requestCollisionCallback(PHY_IPhysicsController* ctrl) {}
+ virtual void removeCollisionCallback(PHY_IPhysicsController* ctrl) {}
virtual PHY_IPhysicsController* CreateSphereController(float radius,const PHY__Vector3& position) {return 0;}
virtual PHY_IPhysicsController* CreateConeController(float coneradius,float coneheight) { return 0;}
diff --git a/source/gameengine/Physics/Sumo/Fuzzics/include/SM_Callback.h b/source/gameengine/Physics/Sumo/Fuzzics/include/SM_Callback.h
index a43ddbec483..42b5ab48ab6 100644
--- a/source/gameengine/Physics/Sumo/Fuzzics/include/SM_Callback.h
+++ b/source/gameengine/Physics/Sumo/Fuzzics/include/SM_Callback.h
@@ -4,6 +4,7 @@
class SM_Callback {
public:
virtual void do_me() = 0;
+ virtual ~SM_Callback() {}
};
#endif
diff --git a/source/gameengine/Physics/Sumo/Fuzzics/src/SM_Scene.cpp b/source/gameengine/Physics/Sumo/Fuzzics/src/SM_Scene.cpp
index b5bf67b14ea..f0791bbf89f 100644
--- a/source/gameengine/Physics/Sumo/Fuzzics/src/SM_Scene.cpp
+++ b/source/gameengine/Physics/Sumo/Fuzzics/src/SM_Scene.cpp
@@ -98,12 +98,17 @@ void SM_Scene::addTouchCallback(int response_class, DT_ResponseCallback callback
void SM_Scene::addSensor(SM_Object& object)
{
- object.calcXform();
- m_objectList.push_back(&object);
- DT_AddObject(m_scene, object.getObjectHandle());
- DT_SetResponseClass(m_respTable, object.getObjectHandle(), m_ResponseClass[SENSOR_RESPONSE]);
- DT_SetResponseClass(m_secondaryRespTable, object.getObjectHandle(), m_secondaryResponseClass[SENSOR_RESPONSE]);
- DT_SetResponseClass(m_fixRespTable, object.getObjectHandle(), m_fixResponseClass[SENSOR_RESPONSE]);
+ T_ObjectList::iterator i =
+ std::find(m_objectList.begin(), m_objectList.end(), &object);
+ if (i == m_objectList.end())
+ {
+ object.calcXform();
+ m_objectList.push_back(&object);
+ DT_AddObject(m_scene, object.getObjectHandle());
+ DT_SetResponseClass(m_respTable, object.getObjectHandle(), m_ResponseClass[SENSOR_RESPONSE]);
+ DT_SetResponseClass(m_secondaryRespTable, object.getObjectHandle(), m_secondaryResponseClass [SENSOR_RESPONSE]);
+ DT_SetResponseClass(m_fixRespTable, object.getObjectHandle(), m_fixResponseClass[SENSOR_RESPONSE]);
+ }
}
void SM_Scene::add(SM_Object& object) {
diff --git a/source/gameengine/Physics/Sumo/SConscript b/source/gameengine/Physics/Sumo/SConscript
index b5900919321..fdf6fdafec2 100644
--- a/source/gameengine/Physics/Sumo/SConscript
+++ b/source/gameengine/Physics/Sumo/SConscript
@@ -1,22 +1,21 @@
#!/usr/bin/python
Import ('env')
-sumoenv = env.Clone()
sources = ['SumoPHYCallbackBridge.cpp',
- 'SumoPhysicsController.cpp',
- 'SumoPhysicsEnvironment.cpp',
- 'Fuzzics/src/SM_FhObject.cpp',
- 'Fuzzics/src/SM_Object.cpp',
- 'Fuzzics/src/SM_Scene.cpp',
- 'Fuzzics/src/SM_MotionState.cpp'
- ]
+ 'SumoPhysicsController.cpp',
+ 'SumoPhysicsEnvironment.cpp',
+ 'Fuzzics/src/SM_FhObject.cpp',
+ 'Fuzzics/src/SM_Object.cpp',
+ 'Fuzzics/src/SM_Scene.cpp',
+ 'Fuzzics/src/SM_MotionState.cpp'
+ ]
incs =['.',
'../common',
'Fuzzics/include',
'#/intern/moto/include'
]
-incs += [sumoenv['BF_SOLID_INC']]
+incs += [env['BF_SOLID_INC']]
cflags = []
if env['OURPLATFORM']=='win32-vc':
diff --git a/source/gameengine/Physics/Sumo/SumoPhysicsController.h b/source/gameengine/Physics/Sumo/SumoPhysicsController.h
index 95f01b45f2b..d8ee54935d7 100644
--- a/source/gameengine/Physics/Sumo/SumoPhysicsController.h
+++ b/source/gameengine/Physics/Sumo/SumoPhysicsController.h
@@ -120,6 +120,7 @@ public:
virtual void SetMargin(float margin) ;
virtual float GetMargin() const;
virtual float GetRadius() const ;
+ virtual void SetRadius(float margin) { SetMargin(margin); }
// clientinfo for raycasts for example
diff --git a/source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.cpp b/source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.cpp
index f324b979fb9..3be5e027345 100644
--- a/source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.cpp
+++ b/source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.cpp
@@ -26,6 +26,7 @@
*
* ***** END GPL LICENSE BLOCK *****
*/
+#include <string.h> // memset
#include "SumoPhysicsEnvironment.h"
#include "PHY_IMotionState.h"
#include "SumoPhysicsController.h"
@@ -110,8 +111,8 @@ int SumoPhysicsEnvironment::createConstraint(
float pivotX,float pivotY,float pivotZ,
float axisX,float axisY,float axisZ,
float axis1X,float axis1Y,float axis1Z,
- float axis2X,float axis2Y,float axis2Z
-
+ float axis2X,float axis2Y,float axis2Z,
+ int flag
)
{
int constraintid = 0;
@@ -125,37 +126,35 @@ void SumoPhysicsEnvironment::removeConstraint(int constraintid)
}
}
-PHY_IPhysicsController* SumoPhysicsEnvironment::rayTest(PHY_IPhysicsController* ignoreClientCtrl,
+PHY_IPhysicsController* SumoPhysicsEnvironment::rayTest(PHY_IRayCastFilterCallback &filterCallback,
float fromX,float fromY,float fromZ,
- float toX,float toY,float toZ,
- float& hitX,float& hitY,float& hitZ,
- float& normalX,float& normalY,float& normalZ)
+ float toX,float toY,float toZ)
{
- SumoPhysicsController* ignoreCtr = static_cast<SumoPhysicsController*> (ignoreClientCtrl);
+ SumoPhysicsController* ignoreCtr = static_cast<SumoPhysicsController*> (filterCallback.m_ignoreController);
//collision detection / raytesting
MT_Point3 hit, normal;
- PHY_IPhysicsController *ret = 0;
+ PHY_RayCastResult result;
SM_Object* sm_ignore = 0;
if (ignoreCtr)
sm_ignore = ignoreCtr->GetSumoObject();
+ memset(&result, 0, sizeof(result));
SM_Object* smOb = m_sumoScene->rayTest(sm_ignore,MT_Point3(fromX, fromY, fromZ),MT_Point3(toX, toY, toZ), hit, normal);
if (smOb)
{
- ret = (PHY_IPhysicsController *) smOb->getPhysicsClientObject();
+ result.m_controller = (PHY_IPhysicsController *) smOb->getPhysicsClientObject();
+ result.m_hitPoint[0] = hit[0];
+ result.m_hitPoint[1] = hit[1];
+ result.m_hitPoint[2] = hit[2];
+ result.m_hitNormal[0] = normal[0];
+ result.m_hitNormal[1] = normal[1];
+ result.m_hitNormal[2] = normal[2];
+ filterCallback.reportHit(&result);
}
- hitX = hit[0];
- hitY = hit[1];
- hitZ = hit[2];
-
- normalX = normal[0];
- normalY = normal[1];
- normalZ = normal[2];
-
- return ret;
+ return result.m_controller;
}
//gamelogic callbacks
void SumoPhysicsEnvironment::addSensor(PHY_IPhysicsController* ctrl)
@@ -203,6 +202,8 @@ void SumoPhysicsEnvironment::addTouchCallback(int response_class, PHY_ResponseCa
case PHY_STATIC_RESPONSE:
sumoRespClass = PHY_STATIC_RESPONSE;
break;
+ case PHY_BROADPH_RESPONSE:
+ return;
default:
assert(0);
return;
@@ -226,6 +227,12 @@ void SumoPhysicsEnvironment::requestCollisionCallback(PHY_IPhysicsController* ct
m_sumoScene->requestCollisionCallback(*smObject);
}
}
+
+void SumoPhysicsEnvironment::removeCollisionCallback(PHY_IPhysicsController* ctrl)
+{
+ // intentionally empty
+}
+
PHY_IPhysicsController* SumoPhysicsEnvironment::CreateSphereController(float radius,const PHY__Vector3& position)
{
DT_ShapeHandle shape = DT_NewSphere(0.0);
diff --git a/source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.h b/source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.h
index ce5cd70e8cc..65b07a7a0be 100644
--- a/source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.h
+++ b/source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.h
@@ -63,7 +63,7 @@ public:
float pivotX,float pivotY,float pivotZ,
float axisX,float axisY,float axisZ,
float axis1X=0,float axis1Y=0,float axis1Z=0,
- float axis2X=0,float axis2Y=0,float axis2Z=0
+ float axis2X=0,float axis2Y=0,float axis2Z=0,int flag=0
);
@@ -75,8 +75,7 @@ public:
return 0;
}
- virtual PHY_IPhysicsController* rayTest(PHY_IPhysicsController* ignoreClient,float fromX,float fromY,float fromZ, float toX,float toY,float toZ,
- float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ);
+ virtual PHY_IPhysicsController* rayTest(PHY_IRayCastFilterCallback &filterCallback,float fromX,float fromY,float fromZ, float toX,float toY,float toZ);
//gamelogic callbacks
@@ -84,6 +83,7 @@ public:
virtual void removeSensor(PHY_IPhysicsController* ctrl);
virtual void addTouchCallback(int response_class, PHY_ResponseCallback callback, void *user);
virtual void requestCollisionCallback(PHY_IPhysicsController* ctrl);
+ virtual void removeCollisionCallback(PHY_IPhysicsController* ctrl);
virtual PHY_IPhysicsController* CreateSphereController(float radius,const PHY__Vector3& position);
virtual PHY_IPhysicsController* CreateConeController(float coneradius,float coneheight);
diff --git a/source/gameengine/Physics/common/PHY_DynamicTypes.h b/source/gameengine/Physics/common/PHY_DynamicTypes.h
index 68b60192fbc..3b3e42c38d2 100644
--- a/source/gameengine/Physics/common/PHY_DynamicTypes.h
+++ b/source/gameengine/Physics/common/PHY_DynamicTypes.h
@@ -19,7 +19,6 @@ subject to the following restrictions:
-class PHY_ResponseTable;
class PHY_Shape;
@@ -40,10 +39,11 @@ struct PHY__Vector3
typedef enum
{
PHY_FH_RESPONSE,
- PHY_SENSOR_RESPONSE, /* Touch Sensors */
+ PHY_SENSOR_RESPONSE, /* Touch Sensors */
PHY_CAMERA_RESPONSE, /* Visibility Culling */
PHY_OBJECT_RESPONSE, /* Object Dynamic Geometry Response */
PHY_STATIC_RESPONSE, /* Static Geometry Response */
+ PHY_BROADPH_RESPONSE, /* broadphase Response */
PHY_NUM_RESPONSE
};
@@ -87,6 +87,18 @@ typedef enum PHY_ConstraintType {
} PHY_ConstraintType;
+typedef enum PHY_ShapeType {
+ PHY_SHAPE_NONE,
+ PHY_SHAPE_BOX,
+ PHY_SHAPE_SPHERE,
+ PHY_SHAPE_CYLINDER,
+ PHY_SHAPE_CONE,
+ PHY_SHAPE_MESH,
+ PHY_SHAPE_POLYTOPE,
+ PHY_SHAPE_COMPOUND
+} PHY_ShapeType;
+
+
typedef float PHY_Vector3[3];
#endif //__PHY_DYNAMIC_TYPES
diff --git a/source/gameengine/Physics/common/PHY_IPhysicsController.h b/source/gameengine/Physics/common/PHY_IPhysicsController.h
index 2f1d0b34eb2..884e14cfb5a 100644
--- a/source/gameengine/Physics/common/PHY_IPhysicsController.h
+++ b/source/gameengine/Physics/common/PHY_IPhysicsController.h
@@ -82,7 +82,6 @@ class PHY_IPhysicsController
// dyna's that are rigidbody are free in orientation, dyna's with non-rigidbody are restricted
virtual void setRigidBody(bool rigid)=0;
-
// clientinfo for raycasts for example
virtual void* getNewClientInfo()=0;
virtual void setNewClientInfo(void* clientinfo)=0;
@@ -91,7 +90,8 @@ class PHY_IPhysicsController
virtual void calcXform() =0;
virtual void SetMargin(float margin) =0;
virtual float GetMargin() const=0;
- virtual float GetRadius() const { return 0.f;}
+ virtual float GetRadius() const=0;
+ virtual void SetRadius(float margin) = 0;
PHY__Vector3 GetWorldPosition(PHY__Vector3& localpos);
};
diff --git a/source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h b/source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h
index 7f01d16a796..0e9c571924c 100644
--- a/source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h
+++ b/source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h
@@ -33,6 +33,50 @@
#include <vector>
#include "PHY_DynamicTypes.h"
class PHY_IVehicle;
+class RAS_MeshObject;
+class PHY_IPhysicsController;
+
+/**
+ * pass back information from rayTest
+ */
+struct PHY_RayCastResult
+{
+ PHY_IPhysicsController* m_controller;
+ PHY__Vector3 m_hitPoint;
+ PHY__Vector3 m_hitNormal;
+ const RAS_MeshObject* m_meshObject; // !=NULL for mesh object (only for Bullet controllers)
+ int m_polygon; // index of the polygon hit by the ray,
+ // only if m_meshObject != NULL
+};
+
+/**
+ * This class replaces the ignoreController parameter of rayTest function.
+ * It allows more sophisticated filtering on the physics controller before computing the ray intersection to save CPU.
+ * It is only used to its full extend by the Ccd physics environement (Bullet).
+ */
+class PHY_IRayCastFilterCallback
+{
+public:
+ PHY_IPhysicsController* m_ignoreController;
+ bool m_faceNormal;
+
+ virtual ~PHY_IRayCastFilterCallback()
+ {
+ }
+
+ virtual bool needBroadphaseRayCast(PHY_IPhysicsController* controller)
+ {
+ return true;
+ }
+
+ virtual void reportHit(PHY_RayCastResult* result) = 0;
+
+ PHY_IRayCastFilterCallback(PHY_IPhysicsController* ignoreController, bool faceNormal=false)
+ :m_ignoreController(ignoreController),
+ m_faceNormal(faceNormal)
+ {
+ }
+};
/**
* Physics Environment takes care of stepping the simulation and is a container for physics entities (rigidbodies,constraints, materials etc.)
@@ -85,7 +129,7 @@ class PHY_IPhysicsEnvironment
float pivotX,float pivotY,float pivotZ,
float axis0X,float axis0Y,float axis0Z,
float axis1X=0,float axis1Y=0,float axis1Z=0,
- float axis2X=0,float axis2Y=0,float axis2Z=0
+ float axis2X=0,float axis2Y=0,float axis2Z=0,int flag=0
)=0;
virtual void removeConstraint(int constraintid)=0;
virtual float getAppliedImpulse(int constraintid){ return 0.f;}
@@ -94,8 +138,7 @@ class PHY_IPhysicsEnvironment
//complex constraint for vehicles
virtual PHY_IVehicle* getVehicleConstraint(int constraintId) =0;
- virtual PHY_IPhysicsController* rayTest(PHY_IPhysicsController* ignoreClient, float fromX,float fromY,float fromZ, float toX,float toY,float toZ,
- float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ)=0;
+ virtual PHY_IPhysicsController* rayTest(PHY_IRayCastFilterCallback &filterCallback, float fromX,float fromY,float fromZ, float toX,float toY,float toZ)=0;
//Methods for gamelogic collision/physics callbacks
@@ -104,6 +147,8 @@ class PHY_IPhysicsEnvironment
virtual void removeSensor(PHY_IPhysicsController* ctrl)=0;
virtual void addTouchCallback(int response_class, PHY_ResponseCallback callback, void *user)=0;
virtual void requestCollisionCallback(PHY_IPhysicsController* ctrl)=0;
+ virtual void removeCollisionCallback(PHY_IPhysicsController* ctrl)=0;
+ //These two methods are *solely* used to create controllers for sensor! Don't use for anything else
virtual PHY_IPhysicsController* CreateSphereController(float radius,const PHY__Vector3& position) =0;
virtual PHY_IPhysicsController* CreateConeController(float coneradius,float coneheight)=0;
diff --git a/source/gameengine/PyDoc/BL_ActionActuator.py b/source/gameengine/PyDoc/BL_ActionActuator.py
index 41f41080c31..b68d3014115 100644
--- a/source/gameengine/PyDoc/BL_ActionActuator.py
+++ b/source/gameengine/PyDoc/BL_ActionActuator.py
@@ -86,6 +86,14 @@ class BL_ActionActuator(SCA_IActuator):
@param mode: KX_ACTIONACT_PLAY, KX_ACTIONACT_PROPERTY, KX_ACTIONACT_FLIPPER, KX_ACTIONACT_LOOPSTOP, KX_ACTIONACT_LOOPEND
@type mode: integer
"""
+
+ def setContinue(cont):
+ """
+ Set the actions continue option True or False. see getContinue.
+
+ @param cont: The continue option.
+ @type cont: bool
+ """
def getType():
"""
@@ -94,6 +102,13 @@ class BL_ActionActuator(SCA_IActuator):
@rtype: integer
@return: KX_ACTIONACT_PLAY, KX_ACTIONACT_PROPERTY, KX_ACTIONACT_FLIPPER, KX_ACTIONACT_LOOPSTOP, KX_ACTIONACT_LOOPEND
"""
+
+ def getContinue():
+ """
+ When True, the action will always play from where last left off, otherwise negative events to this actuator will reset it to its start frame.
+
+ @rtype: bool
+ """
def getAction():
"""
@@ -149,5 +164,14 @@ class BL_ActionActuator(SCA_IActuator):
@param mode: True for armature/world space, False for bone space
@type mode: boolean
"""
-
-
+ def setFrameProperty(prop):
+ """
+ @param prop: A string specifying the property of the object that will be updated with the action frame number.
+ @type prop: string
+ """
+ def getFrameProperty():
+ """
+ Returns the name of the property that is set to the current frame number.
+
+ @rtype: string
+ """
diff --git a/source/gameengine/PyDoc/BL_ShapeActionActuator.py b/source/gameengine/PyDoc/BL_ShapeActionActuator.py
new file mode 100644
index 00000000000..a26b276a2da
--- /dev/null
+++ b/source/gameengine/PyDoc/BL_ShapeActionActuator.py
@@ -0,0 +1,167 @@
+# $Id$
+# Documentation for BL_ShapeActionActuator
+from SCA_IActuator import *
+
+class BL_ShapeActionActuator(SCA_IActuator):
+ """
+ ShapeAction Actuators apply an shape action to an mesh object.
+ """
+ def setAction(action, reset = True):
+ """
+ Sets the current action.
+
+ @param action: The name of the action to set as the current action.
+ @type action: string
+ @param reset: Optional parameter indicating whether to reset the
+ blend timer or not. A value of 1 indicates that the
+ timer should be reset. A value of 0 will leave it
+ unchanged. If reset is not specified, the timer will
+ be reset.
+ """
+
+ def setStart(start):
+ """
+ Specifies the starting frame of the animation.
+
+ @param start: the starting frame of the animation
+ @type start: float
+ """
+
+ def setEnd(end):
+ """
+ Specifies the ending frame of the animation.
+
+ @param end: the ending frame of the animation
+ @type end: float
+ """
+ def setBlendin(blendin):
+ """
+ Specifies the number of frames of animation to generate
+ when making transitions between actions.
+
+ @param blendin: the number of frames in transition.
+ @type blendin: float
+ """
+
+ def setPriority(priority):
+ """
+ Sets the priority of this actuator.
+
+ @param priority: Specifies the new priority. Actuators will lower
+ priority numbers will override actuators with higher
+ numbers.
+ @type priority: integer
+ """
+ def setFrame(frame):
+ """
+ Sets the current frame for the animation.
+
+ @param frame: Specifies the new current frame for the animation
+ @type frame: float
+ """
+
+ def setProperty(prop):
+ """
+ Sets the property to be used in FromProp playback mode.
+
+ @param prop: the name of the property to use.
+ @type prop: string.
+ """
+
+ def setBlendtime(blendtime):
+ """
+ Sets the internal frame timer.
+
+ Allows the script to directly modify the internal timer
+ used when generating transitions between actions.
+
+ @param blendtime: The new time. This parameter must be in the range from 0.0 to 1.0.
+ @type blendtime: float
+ """
+
+ def setType(mode):
+ """
+ Sets the operation mode of the actuator
+
+ @param mode: KX_ACTIONACT_PLAY, KX_ACTIONACT_PROPERTY, KX_ACTIONACT_FLIPPER, KX_ACTIONACT_LOOPSTOP, KX_ACTIONACT_LOOPEND
+ @type mode: integer
+ """
+
+ def setContinue(cont):
+ """
+ Set the actions continue option True or False. see getContinue.
+
+ @param cont: The continue option.
+ @type cont: bool
+ """
+
+ def getType():
+ """
+ Returns the operation mode of the actuator
+
+ @rtype: integer
+ @return: KX_ACTIONACT_PLAY, KX_ACTIONACT_PROPERTY, KX_ACTIONACT_FLIPPER, KX_ACTIONACT_LOOPSTOP, KX_ACTIONACT_LOOPEND
+ """
+
+ def getContinue():
+ """
+ When True, the action will always play from where last left off, otherwise negative events to this actuator will reset it to its start frame.
+
+ @rtype: bool
+ """
+
+ def getAction():
+ """
+ getAction() returns the name of the action associated with this actuator.
+
+ @rtype: string
+ """
+
+ def getStart():
+ """
+ Returns the starting frame of the action.
+
+ @rtype: float
+ """
+ def getEnd():
+ """
+ Returns the last frame of the action.
+
+ @rtype: float
+ """
+ def getBlendin():
+ """
+ Returns the number of interpolation animation frames to be generated when this actuator is triggered.
+
+ @rtype: float
+ """
+ def getPriority():
+ """
+ Returns the priority for this actuator. Actuators with lower Priority numbers will
+ override actuators with higher numbers.
+
+ @rtype: integer
+ """
+ def getFrame():
+ """
+ Returns the current frame number.
+
+ @rtype: float
+ """
+ def getProperty():
+ """
+ Returns the name of the property to be used in FromProp mode.
+
+ @rtype: string
+ """
+ def setFrameProperty(prop):
+ """
+ @param prop: A string specifying the property of the object that will be updated with the action frame number.
+ @type prop: string
+ """
+ def getFrameProperty():
+ """
+ Returns the name of the property that is set to the current frame number.
+
+ @rtype: string
+ """
diff --git a/source/gameengine/PyDoc/GameKeys.py b/source/gameengine/PyDoc/GameKeys.py
index 268fb9cc172..1a0a737718e 100644
--- a/source/gameengine/PyDoc/GameKeys.py
+++ b/source/gameengine/PyDoc/GameKeys.py
@@ -164,3 +164,12 @@ Example::
# Activate Right!
"""
+
+def EventToString(event):
+ """
+ Return the string name of a key event. Will raise a ValueError error if its invalid.
+
+ @type event: int
+ @param event: key event from GameKeys or the keyboard sensor.
+ @rtype: string
+ """
diff --git a/source/gameengine/PyDoc/GameLogic.py b/source/gameengine/PyDoc/GameLogic.py
index fcfd8bfc4eb..9dab7db6081 100644
--- a/source/gameengine/PyDoc/GameLogic.py
+++ b/source/gameengine/PyDoc/GameLogic.py
@@ -13,11 +13,10 @@ Documentation for the GameLogic Module.
See L{WhatsNew} for updates, changes and new functionality in the Game Engine Python API.
Examples::
- # To get a controller:
- import GameLogic
- co = GameLogic.getCurrentController()
+ # To get the controller thats running this python script:
+ co = GameLogic.getCurrentController() # GameLogic is automatically imported
- # To get the game object associated with this controller:
+ # To get the game object this controller is on:
obj = co.getOwner()
L{KX_GameObject} and L{KX_Camera} or L{KX_Light} methods are
available depending on the type of object::
@@ -32,16 +31,18 @@ Documentation for the GameLogic Module.
sensors = co.getSensors()
See the sensor's reference for available methods:
- - L{KX_NetworkMessageSensor}
- - L{KX_RaySensor}
- - L{KX_MouseFocusSensor}
- - L{KX_NearSensor}
- - L{KX_RadarSensor}
- - L{KX_TouchSensor}
- - L{SCA_KeyboardSensor}
- - L{SCA_MouseSensor}
- - L{SCA_PropertySensor}
- - L{SCA_RandomSensor}
+ - L{DelaySensor<SCA_DelaySensor.SCA_DelaySensor>}
+ - L{JoystickSensor<SCA_JoystickSensor.SCA_JoystickSensor>}
+ - L{KeyboardSensor<SCA_KeyboardSensor.SCA_KeyboardSensor>}
+ - L{MouseFocusSensor<KX_MouseFocusSensor.KX_MouseFocusSensor>}
+ - L{MouseSensor<SCA_MouseSensor.SCA_MouseSensor>}
+ - L{NearSensor<KX_NearSensor.KX_NearSensor>}
+ - L{NetworkMessageSensor<KX_NetworkMessageSensor.KX_NetworkMessageSensor>}
+ - L{PropertySensor<SCA_PropertySensor.SCA_PropertySensor>}
+ - L{RadarSensor<KX_RadarSensor.KX_RadarSensor>}
+ - L{RandomSensor<SCA_RandomSensor.SCA_RandomSensor>}
+ - L{RaySensor<KX_RaySensor.KX_RaySensor>}
+ - L{TouchSensor<KX_TouchSensor.KX_TouchSensor>}
You can also access actuators linked to the controller::
# To get an actuator attached to the controller:
@@ -54,23 +55,23 @@ Documentation for the GameLogic Module.
GameLogic.addActiveActuator(actuator, True)
See the actuator's reference for available methods:
- - L{BL_ActionActuator}
- - L{KX_CameraActuator}
- - L{KX_CDActuator}
- - L{KX_ConstraintActuator}
- - L{KX_GameActuator}
- - L{KX_IpoActuator}
- - L{KX_NetworkMessageActuator}
- - L{KX_ObjectActuator}
- - L{KX_SCA_AddObjectActuator}
- - L{KX_SCA_EndObjectActuator}
- - L{KX_SCA_ReplaceMeshActuator}
- - L{KX_SceneActuator}
- - L{KX_SoundActuator}
- - L{KX_TrackToActuator}
- - L{KX_VisibilityActuator}
- - L{SCA_PropertyActuator}
- - L{SCA_RandomActuator}
+ - L{ActionActuator<BL_ActionActuator.BL_ActionActuator>}
+ - L{AddObjectActuator<KX_SCA_AddObjectActuator.KX_SCA_AddObjectActuator>}
+ - L{CameraActuator<KX_CameraActuator.KX_CameraActuator>}
+ - L{CDActuator<KX_CDActuator.KX_CDActuator>}
+ - L{ConstraintActuator<KX_ConstraintActuator.KX_ConstraintActuator>}
+ - L{EndObjectActuator<KX_SCA_EndObjectActuator.KX_SCA_EndObjectActuator>}
+ - L{GameActuator<KX_GameActuator.KX_GameActuator>}
+ - L{IpoActuator<KX_IpoActuator.KX_IpoActuator>}
+ - L{NetworkMessageActuator<KX_NetworkMessageActuator.KX_NetworkMessageActuator>}
+ - L{ObjectActuator<KX_ObjectActuator.KX_ObjectActuator>}
+ - L{PropertyActuator<SCA_PropertyActuator.SCA_PropertyActuator>}
+ - L{RandomActuator<SCA_RandomActuator.SCA_RandomActuator>}
+ - L{ReplaceMeshActuator<KX_SCA_ReplaceMeshActuator.KX_SCA_ReplaceMeshActuator>}
+ - L{SceneActuator<KX_SceneActuator.KX_SceneActuator>}
+ - L{SoundActuator<KX_SoundActuator.KX_SoundActuator>}
+ - L{TrackToActuator<KX_TrackToActuator.KX_TrackToActuator>}
+ - L{VisibilityActuator<KX_VisibilityActuator.KX_VisibilityActuator>}
Most logic brick's methods are accessors for the properties available in the logic buttons.
Consult the logic bricks documentation for more information on how each logic brick works.
@@ -220,4 +221,36 @@ def setPhysicsTicRate(ticrate):
@param ticrate: The new update frequency (in Hz).
@type ticrate: float
"""
+def getAverageFrameRate():
+ """
+ Gets the estimated average framerate
+
+ @return: The estimed average framerate in frames per second
+ @rtype: float
+ """
+
+def expandPath(path):
+ """
+ Converts a blender internal path into a proper file system path.
+ Use / as directory separator in path
+ You can use '//' at the start of the string to define a relative path;
+ Blender replaces that string by the directory of the startup .blend or runtime file
+ to make a full path name (doesn't change during the game, even if you load other .blend).
+ The function also converts the directory separator to the local file system format.
+
+ @param path: The path string to be converted/expanded.
+ @type path: string
+ @return: The converted string
+ @rtype: string
+ """
+
+def getBlendFileList(path = "//"):
+ """
+ Returns a list of blend files in the same directory as the open blend file, or from using the option argument.
+
+ @param path: Optional directory argument, will be expanded (like expandPath) into the full path.
+ @type path: string
+ @return: A list of filenames, with no directory prefix
+ @rtype: list
+ """
diff --git a/source/gameengine/PyDoc/KX_ActuatorSensor.py b/source/gameengine/PyDoc/KX_ActuatorSensor.py
new file mode 100644
index 00000000000..cdfbf27576e
--- /dev/null
+++ b/source/gameengine/PyDoc/KX_ActuatorSensor.py
@@ -0,0 +1,25 @@
+# $Id$
+# Documentation for KX_ActuatorSensor
+from SCA_IActuator import *
+from SCA_ISensor import *
+
+class KX_ActuatorSensor(SCA_ISensor):
+ """
+ Actuator sensor detect change in actuator state of the parent object.
+ It generates a positive pulse if the corresponding actuator is activated
+ and a negative pulse if the actuator is deactivated.
+ """
+ def getActuator():
+ """
+ Return the Actuator with which the sensor operates.
+
+ @rtype: string
+ """
+ def setActuator(name):
+ """
+ Sets the Actuator with which to operate. If there is no Actuator
+ of this name, the function has no effect.
+
+ @param name: actuator name
+ @type name: string
+ """
diff --git a/source/gameengine/PyDoc/KX_CameraActuator.py b/source/gameengine/PyDoc/KX_CameraActuator.py
index 032fc7338ac..9a9abaf3d57 100644
--- a/source/gameengine/PyDoc/KX_CameraActuator.py
+++ b/source/gameengine/PyDoc/KX_CameraActuator.py
@@ -8,11 +8,13 @@ class KX_CameraActuator(SCA_IActuator):
@author: snail
"""
- def getObject():
+ def getObject(name_only = 1):
"""
Returns the name of the object this actuator tracks.
- rtype: string
+ @type name_only: bool
+ @param name_only: optional argument, when 0 return a KX_GameObject
+ @rtype: string, KX_GameObject or None if no object is set
"""
def setObject(target):
@@ -20,7 +22,7 @@ class KX_CameraActuator(SCA_IActuator):
Sets the object this actuator tracks.
@param target: the object to track.
- @type target: string or L{KX_GameObject}
+ @type target: L{KX_GameObject}, string or None
"""
def getMin():
diff --git a/source/gameengine/PyDoc/KX_ConstraintActuator.py b/source/gameengine/PyDoc/KX_ConstraintActuator.py
index 9630690e572..7c7ad5aa0fa 100644
--- a/source/gameengine/PyDoc/KX_ConstraintActuator.py
+++ b/source/gameengine/PyDoc/KX_ConstraintActuator.py
@@ -4,7 +4,7 @@ from SCA_IActuator import *
class KX_ConstraintActuator(SCA_IActuator):
"""
- A constraint actuator limits the position or orientation of an object.
+ A constraint actuator limits the position, rotation, distance or orientation of an object.
"""
def setDamp(time):
"""
@@ -24,7 +24,7 @@ class KX_ConstraintActuator(SCA_IActuator):
"""
Sets the lower bound of the constraint.
- For rotational constraints, lower is specified in degrees.
+ For rotational and orientation constraints, lower is specified in degrees.
@type lower: float
"""
@@ -32,7 +32,7 @@ class KX_ConstraintActuator(SCA_IActuator):
"""
Gets the lower bound of the constraint.
- For rotational constraints, the lower bound is returned in radians.
+ For rotational and orientation constraints, the lower bound is returned in radians.
@rtype: float
"""
@@ -40,7 +40,7 @@ class KX_ConstraintActuator(SCA_IActuator):
"""
Sets the upper bound of the constraint.
- For rotational constraints, upper is specified in degrees.
+ For rotational and orientation constraints, upper is specified in degrees.
@type upper: float
"""
@@ -48,7 +48,7 @@ class KX_ConstraintActuator(SCA_IActuator):
"""
Gets the upper bound of the constraint.
- For rotational constraints, the upper bound is returned in radians.
+ For rotational and orientation constraints, the upper bound is returned in radians.
@rtype: float
"""
@@ -58,8 +58,11 @@ class KX_ConstraintActuator(SCA_IActuator):
See module L{GameLogic} for valid constraint types.
- @param limit: Position constraints: KX_CONSTRAINTACT_LOCX, KX_CONSTRAINTACT_LOCY, KX_CONSTRAINTACT_LOCZ,
- Rotation constraints: KX_CONSTRAINTACT_ROTX, KX_CONSTRAINTACT_ROTY or KX_CONSTRAINTACT_ROTZ
+ @param limit:
+ Position constraints: KX_CONSTRAINTACT_LOCX, KX_CONSTRAINTACT_LOCY, KX_CONSTRAINTACT_LOCZ
+ Rotation constraints: KX_CONSTRAINTACT_ROTX, KX_CONSTRAINTACT_ROTY or KX_CONSTRAINTACT_ROTZ
+ Distance contraints: KX_ACT_CONSTRAINT_DIRPX, KX_ACT_CONSTRAINT_DIRPY, KX_ACT_CONSTRAINT_DIRPZ, KX_ACT_CONSTRAINT_DIRNX, KX_ACT_CONSTRAINT_DIRNY, KX_ACT_CONSTRAINT_DIRNZ
+ Orientation constraints: KX_ACT_CONSTRAINT_ORIX, KX_ACT_CONSTRAINT_ORIY, KX_ACT_CONSTRAINT_ORIZ
"""
def getLimit():
"""
@@ -67,6 +70,111 @@ class KX_ConstraintActuator(SCA_IActuator):
See module L{GameLogic} for valid constraints.
- @return: Position constraints: KX_CONSTRAINTACT_LOCX, KX_CONSTRAINTACT_LOCY, KX_CONSTRAINTACT_LOCZ,
- Rotation constraints: KX_CONSTRAINTACT_ROTX, KX_CONSTRAINTACT_ROTY or KX_CONSTRAINTACT_ROTZ
+ @return:
+ Position constraints: KX_CONSTRAINTACT_LOCX, KX_CONSTRAINTACT_LOCY, KX_CONSTRAINTACT_LOCZ,
+ Rotation constraints: KX_CONSTRAINTACT_ROTX, KX_CONSTRAINTACT_ROTY, KX_CONSTRAINTACT_ROTZ,
+ Distance contraints: KX_ACT_CONSTRAINT_DIRPX, KX_ACT_CONSTRAINT_DIRPY, KX_ACT_CONSTRAINT_DIRPZ, KX_ACT_CONSTRAINT_DIRNX, KX_ACT_CONSTRAINT_DIRNY, KX_ACT_CONSTRAINT_DIRNZ,
+ Orientation constraints: KX_ACT_CONSTRAINT_ORIX, KX_ACT_CONSTRAINT_ORIY, KX_ACT_CONSTRAINT_ORIZ
"""
+ def setRotDamp(duration):
+ """
+ Sets the time constant of the orientation constraint.
+
+ @param duration: If the duration is negative, it is set to 0.
+ @type duration: integer
+ """
+ def getRotDamp():
+ """
+ Returns the damping time for application of the constraint.
+
+ @rtype: integer
+ """
+ def setDirection(vector):
+ """
+ Sets the reference direction in world coordinate for the orientation constraint
+
+ @type vector: 3-tuple
+ """
+ def getDirection():
+ """
+ Returns the reference direction of the orientation constraint in world coordinate.
+
+ @rtype: 3-tuple
+ """
+ def setOption(option):
+ """
+ Sets several options of the distance constraint.
+
+ @type option: integer
+ @param option: Binary combination of the following values:
+ 64 : Activate alignment to surface
+ 128 : Detect material rather than property
+ 256 : No deactivation if ray does not hit target
+ 512 : Activate distance control
+ """
+ def getOption():
+ """
+ Returns the option parameter.
+
+ @rtype: integer
+ """
+ def setTime(duration):
+ """
+ Sets the activation time of the actuator.
+
+ @type duration: integer
+ @param duration: The actuator disables itself after this many frame.
+ If set to 0 or negative, the actuator is not limited in time.
+ """
+ def getTime():
+ """
+ Returns the time parameter.
+
+ @rtype: integer
+ """
+ def setProperty(property):
+ """
+ Sets the name of the property or material for the ray detection of the distance constraint.
+
+ @type property: string
+ @param property: If empty, the ray will detect any collisioning object.
+ """
+ def getProperty():
+ """
+ Returns the property parameter.
+
+ @rtype: string
+ """
+ def setDistance(distance):
+ """
+ Sets the target distance in distance constraint.
+
+ @type distance: float
+ """
+ def getDistance():
+ """
+ Returns the distance parameter.
+
+ @rtype: float
+ """
+ def setRayLength(length):
+ """
+ Sets the maximum ray length of the distance constraint.
+
+ @type length: float
+ """
+ def getRayLength():
+ """
+ Returns the length of the ray
+
+ @rtype: float
+ """
+
+
+
+
+
+
+
+
+
diff --git a/source/gameengine/PyDoc/KX_GameObject.py b/source/gameengine/PyDoc/KX_GameObject.py
index d3428915f25..505ce253dd1 100644
--- a/source/gameengine/PyDoc/KX_GameObject.py
+++ b/source/gameengine/PyDoc/KX_GameObject.py
@@ -22,17 +22,57 @@ class KX_GameObject:
@type orientation: 3x3 Matrix [[float]]
@ivar scaling: The object's scaling factor. list [sx, sy, sz]
@type scaling: list [sx, sy, sz]
+ @ivar timeOffset: adjust the slowparent delay at runtime.
+ @type timeOffset: float
"""
-
+ def endObject(visible):
+ """
+ Delete this object, can be used inpace of the EndObject Actuator.
+ The actual removal of the object from the scene is delayed.
+ """
+ def replaceMesh(mesh_name):
+ """
+ Replace the mesh of this object with a new mesh. This works the same was as the actuator.
+ @type mesh_name: string
+ """
+ def getVisible():
+ """
+ Gets the game object's visible flag.
+
+ @rtype: boolean
+ """
def setVisible(visible):
"""
Sets the game object's visible flag.
@type visible: boolean
"""
+ def getState():
+ """
+ Gets the game object's state bitmask.
+
+ @rtype: int
+ @return: the objects state.
+ """
+ def setState(state):
+ """
+ Sets the game object's state flag.
+ The bitmasks for states from 1 to 30 can be set with (1<<0, 1<<1, 1<<2 ... 1<<29)
+
+ @type state: integer
+ """
def setPosition(pos):
"""
- Sets the game object's position.
+ Sets the game object's position.
+ Global coordinates for root object, local for child objects.
+
+
+ @type pos: [x, y, z]
+ @param pos: the new position, in local coordinates.
+ """
+ def setWorldPosition(pos):
+ """
+ Sets the game object's position in world coordinates regardless if the object is root or child.
@type pos: [x, y, z]
@param pos: the new position, in world coordinates.
@@ -50,6 +90,30 @@ class KX_GameObject:
@type orn: 3x3 rotation matrix, or Quaternion.
@param orn: a rotation matrix specifying the new rotation.
+ @note: When using this matrix with Blender.Mathutils.Matrix() types, it will need to be transposed.
+ """
+ def alignAxisToVect(vect, axis):
+ """
+ Aligns any of the game object's axis along the given vector.
+
+ @type vect: 3d vector.
+ @param vect: a vector to align the axis.
+ @type axis: integer.
+ @param axis:The axis you want to align
+ - 0: X axis
+ - 1: Y axis
+ - 2: Z axis (default)
+ """
+ def getAxisVect(vect):
+ """
+ Returns the axis vector rotates by the objects worldspace orientation.
+ This is the equivalent if multiplying the vector by the orientation matrix.
+
+ @type vect: 3d vector.
+ @param vect: a vector to align the axis.
+ @rtype: 3d vector.
+ @return: The vector in relation to the objects rotation.
+
"""
def getOrientation():
"""
@@ -57,19 +121,54 @@ class KX_GameObject:
@rtype: 3x3 rotation matrix
@return: The game object's rotation matrix
+ @note: When using this matrix with Blender.Mathutils.Matrix() types, it will need to be transposed.
"""
- def getLinearVelocity():
+ def getLinearVelocity(local = 0):
"""
Gets the game object's linear velocity.
This method returns the game object's velocity through it's centre of mass,
ie no angular velocity component.
- cf getVelocity()
-
+ @type local: boolean
+ @param local: - False: you get the "global" velocity ie: relative to world orientation (default).
+ - True: you get the "local" velocity ie: relative to object orientation.
@rtype: list [vx, vy, vz]
@return: the object's linear velocity.
"""
+ def setLinearVelocity(velocity, local = 0):
+ """
+ Sets the game object's linear velocity.
+
+ This method sets game object's velocity through it's centre of mass,
+ ie no angular velocity component.
+
+ @type velocity: 3d vector.
+ @param velocity: linear velocity vector.
+ @type local: boolean
+ @param local: - False: you get the "global" velocity ie: relative to world orientation (default).
+ - True: you get the "local" velocity ie: relative to object orientation.
+ """
+ def getAngularVelocity(local = 0):
+ """
+ Gets the game object's angular velocity.
+
+ @type local: boolean
+ @param local: - False: you get the "global" velocity ie: relative to world orientation (default).
+ - True: you get the "local" velocity ie: relative to object orientation.
+ @rtype: list [vx, vy, vz]
+ @return: the object's angular velocity.
+ """
+ def setAngularVelocity(velocity, local = 0):
+ """
+ Sets the game object's angular velocity.
+
+ @type velocity: 3d vector.
+ @param velocity: angular velocity vector.
+ @type local: boolean
+ @param local: - False: you get the "global" velocity ie: relative to world orientation (default).
+ - True: you get the "local" velocity ie: relative to object orientation.
+ """
def getVelocity(point):
"""
Gets the game object's velocity at the specified point.
@@ -117,16 +216,19 @@ class KX_GameObject:
def restoreDynamics():
"""
Resumes physics for this object.
+ @Note: The objects linear velocity will be applied from when the dynamics were suspended.
"""
def enableRigidBody():
"""
Enables rigid body physics for this object.
Rigid body physics allows the object to roll on collisions.
+ @Note: This is not working with bullet physics yet.
"""
def disableRigidBody():
"""
Disables rigid body physics for this object.
+ @Note: This is not working with bullet physics yet. The angular is removed but rigid body physics can still rotate it later.
"""
def getParent():
"""
@@ -135,6 +237,29 @@ class KX_GameObject:
@rtype: L{KX_GameObject}
@return: this object's parent object, or None if this object has no parent.
"""
+ def setParent(parent):
+ """
+ Sets this object's parent.
+
+ @type parent: L{KX_GameObject}
+ @param parent: new parent object.
+ """
+ def removeParent():
+ """
+ Removes this objects parent.
+ """
+ def getChildren():
+ """
+ Return a list of immediate children of this object.
+ @rtype: list
+ @return: a list of all this objects children.
+ """
+ def getChildrenRecursive():
+ """
+ Return a list of children of this object, including all their childrens children.
+ @rtype: list
+ @return: a list of all this objects children recursivly.
+ """
def getMesh(mesh):
"""
Gets the mesh object for this object.
@@ -148,6 +273,12 @@ class KX_GameObject:
"""
Returns the user data object associated with this game object's physics controller.
"""
+ def getPropertyNames():
+ """
+ Gets a list of all property names.
+ @rtype: list
+ @return: All property names for this object.
+ """
def getDistanceTo(other):
"""
Returns the distance to another object or point.
@@ -156,3 +287,83 @@ class KX_GameObject:
@type other: L{KX_GameObject} or list [x, y, z]
@rtype: float
"""
+ def getVectTo(other):
+ """
+ Returns the vector and the distance to another object or point.
+ The vector is normalized unless the distance is 0, in which a NULL vector is returned.
+
+ @param other: a point or another L{KX_GameObject} to get the vector and distance to.
+ @type other: L{KX_GameObject} or list [x, y, z]
+ @rtype: 3-tuple (float, 3-tuple (x,y,z), 3-tuple (x,y,z))
+ @return: (distance, globalVector(3), localVector(3))
+ """
+ def rayCastTo(other,dist,prop):
+ """
+ Look towards another point/object and find first object hit within dist that matches prop.
+
+ The ray is always casted from the center of the object, ignoring the object itself.
+ The ray is casted towards the center of another object or an explicit [x,y,z] point.
+ Use rayCast() if you need to retrieve the hit point
+
+ @param other: [x,y,z] or object towards which the ray is casted
+ @type other: L{KX_GameObject} or 3-tuple
+ @param dist: max distance to look (can be negative => look behind); 0 or omitted => detect up to other
+ @type dist: float
+ @param prop: property name that object must have; can be omitted => detect any object
+ @type prop: string
+ @rtype: L{KX_GameObject}
+ @return: the first object hit or None if no object or object does not match prop
+ """
+ def rayCast(objto,objfrom,dist,prop,face,xray,poly):
+ """
+ Look from a point/object to another point/object and find first object hit within dist that matches prop.
+ if poly is 0, returns a 3-tuple with object reference, hit point and hit normal or (None,None,None) if no hit.
+ if poly is 1, returns a 4-tuple with in addition a L{KX_PolyProxy} as 4th element.
+
+ Ex::
+ # shoot along the axis gun-gunAim (gunAim should be collision-free)
+ ob,point,normal = gun.rayCast(gunAim,None,50)
+ if ob:
+ # hit something
+
+ Notes:
+ The ray ignores the object on which the method is called.
+ It is casted from/to object center or explicit [x,y,z] points.
+
+ The face paremeter determines the orientation of the normal::
+ 0 => hit normal is always oriented towards the ray origin (as if you casted the ray from outside)
+ 1 => hit normal is the real face normal (only for mesh object, otherwise face has no effect)
+
+ The ray has X-Ray capability if xray parameter is 1, otherwise the first object hit (other than self object) stops the ray.
+ The prop and xray parameters interact as follow::
+ prop off, xray off: return closest hit or no hit if there is no object on the full extend of the ray.
+ prop off, xray on : idem.
+ prop on, xray off: return closest hit if it matches prop, no hit otherwise.
+ prop on, xray on : return closest hit matching prop or no hit if there is no object matching prop on the full extend of the ray.
+ The L{KX_PolyProxy} 4th element of the return tuple when poly=1 allows to retrieve information on the polygon hit by the ray.
+ If there is no hit or the hit object is not a static mesh, None is returned as 4th element.
+
+ The ray ignores collision-free objects and faces that dont have the collision flag enabled, you can however use ghost objects.
+
+ @param objto: [x,y,z] or object to which the ray is casted
+ @type objto: L{KX_GameObject} or 3-tuple
+ @param objfrom: [x,y,z] or object from which the ray is casted; None or omitted => use self object center
+ @type objfrom: L{KX_GameObject} or 3-tuple or None
+ @param dist: max distance to look (can be negative => look behind); 0 or omitted => detect up to to
+ @type dist: float
+ @param prop: property name that object must have; can be omitted => detect any object
+ @type prop: string
+ @param face: normal option: 1=>return face normal; 0 or omitted => normal is oriented towards origin
+ @type face: int
+ @param xray: X-ray option: 1=>skip objects that don't match prop; 0 or omitted => stop on first object
+ @type xray: int
+ @param poly: polygon option: 1=>return value is a 4-tuple and the 4th element is a L{KX_PolyProxy}
+ @type poly: int
+ @rtype: 3-tuple (L{KX_GameObject}, 3-tuple (x,y,z), 3-tuple (nx,ny,nz))
+ or 4-tuple (L{KX_GameObject}, 3-tuple (x,y,z), 3-tuple (nx,ny,nz), L{KX_PolyProxy})
+ @return: (object,hitpoint,hitnormal) or (object,hitpoint,hitnormal,polygon)
+ If no hit, returns (None,None,None) or (None,None,None,None)
+ If the object hit is not a static mesh, polygon is None
+ """
+
+
diff --git a/source/gameengine/PyDoc/KX_IpoActuator.py b/source/gameengine/PyDoc/KX_IpoActuator.py
index da8d05ddd5e..e2fe3b289e3 100644
--- a/source/gameengine/PyDoc/KX_IpoActuator.py
+++ b/source/gameengine/PyDoc/KX_IpoActuator.py
@@ -16,8 +16,8 @@ class KX_IpoActuator(SCA_IActuator):
@type startframe: integer
@param endframe: last frame to use
@type endframe: integer
- @param force: interpret this ipo as a force
- @type force: boolean (KX_TRUE, KX_FALSE)
+ @param force: special mode
+ @type force: integer (0=normal, 1=interpret location as force, 2=additive)
"""
def setProperty(property):
"""
@@ -62,6 +62,19 @@ class KX_IpoActuator(SCA_IActuator):
@rtype: boolean
"""
+ def setIpoAdd(add):
+ """
+ Set whether to interpret the ipo as additive rather than absolute.
+
+ @type add: boolean
+ @param add: KX_TRUE or KX_FALSE
+ """
+ def getIpoAdd():
+ """
+ Returns whether to interpret the ipo as additive rather than absolute.
+
+ @rtype: boolean
+ """
def setType(mode):
"""
Sets the operation mode of the actuator.
diff --git a/source/gameengine/PyDoc/KX_MeshProxy.py b/source/gameengine/PyDoc/KX_MeshProxy.py
index e43fa3598f0..03bc36b6ac1 100644
--- a/source/gameengine/PyDoc/KX_MeshProxy.py
+++ b/source/gameengine/PyDoc/KX_MeshProxy.py
@@ -95,6 +95,21 @@ class KX_MeshProxy:
@rtype: L{KX_VertexProxy}
@return: a vertex object.
"""
+ def getNumPolygons():
+ """
+ Returns the number of polygon in the mesh.
+
+ @rtype: integer
+ """
+ def getPolygon(index):
+ """
+ Gets the specified polygon from the mesh.
+
+ @type index: integer
+ @param index: polygon number
+ @rtype: L{KX_PolyProxy}
+ @return: a polygon object.
+ """
def reinstancePhysicsMesh():
"""
Updates the physics system with the changed mesh.
diff --git a/source/gameengine/PyDoc/KX_ObjectActuator.py b/source/gameengine/PyDoc/KX_ObjectActuator.py
index 532c18eea5c..b7b76473292 100644
--- a/source/gameengine/PyDoc/KX_ObjectActuator.py
+++ b/source/gameengine/PyDoc/KX_ObjectActuator.py
@@ -6,6 +6,7 @@ class KX_ObjectActuator(SCA_IActuator):
"""
The object actuator ("Motion Actuator") applies force, torque, displacement, angular displacement,
velocity, or angular velocity to an object.
+ Servo control allows to regulate force to achieve a certain speed target.
"""
def getForce():
"""
@@ -107,15 +108,15 @@ class KX_ObjectActuator(SCA_IActuator):
def getLinearVelocity():
"""
Returns the linear velocity applied by the actuator.
+ For the servo control actuator, this is the target speed.
@rtype: list [vx, vy, vz, local]
- @return: A four item list, containing the vector velocity, and whether
- the velocity is applied in local coordinates (True) or world
- coordinates (False)
+ @return: A four item list, containing the vector velocity, and whether the velocity is applied in local coordinates (True) or world coordinates (False)
"""
def setLinearVelocity(vx, vy, vz, local):
"""
Sets the linear velocity applied by the actuator.
+ For the servo control actuator, sets the target speed.
@type vx: float
@param vx: the x component of the velocity vector.
@@ -124,8 +125,8 @@ class KX_ObjectActuator(SCA_IActuator):
@type vz: float
@param vz: the z component of the velocity vector.
@type local: boolean
- @param local: - False: the velocity vector is applied in world coordinates.
- - True: the velocity vector is applied in local coordinates.
+ @param local: - False: the velocity vector is in world coordinates.
+ - True: the velocity vector is in local coordinates.
"""
def getAngularVelocity():
"""
@@ -150,5 +151,100 @@ class KX_ObjectActuator(SCA_IActuator):
@param local: - False: the velocity vector is applied in world coordinates.
- True: the velocity vector is applied in local coordinates.
"""
+ def getDamping():
+ """
+ Returns the damping parameter of the servo controller.
+
+ @rtype: integer
+ @return: the time constant of the servo controller in frame unit.
+ """
+ def setDamping(damp):
+ """
+ Sets the damping parameter of the servo controller.
+
+ @type damp: integer
+ @param damp: the damping parameter in frame unit.
+ """
+ def getForceLimitX():
+ """
+ Returns the min/max force limit along the X axis used by the servo controller.
+
+ @rtype: list [min, max, enabled]
+ @return: A three item list, containing the min and max limits of the force as float
+ and whether the limits are active(true) or inactive(true)
+ """
+ def setForceLimitX(min, max, enable):
+ """
+ Sets the min/max force limit along the X axis and activates or deactivates the limits in the servo controller.
+
+ @type min: float
+ @param min: the minimum value of the force along the X axis.
+ @type max: float
+ @param max: the maximum value of the force along the X axis.
+ @type enable: boolean
+ @param enable: - True: the force will be limited to the min/max
+ - False: the force will not be limited
+ """
+ def getForceLimitY():
+ """
+ Returns the min/max force limit along the Y axis used by the servo controller.
+
+ @rtype: list [min, max, enabled]
+ @return: A three item list, containing the min and max limits of the force as float
+ and whether the limits are active(true) or inactive(true)
+ """
+ def setForceLimitY(min, max, enable):
+ """
+ Sets the min/max force limit along the Y axis and activates or deactivates the limits in the servo controller.
+
+ @type min: float
+ @param min: the minimum value of the force along the Y axis.
+ @type max: float
+ @param max: the maximum value of the force along the Y axis.
+ @type enable: boolean
+ @param enable: - True: the force will be limited to the min/max
+ - False: the force will not be limited
+ """
+ def getForceLimitZ():
+ """
+ Returns the min/max force limit along the Z axis used by the servo controller.
+
+ @rtype: list [min, max, enabled]
+ @return: A three item list, containing the min and max limits of the force as float
+ and whether the limits are active(true) or inactive(true)
+ """
+ def setForceLimitZ(min, max, enable):
+ """
+ Sets the min/max force limit along the Z axis and activates or deactivates the limits in the servo controller.
+
+ @type min: float
+ @param min: the minimum value of the force along the Z axis.
+ @type max: float
+ @param max: the maximum value of the force along the Z axis.
+ @type enable: boolean
+ @param enable: - True: the force will be limited to the min/max
+ - False: the force will not be limited
+ """
+ def getPID():
+ """
+ Returns the PID coefficient of the servo controller.
+
+ @rtype: list [P, I, D]
+ @return: A three item list, containing the PID coefficient as floats:
+ P : proportional coefficient
+ I : Integral coefficient
+ D : Derivate coefficient
+ """
+ def setPID(P, I, D):
+ """
+ Sets the PID coefficients of the servo controller.
+
+ @type P: flat
+ @param P: proportional coefficient
+ @type I: float
+ @param I: Integral coefficient
+ @type D: float
+ @param D: Derivate coefficient
+ """
diff --git a/source/gameengine/PyDoc/KX_ParentActuator.py b/source/gameengine/PyDoc/KX_ParentActuator.py
new file mode 100644
index 00000000000..6d6e0937257
--- /dev/null
+++ b/source/gameengine/PyDoc/KX_ParentActuator.py
@@ -0,0 +1,23 @@
+# $Id: KX_ParentActuator.py 2615 2004-06-02 12:43:27Z kester $
+# Documentation for KX_ParentActuator
+from SCA_IActuator import *
+
+class KX_ParentActuator(SCA_IActuator):
+ """
+ The parent actuator can set or remove an objects parent object.
+ """
+ def setObject(object):
+ """
+ Sets the object to set as parent.
+
+ Object can be either a L{KX_GameObject} or the name of the object.
+
+ @type object: L{KX_GameObject}, string or None
+ """
+ def getObject(name_only = 1):
+ """
+ Returns the name of the object to change to.
+ @type name_only: bool
+ @param name_only: optional argument, when 0 return a KX_GameObject
+ @rtype: string, KX_GameObject or None if no object is set
+ """
diff --git a/source/gameengine/PyDoc/KX_PolyProxy.py b/source/gameengine/PyDoc/KX_PolyProxy.py
new file mode 100644
index 00000000000..bcd42c2ac2e
--- /dev/null
+++ b/source/gameengine/PyDoc/KX_PolyProxy.py
@@ -0,0 +1,100 @@
+# $Id$
+# Documentation for the polygon proxy class
+
+class KX_PolyProxy:
+ """
+ A polygon holds the index of the vertex forming the poylgon.
+
+ Note:
+ The polygon attributes are read-only, you need to retrieve the vertex proxy if you want
+ to change the vertex settings.
+
+ @ivar matname: The name of polygon material, empty if no material.
+ @type matname: string
+ @ivar material: The material of the polygon
+ @type material: L{KX_PolygonMaterial} or KX_BlenderMaterial
+ @ivar texture: The texture name of the polygon.
+ @type texture: string
+ @ivar matid: The material index of the polygon, use this to retrieve vertex proxy from mesh proxy
+ @type matid: integer
+ @ivar v1: vertex index of the first vertex of the polygon, use this to retrieve vertex proxy from mesh proxy
+ @type v1: integer
+ @ivar v2: vertex index of the second vertex of the polygon, use this to retrieve vertex proxy from mesh proxy
+ @type v2: integer
+ @ivar v3: vertex index of the third vertex of the polygon, use this to retrieve vertex proxy from mesh proxy
+ @type v3: integer
+ @ivar v4: vertex index of the fourth vertex of the polygon, 0 if polygon has only 3 vertex
+ use this to retrieve vertex proxy from mesh proxy
+ @type v4: integer
+ @ivar visible: visible state of the polygon: 1=visible, 0=invisible
+ @type visible: integer
+ @ivar collide: collide state of the polygon: 1=receives collision, 0=collision free.
+ @type collide: integer
+ """
+
+ def getMaterialName():
+ """
+ Returns the polygon material name with MA prefix
+
+ @rtype: string
+ @return: material name
+ """
+ def getMaterial():
+ """
+ Returns the polygon material
+
+ @rtype: L{KX_PolygonMaterial} or KX_BlenderMaterial
+ """
+ def getTextureName():
+ """
+ Returns the polygon texture name
+
+ @rtype: string
+ @return: texture name
+ """
+ def getMaterialIndex():
+ """
+ Returns the material bucket index of the polygon.
+ This index and the ones returned by getVertexIndex() are needed to retrieve the vertex proxy from L{KX_MeshProxy}.
+
+ @rtype: integer
+ @return: the material index in the mesh
+ """
+ def getNumVertex():
+ """
+ Returns the number of vertex of the polygon.
+
+ @rtype: integer
+ @return: number of vertex, 3 or 4.
+ """
+ def isVisible():
+ """
+ Returns whether the polygon is visible or not
+
+ @rtype: integer
+ @return: 0=invisible, 1=visible
+ """
+ def isCollider():
+ """
+ Returns whether the polygon is receives collision or not
+
+ @rtype: integer
+ @return: 0=collision free, 1=receives collision
+ """
+ def getVertexIndex(vertex):
+ """
+ Returns the mesh vertex index of a polygon vertex
+ This index and the one returned by getMaterialIndex() are needed to retrieve the vertex proxy from L{KX_MeshProxy}.
+
+ @type vertex: integer
+ @param vertex: index of the vertex in the polygon: 0->3
+ @rtype: integer
+ @return: mesh vertex index
+ """
+ def getMesh():
+ """
+ Returns a mesh proxy
+
+ @rtype: L{KX_MeshProxy}
+ @return: mesh proxy
+ """
diff --git a/source/gameengine/PyDoc/KX_SCA_AddObjectActuator.py b/source/gameengine/PyDoc/KX_SCA_AddObjectActuator.py
index 44f9e051c8c..c3b2e947ddb 100644
--- a/source/gameengine/PyDoc/KX_SCA_AddObjectActuator.py
+++ b/source/gameengine/PyDoc/KX_SCA_AddObjectActuator.py
@@ -13,7 +13,7 @@ class KX_SCA_AddObjectActuator(SCA_IActuator):
C{ERROR: GameObject I{OBName} has a AddObjectActuator I{ActuatorName} without object (in 'nonactive' layer)}
"""
- def setObject(obj):
+ def setObject(object):
"""
Sets the game object to add.
@@ -21,17 +21,18 @@ class KX_SCA_AddObjectActuator(SCA_IActuator):
If the object does not exist, this function is ignored.
- obj can either be a L{KX_GameObject} or the name of an object.
+ object can either be a L{KX_GameObject} or the name of an object or None.
- @type obj: L{KX_GameObject} or string
+ @type object: L{KX_GameObject}, string or None
"""
- def getObject():
+ def getObject(name_only = 0):
"""
Returns the name of the game object to be added.
Returns None if no game object has been assigned to be added.
-
- @rtype: string
+ @type name_only: bool
+ @param name_only: optional argument, when 0 return a KX_GameObject
+ @rtype: string, KX_GameObject or None if no object is set
"""
def setTime(time):
"""
@@ -65,6 +66,23 @@ class KX_SCA_AddObjectActuator(SCA_IActuator):
@rtype: list [vx, vy, vz]
"""
+ def setAngularVelocity(vx, vy, vz):
+ """
+ Sets the initial angular velocity of added objects.
+
+ @type vx: float
+ @param vx: the x component of the initial angular velocity.
+ @type vy: float
+ @param vy: the y component of the initial angular velocity.
+ @type vz: float
+ @param vz: the z component of the initial angular velocity.
+ """
+ def getAngularVelocity():
+ """
+ Returns the initial angular velocity of added objects.
+
+ @rtype: list [vx, vy, vz]
+ """
def getLastCreatedObject():
"""
Returns the last object created by this actuator.
diff --git a/source/gameengine/PyDoc/KX_SCA_ReplaceMeshActuator.py b/source/gameengine/PyDoc/KX_SCA_ReplaceMeshActuator.py
index eb00a91a4ce..498f6072e23 100644
--- a/source/gameengine/PyDoc/KX_SCA_ReplaceMeshActuator.py
+++ b/source/gameengine/PyDoc/KX_SCA_ReplaceMeshActuator.py
@@ -59,8 +59,9 @@ class KX_SCA_ReplaceMeshActuator(SCA_IActuator):
def setMesh(name):
"""
Sets the name of the mesh that will replace the current one.
+ When the name is None it will unset the mesh value so no action is taken.
- @type name: string
+ @type name: string or None
"""
def getMesh():
"""
@@ -68,6 +69,6 @@ class KX_SCA_ReplaceMeshActuator(SCA_IActuator):
Returns None if no mesh has been scheduled to be added.
- @rtype: string
+ @rtype: string or None
"""
diff --git a/source/gameengine/PyDoc/KX_StateActuator.py b/source/gameengine/PyDoc/KX_StateActuator.py
new file mode 100644
index 00000000000..fb6ae5a3621
--- /dev/null
+++ b/source/gameengine/PyDoc/KX_StateActuator.py
@@ -0,0 +1,26 @@
+# $Id$
+# Documentation for KX_StateActuator
+from SCA_IActuator import *
+
+class KX_StateActuator(SCA_IActuator):
+ """
+ State actuator changes the state mask of parent object.
+ """
+ def setOperation(op):
+ """
+ Set the type of bit operation to be applied on object state mask.
+ Use setMask() to specify the bits that will be modified.
+
+ @param op: bit operation (0=Copy, 1=Add, 2=Substract, 3=Invert)
+ @type op: integer
+ """
+ def setMask(mask):
+ """
+ Set the value that defines the bits that will be modified by the operation.
+ The bits that are 1 in the value will be updated in the object state,
+ the bits that are 0 are will be left unmodified expect for the Copy operation
+ which copies the value to the object state.
+
+ @param mask: bits that will be modified
+ @type mask: integer
+ """
diff --git a/source/gameengine/PyDoc/KX_TrackToActuator.py b/source/gameengine/PyDoc/KX_TrackToActuator.py
index 39fb99ec2e2..948302991b7 100644
--- a/source/gameengine/PyDoc/KX_TrackToActuator.py
+++ b/source/gameengine/PyDoc/KX_TrackToActuator.py
@@ -18,16 +18,16 @@ class KX_TrackToActuator(SCA_IActuator):
"""
Sets the object to track.
- @type object: L{KX_GameObject} or string
+ @type object: L{KX_GameObject}, string or None
@param object: Either a reference to a game object or the name of the object to track.
"""
- def getObject():
+ def getObject(name_only):
"""
Returns the name of the object to track.
- Returns None if no object has been set to track.
-
- @rtype: string
+ @type name_only: bool
+ @param name_only: optional argument, when 0 return a KX_GameObject
+ @rtype: string, KX_GameObject or None if no object is set
"""
def setTime(time):
"""
diff --git a/source/gameengine/PyDoc/Makefile b/source/gameengine/PyDoc/Makefile
deleted file mode 100644
index 7861894ddec..00000000000
--- a/source/gameengine/PyDoc/Makefile
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-SOURCES=$(shell ls *.py)
-TARGETS:=$(SOURCES:.py=.html)
-PYDOC=/usr/lib/python2.2/pydoc.py
-
-all: $(SOURCES)
- epydoc -o BPY_GE_236 --url "http://www.blender.org" -t GameLogic.py \
- -n "Blender GameEngine" --no-private --no-frames \
- $(shell ls *.py )
-
-clean:
- rm *.html
diff --git a/source/gameengine/PyDoc/Rasterizer.py b/source/gameengine/PyDoc/Rasterizer.py
index f0e48b6ed43..6a67cdcc71b 100644
--- a/source/gameengine/PyDoc/Rasterizer.py
+++ b/source/gameengine/PyDoc/Rasterizer.py
@@ -37,7 +37,11 @@ Example Uses an L{SCA_MouseSensor}, and two L{KX_ObjectActuator}s to implement M
# Centre the mouse
Rasterizer.setMousePosition(Rasterizer.getWindowWidth()/2, Rasterizer.getWindowHeight()/2)
-
+@group Material Types: KX_TEXFACE_MATERIAL, KX_BLENDER_MULTITEX_MATERIAL, KX_BLENDER_GLSL_MATERIAL
+@var KX_TEXFACE_MATERIAL: Materials as defined by the texture face settings.
+@var KX_BLENDER_MULTITEX_MATERIAL: Materials approximating blender materials with multitexturing.
+@var KX_BLENDER_GLSL_MATERIAL: Materials approximating blender materials with GLSL.
+
"""
def getWindowWidth():
@@ -84,7 +88,8 @@ def setMousePosition(x, y):
"""
Sets the mouse cursor position.
- @type x, y: integer
+ @type x: integer
+ @type y: integer
"""
def setBackgroundColor(rgba):
@@ -145,3 +150,47 @@ def getFocalLength():
@rtype: float
"""
+
+def setMaterialMode(mode):
+ """
+ Set the material mode to use for OpenGL rendering.
+
+ @type mode: KX_TEXFACE_MATERIAL, KX_BLENDER_MULTITEX_MATERIAL, KX_BLENDER_GLSL_MATERIAL
+ @note: Changes will only affect newly created scenes.
+ """
+
+def getMaterialMode(mode):
+ """
+ Get the material mode to use for OpenGL rendering.
+
+ @rtype: KX_TEXFACE_MATERIAL, KX_BLENDER_MULTITEX_MATERIAL, KX_BLENDER_GLSL_MATERIAL
+ """
+
+def setGLSLMaterialSetting(setting, enable):
+ """
+ Enables or disables a GLSL material setting.
+
+ @type setting: string (lights, shaders, shadows, ramps, nodes, extra_textures)
+ @type enable: boolean
+ """
+
+def getGLSLMaterialSetting(setting, enable):
+ """
+ Get the state of a GLSL material setting.
+
+ @type setting: string (lights, shaders, shadows, ramps, nodes, extra_textures)
+ @rtype: boolean
+ """
+
+def drawLine(fromVec,toVec,color):
+ """
+ Draw a line in the 3D scene.
+
+ @param fromVec: the origin of the line
+ @type fromVec: list [x, y, z]
+ @param toVec: the end of the line
+ @type toVec: list [x, y, z]
+ @param color: the color of the line
+ @type color: list [r, g, b]
+ """
+
diff --git a/source/gameengine/PyDoc/SCA_DelaySensor.py b/source/gameengine/PyDoc/SCA_DelaySensor.py
new file mode 100644
index 00000000000..19df589ea7b
--- /dev/null
+++ b/source/gameengine/PyDoc/SCA_DelaySensor.py
@@ -0,0 +1,56 @@
+# $Id$
+# Documentation for SCA_DelaySensor
+from SCA_ISensor import *
+
+class SCA_DelaySensor(SCA_ISensor):
+ """
+ The Delay sensor generates positive and negative triggers at precise time,
+ expressed in number of frames. The delay parameter defines the length
+ of the initial OFF period. A positive trigger is generated at the end of this period.
+ The duration parameter defines the length of the ON period following the OFF period.
+ There is a negative trigger at the end of the ON period. If duration is 0, the sensor
+ stays ON and there is no negative trigger.
+ The sensor runs the OFF-ON cycle once unless the repeat option is set: the
+ OFF-ON cycle repeats indefinately (or the OFF cycle if duration is 0).
+ Use SCA_ISensor::reset() at any time to restart sensor.
+ """
+ def setDelay(delay):
+ """
+ Set the initial delay before the positive trigger.
+
+ @param delay: length of the initial OFF period as number of frame, 0 for immediate trigger
+ @type delay: integer
+ """
+ def setDuration(duration):
+ """
+ Set the duration of the ON pulse after initial delay and the generation of the positive trigger.
+ If duration is greater than 0, a negative trigger is sent at the end of the ON pulse.
+
+ @param duration: length of the ON period in number of frame after the initial OFF period
+ @type duration: integer
+ """
+ def setRepeat(repeat):
+ """
+ Set if the sensor repeat mode.
+
+ @param repeat: 1 if the OFF-ON cycle should be repeated indefinately, 0 if it should run once.
+ @type repeat: integer
+ """
+ def getDelay():
+ """
+ Return the delay parameter value.
+
+ @rtype: integer
+ """
+ def getDuration():
+ """
+ Return the duration parameter value
+
+ @rtype: integer
+ """
+ def getRepeat():
+ """
+ Return the repeat parameter value
+
+ @rtype: KX_TRUE or KX_FALSE
+ """
diff --git a/source/gameengine/PyDoc/SCA_ISensor.py b/source/gameengine/PyDoc/SCA_ISensor.py
index b96d8c8c075..14858505e24 100644
--- a/source/gameengine/PyDoc/SCA_ISensor.py
+++ b/source/gameengine/PyDoc/SCA_ISensor.py
@@ -9,7 +9,12 @@ class SCA_ISensor(SCA_ILogicBrick):
def isPositive():
"""
- True if this sensor brick has been activated.
+ True if this sensor brick is in a positive state.
+ """
+
+ def isTriggered():
+ """
+ True if this sensor brick has triggered the current controller.
"""
def getUsePosPulseMode():
@@ -59,4 +64,28 @@ class SCA_ISensor(SCA_ILogicBrick):
@type invert: boolean
@param invert: true if activates on negative events; false if activates on positive events.
"""
+ def getLevel():
+ """
+ Returns whether this sensor is a level detector or a edge detector.
+ It makes a difference only in case of logic state transition (state actuator).
+ A level detector will immediately generate a pulse, negative or positive
+ depending on the sensor condition, as soon as the state is activated.
+ A edge detector will wait for a state change before generating a pulse.
+
+ @rtype: boolean
+ @return: true if sensor is level sensitive, false if it is edge sensitive
+ """
+ def setLevel(level):
+ """
+ Set whether to detect level or edge transition when entering a state.
+
+ @param level: Detect level instead of edge? (KX_TRUE, KX_FALSE)
+ @type level: boolean
+ """
+ def reset():
+ """
+ Reset sensor internal state, effect depends on the type of sensor and settings.
+
+ The sensor is put in its initial state as if it was just activated.
+ """
diff --git a/source/gameengine/PyDoc/SCA_JoystickSensor.py b/source/gameengine/PyDoc/SCA_JoystickSensor.py
new file mode 100644
index 00000000000..d1dab9afcaf
--- /dev/null
+++ b/source/gameengine/PyDoc/SCA_JoystickSensor.py
@@ -0,0 +1,106 @@
+# $Id: SCA_RandomSensor.py 15444 2008-07-05 17:05:05Z lukep $
+# Documentation for SCA_RandomSensor
+from SCA_ISensor import *
+
+class SCA_JoystickSensor(SCA_ISensor):
+ """
+ This sensor detects player joystick events.
+ """
+
+ def getIndex():
+ """
+ Returns the joystick index to use (from 1 to 8).
+ @rtype: integer
+ """
+ def setIndex(index):
+ """
+ Sets the joystick index to use.
+ @param index: The index of this joystick sensor, Clamped between 1 and 8.
+ @type index: integer
+ @note: This is only useful when you have more then 1 joystick connected to your computer - multiplayer games.
+ """
+ def getAxis():
+ """
+ Returns the current axis this sensor reacts to. See L{getAxisValue()<SCA_JoystickSensor.getAxisValue>} for the current axis state.
+ @rtype: list
+ @return: 2 values returned are [axisIndex, axisDirection] - see L{setAxis()<SCA_JoystickSensor.setAxis>} for their purpose.
+ @note: When the "All Events" toggle is set, this option has no effect.
+ """
+ def setAxis(axisIndex, axisDirection):
+ """
+ @param axisIndex: Set the axis index to use when detecting axis movement.
+ @type axisIndex: integer from 1 to 2
+ @param axisDirection: Set the axis direction used for detecting motion. 0:right, 1:up, 2:left, 3:down.
+ @type axisDirection: integer from 0 to 3
+ @note: When the "All Events" toggle is set, this option has no effect.
+ """
+ def getAxisValue():
+ """
+ Returns the state of the joysticks axis. See differs to L{getAxis()<SCA_JoystickSensor.getAxis>} returning the current state of the joystick.
+ @rtype: list
+ @return: 4 values, each spesifying the value of an axis between -32767 and 32767 depending on how far the axis is pushed, 0 for nothing.
+
+ The first 2 values are used by most joysticks and gamepads for directional control. 3rd and 4th values are only on some joysticks and can be used for arbitary controls.
+
+ left:[-32767, 0, ...], right:[32767, 0, ...], up:[0, -32767, ...], down:[0, 32767, ...]
+ @note: Some gamepads only set the axis on and off like a button.
+ """
+ def getThreshold():
+ """
+ Get the axis threshold. See L{setThreshold()<SCA_JoystickSensor.setThreshold>} for details.
+ @rtype: integer
+ """
+ def setThreshold(threshold):
+ """
+ Set the axis threshold.
+ @param threshold: Joystick axis motion below this threshold wont trigger an event. Use values between (0 and 32767), lower values are more sensitive.
+ @type threshold: integer
+ """
+ def getButton():
+ """
+ Returns the button index the sensor reacts to. See L{getButtonValue()<SCA_JoystickSensor.getButtonValue>} for a list of pressed buttons.
+ @rtype: integer
+ @note: When the "All Events" toggle is set, this option has no effect.
+ """
+ def setButton(index):
+ """
+ Sets the button index the sensor reacts to when the "All Events" option is not set.
+ @note: When the "All Events" toggle is set, this option has no effect.
+ """
+ def getButtonValue():
+ """
+ Returns a list containing the indicies of the currently pressed buttons.
+ @rtype: list
+ """
+ def getHat():
+ """
+ Returns the current hat direction this sensor is set to.
+ [hatNumber, hatDirection].
+ @rtype: list
+ @note: When the "All Events" toggle is set, this option has no effect.
+ """
+ def setHat(index):
+ """
+ Sets the hat index the sensor reacts to when the "All Events" option is not set.
+ @type index: integer
+ """
+ def getNumAxes():
+ """
+ Returns the number of axes for the joystick at this index.
+ @rtype: integer
+ """
+ def getNumButtons():
+ """
+ Returns the number of buttons for the joystick at this index.
+ @rtype: integer
+ """
+ def getNumHats():
+ """
+ Returns the number of hats for the joystick at this index.
+ @rtype: integer
+ """
+ def isConnected():
+ """
+ Returns True if a joystick is detected at this joysticks index.
+ @rtype: bool
+ """
diff --git a/source/gameengine/PyDoc/SCA_PythonController.py b/source/gameengine/PyDoc/SCA_PythonController.py
index eb9e57c0819..6d91736d636 100644
--- a/source/gameengine/PyDoc/SCA_PythonController.py
+++ b/source/gameengine/PyDoc/SCA_PythonController.py
@@ -46,4 +46,12 @@ class SCA_PythonController(SCA_IController):
@type script: string.
"""
+ def getState():
+ """
+ Get the controllers state bitmask, this can be used with the GameObject's state to test if the the controller is active.
+ This for instance will always be true however you could compare with a previous state to see when the state was activated.
+ GameLogic.getCurrentController().getState() & GameLogic.getCurrentController().getOwner().getState()
+
+ @rtype: int
+ """
diff --git a/source/gameengine/PyDoc/SConscript b/source/gameengine/PyDoc/SConscript
new file mode 100644
index 00000000000..ac0b163d7bd
--- /dev/null
+++ b/source/gameengine/PyDoc/SConscript
@@ -0,0 +1,28 @@
+#!/usr/bin/python
+Import ('env')
+
+
+from optparse import OptionParser
+try:
+ import epydoc
+except ImportError:
+ print "No epydoc install detected, Python API Docs will not be generated "
+if epydoc:
+ from epydoc.docbuilder import build_doc_index
+ from epydoc import cli
+ names = env.Glob("source/gameengine/PyDoc/*.py")
+ docindex = build_doc_index(names)
+ optvalues = cli.OPTION_DEFAULTS
+ optvalues["verbose"] = 1
+ optvalues["target"] = env["BF_DOCDIR"]+"/BGE_API/"
+ optvalues["url"] = "http://www.blender.org"
+ optvalues["top"] = "Game Engine API"
+ optvalues["name"] = "Blender"
+ optvalues["noprivate"] = 1
+ optvalues["noframes"] = 1
+ optvalues["names"] = names
+ optparser = OptionParser()
+ optparser.set_defaults(**optvalues)
+ (options, args) = optparser.parse_args([])
+ cli.write_html(docindex, options)
+
diff --git a/source/gameengine/PyDoc/epy_docgen.sh b/source/gameengine/PyDoc/epy_docgen.sh
new file mode 100644
index 00000000000..b243101ddcb
--- /dev/null
+++ b/source/gameengine/PyDoc/epy_docgen.sh
@@ -0,0 +1,11 @@
+# epy_docgen.sh
+# generates blender python doc using epydoc
+# requires epydoc in your PATH.
+# run from the doc directory containing the .py files
+# usage: sh epy_docgen.sh
+
+# set posix locale so regex works properly for [A-Z]*.py
+LC_ALL=POSIX
+
+epydoc --debug -v -o BPY_GE --url "http://www.blender.org" --top GameLogic \
+ --name "Blender GameEngine" --no-private --no-frames *.py
diff --git a/source/gameengine/Rasterizer/CMakeLists.txt b/source/gameengine/Rasterizer/CMakeLists.txt
index e604fe0e133..6d53ee53471 100644
--- a/source/gameengine/Rasterizer/CMakeLists.txt
+++ b/source/gameengine/Rasterizer/CMakeLists.txt
@@ -31,6 +31,9 @@ SET(INC
../../../source/kernel/gen_system
../../../intern/string
../../../intern/moto/include
+ ../../../extern/glew/include
+ ../Expressions
+ ${PYTHON_INC}
)
BLENDERLIB(bf_rasterizer "${SRC}" "${INC}")
diff --git a/source/gameengine/Rasterizer/Makefile b/source/gameengine/Rasterizer/Makefile
index 3fb8dda588c..917f70c7108 100644
--- a/source/gameengine/Rasterizer/Makefile
+++ b/source/gameengine/Rasterizer/Makefile
@@ -35,13 +35,20 @@ include nan_compile.mk
CCFLAGS += $(LEVEL_1_CPP_WARNINGS)
+CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(OPENGL_HEADERS)
CPPFLAGS += -I$(NAN_STRING)/include
CPPFLAGS += -I$(NAN_MOTO)/include
CPPFLAGS += -I../../kernel/gen_system
+CPPFLAGS += -I../BlenderRoutines
+CPPFLAGS += -I../Expressions
+
+CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION)
+
ifeq ($(OS),darwin)
CPPFLAGS += -fpascal-strings
endif
+
###############
SOURCEDIR = source/gameengine/Rasterizer
diff --git a/source/gameengine/Rasterizer/RAS_2DFilterManager.cpp b/source/gameengine/Rasterizer/RAS_2DFilterManager.cpp
new file mode 100644
index 00000000000..d2cfa7d07f9
--- /dev/null
+++ b/source/gameengine/Rasterizer/RAS_2DFilterManager.cpp
@@ -0,0 +1,500 @@
+/**
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#define STRINGIFY(A) #A
+
+#include "RAS_OpenGLFilters/RAS_Blur2DFilter.h"
+#include "RAS_OpenGLFilters/RAS_Sharpen2DFilter.h"
+#include "RAS_OpenGLFilters/RAS_Dilation2DFilter.h"
+#include "RAS_OpenGLFilters/RAS_Erosion2DFilter.h"
+#include "RAS_OpenGLFilters/RAS_Laplacian2DFilter.h"
+#include "RAS_OpenGLFilters/RAS_Sobel2DFilter.h"
+#include "RAS_OpenGLFilters/RAS_Prewitt2DFilter.h"
+#include "RAS_OpenGLFilters/RAS_GrayScale2DFilter.h"
+#include "RAS_OpenGLFilters/RAS_Sepia2DFilter.h"
+#include "RAS_OpenGLFilters/RAS_Invert2DFilter.h"
+
+#include "STR_String.h"
+#include "RAS_ICanvas.h"
+#include "RAS_Rect.h"
+#include "RAS_2DFilterManager.h"
+#include <iostream>
+
+#include "GL/glew.h"
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include "Value.h"
+
+RAS_2DFilterManager::RAS_2DFilterManager():
+texturewidth(-1), textureheight(-1),
+canvaswidth(-1), canvasheight(-1),
+numberoffilters(0)
+{
+ isshadersupported = GLEW_ARB_shader_objects &&
+ GLEW_ARB_fragment_shader && GLEW_ARB_multitexture;
+
+ if(!isshadersupported)
+ {
+ std::cout<<"shaders not supported!" << std::endl;
+ return;
+ }
+
+ int passindex;
+ for(passindex =0; passindex<MAX_RENDER_PASS; passindex++)
+ {
+ m_filters[passindex] = 0;
+ m_enabled[passindex] = 0;
+ texflag[passindex] = 0;
+ m_gameObjects[passindex] = NULL;
+ }
+ texname[0] = texname[1] = texname[2] = -1;
+ errorprinted= false;
+}
+
+RAS_2DFilterManager::~RAS_2DFilterManager()
+{
+ FreeTextures();
+}
+
+void RAS_2DFilterManager::PrintShaderErrors(unsigned int shader, const char *task, const char *code)
+{
+ GLcharARB log[5000];
+ GLsizei length = 0;
+ const char *c, *pos, *end;
+ int line = 1;
+
+ if(errorprinted)
+ return;
+
+ errorprinted= true;
+
+ glGetInfoLogARB(shader, sizeof(log), &length, log);
+ end = code + strlen(code);
+
+ printf("2D Filter GLSL Shader: %s error:\n", task);
+
+ c = code;
+ while ((c < end) && (pos = strchr(c, '\n'))) {
+ printf("%2d ", line);
+ fwrite(c, (pos+1)-c, 1, stdout);
+ c = pos+1;
+ line++;
+ }
+ printf("%s", c);
+
+ printf("%s\n", log);
+}
+
+unsigned int RAS_2DFilterManager::CreateShaderProgram(const char* shadersource)
+{
+ GLuint program = 0;
+ GLuint fShader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER);
+ GLint success;
+
+ glShaderSourceARB(fShader, 1, (const char**)&shadersource, NULL);
+
+ glCompileShaderARB(fShader);
+
+
+ glGetObjectParameterivARB(fShader, GL_COMPILE_STATUS, &success);
+ if(!success)
+ {
+ /*Shader Comile Error*/
+ PrintShaderErrors(fShader, "compile", shadersource);
+ return 0;
+ }
+
+ program = glCreateProgramObjectARB();
+ glAttachObjectARB(program, fShader);
+
+ glLinkProgramARB(program);
+ glGetObjectParameterivARB(program, GL_LINK_STATUS, &success);
+ if (!success)
+ {
+ /*Program Link Error*/
+ PrintShaderErrors(fShader, "link", shadersource);
+ return 0;
+ }
+
+ glValidateProgramARB(program);
+ glGetObjectParameterivARB(program, GL_VALIDATE_STATUS, &success);
+ if (!success)
+ {
+ /*Program Validation Error*/
+ PrintShaderErrors(fShader, "validate", shadersource);
+ return 0;
+ }
+
+ return program;
+}
+
+unsigned int RAS_2DFilterManager::CreateShaderProgram(int filtermode)
+{
+ switch(filtermode)
+ {
+ case RAS_2DFILTER_BLUR:
+ return CreateShaderProgram(BlurFragmentShader);
+ case RAS_2DFILTER_SHARPEN:
+ return CreateShaderProgram(SharpenFragmentShader);
+ case RAS_2DFILTER_DILATION:
+ return CreateShaderProgram(DilationFragmentShader);
+ case RAS_2DFILTER_EROSION:
+ return CreateShaderProgram(ErosionFragmentShader);
+ case RAS_2DFILTER_LAPLACIAN:
+ return CreateShaderProgram(LaplacionFragmentShader);
+ case RAS_2DFILTER_SOBEL:
+ return CreateShaderProgram(SobelFragmentShader);
+ case RAS_2DFILTER_PREWITT:
+ return CreateShaderProgram(PrewittFragmentShader);
+ case RAS_2DFILTER_GRAYSCALE:
+ return CreateShaderProgram(GrayScaleFragmentShader);
+ case RAS_2DFILTER_SEPIA:
+ return CreateShaderProgram(SepiaFragmentShader);
+ case RAS_2DFILTER_INVERT:
+ return CreateShaderProgram(InvertFragmentShader);
+ }
+ return 0;
+}
+
+void RAS_2DFilterManager::AnalyseShader(int passindex, vector<STR_String>& propNames)
+{
+ texflag[passindex] = 0;
+ if(glGetUniformLocationARB(m_filters[passindex], "bgl_DepthTexture") != -1)
+ {
+ if(GLEW_ARB_depth_texture)
+ texflag[passindex] |= 0x1;
+ }
+ if(glGetUniformLocationARB(m_filters[passindex], "bgl_LuminanceTexture") != -1)
+ {
+ texflag[passindex] |= 0x2;
+ }
+
+ if(m_gameObjects[passindex])
+ {
+ int objProperties = propNames.size();
+ int i;
+ for(i=0; i<objProperties; i++)
+ if(glGetUniformLocationARB(m_filters[passindex], propNames[i]) != -1)
+ m_properties[passindex].push_back(propNames[i]);
+ }
+}
+
+void RAS_2DFilterManager::StartShaderProgram(int passindex)
+{
+ GLint uniformLoc;
+ glUseProgramObjectARB(m_filters[passindex]);
+ uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_RenderedTexture");
+ glActiveTextureARB(GL_TEXTURE0);
+ glBindTexture(GL_TEXTURE_2D, texname[0]);
+
+ if (uniformLoc != -1)
+ {
+ glUniform1iARB(uniformLoc, 0);
+ }
+
+ /* send depth texture to glsl program if it needs */
+ if(texflag[passindex] & 0x1){
+ uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_DepthTexture");
+ glActiveTextureARB(GL_TEXTURE1);
+ glBindTexture(GL_TEXTURE_2D, texname[1]);
+
+ if (uniformLoc != -1)
+ {
+ glUniform1iARB(uniformLoc, 1);
+ }
+ }
+
+ /* send luminance texture to glsl program if it needs */
+ if(texflag[passindex] & 0x2){
+ uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_LuminanceTexture");
+ glActiveTextureARB(GL_TEXTURE2);
+ glBindTexture(GL_TEXTURE_2D, texname[2]);
+
+ if (uniformLoc != -1)
+ {
+ glUniform1iARB(uniformLoc, 2);
+ }
+ }
+
+ uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_TextureCoordinateOffset");
+ if (uniformLoc != -1)
+ {
+ glUniform2fvARB(uniformLoc, 9, textureoffsets);
+ }
+ uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_RenderedTextureWidth");
+ if (uniformLoc != -1)
+ {
+ glUniform1fARB(uniformLoc,texturewidth);
+ }
+ uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_RenderedTextureHeight");
+ if (uniformLoc != -1)
+ {
+ glUniform1fARB(uniformLoc,textureheight);
+ }
+
+ int i, objProperties = m_properties[passindex].size();
+ for(i=0; i<objProperties; i++)
+ {
+ uniformLoc = glGetUniformLocationARB(m_filters[passindex], m_properties[passindex][i]);
+ if(uniformLoc != -1)
+ {
+ float value = ((CValue*)m_gameObjects[passindex])->GetPropertyNumber(m_properties[passindex][i], 0.0);
+ glUniform1fARB(uniformLoc,value);
+ }
+ }
+}
+
+void RAS_2DFilterManager::EndShaderProgram()
+{
+ glUseProgramObjectARB(0);
+}
+
+void RAS_2DFilterManager::FreeTextures()
+{
+ if(texname[0]!=(unsigned int)-1)
+ glDeleteTextures(1, (GLuint*)&texname[0]);
+ if(texname[1]!=(unsigned int)-1)
+ glDeleteTextures(1, (GLuint*)&texname[1]);
+ if(texname[2]!=(unsigned int)-1)
+ glDeleteTextures(1, (GLuint*)&texname[2]);
+}
+
+void RAS_2DFilterManager::SetupTextures(bool depth, bool luminance)
+{
+ FreeTextures();
+
+ glGenTextures(1, (GLuint*)&texname[0]);
+ glBindTexture(GL_TEXTURE_2D, texname[0]);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texturewidth, textureheight, 0, GL_RGBA,
+ GL_UNSIGNED_BYTE, 0);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
+
+ if(depth){
+ glGenTextures(1, (GLuint*)&texname[1]);
+ glBindTexture(GL_TEXTURE_2D, texname[1]);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, texturewidth,textureheight,
+ 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE,NULL);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE,
+ GL_NONE);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
+ }
+
+ if(luminance){
+ glGenTextures(1, (GLuint*)&texname[2]);
+ glBindTexture(GL_TEXTURE_2D, texname[2]);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE16, texturewidth, textureheight,
+ 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, 0);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
+ }
+}
+
+void RAS_2DFilterManager::UpdateOffsetMatrix(RAS_ICanvas* canvas)
+{
+ RAS_Rect canvas_rect = canvas->GetWindowArea();
+ canvaswidth = canvas->GetWidth();
+ canvasheight = canvas->GetHeight();
+ texturewidth = canvaswidth;
+ textureheight = canvasheight;
+
+ GLint i,j;
+ i = 0;
+ while ((1 << i) <= texturewidth)
+ i++;
+ texturewidth = (1 << (i));
+
+ // Now for height
+ i = 0;
+ while ((1 << i) <= textureheight)
+ i++;
+ textureheight = (1 << (i));
+
+ GLfloat xInc = 1.0f / (GLfloat)texturewidth;
+ GLfloat yInc = 1.0f / (GLfloat)textureheight;
+
+ for (i = 0; i < 3; i++)
+ {
+ for (j = 0; j < 3; j++)
+ {
+ textureoffsets[(((i*3)+j)*2)+0] = (-1.0f * xInc) + ((GLfloat)i * xInc);
+ textureoffsets[(((i*3)+j)*2)+1] = (-1.0f * yInc) + ((GLfloat)j * yInc);
+ }
+ }
+}
+
+void RAS_2DFilterManager::RenderFilters(RAS_ICanvas* canvas)
+{
+ bool need_depth=false;
+ bool need_luminance=false;
+ int num_filters = 0;
+
+ int passindex;
+
+ if(!isshadersupported)
+ return;
+
+ for(passindex =0; passindex<MAX_RENDER_PASS; passindex++)
+ {
+ if(m_filters[passindex] && m_enabled[passindex]){
+ num_filters ++;
+ if(texflag[passindex] & 0x1)
+ need_depth = true;
+ if(texflag[passindex] & 0x2)
+ need_luminance = true;
+ if(need_depth && need_luminance)
+ break;
+ }
+ }
+
+ if(num_filters <= 0)
+ return;
+
+ if(canvaswidth != canvas->GetWidth() || canvasheight != canvas->GetHeight())
+ {
+ UpdateOffsetMatrix(canvas);
+ SetupTextures(need_depth, need_luminance);
+ }
+ GLuint viewport[4]={0};
+
+ if(need_depth){
+ glActiveTextureARB(GL_TEXTURE1);
+ glBindTexture(GL_TEXTURE_2D, texname[1]);
+ glCopyTexImage2D(GL_TEXTURE_2D,0,GL_DEPTH_COMPONENT, viewport[0], viewport[1], texturewidth,textureheight, 0);
+ }
+
+ if(need_luminance){
+ glActiveTextureARB(GL_TEXTURE2);
+ glBindTexture(GL_TEXTURE_2D, texname[2]);
+ glCopyTexImage2D(GL_TEXTURE_2D,0,GL_LUMINANCE16, viewport[0], viewport[1] , texturewidth,textureheight, 0);
+ }
+
+ glGetIntegerv(GL_VIEWPORT,(GLint *)viewport);
+ glViewport(viewport[0],viewport[1], texturewidth, textureheight);
+
+ glDisable(GL_DEPTH_TEST);
+ glMatrixMode(GL_TEXTURE);
+ glLoadIdentity();
+ glMatrixMode(GL_PROJECTION);
+ glLoadIdentity();
+ glMatrixMode(GL_MODELVIEW);
+ glLoadIdentity();
+
+ for(passindex =0; passindex<MAX_RENDER_PASS; passindex++)
+ {
+ if(m_filters[passindex] && m_enabled[passindex])
+ {
+ StartShaderProgram(passindex);
+
+ glActiveTextureARB(GL_TEXTURE0);
+ glBindTexture(GL_TEXTURE_2D, texname[0]);
+ glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, viewport[0], viewport[1], texturewidth, textureheight, 0);
+ glClear(GL_COLOR_BUFFER_BIT);
+
+ float canvascoordx, canvascoordy;
+
+ canvascoordx = (GLfloat) texturewidth / canvaswidth;
+ canvascoordy = (GLfloat) textureheight / canvasheight;
+
+ glBegin(GL_QUADS);
+ glColor4f(1.f, 1.f, 1.f, 1.f);
+ glTexCoord2f(1.0, 1.0); glMultiTexCoord2fARB(GL_TEXTURE1_ARB, canvascoordx, canvascoordy); glVertex2f(1,1);
+ glTexCoord2f(0.0, 1.0); glMultiTexCoord2fARB(GL_TEXTURE1_ARB, 0.0, canvascoordy); glVertex2f(-1,1);
+ glTexCoord2f(0.0, 0.0); glMultiTexCoord2fARB(GL_TEXTURE1_ARB, 0.0, 0.0); glVertex2f(-1,-1);
+ glTexCoord2f(1.0, 0.0); glMultiTexCoord2fARB(GL_TEXTURE1_ARB, canvascoordx, 0.0); glVertex2f(1,-1);
+ glEnd();
+ }
+ }
+
+ glEnable(GL_DEPTH_TEST);
+ glViewport(viewport[0],viewport[1],viewport[2],viewport[3]);
+ EndShaderProgram();
+}
+
+void RAS_2DFilterManager::EnableFilter(vector<STR_String>& propNames, void* gameObj, RAS_2DFILTER_MODE mode, int pass, STR_String& text)
+{
+ if(!isshadersupported)
+ return;
+ if(pass<0 || pass>=MAX_RENDER_PASS)
+ return;
+
+ if(mode == RAS_2DFILTER_DISABLED)
+ {
+ m_enabled[pass] = 0;
+ return;
+ }
+
+ if(mode == RAS_2DFILTER_ENABLED)
+ {
+ m_enabled[pass] = 1;
+ return;
+ }
+
+ if(mode == RAS_2DFILTER_NOFILTER)
+ {
+ if(m_filters[pass])
+ glDeleteObjectARB(m_filters[pass]);
+ m_enabled[pass] = 0;
+ m_filters[pass] = 0;
+ m_gameObjects[pass] = NULL;
+ m_properties[pass].clear();
+ texflag[pass] = 0;
+ return;
+ }
+
+ if(mode == RAS_2DFILTER_CUSTOMFILTER)
+ {
+ if(m_filters[pass])
+ glDeleteObjectARB(m_filters[pass]);
+ m_filters[pass] = CreateShaderProgram(text.Ptr());
+ m_gameObjects[pass] = gameObj;
+ AnalyseShader(pass, propNames);
+ m_enabled[pass] = 1;
+ return;
+ }
+
+ if(mode>=RAS_2DFILTER_MOTIONBLUR && mode<=RAS_2DFILTER_INVERT)
+ {
+ if(m_filters[pass])
+ glDeleteObjectARB(m_filters[pass]);
+ m_filters[pass] = CreateShaderProgram(mode);
+ m_enabled[pass] = 1;
+ }
+}
diff --git a/source/gameengine/Rasterizer/RAS_2DFilterManager.h b/source/gameengine/Rasterizer/RAS_2DFilterManager.h
new file mode 100644
index 00000000000..454643a5077
--- /dev/null
+++ b/source/gameengine/Rasterizer/RAS_2DFilterManager.h
@@ -0,0 +1,98 @@
+/**
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __RAS_I2DFILTER
+#define __RAS_I2DFILTER
+
+#define MAX_RENDER_PASS 100
+
+class RAS_2DFilterManager
+{
+private:
+ unsigned int CreateShaderProgram(const char* shadersource);
+ unsigned int CreateShaderProgram(int filtermode);
+ void AnalyseShader(int passindex, vector<STR_String>& propNames);
+ void StartShaderProgram(int passindex);
+ void EndShaderProgram();
+ void PrintShaderErrors(unsigned int shader, const char *task, const char *code);
+
+ void SetupTextures(bool depth, bool luminance);
+ void FreeTextures();
+
+ void UpdateOffsetMatrix(RAS_ICanvas* canvas);
+
+ float textureoffsets[18];
+ float view[4];
+ /* texname[0] contains render to texture, texname[1] contains depth texture, texname[2] contains luminance texture*/
+ unsigned int texname[3];
+ int texturewidth;
+ int textureheight;
+ int canvaswidth;
+ int canvasheight;
+ int numberoffilters;
+ /* bit 0: enable/disable depth texture
+ * bit 1: enable/disable luminance texture*/
+ short texflag[MAX_RENDER_PASS];
+
+ bool isshadersupported;
+ bool errorprinted;
+
+ unsigned int m_filters[MAX_RENDER_PASS];
+ short m_enabled[MAX_RENDER_PASS];
+
+ // stores object properties to send to shaders in each pass
+ vector<STR_String> m_properties[MAX_RENDER_PASS];
+ void* m_gameObjects[MAX_RENDER_PASS];
+public:
+ enum RAS_2DFILTER_MODE {
+ RAS_2DFILTER_ENABLED = -2,
+ RAS_2DFILTER_DISABLED = -1,
+ RAS_2DFILTER_NOFILTER = 0,
+ RAS_2DFILTER_MOTIONBLUR,
+ RAS_2DFILTER_BLUR,
+ RAS_2DFILTER_SHARPEN,
+ RAS_2DFILTER_DILATION,
+ RAS_2DFILTER_EROSION,
+ RAS_2DFILTER_LAPLACIAN,
+ RAS_2DFILTER_SOBEL,
+ RAS_2DFILTER_PREWITT,
+ RAS_2DFILTER_GRAYSCALE,
+ RAS_2DFILTER_SEPIA,
+ RAS_2DFILTER_INVERT,
+ RAS_2DFILTER_CUSTOMFILTER,
+ RAS_2DFILTER_NUMBER_OF_FILTERS
+ };
+
+ RAS_2DFilterManager();
+
+ ~RAS_2DFilterManager();
+
+ void RenderFilters(RAS_ICanvas* canvas);
+
+ void EnableFilter(vector<STR_String>& propNames, void* gameObj, RAS_2DFILTER_MODE mode, int pass, STR_String& text);
+};
+#endif
diff --git a/source/gameengine/Rasterizer/RAS_BucketManager.cpp b/source/gameengine/Rasterizer/RAS_BucketManager.cpp
index 48e761cfc5a..f7938bb62e6 100644
--- a/source/gameengine/Rasterizer/RAS_BucketManager.cpp
+++ b/source/gameengine/Rasterizer/RAS_BucketManager.cpp
@@ -26,10 +26,6 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
#ifdef WIN32
// don't show these anoying STL warnings
#pragma warning (disable:4786)
@@ -39,156 +35,236 @@
#include "RAS_MaterialBucket.h"
#include "STR_HashedString.h"
#include "RAS_MeshObject.h"
-#define KX_NUM_MATERIALBUCKETS 100
#include "RAS_IRasterizer.h"
#include "RAS_IRenderTools.h"
#include "RAS_BucketManager.h"
+#include <algorithm>
#include <set>
-RAS_BucketManager::RAS_BucketManager()
+/* sorting */
+
+struct RAS_BucketManager::sortedmeshslot
{
+public:
+ MT_Scalar m_z; /* depth */
+ RAS_MeshSlot *m_ms; /* mesh slot */
+ RAS_MaterialBucket *m_bucket; /* buck mesh slot came from */
-}
+ sortedmeshslot() {}
-RAS_BucketManager::~RAS_BucketManager()
-{
- RAS_BucketManagerClearAll();
-}
+ void set(RAS_MeshSlot *ms, RAS_MaterialBucket *bucket, const MT_Vector3& pnorm)
+ {
+ // would be good to use the actual bounding box center instead
+ MT_Point3 pos(ms->m_OpenGLMatrix[12], ms->m_OpenGLMatrix[13], ms->m_OpenGLMatrix[14]);
-/**
- * struct alphamesh holds a mesh, (m_ms) it's depth, (m_z) and the bucket it came from (m_bucket.)
- */
-struct RAS_BucketManager::alphamesh
-{
-public:
- MT_Scalar m_z;
- RAS_MaterialBucket::T_MeshSlotList::iterator m_ms;
- RAS_MaterialBucket *m_bucket;
- alphamesh(MT_Scalar z, RAS_MaterialBucket::T_MeshSlotList::iterator &ms, RAS_MaterialBucket *bucket) :
- m_z(z),
- m_ms(ms),
- m_bucket(bucket)
- {}
+ m_z = MT_dot(pnorm, pos);
+ m_ms = ms;
+ m_bucket = bucket;
+ }
};
struct RAS_BucketManager::backtofront
{
- bool operator()(const alphamesh &a, const alphamesh &b)
+ bool operator()(const sortedmeshslot &a, const sortedmeshslot &b)
{
- return a.m_z < b.m_z;
+ return (a.m_z < b.m_z) || (a.m_z == b.m_z && a.m_ms < b.m_ms);
}
};
-
-void RAS_BucketManager::RenderAlphaBuckets(
- const MT_Transform& cameratrans, RAS_IRasterizer* rasty, RAS_IRenderTools* rendertools)
+struct RAS_BucketManager::fronttoback
{
- BucketList::iterator bit;
- std::multiset<alphamesh, backtofront> alphameshset;
- RAS_MaterialBucket::T_MeshSlotList::iterator mit;
-
- /* Camera's near plane equation: cam_norm.dot(point) + cam_origin */
- const MT_Vector3 cam_norm(cameratrans.getBasis()[2]);
- const MT_Scalar cam_origin = cameratrans.getOrigin()[2];
- for (bit = m_AlphaBuckets.begin(); bit != m_AlphaBuckets.end(); ++bit)
+ bool operator()(const sortedmeshslot &a, const sortedmeshslot &b)
{
- (*bit)->ClearScheduledPolygons();
- for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit)
- {
- if ((*mit).m_bVisible)
- {
- MT_Point3 pos((*mit).m_OpenGLMatrix[12], (*mit).m_OpenGLMatrix[13], (*mit).m_OpenGLMatrix[14]);
- alphameshset.insert(alphamesh(MT_dot(cam_norm, pos) + cam_origin, mit, *bit));
- }
- }
+ return (a.m_z > b.m_z) || (a.m_z == b.m_z && a.m_ms > b.m_ms);
}
+};
+
+/* bucket manager */
+
+RAS_BucketManager::RAS_BucketManager()
+{
+
+}
+
+RAS_BucketManager::~RAS_BucketManager()
+{
+ BucketList::iterator it;
+
+ for (it = m_SolidBuckets.begin(); it != m_SolidBuckets.end(); it++)
+ delete (*it);
+
+ for (it = m_AlphaBuckets.begin(); it != m_AlphaBuckets.end(); it++)
+ delete(*it);
- // It shouldn't be strictly necessary to disable depth writes; but
- // it is needed for compatibility.
+ m_SolidBuckets.clear();
+ m_AlphaBuckets.clear();
+}
+
+void RAS_BucketManager::OrderBuckets(const MT_Transform& cameratrans, BucketList& buckets, vector<sortedmeshslot>& slots, bool alpha)
+{
+ BucketList::iterator bit;
+ list<RAS_MeshSlot>::iterator mit;
+ size_t size = 0, i = 0;
+
+ /* Camera's near plane equation: pnorm.dot(point) + pval,
+ * but we leave out pval since it's constant anyway */
+ const MT_Vector3 pnorm(cameratrans.getBasis()[2]);
+
+ for (bit = buckets.begin(); bit != buckets.end(); ++bit)
+ for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit)
+ if (!mit->IsCulled())
+ size++;
+
+ slots.resize(size);
+
+ for (bit = buckets.begin(); bit != buckets.end(); ++bit)
+ for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit)
+ if (!mit->IsCulled())
+ slots[i++].set(&*mit, *bit, pnorm);
+
+ if(alpha)
+ sort(slots.begin(), slots.end(), backtofront());
+ else
+ sort(slots.begin(), slots.end(), fronttoback());
+}
+
+void RAS_BucketManager::RenderAlphaBuckets(
+ const MT_Transform& cameratrans, RAS_IRasterizer* rasty, RAS_IRenderTools* rendertools)
+{
+ vector<sortedmeshslot> slots;
+ vector<sortedmeshslot>::iterator sit;
+
+ // Having depth masks disabled/enabled gives different artifacts in
+ // case no sorting is done or is done inexact. For compatibility, we
+ // disable it.
rasty->SetDepthMask(RAS_IRasterizer::KX_DEPTHMASK_DISABLED);
- int drawingmode;
- std::multiset< alphamesh, backtofront>::iterator msit = alphameshset.begin();
- for (; msit != alphameshset.end(); ++msit)
- {
- while ((*msit).m_bucket->ActivateMaterial(cameratrans, rasty, rendertools, drawingmode))
- (*msit).m_bucket->RenderMeshSlot(cameratrans, rasty, rendertools, *(*msit).m_ms, drawingmode);
- }
+ OrderBuckets(cameratrans, m_AlphaBuckets, slots, true);
+ for(sit=slots.begin(); sit!=slots.end(); ++sit) {
+ rendertools->SetClientObject(rasty, sit->m_ms->m_clientObj);
+
+ while(sit->m_bucket->ActivateMaterial(cameratrans, rasty, rendertools))
+ sit->m_bucket->RenderMeshSlot(cameratrans, rasty, rendertools, *(sit->m_ms));
+ }
+
rasty->SetDepthMask(RAS_IRasterizer::KX_DEPTHMASK_ENABLED);
}
-void RAS_BucketManager::Renderbuckets(
+void RAS_BucketManager::RenderSolidBuckets(
const MT_Transform& cameratrans, RAS_IRasterizer* rasty, RAS_IRenderTools* rendertools)
{
- BucketList::iterator bucket;
-
- rasty->EnableTextures(false);
+ BucketList::iterator bit;
+ list<RAS_MeshSlot>::iterator mit;
+
rasty->SetDepthMask(RAS_IRasterizer::KX_DEPTHMASK_ENABLED);
-
- // beginning each frame, clear (texture/material) caching information
- rasty->ClearCachingInfo();
- RAS_MaterialBucket::StartFrame();
- for (bucket = m_MaterialBuckets.begin(); bucket != m_MaterialBuckets.end(); ++bucket)
- {
- (*bucket)->ClearScheduledPolygons();
+ for (bit = m_SolidBuckets.begin(); bit != m_SolidBuckets.end(); ++bit) {
+ for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) {
+ if (mit->IsCulled())
+ continue;
+
+ rendertools->SetClientObject(rasty, mit->m_clientObj);
+
+ while ((*bit)->ActivateMaterial(cameratrans, rasty, rendertools))
+ (*bit)->RenderMeshSlot(cameratrans, rasty, rendertools, *mit);
+ }
}
- for (bucket = m_MaterialBuckets.begin(); bucket != m_MaterialBuckets.end(); ++bucket)
- {
- RAS_IPolyMaterial *tmp = (*bucket)->GetPolyMaterial();
- if(tmp->IsZSort() || tmp->GetFlag() &RAS_FORCEALPHA )
- rasty->SetAlphaTest(true);
- else
- rasty->SetAlphaTest(false);
+ /* this code draws meshes order front-to-back instead to reduce overdraw.
+ * it turned out slower due to much material state switching, a more clever
+ * algorithm might do better. */
+#if 0
+ vector<sortedmeshslot> slots;
+ vector<sortedmeshslot>::iterator sit;
+
+ OrderBuckets(cameratrans, m_SolidBuckets, slots, false);
+
+ for(sit=slots.begin(); sit!=slots.end(); ++sit) {
+ rendertools->SetClientObject(rasty, sit->m_ms->m_clientObj);
- (*bucket)->Render(cameratrans,rasty,rendertools);
+ while(sit->m_bucket->ActivateMaterial(cameratrans, rasty, rendertools))
+ sit->m_bucket->RenderMeshSlot(cameratrans, rasty, rendertools, *(sit->m_ms));
}
- rasty->SetAlphaTest(false);
+#endif
+}
+
+void RAS_BucketManager::Renderbuckets(
+ const MT_Transform& cameratrans, RAS_IRasterizer* rasty, RAS_IRenderTools* rendertools)
+{
+ /* beginning each frame, clear (texture/material) caching information */
+ rasty->ClearCachingInfo();
+ RenderSolidBuckets(cameratrans, rasty, rendertools);
RenderAlphaBuckets(cameratrans, rasty, rendertools);
- RAS_MaterialBucket::EndFrame();
+
+ rendertools->SetClientObject(rasty, NULL);
}
-RAS_MaterialBucket* RAS_BucketManager::RAS_BucketManagerFindBucket(RAS_IPolyMaterial * material)
+RAS_MaterialBucket* RAS_BucketManager::FindBucket(RAS_IPolyMaterial * material, bool &bucketCreated)
{
BucketList::iterator it;
- for (it = m_MaterialBuckets.begin(); it != m_MaterialBuckets.end(); it++)
- {
+
+ bucketCreated = false;
+
+ for (it = m_SolidBuckets.begin(); it != m_SolidBuckets.end(); it++)
if (*(*it)->GetPolyMaterial() == *material)
return *it;
- }
for (it = m_AlphaBuckets.begin(); it != m_AlphaBuckets.end(); it++)
- {
if (*(*it)->GetPolyMaterial() == *material)
return *it;
- }
RAS_MaterialBucket *bucket = new RAS_MaterialBucket(material);
- if (bucket->IsTransparant())
+ bucketCreated = true;
+
+ if (bucket->IsAlpha())
m_AlphaBuckets.push_back(bucket);
else
- m_MaterialBuckets.push_back(bucket);
+ m_SolidBuckets.push_back(bucket);
return bucket;
}
-void RAS_BucketManager::RAS_BucketManagerClearAll()
+void RAS_BucketManager::OptimizeBuckets(MT_Scalar distance)
{
- BucketList::iterator it;
- for (it = m_MaterialBuckets.begin(); it != m_MaterialBuckets.end(); it++)
- {
- delete (*it);
- }
- for (it = m_AlphaBuckets.begin(); it != m_AlphaBuckets.end(); it++)
- {
- delete(*it);
+ BucketList::iterator bit;
+
+ distance = 10.0;
+
+ for (bit = m_SolidBuckets.begin(); bit != m_SolidBuckets.end(); ++bit)
+ (*bit)->Optimize(distance);
+ for (bit = m_AlphaBuckets.begin(); bit != m_AlphaBuckets.end(); ++bit)
+ (*bit)->Optimize(distance);
+}
+
+void RAS_BucketManager::ReleaseDisplayLists(RAS_IPolyMaterial *mat)
+{
+ BucketList::iterator bit;
+ list<RAS_MeshSlot>::iterator mit;
+
+ for (bit = m_SolidBuckets.begin(); bit != m_SolidBuckets.end(); ++bit) {
+ if (mat == NULL || (mat == (*bit)->GetPolyMaterial())) {
+ for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) {
+ if(mit->m_DisplayList) {
+ mit->m_DisplayList->Release();
+ mit->m_DisplayList = NULL;
+ }
+ }
+ }
}
- m_MaterialBuckets.clear();
- m_AlphaBuckets.clear();
+ for (bit = m_AlphaBuckets.begin(); bit != m_AlphaBuckets.end(); ++bit) {
+ if (mat == NULL || (mat == (*bit)->GetPolyMaterial())) {
+ for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) {
+ if(mit->m_DisplayList) {
+ mit->m_DisplayList->Release();
+ mit->m_DisplayList = NULL;
+ }
+ }
+ }
+ }
}
+
diff --git a/source/gameengine/Rasterizer/RAS_BucketManager.h b/source/gameengine/Rasterizer/RAS_BucketManager.h
index d99053c1e37..74526f365a0 100644
--- a/source/gameengine/Rasterizer/RAS_BucketManager.h
+++ b/source/gameengine/Rasterizer/RAS_BucketManager.h
@@ -39,31 +39,33 @@
class RAS_BucketManager
{
- //GEN_Map<class RAS_IPolyMaterial,class RAS_MaterialBucket*> m_MaterialBuckets;
-
typedef std::vector<class RAS_MaterialBucket*> BucketList;
- BucketList m_MaterialBuckets;
+ BucketList m_SolidBuckets;
BucketList m_AlphaBuckets;
- struct alphamesh;
+ struct sortedmeshslot;
struct backtofront;
+ struct fronttoback;
public:
RAS_BucketManager();
virtual ~RAS_BucketManager();
- void RenderAlphaBuckets(const MT_Transform& cameratrans,
- RAS_IRasterizer* rasty, RAS_IRenderTools* rendertools);
void Renderbuckets(const MT_Transform & cameratrans,
- RAS_IRasterizer* rasty,
- class RAS_IRenderTools* rendertools);
+ RAS_IRasterizer* rasty, RAS_IRenderTools* rendertools);
- RAS_MaterialBucket* RAS_BucketManagerFindBucket(RAS_IPolyMaterial * material);
+ RAS_MaterialBucket* FindBucket(RAS_IPolyMaterial * material, bool &bucketCreated);
+ void OptimizeBuckets(MT_Scalar distance);
+ void ReleaseDisplayLists(RAS_IPolyMaterial * material = NULL);
private:
- void RAS_BucketManagerClearAll();
+ void OrderBuckets(const MT_Transform& cameratrans, BucketList& buckets, vector<sortedmeshslot>& slots, bool alpha);
+ void RenderSolidBuckets(const MT_Transform& cameratrans,
+ RAS_IRasterizer* rasty, RAS_IRenderTools* rendertools);
+ void RenderAlphaBuckets(const MT_Transform& cameratrans,
+ RAS_IRasterizer* rasty, RAS_IRenderTools* rendertools);
};
#endif //__RAS_BUCKETMANAGER
diff --git a/source/gameengine/Rasterizer/RAS_CameraData.h b/source/gameengine/Rasterizer/RAS_CameraData.h
index 99c0c412cf7..e3af43fb839 100644
--- a/source/gameengine/Rasterizer/RAS_CameraData.h
+++ b/source/gameengine/Rasterizer/RAS_CameraData.h
@@ -40,9 +40,11 @@ struct RAS_CameraData
int m_viewportbottom;
int m_viewportright;
int m_viewporttop;
+ float m_focallength;
- RAS_CameraData(float lens = 35., float clipstart = 0.1, float clipend = 100., bool perspective = true,
- bool viewport = false, int viewportleft = 0, int viewportbottom = 0, int viewportright = 0, int viewporttop = 0) :
+ RAS_CameraData(float lens = 35.0, float clipstart = 0.1, float clipend = 5000.0, bool perspective = true,
+ float focallength = 0.0f, bool viewport = false, int viewportleft = 0, int viewportbottom = 0,
+ int viewportright = 0, int viewporttop = 0) :
m_lens(lens),
m_clipstart(clipstart),
m_clipend(clipend),
@@ -51,7 +53,8 @@ struct RAS_CameraData
m_viewportleft(viewportleft),
m_viewportbottom(viewportbottom),
m_viewportright(viewportright),
- m_viewporttop(viewporttop)
+ m_viewporttop(viewporttop),
+ m_focallength(focallength)
{
}
};
diff --git a/source/gameengine/Rasterizer/RAS_Deformer.h b/source/gameengine/Rasterizer/RAS_Deformer.h
index bea68e203a9..3332ac4c0a7 100644
--- a/source/gameengine/Rasterizer/RAS_Deformer.h
+++ b/source/gameengine/Rasterizer/RAS_Deformer.h
@@ -43,8 +43,12 @@ public:
virtual ~RAS_Deformer(){};
virtual void Relink(GEN_Map<class GEN_HashedPtr, void*>*map)=0;
virtual bool Apply(class RAS_IPolyMaterial *polymat)=0;
- virtual void Update(void)=0;
- virtual RAS_Deformer *GetReplica()=0;
+ virtual bool Update(void)=0;
+ virtual RAS_Deformer *GetReplica(class KX_GameObject* replica)=0;
+ virtual bool SkipVertexTransform()
+ {
+ return false;
+ }
protected:
class RAS_MeshObject *m_pMesh;
};
diff --git a/source/gameengine/Rasterizer/RAS_FramingManager.h b/source/gameengine/Rasterizer/RAS_FramingManager.h
index dcb48c1c2a0..9cb59f300f7 100644
--- a/source/gameengine/Rasterizer/RAS_FramingManager.h
+++ b/source/gameengine/Rasterizer/RAS_FramingManager.h
@@ -108,6 +108,13 @@ public :
) const {
return m_frame_type;
};
+
+ void
+ SetFrameType(
+ RAS_FrameType type
+ ) {
+ m_frame_type = type;
+ };
float
BarRed(
@@ -140,14 +147,6 @@ public :
};
private :
-
- /**
- * private to force use of public constructor
- */
-
- RAS_FrameSettings(
- const RAS_FrameSettings &
- );
RAS_FrameType m_frame_type;
float m_bar_r;
diff --git a/source/gameengine/Rasterizer/RAS_ICanvas.h b/source/gameengine/Rasterizer/RAS_ICanvas.h
index d799dc9c9bb..f3f817a943d 100644
--- a/source/gameengine/Rasterizer/RAS_ICanvas.h
+++ b/source/gameengine/Rasterizer/RAS_ICanvas.h
@@ -137,6 +137,14 @@ public:
) = 0;
/**
+ * Used to get canvas area within blender.
+ */
+ virtual
+ RAS_Rect &
+ GetWindowArea(
+ ) = 0;
+
+ /**
* Set the visible vieport
*/
diff --git a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp b/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp
index 61860c4c405..fb3607f89f4 100644
--- a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp
+++ b/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp
@@ -27,6 +27,7 @@
*/
#include "RAS_IPolygonMaterial.h"
+#include "RAS_IRasterizer.h"
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -38,25 +39,22 @@ RAS_IPolyMaterial::RAS_IPolyMaterial(const STR_String& texname,
int tilexrep,
int tileyrep,
int mode,
- bool transparant,
+ int transp,
+ bool alpha,
bool zsort,
- int lightlayer,
- bool bIsTriangle,
- void* clientobject=NULL) :
-
- m_texturename(texname),
+ int lightlayer)
+ : m_texturename(texname),
m_materialname(matname),
m_tile(tile),
m_tilexrep(tilexrep),
m_tileyrep(tileyrep),
m_drawingmode (mode),
- m_transparant(transparant),
+ m_transp(transp),
+ m_alpha(alpha),
m_zsort(zsort),
m_lightlayer(lightlayer),
- m_bIsTriangle(bIsTriangle),
m_polymatid(m_newpolymatid++),
m_flag(0),
- m_enabled(0),
m_multimode(0)
{
m_shininess = 35.0;
@@ -70,14 +68,16 @@ bool RAS_IPolyMaterial::Equals(const RAS_IPolyMaterial& lhs) const
{
if(m_flag &RAS_BLENDERMAT)
{
- return (
+ bool test = (
this->m_multimode == lhs.m_multimode &&
this->m_flag == lhs.m_flag &&
this->m_drawingmode == lhs.m_drawingmode &&
- this->m_lightlayer == lhs.m_lightlayer &&
+ this->m_transp == lhs.m_transp &&
this->m_texturename.hash() == lhs.m_texturename.hash() &&
this->m_materialname.hash() == lhs.m_materialname.hash()
);
+
+ return test;
}
else
{
@@ -85,11 +85,10 @@ bool RAS_IPolyMaterial::Equals(const RAS_IPolyMaterial& lhs) const
this->m_tile == lhs.m_tile &&
this->m_tilexrep == lhs.m_tilexrep &&
this->m_tileyrep == lhs.m_tileyrep &&
- this->m_transparant == lhs.m_transparant &&
+ this->m_transp == lhs.m_transp &&
+ this->m_alpha == lhs.m_alpha &&
this->m_zsort == lhs.m_zsort &&
this->m_drawingmode == lhs.m_drawingmode &&
- this->m_bIsTriangle == lhs.m_bIsTriangle &&
- this->m_lightlayer == lhs.m_lightlayer &&
this->m_texturename.hash() == lhs.m_texturename.hash() &&
this->m_materialname.hash() == lhs.m_materialname.hash()
);
@@ -109,9 +108,9 @@ int RAS_IPolyMaterial::GetLightLayer() const
return m_lightlayer;
}
-bool RAS_IPolyMaterial::IsTransparant() const
+bool RAS_IPolyMaterial::IsAlpha() const
{
- return m_transparant;
+ return m_alpha || m_zsort;
}
bool RAS_IPolyMaterial::IsZSort() const
@@ -119,11 +118,6 @@ bool RAS_IPolyMaterial::IsZSort() const
return m_zsort;
}
-bool RAS_IPolyMaterial::UsesTriangles() const
-{
- return m_bIsTriangle;
-}
-
unsigned int RAS_IPolyMaterial::hash() const
{
return m_texturename.hash();
@@ -139,6 +133,11 @@ const STR_String& RAS_IPolyMaterial::GetMaterialName() const
return m_materialname;
}
+dword RAS_IPolyMaterial::GetMaterialNameHash() const
+{
+ return m_materialname.hash();
+}
+
const STR_String& RAS_IPolyMaterial::GetTextureName() const
{
return m_texturename;
@@ -148,10 +147,25 @@ const unsigned int RAS_IPolyMaterial::GetFlag() const
{
return m_flag;
}
-const unsigned int RAS_IPolyMaterial::GetEnabled() const
+
+bool RAS_IPolyMaterial::UsesLighting(RAS_IRasterizer *rasty) const
{
- return m_enabled;
+ bool dolights = false;
+
+ if(m_flag & RAS_BLENDERMAT)
+ dolights = (m_flag &RAS_MULTILIGHT)!=0;
+ else if(rasty->GetDrawingMode() < RAS_IRasterizer::KX_SOLID);
+ else if(rasty->GetDrawingMode() == RAS_IRasterizer::KX_SHADOW);
+ else
+ dolights = (m_drawingmode & 16)!=0;
+
+ return dolights;
}
+bool RAS_IPolyMaterial::UsesObjectColor() const
+{
+ return !(m_flag & RAS_BLENDERGLSL);
+}
unsigned int RAS_IPolyMaterial::m_newpolymatid = 0;
+
diff --git a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.h b/source/gameengine/Rasterizer/RAS_IPolygonMaterial.h
index 3284ddb7ddd..218dd91cb30 100644
--- a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.h
+++ b/source/gameengine/Rasterizer/RAS_IPolygonMaterial.h
@@ -52,7 +52,7 @@ enum MaterialProps
RAS_AUTOGEN =128,
RAS_NORMAL =256,
RAS_DEFMULTI =512,
- RAS_FORCEALPHA =1024
+ RAS_BLENDERGLSL =1024
};
/**
@@ -67,17 +67,16 @@ protected:
int m_tile;
int m_tilexrep,m_tileyrep;
int m_drawingmode; // tface->mode
- bool m_transparant;
+ int m_transp;
+ bool m_alpha;
bool m_zsort;
int m_lightlayer;
- bool m_bIsTriangle;
unsigned int m_polymatid;
static unsigned int m_newpolymatid;
// will move...
unsigned int m_flag;//MaterialProps
- unsigned int m_enabled;// enabled for this mat
int m_multimode; // sum of values
public:
@@ -103,11 +102,10 @@ public:
int tilexrep,
int tileyrep,
int mode,
- bool transparant,
+ int transp,
+ bool alpha,
bool zsort,
- int lightlayer,
- bool bIsTriangle,
- void* clientobject);
+ int lightlayer);
virtual ~RAS_IPolyMaterial() {};
/**
@@ -128,20 +126,22 @@ public:
{
return false;
}
- virtual void ActivateMeshSlot(const class KX_MeshSlot & ms, RAS_IRasterizer* rasty) const {}
+ virtual void ActivateMeshSlot(const class RAS_MeshSlot & ms, RAS_IRasterizer* rasty) const {}
virtual bool Equals(const RAS_IPolyMaterial& lhs) const;
bool Less(const RAS_IPolyMaterial& rhs) const;
int GetLightLayer() const;
- bool IsTransparant() const;
+ bool IsAlpha() const;
bool IsZSort() const;
- bool UsesTriangles() const;
unsigned int hash() const;
int GetDrawingMode() const;
const STR_String& GetMaterialName() const;
+ dword GetMaterialNameHash() const;
const STR_String& GetTextureName() const;
const unsigned int GetFlag() const;
- const unsigned int GetEnabled() const;
+
+ virtual bool UsesLighting(RAS_IRasterizer *rasty) const;
+ virtual bool UsesObjectColor() const;
/*
* PreCalculate texture gen
diff --git a/source/gameengine/Rasterizer/RAS_IRasterizer.h b/source/gameengine/Rasterizer/RAS_IRasterizer.h
index 5e8b5ad8276..411b28fa3b7 100644
--- a/source/gameengine/Rasterizer/RAS_IRasterizer.h
+++ b/source/gameengine/Rasterizer/RAS_IRasterizer.h
@@ -33,12 +33,23 @@
#pragma warning (disable:4786)
#endif
+#include "STR_HashedString.h"
+
#include "MT_CmMatrix4x4.h"
#include "MT_Matrix4x4.h"
+#include "RAS_TexVert.h"
+
+#include <vector>
+using namespace std;
+
class RAS_ICanvas;
class RAS_IPolyMaterial;
-#include "RAS_MaterialBucket.h"
+
+typedef vector<unsigned short> KX_IndexArray;
+typedef vector<RAS_TexVert> KX_VertexArray;
+typedef vector< KX_VertexArray* > vecVertexArray;
+typedef vector< KX_IndexArray* > vecIndexArrays;
/**
* 3D rendering device context interface.
@@ -62,7 +73,18 @@ public:
KX_WIREFRAME,
KX_SOLID,
KX_SHADED,
- KX_TEXTURED
+ KX_TEXTURED,
+ KX_SHADOW
+ };
+
+ /**
+ * Drawing modes
+ */
+
+ enum DrawMode {
+ KX_MODE_LINES = 1,
+ KX_MODE_TRIANGLES,
+ KX_MODE_QUADS
};
/**
@@ -111,6 +133,7 @@ public:
RAS_TEXCO_NORM, //< Normal coordinates
RAS_TEXTANGENT, //<
RAS_TEXCO_UV2, //<
+ RAS_TEXCO_VCOL, //< Vertex Color
RAS_TEXCO_DISABLE //< Disable this texture unit (cached)
};
@@ -146,6 +169,10 @@ public:
*/
virtual bool BeginFrame(int drawingmode, double time)=0;
/**
+ * ClearColorBuffer clears the color buffer.
+ */
+ virtual void ClearColorBuffer()=0;
+ /**
* ClearDepthBuffer clears the depth buffer.
*/
virtual void ClearDepthBuffer()=0;
@@ -158,7 +185,8 @@ public:
*/
virtual void EndFrame()=0;
/**
- * SetRenderArea sets the render area from the 2d canvas
+ * SetRenderArea sets the render area from the 2d canvas.
+ * Returns true if only of subset of the canvas is used.
*/
virtual void SetRenderArea()=0;
@@ -172,6 +200,7 @@ public:
* @return true if stereo mode is enabled.
*/
virtual bool Stereo()=0;
+ virtual bool InterlacedStereo()=0;
/**
* Sets which eye buffer subsequent primitives will be rendered to.
*/
@@ -194,67 +223,18 @@ public:
// Drawing Functions
/**
- * IndexPrimitives: Renders primitives.
- * @param vertexarrays is an array of vertex arrays
- * @param indexarrays is an array of index arrays
- * @param mode determines the type of primitive stored in the vertex/index arrays:
- * 0 triangles
- * 1 lines (default)
- * 2 quads
- * @param polymat (reserved)
- * @param useObjectColor will render the object using @param rgbacolor instead of
- * vertex colors.
- */
- virtual void IndexPrimitives( const vecVertexArray& vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
- class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor,
- class KX_ListSlot** slot)=0;
- /**
- * @copydoc IndexPrimitives
- * IndexPrimitivesEx will renormalize faces if @param vertexarrays[i].getFlag() & TV_CALCFACENORMAL
+ * IndexPrimitives: Renders primitives from mesh slot.
*/
- virtual void IndexPrimitives_Ex( const vecVertexArray& vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
- class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor)=0;
+ virtual void IndexPrimitives(class RAS_MeshSlot& ms)=0;
+ virtual void IndexPrimitivesMulti(class RAS_MeshSlot& ms)=0;
+
/**
* IndexPrimitives_3DText will render text into the polygons.
* The text to be rendered is from @param rendertools client object's text property.
*/
- virtual void IndexPrimitives_3DText( const vecVertexArray& vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
+ virtual void IndexPrimitives_3DText(class RAS_MeshSlot& ms,
class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor)=0;
-
- virtual void IndexPrimitivesMulti(
- const vecVertexArray& vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
- class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor,
- class KX_ListSlot** slot)=0;
-
- virtual void IndexPrimitivesMulti_Ex(
- const vecVertexArray& vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
- class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor)=0;
-
+ class RAS_IRenderTools* rendertools)=0;
virtual void SetProjectionMatrix(MT_CmMatrix4x4 & mat)=0;
/* This one should become our final version, methinks. */
@@ -276,9 +256,6 @@ public:
virtual const MT_Point3& GetCameraPosition()=0;
/**
*/
- virtual void LoadViewMatrix()=0;
- /**
- */
virtual void SetFog(float start,
float dist,
float r,
@@ -314,9 +291,6 @@ public:
*/
virtual int GetDrawingMode()=0;
/**
- */
- virtual void EnableTextures(bool enable)=0;
- /**
* Sets face culling
*/
virtual void SetCullFace(bool enable)=0;
@@ -344,6 +318,7 @@ public:
float top,
float frustnear,
float frustfar,
+ float focallength = 0.0f,
bool perspective = true
)=0;
/**
@@ -376,10 +351,6 @@ public:
virtual void SetAmbientColor(float red, float green, float blue)=0;
virtual void SetAmbient(float factor)=0;
- /**
- * Sets alpha testing
- */
- virtual void SetAlphaTest(bool enable)=0;
/**
* Sets a polygon offset. z depth will be: z1 = mult*z0 + add
@@ -388,9 +359,14 @@ public:
virtual void DrawDebugLine(const MT_Vector3& from,const MT_Vector3& to,const MT_Vector3& color)=0;
- virtual void SetTexCoords(TexCoGen coords, int unit) = 0;
- virtual void SetAttrib(int type) = 0;
- virtual void GetViewMatrix(MT_Matrix4x4 &mat) const = 0;
+
+ virtual void SetTexCoordNum(int num) = 0;
+ virtual void SetAttribNum(int num) = 0;
+ virtual void SetTexCoord(TexCoGen coords, int unit) = 0;
+ virtual void SetAttrib(TexCoGen coords, int unit) = 0;
+
+ virtual const MT_Matrix4x4& GetViewMatrix() const = 0;
+ virtual const MT_Matrix4x4& GetViewInvMatrix() const = 0;
virtual bool QueryLists(){return false;}
virtual bool QueryArrays(){return false;}
@@ -399,8 +375,11 @@ public:
virtual void DisableMotionBlur()=0;
virtual float GetMotionBlurValue()=0;
- virtual int GetMotionBlurState()=0;
- virtual void SetMotionBlurState(int newstate)=0;
+ virtual int GetMotionBlurState()=0;
+ virtual void SetMotionBlurState(int newstate)=0;
+
+ virtual void SetBlendingMode(int blendmode)=0;
+ virtual void SetFrontFace(bool ccw)=0;
};
#endif //__RAS_IRASTERIZER
diff --git a/source/gameengine/Rasterizer/RAS_IRenderTools.cpp b/source/gameengine/Rasterizer/RAS_IRenderTools.cpp
index 2be9bb75ebf..555a3520bb4 100644
--- a/source/gameengine/Rasterizer/RAS_IRenderTools.cpp
+++ b/source/gameengine/Rasterizer/RAS_IRenderTools.cpp
@@ -28,42 +28,22 @@
#include "RAS_IRenderTools.h"
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-void RAS_IRenderTools::SetViewMat(const MT_Transform& trans)
-{
- trans.getValue(m_viewmat);
-}
-
-
-
-void RAS_IRenderTools::SetClientObject(void* obj)
+void RAS_IRenderTools::SetClientObject(RAS_IRasterizer* rasty, void *obj)
{
if (m_clientobject != obj)
- {
m_clientobject = obj;
- m_modified = true;
- }
}
-
-
void RAS_IRenderTools::SetAuxilaryClientInfo(void* inf)
{
m_auxilaryClientInfo = inf;
}
-
-
void RAS_IRenderTools::AddLight(struct RAS_LightObject* lightobject)
{
m_lights.push_back(lightobject);
}
-
-
void RAS_IRenderTools::RemoveLight(struct RAS_LightObject* lightobject)
{
std::vector<struct RAS_LightObject*>::iterator lit =
@@ -71,5 +51,5 @@ void RAS_IRenderTools::RemoveLight(struct RAS_LightObject* lightobject)
if (!(lit==m_lights.end()))
m_lights.erase(lit);
-
}
+
diff --git a/source/gameengine/Rasterizer/RAS_IRenderTools.h b/source/gameengine/Rasterizer/RAS_IRenderTools.h
index b4c0386613f..57f331e64cb 100644
--- a/source/gameengine/Rasterizer/RAS_IRenderTools.h
+++ b/source/gameengine/Rasterizer/RAS_IRenderTools.h
@@ -31,6 +31,7 @@
#include "MT_Transform.h"
#include "RAS_IRasterizer.h"
+#include "RAS_2DFilterManager.h"
#include <vector>
#include <algorithm>
@@ -38,18 +39,17 @@
class RAS_IPolyMaterial;
struct RAS_LightObject;
+
class RAS_IRenderTools
{
protected:
- float m_viewmat[16];
void* m_clientobject;
void* m_auxilaryClientInfo;
- bool m_modified;
-
std::vector<struct RAS_LightObject*> m_lights;
-
+
+ RAS_2DFilterManager m_filtermanager;
public:
enum RAS_TEXT_RENDER_MODE {
@@ -58,11 +58,14 @@ public:
RAS_TEXT_PADDED,
RAS_TEXT_MAX
};
-
+ enum RAS_LIGHT_MODE {
+ RAS_LIGHT_NONE = -1,
+ RAS_LIGHT_OBJECT_LAYER = 0
+ };
+
RAS_IRenderTools(
) :
- m_clientobject(NULL),
- m_modified(true)
+ m_clientobject(NULL)
{
};
@@ -124,23 +127,21 @@ public:
float v1[3],
float v2[3],
float v3[3],
- float v4[3]
+ float v4[3],
+ int glattrib
)=0;
virtual
- void
- SetViewMat(
- const MT_Transform& trans
- );
-
- virtual
- int
+ void
ProcessLighting(
- int layer
+ int layer,
+ const MT_Transform& trans
)=0;
+ virtual
void
SetClientObject(
+ RAS_IRasterizer* rasty,
void* obj
);
@@ -175,25 +176,16 @@ public:
void
MotionBlur(RAS_IRasterizer* rasterizer)=0;
- virtual
- class RAS_IPolyMaterial*
- CreateBlenderPolyMaterial(
- const STR_String &texname,
- bool ba,
- const STR_String& matname,
- int tile,
- int tilexrep,
- int tileyrep,
- int mode,
- bool transparant,
- bool zsort,
- int lightlayer,
- bool bIsTriangle,
- void* clientobject,
- void* tface
- )=0;
+ virtual
+ void
+ Update2DFilter(vector<STR_String>& propNames, void* gameObj, RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode, int pass, STR_String& text)=0;
+
+ virtual
+ void
+ Render2DFilters(RAS_ICanvas* canvas)=0;
};
#endif //__RAS_IRENDERTOOLS
+
diff --git a/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp b/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp
index 1a736080e25..ad8d7ebd5b0 100644
--- a/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp
+++ b/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp
@@ -28,10 +28,6 @@
#include "RAS_MaterialBucket.h"
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
#ifdef WIN32
#pragma warning (disable:4786)
#include <windows.h>
@@ -44,286 +40,561 @@
#include "RAS_MeshObject.h"
#include "RAS_Deformer.h" // __NLA
+/* mesh slot */
-
-KX_VertexIndex::KX_VertexIndex(int size)
+RAS_MeshSlot::RAS_MeshSlot()
{
- m_size = size;
+ m_clientObj = NULL;
+ m_pDeformer = NULL;
+ m_OpenGLMatrix = NULL;
+ m_mesh = NULL;
+ m_bucket = NULL;
+ m_bVisible = false;
+ m_bCulled = true;
+ m_bObjectColor = false;
+ m_RGBAcolor = MT_Vector4(0.0, 0.0, 0.0, 0.0);
+ m_DisplayList = NULL;
+ m_bDisplayList = true;
+ m_joinSlot = NULL;
}
+RAS_MeshSlot::~RAS_MeshSlot()
+{
+ vector<RAS_DisplayArray*>::iterator it;
+ Split(true);
-void KX_VertexIndex::SetIndex(short loc,unsigned int index)
-{
- m_indexarray[loc]=index;
+ while(m_joinedSlots.size())
+ m_joinedSlots.front()->Split(true);
+
+ for(it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) {
+ (*it)->m_users--;
+ if((*it)->m_users == 0)
+ delete *it;
+ }
+
+ if (m_DisplayList) {
+ m_DisplayList->Release();
+ m_DisplayList = NULL;
+ }
}
-bool KX_MeshSlot::Less(const KX_MeshSlot& lhs) const
+RAS_MeshSlot::RAS_MeshSlot(const RAS_MeshSlot& slot)
{
- bool result = ((m_mesh < lhs.m_mesh ) ||
- ((m_mesh == lhs.m_mesh)&&(m_OpenGLMatrix < lhs.m_OpenGLMatrix)));
-
- return result;
+ vector<RAS_DisplayArray*>::iterator it;
+
+ m_clientObj = NULL;
+ m_pDeformer = NULL;
+ m_OpenGLMatrix = NULL;
+ m_mesh = slot.m_mesh;
+ m_bucket = slot.m_bucket;
+ m_bVisible = slot.m_bVisible;
+ m_bCulled = slot.m_bCulled;
+ m_bObjectColor = slot.m_bObjectColor;
+ m_RGBAcolor = slot.m_RGBAcolor;
+ m_DisplayList = NULL;
+ m_bDisplayList = slot.m_bDisplayList;
+ m_joinSlot = NULL;
+ m_currentArray = slot.m_currentArray;
+ m_displayArrays = slot.m_displayArrays;
+ m_joinedSlots = slot.m_joinedSlots;
+
+ m_startarray = slot.m_startarray;
+ m_startvertex = slot.m_startvertex;
+ m_startindex = slot.m_startindex;
+ m_endarray = slot.m_endarray;
+ m_endvertex = slot.m_endvertex;
+ m_endindex = slot.m_endindex;
+
+ for(it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) {
+ // don't copy display arrays for now because it breaks python
+ // access to vertices, but we'll need a solution if we want to
+ // join display arrays for reducing draw calls.
+ //*it = new RAS_DisplayArray(**it);
+ //(*it)->m_users = 1;
+
+ (*it)->m_users++;
+ }
}
+void RAS_MeshSlot::init(RAS_MaterialBucket *bucket, int numverts)
+{
+ m_bucket = bucket;
+ SetDisplayArray(numverts);
-RAS_MaterialBucket::RAS_MaterialBucket(RAS_IPolyMaterial* mat)
- :m_bModified(true)
+ m_startarray = 0;
+ m_startvertex = 0;
+ m_startindex = 0;
+ m_endarray = 0;
+ m_endvertex = 0;
+ m_endindex = 0;
+}
+
+void RAS_MeshSlot::begin(RAS_MeshSlot::iterator& it)
{
- m_bScheduled=true;
- m_material = mat;
+ int startvertex, endvertex;
+ int startindex, endindex;
+
+ it.array = (m_displayArrays.size() > 0)? m_displayArrays[m_startarray]: NULL;
+
+ if(it.array == NULL || it.array->m_index.size() == 0 || it.array->m_vertex.size() == 0) {
+ it.array = NULL;
+ it.vertex = NULL;
+ it.index = NULL;
+ it.startvertex = 0;
+ it.endvertex = 0;
+ it.totindex = 0;
+ }
+ else {
+ startvertex = m_startvertex;
+ endvertex = (m_startarray == m_endarray)? m_endvertex: it.array->m_vertex.size();
+ startindex = m_startindex;
+ endindex = (m_startarray == m_endarray)? m_endindex: it.array->m_index.size();
+
+ it.vertex = &it.array->m_vertex[0];
+ it.index = &it.array->m_index[startindex];
+ it.startvertex = startvertex;
+ it.endvertex = endvertex;
+ it.totindex = endindex-startindex;
+ it.arraynum = m_startarray;
+ }
}
+void RAS_MeshSlot::next(RAS_MeshSlot::iterator& it)
+{
+ int startvertex, endvertex;
+ int startindex, endindex;
+
+ if(it.arraynum == (size_t)m_endarray) {
+ it.array = NULL;
+ it.vertex = NULL;
+ it.index = NULL;
+ it.startvertex = 0;
+ it.endvertex = 0;
+ it.totindex = 0;
+ }
+ else {
+ it.arraynum++;
+ it.array = m_displayArrays[it.arraynum];
+
+ startindex = 0;
+ endindex = (it.arraynum == (size_t)m_endarray)? m_endindex: it.array->m_index.size();
+ startvertex = 0;
+ endvertex = (it.arraynum == (size_t)m_endarray)? m_endvertex: it.array->m_vertex.size();
+
+ it.vertex = &it.array->m_vertex[0];
+ it.index = &it.array->m_index[startindex];
+ it.startvertex = startvertex;
+ it.endvertex = endvertex;
+ it.totindex = endindex-startindex;
+ }
+}
+bool RAS_MeshSlot::end(RAS_MeshSlot::iterator& it)
+{
+ return (it.array == NULL);
+}
-void RAS_MaterialBucket::SchedulePolygons(int drawingmode)
-{
- m_bScheduled = true;
+RAS_DisplayArray *RAS_MeshSlot::CurrentDisplayArray()
+{
+ return m_currentArray;
}
+void RAS_MeshSlot::SetDisplayArray(int numverts)
+{
+ vector<RAS_DisplayArray*>::iterator it;
+ RAS_DisplayArray *darray = NULL;
+
+ for(it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) {
+ darray = *it;
+
+ if(darray->m_type == numverts) {
+ if(darray->m_index.size()+numverts >= RAS_DisplayArray::BUCKET_MAX_INDEX)
+ darray = NULL;
+ else if(darray->m_vertex.size()+numverts >= RAS_DisplayArray::BUCKET_MAX_VERTEX)
+ darray = NULL;
+ else
+ break;
+ }
+ else
+ darray = NULL;
+ }
+
+ if(!darray) {
+ darray = new RAS_DisplayArray();
+ darray->m_users = 1;
+ if(numverts == 2) darray->m_type = RAS_DisplayArray::LINE;
+ else if(numverts == 3) darray->m_type = RAS_DisplayArray::TRIANGLE;
+ else darray->m_type = RAS_DisplayArray::QUAD;
-void RAS_MaterialBucket::ClearScheduledPolygons()
-{
- m_bScheduled = false;
+ m_displayArrays.push_back(darray);
+
+ if(numverts == 2)
+ darray->m_type = RAS_DisplayArray::LINE;
+ else if(numverts == 3)
+ darray->m_type = RAS_DisplayArray::TRIANGLE;
+ else if(numverts == 4)
+ darray->m_type = RAS_DisplayArray::QUAD;
+
+ m_endarray = m_displayArrays.size()-1;
+ m_endvertex = 0;
+ m_endindex = 0;
+ }
+
+ m_currentArray = darray;
+}
+
+void RAS_MeshSlot::AddPolygon(int numverts)
+{
+ SetDisplayArray(numverts);
}
+int RAS_MeshSlot::AddVertex(const RAS_TexVert& tv)
+{
+ RAS_DisplayArray *darray;
+ int offset;
+ darray = m_currentArray;
+ darray->m_vertex.push_back(tv);
+ offset = darray->m_vertex.size()-1;
-RAS_IPolyMaterial* RAS_MaterialBucket::GetPolyMaterial() const
-{
- return m_material;
+ if(darray == m_displayArrays[m_endarray])
+ m_endvertex++;
+
+ return offset;
}
+void RAS_MeshSlot::AddPolygonVertex(int offset)
+{
+ RAS_DisplayArray *darray;
+
+ darray = m_currentArray;
+ darray->m_index.push_back(offset);
+ if(darray == m_displayArrays[m_endarray])
+ m_endindex++;
+}
+
+bool RAS_MeshSlot::Equals(RAS_MeshSlot *target)
+{
+ if(!m_OpenGLMatrix || !target->m_OpenGLMatrix)
+ return false;
+ if(m_pDeformer || target->m_pDeformer)
+ return false;
+ if(m_bVisible != target->m_bVisible)
+ return false;
+ if(m_bObjectColor != target->m_bObjectColor)
+ return false;
+ if(m_bObjectColor && !(m_RGBAcolor == target->m_RGBAcolor))
+ return false;
-void RAS_MaterialBucket::SetMeshSlot(KX_MeshSlot& ms)
+ return true;
+}
+
+bool RAS_MeshSlot::Join(RAS_MeshSlot *target, MT_Scalar distance)
{
- m_meshSlots.insert(ms);
+ vector<RAS_DisplayArray*>::iterator it;
+ iterator mit;
+ size_t i;
+
+ // verify if we can join
+ if(m_joinSlot || m_joinedSlots.size() || target->m_joinSlot)
+ return false;
+
+ if(!Equals(target))
+ return false;
+
+ MT_Vector3 co(&m_OpenGLMatrix[12]);
+ MT_Vector3 targetco(&target->m_OpenGLMatrix[12]);
+
+ if((co - targetco).length() > distance)
+ return false;
+
+ MT_Matrix4x4 mat(m_OpenGLMatrix);
+ MT_Matrix4x4 targetmat(target->m_OpenGLMatrix);
+ targetmat.invert();
+
+ MT_Matrix4x4 transform = targetmat*mat;
+
+ // m_mesh, clientobj
+ m_joinSlot = target;
+ m_joinInvTransform = transform;
+ m_joinInvTransform.invert();
+ target->m_joinedSlots.push_back(this);
+
+ MT_Matrix4x4 ntransform = m_joinInvTransform.transposed();
+ ntransform[0][3]= ntransform[1][3]= ntransform[2][3]= 0.0f;
+
+ for(begin(mit); !end(mit); next(mit))
+ for(i=mit.startvertex; i<mit.endvertex; i++)
+ mit.vertex[i].Transform(transform, ntransform);
+
+ for(it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) {
+ target->m_displayArrays.push_back(*it);
+ target->m_endarray++;
+ target->m_endvertex = target->m_displayArrays.back()->m_vertex.size();
+ target->m_endindex = target->m_displayArrays.back()->m_index.size();
+ }
+
+ if (m_DisplayList) {
+ m_DisplayList->Release();
+ m_DisplayList = NULL;
+ }
+ if (target->m_DisplayList) {
+ target->m_DisplayList->Release();
+ target->m_DisplayList = NULL;
+ }
+
+ return true;
+#if 0
+ return false;
+#endif
}
+bool RAS_MeshSlot::Split(bool force)
+{
+ list<RAS_MeshSlot*>::iterator jit;
+ RAS_MeshSlot *target = m_joinSlot;
+ vector<RAS_DisplayArray*>::iterator it, jt;
+ iterator mit;
+ size_t i, found0 = 0, found1 = 0;
+
+ if(target && (force || !Equals(target))) {
+ m_joinSlot = NULL;
+
+ for(jit=target->m_joinedSlots.begin(); jit!=target->m_joinedSlots.end(); jit++) {
+ if(*jit == this) {
+ target->m_joinedSlots.erase(jit);
+ found0 = 1;
+ break;
+ }
+ }
+
+ if(!found0)
+ abort();
+
+ for(it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) {
+ found1 = 0;
+ for(jt=target->m_displayArrays.begin(); jt!=target->m_displayArrays.end(); jt++) {
+ if(*jt == *it) {
+ target->m_displayArrays.erase(jt);
+ target->m_endarray--;
+ found1 = 1;
+ break;
+ }
+ }
+
+ if(!found1)
+ abort();
+ }
+
+ if(target->m_displayArrays.size()) {
+ target->m_endvertex = target->m_displayArrays.back()->m_vertex.size();
+ target->m_endindex = target->m_displayArrays.back()->m_index.size();
+ }
+ else {
+ target->m_endvertex = 0;
+ target->m_endindex = 0;
+ }
+
+ MT_Matrix4x4 ntransform = m_joinInvTransform.inverse().transposed();
+ ntransform[0][3]= ntransform[1][3]= ntransform[2][3]= 0.0f;
+
+ for(begin(mit); !end(mit); next(mit))
+ for(i=mit.startvertex; i<mit.endvertex; i++)
+ mit.vertex[i].Transform(m_joinInvTransform, ntransform);
+
+ if (target->m_DisplayList) {
+ target->m_DisplayList->Release();
+ target->m_DisplayList = NULL;
+ }
+
+ return true;
+ }
+ return false;
+}
-void RAS_MaterialBucket::RemoveMeshSlot(KX_MeshSlot& ms)
+bool RAS_MeshSlot::IsCulled()
{
- T_MeshSlotList::iterator it = m_meshSlots.find(ms);
+ list<RAS_MeshSlot*>::iterator it;
- if (!(it == m_meshSlots.end()))
- m_meshSlots.erase(it);
-
+ if(m_joinSlot)
+ return true;
+ if(!m_bCulled)
+ return false;
+
+ for(it=m_joinedSlots.begin(); it!=m_joinedSlots.end(); it++)
+ if(!(*it)->m_bCulled)
+ return false;
+
+ return true;
}
+/* material bucket sorting */
+
+struct RAS_MaterialBucket::less
+{
+ bool operator()(const RAS_MaterialBucket* x, const RAS_MaterialBucket* y) const
+ {
+ return *x->GetPolyMaterial() < *y->GetPolyMaterial();
+ }
+};
+/* material bucket */
-void RAS_MaterialBucket::MarkVisibleMeshSlot(KX_MeshSlot& ms,
- bool visible,
- bool color,
- const MT_Vector4& rgbavec)
+RAS_MaterialBucket::RAS_MaterialBucket(RAS_IPolyMaterial* mat)
{
- T_MeshSlotList::iterator it = m_meshSlots.find(ms);
-
- assert (!(it == m_meshSlots.end()));
- (*it).m_bVisible = visible;
- (*it).m_bObjectColor = color;
- (*it).m_RGBAcolor= rgbavec;
+ m_material = mat;
}
-bool RAS_MaterialBucket::IsTransparant() const
-{
- return (m_material->IsTransparant());
+RAS_MaterialBucket::~RAS_MaterialBucket()
+{
+}
+
+RAS_IPolyMaterial* RAS_MaterialBucket::GetPolyMaterial() const
+{
+ return m_material;
}
+bool RAS_MaterialBucket::IsAlpha() const
+{
+ return (m_material->IsAlpha());
+}
+bool RAS_MaterialBucket::IsZSort() const
+{
+ return (m_material->IsZSort());
+}
-void RAS_MaterialBucket::StartFrame()
+RAS_MeshSlot* RAS_MaterialBucket::AddMesh(int numverts)
{
-}
+ RAS_MeshSlot *ms;
+ m_meshSlots.push_back(RAS_MeshSlot());
+
+ ms = &m_meshSlots.back();
+ ms->init(this, numverts);
+ return ms;
+}
-void RAS_MaterialBucket::EndFrame()
+RAS_MeshSlot* RAS_MaterialBucket::CopyMesh(RAS_MeshSlot *ms)
{
+ m_meshSlots.push_back(RAS_MeshSlot(*ms));
+
+ return &m_meshSlots.back();
}
-unsigned int RAS_MaterialBucket::NumMeshSlots()
+void RAS_MaterialBucket::RemoveMesh(RAS_MeshSlot* ms)
{
- return m_meshSlots.size();
+ list<RAS_MeshSlot>::iterator it;
+
+ for(it=m_meshSlots.begin(); it!=m_meshSlots.end(); it++) {
+ if(&*it == ms) {
+ m_meshSlots.erase(it);
+ return;
+ }
+ }
}
-RAS_MaterialBucket::T_MeshSlotList::iterator RAS_MaterialBucket::msBegin()
+list<RAS_MeshSlot>::iterator RAS_MaterialBucket::msBegin()
{
return m_meshSlots.begin();
}
-RAS_MaterialBucket::T_MeshSlotList::iterator RAS_MaterialBucket::msEnd()
+list<RAS_MeshSlot>::iterator RAS_MaterialBucket::msEnd()
{
return m_meshSlots.end();
}
bool RAS_MaterialBucket::ActivateMaterial(const MT_Transform& cameratrans, RAS_IRasterizer* rasty,
- RAS_IRenderTools *rendertools, int &drawmode)
+ RAS_IRenderTools *rendertools)
{
- rendertools->SetViewMat(cameratrans);
-
if (!rasty->SetMaterial(*m_material))
return false;
- bool dolights = false;
- const unsigned int flag = m_material->GetFlag();
-
-
- if( flag & RAS_BLENDERMAT)
- dolights = (flag &RAS_MULTILIGHT)!=0;
+ if (m_material->UsesLighting(rasty))
+ rendertools->ProcessLighting(RAS_IRenderTools::RAS_LIGHT_OBJECT_LAYER, cameratrans);
else
- dolights = (m_material->GetDrawingMode()&16)!=0;
-
- if ((rasty->GetDrawingMode() < RAS_IRasterizer::KX_SOLID) || !dolights)
- {
- rendertools->ProcessLighting(-1);
- }
- else
- {
- rendertools->ProcessLighting(m_material->GetLightLayer());
- }
-
- drawmode = (rasty->GetDrawingMode() < RAS_IRasterizer::KX_SOLID ?
- 1: (m_material->UsesTriangles() ? 0 : 2));
+ rendertools->ProcessLighting(-1, cameratrans);
return true;
}
void RAS_MaterialBucket::RenderMeshSlot(const MT_Transform& cameratrans, RAS_IRasterizer* rasty,
- RAS_IRenderTools* rendertools, const KX_MeshSlot &ms, int drawmode)
+ RAS_IRenderTools* rendertools, RAS_MeshSlot &ms)
{
- if (!ms.m_bVisible)
- return;
-
- rendertools->SetClientObject(ms.m_clientObj);
m_material->ActivateMeshSlot(ms, rasty);
- /* __NLA Do the deformation */
if (ms.m_pDeformer)
{
ms.m_pDeformer->Apply(m_material);
// KX_ReInstanceShapeFromMesh(ms.m_mesh); // Recompute the physics mesh. (Can't call KX_* from RAS_)
}
- /* End __NLA */
- if (rasty->GetDrawingMode() >= RAS_IRasterizer::KX_SOLID)
- ms.m_mesh->SortPolygons(cameratrans*MT_Transform(ms.m_OpenGLMatrix));
+ if(IsZSort() && rasty->GetDrawingMode() >= RAS_IRasterizer::KX_SOLID)
+ ms.m_mesh->SortPolygons(ms, cameratrans*MT_Transform(ms.m_OpenGLMatrix));
rendertools->PushMatrix();
- rendertools->applyTransform(rasty,ms.m_OpenGLMatrix,m_material->GetDrawingMode());
+ if (!ms.m_pDeformer || !ms.m_pDeformer->SkipVertexTransform())
+ {
+ rendertools->applyTransform(rasty,ms.m_OpenGLMatrix,m_material->GetDrawingMode());
+ }
if(rasty->QueryLists())
- {
if(ms.m_DisplayList)
ms.m_DisplayList->SetModified(ms.m_mesh->MeshModified());
- }
- // Use the text-specific IndexPrimitives for text faces
- if (m_material->GetDrawingMode() & RAS_IRasterizer::RAS_RENDER_3DPOLYGON_TEXT)
- {
- rasty->IndexPrimitives_3DText(
- ms.m_mesh->GetVertexCache(m_material),
- ms.m_mesh->GetIndexCache(m_material),
- drawmode,
- m_material,
- rendertools, // needed for textprinting on polys
- ms.m_bObjectColor,
- ms.m_RGBAcolor);
-
- }
-
- // for using glMultiTexCoord
- else if(m_material->GetFlag() & RAS_MULTITEX )
- {
- rasty->IndexPrimitivesMulti(
- ms.m_mesh->GetVertexCache(m_material),
- ms.m_mesh->GetIndexCache(m_material),
- drawmode,
- m_material,
- rendertools,
- ms.m_bObjectColor,
- ms.m_RGBAcolor,
- &ms.m_DisplayList
- );
- }
-
- // for using glMultiTexCoord on deformer
- else if(m_material->GetFlag() & RAS_DEFMULTI )
- {
- rasty->IndexPrimitivesMulti_Ex(
- ms.m_mesh->GetVertexCache(m_material),
- ms.m_mesh->GetIndexCache(m_material),
- drawmode,
- m_material,
- rendertools,
- ms.m_bObjectColor,
- ms.m_RGBAcolor
- );
- }
+ // verify if we can use display list, not for deformed object, and
+ // also don't create a new display list when drawing shadow buffers,
+ // then it won't have texture coordinates for actual drawing. also
+ // for zsort we can't make a display list, since the polygon order
+ // changes all the time.
+ if(ms.m_pDeformer)
+ ms.m_bDisplayList = false;
+ else if(!ms.m_DisplayList && rasty->GetDrawingMode() == RAS_IRasterizer::KX_SHADOW)
+ ms.m_bDisplayList = false;
+ else if (IsZSort())
+ ms.m_bDisplayList = false;
+ else if(m_material->UsesObjectColor() && ms.m_bObjectColor)
+ ms.m_bDisplayList = false;
+ else
+ ms.m_bDisplayList = true;
- // Use the (slower) IndexPrimitives_Ex which can recalc face normals & such
- // for deformed objects - eventually should be extended to recalc ALL normals
- else if (ms.m_pDeformer){
- rasty->IndexPrimitives_Ex(
- ms.m_mesh->GetVertexCache(m_material),
- ms.m_mesh->GetIndexCache(m_material),
- drawmode,
- m_material,
- rendertools, // needed for textprinting on polys
- ms.m_bObjectColor,
- ms.m_RGBAcolor
- );
- }
- // Use the normal IndexPrimitives
+ // for text drawing using faces
+ if (m_material->GetDrawingMode() & RAS_IRasterizer::RAS_RENDER_3DPOLYGON_TEXT)
+ rasty->IndexPrimitives_3DText(ms, m_material, rendertools);
+ // for multitexturing
+ else if((m_material->GetFlag() & (RAS_MULTITEX|RAS_BLENDERGLSL)))
+ rasty->IndexPrimitivesMulti(ms);
+ // use normal IndexPrimitives
else
- {
- rasty->IndexPrimitives(
- ms.m_mesh->GetVertexCache(m_material),
- ms.m_mesh->GetIndexCache(m_material),
- drawmode,
- m_material,
- rendertools, // needed for textprinting on polys
- ms.m_bObjectColor,
- ms.m_RGBAcolor,
- &ms.m_DisplayList
- );
- }
+ rasty->IndexPrimitives(ms);
- if(rasty->QueryLists()) {
+ if(rasty->QueryLists())
if(ms.m_DisplayList)
ms.m_mesh->SetMeshModified(false);
- }
rendertools->PopMatrix();
}
-void RAS_MaterialBucket::Render(const MT_Transform& cameratrans,
- RAS_IRasterizer* rasty,
- RAS_IRenderTools* rendertools)
+void RAS_MaterialBucket::Optimize(MT_Scalar distance)
{
- if (m_meshSlots.begin()== m_meshSlots.end())
- return;
-
- //rendertools->SetViewMat(cameratrans);
-
- //rasty->SetMaterial(*m_material);
-
- if (m_meshSlots.size() >0)
- {
- rendertools->SetClientObject((*m_meshSlots.begin()).m_clientObj);
- }
+ /* TODO: still have to check before this works correct:
+ * - lightlayer, frontface, text, billboard
+ * - make it work with physics */
- int drawmode;
- for (T_MeshSlotList::const_iterator it = m_meshSlots.begin();
- ! (it == m_meshSlots.end()); ++it)
- {
- while (ActivateMaterial(cameratrans, rasty, rendertools, drawmode))
- RenderMeshSlot(cameratrans, rasty, rendertools, *it, drawmode);
- }
+#if 0
+ list<RAS_MeshSlot>::iterator it;
+ list<RAS_MeshSlot>::iterator jt;
+
+ // greed joining on all following buckets
+ for(it=m_meshSlots.begin(); it!=m_meshSlots.end(); it++)
+ for(jt=it, jt++; jt!=m_meshSlots.end(); jt++)
+ jt->Join(&*it, distance);
+#endif
}
-
diff --git a/source/gameengine/Rasterizer/RAS_MaterialBucket.h b/source/gameengine/Rasterizer/RAS_MaterialBucket.h
index 78424689b35..475f01d549a 100644
--- a/source/gameengine/Rasterizer/RAS_MaterialBucket.h
+++ b/source/gameengine/Rasterizer/RAS_MaterialBucket.h
@@ -35,132 +35,179 @@
#include "MT_Transform.h"
#include "RAS_IPolygonMaterial.h"
-#include "RAS_Deformer.h" // __NLA
+#include "RAS_IRasterizer.h"
+#include "RAS_Deformer.h"
+
#include <vector>
-#include <map>
#include <set>
+#include <list>
using namespace std;
-typedef vector<unsigned short> KX_IndexArray;
-typedef vector<RAS_TexVert> KX_VertexArray;
-typedef vector< KX_VertexArray* > vecVertexArray;
-typedef vector< KX_IndexArray* > vecIndexArrays;
+/* Display List Slot */
-/**
- * KX_VertexIndex
- */
-struct KX_VertexIndex {
+class KX_ListSlot
+{
+protected:
+ int m_refcount;
public:
- KX_VertexIndex(int size);
- void SetIndex(short loc,unsigned int index);
-
- // The vertex array
- short m_vtxarray;
- // An index into the vertex array for up to 4 verticies
- unsigned short m_indexarray[4];
- short m_size;
+ KX_ListSlot(){ m_refcount=1; }
+ virtual ~KX_ListSlot() {}
+ virtual int Release() {
+ if (--m_refcount > 0)
+ return m_refcount;
+ delete this;
+ return 0;
+ }
+ virtual KX_ListSlot* AddRef() {
+ m_refcount++;
+ return this;
+ }
+ virtual void SetModified(bool mod)=0;
};
-/**
- * KX_ListSlot.
- */
-class KX_ListSlot
+class RAS_DisplayArray;
+class RAS_MeshSlot;
+class RAS_MeshMaterial;
+class RAS_MaterialBucket;
+
+/* An array with data used for OpenGL drawing */
+
+class RAS_DisplayArray
{
public:
- KX_ListSlot(){}
- virtual ~KX_ListSlot(){}
+ vector<RAS_TexVert> m_vertex;
+ vector<unsigned short> m_index;
+ enum { LINE = 2, TRIANGLE = 3, QUAD = 4 } m_type;
+ //RAS_MeshSlot *m_origSlot;
+ int m_users;
- virtual void SetModified(bool mod)=0;
+ enum { BUCKET_MAX_INDEX = 65535 };
+ enum { BUCKET_MAX_VERTEX = 65535 };
};
-/**
- * KX_MeshSlot.
- */
-class KX_MeshSlot
+/* Entry of a RAS_MeshObject into RAS_MaterialBucket */
+
+class RAS_MeshSlot
{
+private:
+ // indices into display arrays
+ int m_startarray;
+ int m_endarray;
+ int m_startindex;
+ int m_endindex;
+ int m_startvertex;
+ int m_endvertex;
+ vector<RAS_DisplayArray*> m_displayArrays;
+
+ // for construction only
+ RAS_DisplayArray* m_currentArray;
+
public:
- void* m_clientObj;
- RAS_Deformer* m_pDeformer; // __NLA
- double* m_OpenGLMatrix;
- class RAS_MeshObject* m_mesh;
- mutable bool m_bVisible; // for visibility
- mutable bool m_bObjectColor;
- mutable MT_Vector4 m_RGBAcolor;
- mutable KX_ListSlot* m_DisplayList; // for lists
- KX_MeshSlot() :
- m_pDeformer(NULL),
- m_bVisible(true),
- m_DisplayList(0)
- {
- }
- ~KX_MeshSlot(){}
- bool Less(const KX_MeshSlot& lhs) const;
+ // for rendering
+ RAS_MaterialBucket* m_bucket;
+ RAS_MeshObject* m_mesh;
+ void* m_clientObj;
+ RAS_Deformer* m_pDeformer;
+ double* m_OpenGLMatrix;
+ // visibility
+ bool m_bVisible;
+ bool m_bCulled;
+ // object color
+ bool m_bObjectColor;
+ MT_Vector4 m_RGBAcolor;
+ // display lists
+ KX_ListSlot* m_DisplayList;
+ bool m_bDisplayList;
+ // joined mesh slots
+ RAS_MeshSlot* m_joinSlot;
+ MT_Matrix4x4 m_joinInvTransform;
+ list<RAS_MeshSlot*> m_joinedSlots;
+
+ RAS_MeshSlot();
+ RAS_MeshSlot(const RAS_MeshSlot& slot);
+ virtual ~RAS_MeshSlot();
+
+ void init(RAS_MaterialBucket *bucket, int numverts);
+
+ struct iterator {
+ RAS_DisplayArray *array;
+ RAS_TexVert *vertex;
+ unsigned short *index;
+ size_t startvertex;
+ size_t endvertex;
+ size_t totindex;
+ size_t arraynum;
+ };
+
+ void begin(iterator& it);
+ void next(iterator& it);
+ bool end(iterator& it);
+
+ /* used during construction */
+ void SetDisplayArray(int numverts);
+ RAS_DisplayArray *CurrentDisplayArray();
+
+ void AddPolygon(int numverts);
+ int AddVertex(const RAS_TexVert& tv);
+ void AddPolygonVertex(int offset);
+
+ /* optimization */
+ bool Split(bool force=false);
+ bool Join(RAS_MeshSlot *target, MT_Scalar distance);
+ bool Equals(RAS_MeshSlot *target);
+ bool IsCulled();
};
+/* Used by RAS_MeshObject, to point to it's slots in a bucket */
-inline bool operator <( const KX_MeshSlot& rhs,const KX_MeshSlot& lhs)
+class RAS_MeshMaterial
{
- return ( rhs.Less(lhs));
-}
+public:
+ RAS_MeshSlot *m_baseslot;
+ class RAS_MaterialBucket *m_bucket;
+
+ GEN_Map<GEN_HashedPtr,RAS_MeshSlot*> m_slots;
+};
+
+/* Contains a list of display arrays with the same material,
+ * and a mesh slot for each mesh that uses display arrays in
+ * this bucket */
-/**
- * Contains a list of meshs with the same material properties.
- */
class RAS_MaterialBucket
{
public:
- typedef std::set<KX_MeshSlot> T_MeshSlotList;
-
RAS_MaterialBucket(RAS_IPolyMaterial* mat);
- virtual ~RAS_MaterialBucket() {}
-
- void Render(const MT_Transform& cameratrans,
- class RAS_IRasterizer* rasty,
- class RAS_IRenderTools* rendertools);
-
- void SchedulePolygons(int drawingmode);
- void ClearScheduledPolygons();
+ virtual ~RAS_MaterialBucket();
+ /* Bucket Sorting */
+ struct less;
+ typedef set<RAS_MaterialBucket*, less> Set;
+
+ /* Material Properties */
RAS_IPolyMaterial* GetPolyMaterial() const;
- bool IsTransparant() const;
+ bool IsAlpha() const;
+ bool IsZSort() const;
- static void StartFrame();
- static void EndFrame();
-
- void SetMeshSlot(KX_MeshSlot& ms);
- void RemoveMeshSlot(KX_MeshSlot& ms);
- void MarkVisibleMeshSlot(KX_MeshSlot& ms,
- bool visible,
- bool color,
- const MT_Vector4& rgbavec);
-
- void RenderMeshSlot(const MT_Transform& cameratrans, RAS_IRasterizer* rasty,
- RAS_IRenderTools* rendertools, const KX_MeshSlot &ms, int drawmode);
+ /* Rendering */
bool ActivateMaterial(const MT_Transform& cameratrans, RAS_IRasterizer* rasty,
- RAS_IRenderTools *rendertools, int &drawmode);
-
- unsigned int NumMeshSlots();
- T_MeshSlotList::iterator msBegin();
- T_MeshSlotList::iterator msEnd();
-
- struct less
- {
- bool operator()(const RAS_MaterialBucket* x, const RAS_MaterialBucket* y) const
- {
- return *x->GetPolyMaterial() < *y->GetPolyMaterial();
- }
- };
+ RAS_IRenderTools *rendertools);
+ void RenderMeshSlot(const MT_Transform& cameratrans, RAS_IRasterizer* rasty,
+ RAS_IRenderTools* rendertools, RAS_MeshSlot &ms);
- typedef set<RAS_MaterialBucket*, less> Set;
+ /* Mesh Slot Access */
+ list<RAS_MeshSlot>::iterator msBegin();
+ list<RAS_MeshSlot>::iterator msEnd();
+
+ class RAS_MeshSlot* AddMesh(int numverts);
+ class RAS_MeshSlot* CopyMesh(class RAS_MeshSlot *ms);
+ void RemoveMesh(class RAS_MeshSlot* ms);
+ void Optimize(MT_Scalar distance);
+
private:
-
- T_MeshSlotList m_meshSlots;
- bool m_bScheduled;
- bool m_bModified;
+ list<RAS_MeshSlot> m_meshSlots;
RAS_IPolyMaterial* m_material;
- double* m_pOGLMatrix;
};
-#endif //__KX_BUCKET
+#endif //__RAS_MATERIAL_BUCKET
diff --git a/source/gameengine/Rasterizer/RAS_MeshObject.cpp b/source/gameengine/Rasterizer/RAS_MeshObject.cpp
index e441908532f..a907994bf57 100644
--- a/source/gameengine/Rasterizer/RAS_MeshObject.cpp
+++ b/source/gameengine/Rasterizer/RAS_MeshObject.cpp
@@ -26,70 +26,91 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
#include "RAS_MeshObject.h"
#include "RAS_IRasterizer.h"
#include "MT_MinMax.h"
#include "MT_Point3.h"
+#include <algorithm>
-STR_String RAS_MeshObject::s_emptyname = "";
-
-
+/* polygon sorting */
-KX_ArrayOptimizer::~KX_ArrayOptimizer()
+struct RAS_MeshObject::polygonSlot
{
- for (vector<KX_VertexArray*>::iterator itv = m_VertexArrayCache1.begin();
- !(itv == m_VertexArrayCache1.end());++itv)
- {
- delete (*itv);
- }
+ float m_z;
+ int m_index[4];
+
+ polygonSlot() {}
- for (vector<KX_IndexArray*>::iterator iti = m_IndexArrayCache1.begin();
- !(iti == m_IndexArrayCache1.end());++iti)
+ /* pnorm is the normal from the plane equation that the distance from is
+ * used to sort again. */
+ void get(const RAS_TexVert *vertexarray, const unsigned short *indexarray,
+ int offset, int nvert, const MT_Vector3& pnorm)
{
- delete (*iti);
- }
-
- m_TriangleArrayCount.clear();
- m_VertexArrayCache1.clear();
- m_IndexArrayCache1.clear();
+ MT_Vector3 center(0, 0, 0);
+ int i;
+ for(i=0; i<nvert; i++) {
+ m_index[i] = indexarray[offset+i];
+ center += vertexarray[m_index[i]].getXYZ();
+ }
-}
+ /* note we don't divide center by the number of vertices, since all
+ * polygons have the same number of vertices, and that we leave out
+ * the 4-th component of the plane equation since it is constant. */
+ m_z = MT_dot(pnorm, center);
+ }
+ void set(unsigned short *indexarray, int offset, int nvert)
+ {
+ int i;
+ for(i=0; i<nvert; i++)
+ indexarray[offset+i] = m_index[i];
+ }
+};
+
+struct RAS_MeshObject::backtofront
+{
+ bool operator()(const polygonSlot &a, const polygonSlot &b) const
+ {
+ return a.m_z < b.m_z;
+ }
+};
-RAS_MeshObject::RAS_MeshObject(int lightlayer)
- : m_bModified(true),
- m_lightlayer(lightlayer),
- m_zsort(false),
- m_MeshMod(true),
- m_class(0)
+struct RAS_MeshObject::fronttoback
{
-}
+ bool operator()(const polygonSlot &a, const polygonSlot &b) const
+ {
+ return a.m_z > b.m_z;
+ }
+};
+/* mesh object */
-bool RAS_MeshObject::MeshModified()
+STR_String RAS_MeshObject::s_emptyname = "";
+
+RAS_MeshObject::RAS_MeshObject(Mesh* mesh, int lightlayer)
+ : m_lightlayer(lightlayer),
+ m_bModified(true),
+ m_bMeshModified(true),
+ m_mesh(mesh),
+ m_bDeformed(false)
{
- return m_MeshMod;
}
-
RAS_MeshObject::~RAS_MeshObject()
{
- for (vector<RAS_Polygon*>::iterator it=m_Polygons.begin();!(it==m_Polygons.end());it++)
- {
- delete (*it);
- }
+ vector<RAS_Polygon*>::iterator it;
- ClearArrayData();
+ for(it=m_Polygons.begin(); it!=m_Polygons.end(); it++)
+ delete (*it);
}
-
+bool RAS_MeshObject::MeshModified()
+{
+ return m_bMeshModified;
+}
unsigned int RAS_MeshObject::GetLightLayer()
{
@@ -105,18 +126,21 @@ int RAS_MeshObject::NumMaterials()
const STR_String& RAS_MeshObject::GetMaterialName(unsigned int matid)
{
- RAS_MaterialBucket* bucket = GetMaterialBucket(matid);
+ RAS_MeshMaterial* mmat = GetMeshMaterial(matid);
+
+ if(mmat)
+ return mmat->m_bucket->GetPolyMaterial()->GetMaterialName();
- return bucket?bucket->GetPolyMaterial()->GetMaterialName():s_emptyname;
+ return s_emptyname;
}
-RAS_MaterialBucket* RAS_MeshObject::GetMaterialBucket(unsigned int matid)
+RAS_MeshMaterial* RAS_MeshObject::GetMeshMaterial(unsigned int matid)
{
if (m_materials.size() > 0 && (matid < m_materials.size()))
{
- RAS_MaterialBucket::Set::const_iterator it = m_materials.begin();
+ list<RAS_MeshMaterial>::iterator it = m_materials.begin();
while (matid--) ++it;
- return *it;
+ return &*it;
}
return NULL;
@@ -131,21 +155,24 @@ int RAS_MeshObject::NumPolygons()
-RAS_Polygon* RAS_MeshObject::GetPolygon(int num)
+RAS_Polygon* RAS_MeshObject::GetPolygon(int num) const
{
return m_Polygons[num];
}
-RAS_MaterialBucket::Set::iterator RAS_MeshObject::GetFirstMaterial()
+
+ list<RAS_MeshMaterial>::iterator GetFirstMaterial();
+ list<RAS_MeshMaterial>::iterator GetLastMaterial();
+list<RAS_MeshMaterial>::iterator RAS_MeshObject::GetFirstMaterial()
{
return m_materials.begin();
}
-RAS_MaterialBucket::Set::iterator RAS_MeshObject::GetLastMaterial()
+list<RAS_MeshMaterial>::iterator RAS_MeshObject::GetLastMaterial()
{
return m_materials.end();
}
@@ -168,355 +195,238 @@ const STR_String& RAS_MeshObject::GetName()
const STR_String& RAS_MeshObject::GetTextureName(unsigned int matid)
{
- RAS_MaterialBucket* bucket = GetMaterialBucket(matid);
+ RAS_MeshMaterial* mmat = GetMeshMaterial(matid);
- return bucket?bucket->GetPolyMaterial()->GetTextureName():s_emptyname;
+ if(mmat)
+ return mmat->m_bucket->GetPolyMaterial()->GetTextureName();
+
+ return s_emptyname;
}
+RAS_MeshMaterial *RAS_MeshObject::GetMeshMaterial(RAS_IPolyMaterial *mat)
+{
+ list<RAS_MeshMaterial>::iterator mit;
+ /* find a mesh material */
+ for(mit = m_materials.begin(); mit != m_materials.end(); mit++)
+ if(mit->m_bucket->GetPolyMaterial() == mat)
+ return &*mit;
-void RAS_MeshObject::AddPolygon(RAS_Polygon* poly)
-{
- m_Polygons.push_back(poly);
+ return NULL;
}
+RAS_Polygon* RAS_MeshObject::AddPolygon(RAS_MaterialBucket *bucket, int numverts)
+{
+ RAS_MeshMaterial *mmat;
+ RAS_Polygon *poly;
+ RAS_MeshSlot *slot;
+
+ /* find a mesh material */
+ mmat = GetMeshMaterial(bucket->GetPolyMaterial());
+ /* none found, create a new one */
+ if(!mmat) {
+ RAS_MeshMaterial meshmat;
+ meshmat.m_bucket = bucket;
+ meshmat.m_baseslot = meshmat.m_bucket->AddMesh(numverts);
+ m_materials.push_back(meshmat);
+ mmat = &m_materials.back();
+ }
+
+ /* add it to the bucket, this also adds new display arrays */
+ slot = mmat->m_baseslot;
+ slot->AddPolygon(numverts);
+
+ /* create a new polygon */
+ RAS_DisplayArray *darray = slot->CurrentDisplayArray();
+ poly = new RAS_Polygon(bucket, darray, numverts);
+ m_Polygons.push_back(poly);
+
+ return poly;
+}
void RAS_MeshObject::DebugColor(unsigned int abgr)
{
-/*
- int numpolys = NumPolygons();
- for (int i=0;i<numpolys;i++)
- {
+ /*int numpolys = NumPolygons();
+
+ for (int i=0;i<numpolys;i++) {
RAS_Polygon* poly = m_polygons[i];
for (int v=0;v<poly->VertexCount();v++)
- {
- RAS_TexVert* vtx = poly->GetVertex(v);
- vtx->setDebugRGBA(abgr);
- }
+ RAS_TexVert* vtx = poly->GetVertex(v)->setDebugRGBA(abgr);
}
*/
- m_debugcolor = abgr;
+ /* m_debugcolor = abgr; */
}
-
-
-void RAS_MeshObject::SchedulePoly(const KX_VertexIndex& idx,
- int numverts,
- RAS_IPolyMaterial* mat)
+void RAS_MeshObject::SetVertexColor(RAS_IPolyMaterial* mat,MT_Vector4 rgba)
{
- //int indexpos = m_IndexArrayCount[idx.m_vtxarray];
- //m_IndexArrayCount[idx.m_vtxarray] = indexpos + 3;
-
- KX_ArrayOptimizer* ao = GetArrayOptimizer(mat);
- ao->m_IndexArrayCache1[idx.m_vtxarray]->push_back(idx.m_indexarray[0]);
- ao->m_IndexArrayCache1[idx.m_vtxarray]->push_back(idx.m_indexarray[1]);
- ao->m_IndexArrayCache1[idx.m_vtxarray]->push_back(idx.m_indexarray[2]);
- if (!mat->UsesTriangles()) //if (!m_bUseTriangles)
- {
- //m_IndexArrayCount[idx.m_vtxarray] = indexpos+4;
- ao->m_IndexArrayCache1[idx.m_vtxarray]->push_back(idx.m_indexarray[3]);
- }
-}
-
+ RAS_MeshMaterial *mmat = GetMeshMaterial(mat);
+ RAS_MeshSlot *slot = mmat->m_baseslot;
+ RAS_MeshSlot::iterator it;
+ size_t i;
-
-void RAS_MeshObject::ScheduleWireframePoly(const KX_VertexIndex& idx,
- int numverts,
- int edgecode,
- RAS_IPolyMaterial* mat)
-{
- //int indexpos = m_IndexArrayCount[idx.m_vtxarray];
- int edgetrace = 1<<(numverts-1);
- bool drawedge = (edgecode & edgetrace)!=0;
- edgetrace = 1;
- int prevvert = idx.m_indexarray[numverts-1];
- KX_ArrayOptimizer* ao = GetArrayOptimizer(mat);
-
- for (int v = 0; v < numverts; v++)
- {
- unsigned int curvert = idx.m_indexarray[v];
- if (drawedge)
- {
- ao->m_IndexArrayCache1[idx.m_vtxarray]->push_back(prevvert);
- ao->m_IndexArrayCache1[idx.m_vtxarray]->push_back(curvert);
- }
- prevvert = curvert;
- drawedge = (edgecode & edgetrace)!=0;
- edgetrace*=2;
- }
- //m_IndexArrayCount[idx.m_vtxarray] = indexpos;
+ for(slot->begin(it); !slot->end(it); slot->next(it))
+ for(i=it.startvertex; i<it.endvertex; i++)
+ it.vertex[i].SetRGBA(rgba);
}
-int RAS_MeshObject::FindOrAddVertex(int vtxarray,
- const MT_Point3& xyz,
- const MT_Point2& uv,
- const MT_Point2& uv2,
- const MT_Vector4& tangent,
- const unsigned int rgbacolor,
- const MT_Vector3& normal,
- RAS_IPolyMaterial* mat,
- int orgindex)
+void RAS_MeshObject::AddVertex(RAS_Polygon *poly, int i,
+ const MT_Point3& xyz,
+ const MT_Point2& uv,
+ const MT_Point2& uv2,
+ const MT_Vector4& tangent,
+ const unsigned int rgba,
+ const MT_Vector3& normal,
+ bool flat,
+ int origindex)
{
- KX_ArrayOptimizer* ao = GetArrayOptimizer(mat);//*(m_matVertexArrays[*mat]);
-
- int numverts = ao->m_VertexArrayCache1[vtxarray]->size();//m_VertexArrayCount[vtxarray];
- RAS_TexVert newvert(xyz,uv,uv2,tangent,rgbacolor,normal, 0);
-#define KX_FIND_SHARED_VERTICES
-#ifdef KX_FIND_SHARED_VERTICES
+ RAS_TexVert texvert(xyz, uv, uv2, tangent, rgba, normal, flat, origindex);
+ RAS_MeshMaterial *mmat;
+ RAS_DisplayArray *darray;
+ RAS_MeshSlot *slot;
+ int offset;
- for (std::vector<RAS_MatArrayIndex>::iterator it = m_xyz_index_to_vertex_index_mapping[orgindex].begin();
- it != m_xyz_index_to_vertex_index_mapping[orgindex].end();
- it++)
- {
- if ((*it).m_arrayindex1 == ao->m_index1 &&
- (*it).m_array == vtxarray &&
- *(*it).m_matid == *mat &&
- (*ao->m_VertexArrayCache1[vtxarray])[(*it).m_index].closeTo(&newvert)
- )
+ mmat = GetMeshMaterial(poly->GetMaterial()->GetPolyMaterial());
+ slot = mmat->m_baseslot;
+ darray = slot->CurrentDisplayArray();
+
+ if(!flat) {
+ /* find vertices shared between faces, with the restriction
+ * that they exist in the same display array, and have the
+ * same uv coordinate etc */
+ vector<SharedVertex>& sharedmap = m_sharedvertex_map[origindex];
+ vector<SharedVertex>::iterator it;
+
+ for(it = sharedmap.begin(); it != sharedmap.end(); it++)
{
- return (*it).m_index;
+ if(it->m_darray != darray)
+ continue;
+ if(!it->m_darray->m_vertex[it->m_offset].closeTo(&texvert))
+ continue;
+
+ /* found one, add it and we're done */
+ if(poly->IsVisible())
+ slot->AddPolygonVertex(it->m_offset);
+ poly->SetVertexOffset(i, it->m_offset);
+ return;
}
}
-#endif // KX_FIND_SHARED_VERTICES
-
- // no vertex found, add one
- ao->m_VertexArrayCache1[vtxarray]->push_back(newvert);
- // printf("(%f,%f,%f) ",xyz[0],xyz[1],xyz[2]);
- RAS_MatArrayIndex idx;
- idx.m_arrayindex1 = ao->m_index1;
- idx.m_array = vtxarray;
- idx.m_index = numverts;
- idx.m_matid = mat;
- m_xyz_index_to_vertex_index_mapping[orgindex].push_back(idx);
-
- return numverts;
-}
-
-
-
-const vecVertexArray& RAS_MeshObject::GetVertexCache (RAS_IPolyMaterial* mat)
-{
- KX_ArrayOptimizer* ao = GetArrayOptimizer(mat);//*(m_matVertexArrays[*mat]);
- return ao->m_VertexArrayCache1;
+ /* no shared vertex found, add a new one */
+ offset = slot->AddVertex(texvert);
+ if(poly->IsVisible())
+ slot->AddPolygonVertex(offset);
+ poly->SetVertexOffset(i, offset);
+
+ if(!flat) {
+ SharedVertex shared;
+ shared.m_darray = darray;
+ shared.m_offset = offset;
+ m_sharedvertex_map[origindex].push_back(shared);
+ }
}
-
-
-int RAS_MeshObject::GetVertexArrayLength(RAS_IPolyMaterial* mat)
+int RAS_MeshObject::NumVertices(RAS_IPolyMaterial* mat)
{
- int len = 0;
+ RAS_MeshMaterial *mmat;
+ RAS_MeshSlot *slot;
+ RAS_MeshSlot::iterator it;
+ size_t len = 0;
- const vecVertexArray & vertexvec = GetVertexCache(mat);
- vector<KX_VertexArray*>::const_iterator it = vertexvec.begin();
+ mmat = GetMeshMaterial(mat);
+ slot = mmat->m_baseslot;
+ for(slot->begin(it); !slot->end(it); slot->next(it))
+ len += it.endvertex - it.startvertex;
- for (; it != vertexvec.end(); ++it)
- {
- len += (*it)->size();
- }
-
return len;
}
-
RAS_TexVert* RAS_MeshObject::GetVertex(unsigned int matid,
unsigned int index)
{
- RAS_TexVert* vertex = NULL;
-
- RAS_MaterialBucket* bucket = GetMaterialBucket(matid);
- if (bucket)
- {
- RAS_IPolyMaterial* mat = bucket->GetPolyMaterial();
- if (mat)
- {
- const vecVertexArray & vertexvec = GetVertexCache(mat);
- vector<KX_VertexArray*>::const_iterator it = vertexvec.begin();
-
- for (unsigned int len = 0; it != vertexvec.end(); ++it)
- {
- if (index < len + (*it)->size())
- {
- vertex = &(*(*it))[index-len];
- break;
- }
- else
- {
- len += (*it)->size();
- }
- }
- }
- }
-
- return vertex;
-}
-
-
+ RAS_MeshMaterial *mmat;
+ RAS_MeshSlot *slot;
+ RAS_MeshSlot::iterator it;
+ size_t len;
-const vecIndexArrays& RAS_MeshObject::GetIndexCache (RAS_IPolyMaterial* mat)
-{
- KX_ArrayOptimizer* ao = GetArrayOptimizer(mat);//*(m_matVertexArrays[*mat]);
-
- return ao->m_IndexArrayCache1;
-}
+ mmat = GetMeshMaterial(matid);
-
-
-KX_ArrayOptimizer* RAS_MeshObject::GetArrayOptimizer(RAS_IPolyMaterial* polymat)
-{
- KX_ArrayOptimizer** aop = (m_matVertexArrayS[*polymat]);
-
- if (aop)
- return *aop;
+ if(!mmat)
+ return NULL;
- int numelements = m_matVertexArrayS.size();
- m_sortedMaterials.push_back(polymat);
-
- KX_ArrayOptimizer* ao = new KX_ArrayOptimizer(numelements);
- m_matVertexArrayS.insert(*polymat,ao);
+ slot = mmat->m_baseslot;
+ len = 0;
+ for(slot->begin(it); !slot->end(it); slot->next(it)) {
+ if(index >= len + it.endvertex - it.startvertex)
+ len += it.endvertex - it.startvertex;
+ else
+ return &it.vertex[index - len];
+ }
- return ao;
+ return NULL;
}
-
-
-void RAS_MeshObject::Bucketize(double* oglmatrix,
- void* clientobj,
- bool useObjectColor,
- const MT_Vector4& rgbavec)
+void RAS_MeshObject::AddMeshUser(void *clientobj)
{
- KX_MeshSlot ms;
- ms.m_clientObj = clientobj;
- ms.m_mesh = this;
- ms.m_OpenGLMatrix = oglmatrix;
- ms.m_bObjectColor = useObjectColor;
- ms.m_RGBAcolor = rgbavec;
-
- for (RAS_MaterialBucket::Set::iterator it = m_materials.begin();it!=m_materials.end();++it)
- {
- RAS_MaterialBucket* bucket = *it;
- bucket->SchedulePolygons(0);
-// KX_ArrayOptimizer* oa = GetArrayOptimizer(bucket->GetPolyMaterial());
- bucket->SetMeshSlot(ms);
- }
+ list<RAS_MeshMaterial>::iterator it;
-}
-
-
-
-void RAS_MeshObject::MarkVisible(double* oglmatrix,
- void* clientobj,
- bool visible,
- bool useObjectColor,
- const MT_Vector4& rgbavec)
-{
- KX_MeshSlot ms;
- ms.m_clientObj = clientobj;
- ms.m_mesh = this;
- ms.m_OpenGLMatrix = oglmatrix;
- ms.m_RGBAcolor = rgbavec;
- ms.m_bObjectColor= useObjectColor;
-
- for (RAS_MaterialBucket::Set::iterator it = m_materials.begin();it!=m_materials.end();++it)
- {
- RAS_MaterialBucket* bucket = *it;
- bucket->SchedulePolygons(0);
-// KX_ArrayOptimizer* oa = GetArrayOptimizer(bucket->GetPolyMaterial());
- bucket->MarkVisibleMeshSlot(ms,visible,useObjectColor,rgbavec);
+ for(it = m_materials.begin();it!=m_materials.end();++it) {
+ /* always copy from the base slot, which is never removed
+ * since new objects can be created with the same mesh data */
+ RAS_MeshSlot *ms = it->m_bucket->CopyMesh(it->m_baseslot);
+ ms->m_clientObj = clientobj;
+ it->m_slots.insert(clientobj, ms);
}
}
-
-void RAS_MeshObject::RemoveFromBuckets(double* oglmatrix,
- void* clientobj)
+void RAS_MeshObject::UpdateBuckets(void* clientobj,
+ double* oglmatrix,
+ bool useObjectColor,
+ const MT_Vector4& rgbavec,
+ bool visible,
+ bool culled)
{
- KX_MeshSlot ms;
- ms.m_clientObj = clientobj;
- ms.m_mesh = this;
- ms.m_OpenGLMatrix = oglmatrix;
-
- for (RAS_MaterialBucket::Set::iterator it = m_materials.begin();it!=m_materials.end();++it)
- {
- RAS_MaterialBucket* bucket = *it;
-// RAS_IPolyMaterial* polymat = bucket->GetPolyMaterial();
- bucket->SchedulePolygons(0);
- //KX_ArrayOptimizer* oa = GetArrayOptimizer(polymat);
- bucket->RemoveMeshSlot(ms);
- }
-
-}
+ list<RAS_MeshMaterial>::iterator it;
+ for(it = m_materials.begin();it!=m_materials.end();++it) {
+ RAS_MeshSlot **msp = it->m_slots[clientobj];
+ if(!msp)
+ continue;
-/*
- * RAS_MeshObject::GetVertex returns the vertex located somewhere in the vertexpool
- * it is the clients responsibility to make sure the array and index are valid
- */
-RAS_TexVert* RAS_MeshObject::GetVertex(short array,
- unsigned int index,
- RAS_IPolyMaterial* polymat)
-{
- KX_ArrayOptimizer* ao = GetArrayOptimizer(polymat);//*(m_matVertexArrays[*polymat]);
- return &((*(ao->m_VertexArrayCache1)[array])[index]);
-}
+ RAS_MeshSlot *ms = *msp;
+ ms->m_mesh = this;
+ ms->m_OpenGLMatrix = oglmatrix;
+ ms->m_bObjectColor = useObjectColor;
+ ms->m_RGBAcolor = rgbavec;
+ ms->m_bVisible = visible;
+ ms->m_bCulled = culled || !visible;
-
-void RAS_MeshObject::ClearArrayData()
-{
- for (int i=0;i<m_matVertexArrayS.size();i++)
- {
- KX_ArrayOptimizer** ao = m_matVertexArrayS.at(i);
- if (ao)
- delete *ao;
+ /* split if necessary */
+ ms->Split();
}
}
-
-
-/**
- * RAS_MeshObject::CreateNewVertices creates vertices within sorted pools of vertices that share same material
-*/
-int RAS_MeshObject::FindVertexArray(int numverts,
- RAS_IPolyMaterial* polymat)
+void RAS_MeshObject::RemoveFromBuckets(void *clientobj)
{
-// bool found=false;
- int array=-1;
+ list<RAS_MeshMaterial>::iterator it;
- KX_ArrayOptimizer* ao = GetArrayOptimizer(polymat);
+ for(it = m_materials.begin();it!=m_materials.end();++it) {
+ RAS_MeshSlot **msp = it->m_slots[clientobj];
- for (unsigned int i=0;i<ao->m_VertexArrayCache1.size();i++)
- {
- if ( (ao->m_TriangleArrayCount[i] + (numverts-2)) < BUCKET_MAX_TRIANGLES)
- {
- if((ao->m_VertexArrayCache1[i]->size()+numverts < BUCKET_MAX_INDICES))
- {
- array = i;
- ao->m_TriangleArrayCount[array]+=numverts-2;
- break;
- }
- }
- }
+ if(!msp)
+ continue;
- if (array == -1)
- {
- array = ao->m_VertexArrayCache1.size();
- vector<RAS_TexVert>* va = new vector<RAS_TexVert>;
- ao->m_VertexArrayCache1.push_back(va);
- KX_IndexArray *ia = new KX_IndexArray();
- ao->m_IndexArrayCache1.push_back(ia);
- ao->m_TriangleArrayCount.push_back(numverts-2);
- }
+ RAS_MeshSlot *ms = *msp;
- return array;
+ it->m_bucket->RemoveMesh(ms);
+ it->m_slots.remove(clientobj);
+ }
}
-
-
-
//void RAS_MeshObject::Transform(const MT_Transform& trans)
//{
//m_trans.translate(MT_Vector3(0,0,1));//.operator *=(trans);
@@ -538,159 +448,62 @@ void RAS_MeshObject::RelativeTransform(const MT_Vector3& vec)
}
*/
-
-
-void RAS_MeshObject::UpdateMaterialList()
-{
- m_materials.clear();
- unsigned int numpolys = m_Polygons.size();
- // for all polygons, find out which material they use, and add it to the set of materials
- for (unsigned int i=0;i<numpolys;i++)
- {
- m_materials.insert(m_Polygons[i]->GetMaterial());
+void RAS_MeshObject::SortPolygons(RAS_MeshSlot& ms, const MT_Transform &transform)
+{
+ // Limitations: sorting is quite simple, and handles many
+ // cases wrong, partially due to polygons being sorted per
+ // bucket.
+ //
+ // a) mixed triangles/quads are sorted wrong
+ // b) mixed materials are sorted wrong
+ // c) more than 65k faces are sorted wrong
+ // d) intersecting objects are sorted wrong
+ // e) intersecting polygons are sorted wrong
+ //
+ // a) can be solved by making all faces either triangles or quads
+ // if they need to be z-sorted. c) could be solved by allowing
+ // larger buckets, b) and d) cannot be solved easily if we want
+ // to avoid excessive state changes while drawing. e) would
+ // require splitting polygons.
+
+ RAS_MeshSlot::iterator it;
+ size_t j;
+
+ for(ms.begin(it); !ms.end(it); ms.next(it)) {
+ unsigned int nvert = (int)it.array->m_type;
+ unsigned int totpoly = it.totindex/nvert;
+
+ if(totpoly <= 1)
+ continue;
+ if(it.array->m_type == RAS_DisplayArray::LINE)
+ continue;
+
+ // Extract camera Z plane...
+ const MT_Vector3 pnorm(transform.getBasis()[2]);
+ // unneeded: const MT_Scalar pval = transform.getOrigin()[2];
+
+ vector<polygonSlot> slots(totpoly);
+
+ /* get indices and z into temporary array */
+ for(j=0; j<totpoly; j++)
+ slots[j].get(it.vertex, it.index, j*nvert, nvert, pnorm);
+
+ /* sort (stable_sort might be better, if flickering happens?) */
+ std::sort(slots.begin(), slots.end(), backtofront());
+
+ /* get indices from temporary array again */
+ for(j=0; j<totpoly; j++)
+ slots[j].set(it.index, j*nvert, nvert);
}
}
-struct RAS_MeshObject::polygonSlot
-{
- float m_z;
- RAS_Polygon *m_poly;
-
- polygonSlot(float z, RAS_Polygon* poly) :
- m_z(z),
- m_poly(poly)
- {}
- /**
- * pnorm and pval form the plane equation that the distance from is used to
- * sort against.
- */
- polygonSlot(const MT_Vector3 &pnorm, const MT_Scalar &pval, RAS_MeshObject *mesh, RAS_Polygon* poly) :
- m_poly(poly)
- {
- const KX_VertexIndex &base = m_poly->GetIndexBase();
- RAS_TexVert *vert = mesh->GetVertex(base.m_vtxarray, base.m_indexarray[0], poly->GetMaterial()->GetPolyMaterial());
- m_z = MT_dot(pnorm, vert->getLocalXYZ()) + pval;
-
- for(int i = 1; i < m_poly->VertexCount(); i++)
- {
- vert = mesh->GetVertex(base.m_vtxarray, base.m_indexarray[i], poly->GetMaterial()->GetPolyMaterial());
- float z = MT_dot(pnorm, vert->getLocalXYZ()) + pval;
- m_z += z;
- }
- m_z /= m_poly->VertexCount();
- }
-};
-
-struct RAS_MeshObject::backtofront
-{
- bool operator()(const polygonSlot &a, const polygonSlot &b) const
- {
- return a.m_z < b.m_z;
- }
-};
-struct RAS_MeshObject::fronttoback
+void RAS_MeshObject::SchedulePolygons(int drawingmode)
{
- bool operator()(const polygonSlot &a, const polygonSlot &b) const
- {
- return a.m_z > b.m_z;
- }
-};
-
-
-void RAS_MeshObject::SortPolygons(const MT_Transform &transform)
-{
- if (!m_zsort)
- return;
-
- // Extract camera Z plane...
- const MT_Vector3 pnorm(transform.getBasis()[2]);
- const MT_Scalar pval = transform.getOrigin()[2];
-
- unsigned int numpolys = m_Polygons.size();
- std::multiset<polygonSlot, backtofront> alphapolyset;
- std::multiset<polygonSlot, fronttoback> solidpolyset;
-
- for (unsigned int p = 0; p < numpolys; p++)
- {
- RAS_Polygon* poly = m_Polygons[p];
- if (poly->IsVisible())
- {
- if (poly->GetMaterial()->GetPolyMaterial()->IsTransparant())
- {
- alphapolyset.insert(polygonSlot(pnorm, pval, this, poly));
- } else {
- solidpolyset.insert(polygonSlot(pnorm, pval, this, poly));
- }
- }
- }
-
- // Clear current array data.
- for (RAS_MaterialBucket::Set::iterator it = m_materials.begin();it!=m_materials.end();++it)
- {
- vector<KX_IndexArray*> *indexcache = &GetArrayOptimizer((*it)->GetPolyMaterial())->m_IndexArrayCache1;
- for (vector<KX_IndexArray*>::iterator iit = indexcache->begin(); iit != indexcache->end(); ++iit)
- (*iit)->clear();
- }
-
- std::multiset<polygonSlot, fronttoback>::iterator sit = solidpolyset.begin();
- for (; sit != solidpolyset.end(); ++sit)
- SchedulePoly((*sit).m_poly->GetVertexIndexBase(), (*sit).m_poly->VertexCount(), (*sit).m_poly->GetMaterial()->GetPolyMaterial());
-
- std::multiset<polygonSlot, backtofront>::iterator ait = alphapolyset.begin();
- for (; ait != alphapolyset.end(); ++ait)
- SchedulePoly((*ait).m_poly->GetVertexIndexBase(), (*ait).m_poly->VertexCount(), (*ait).m_poly->GetMaterial()->GetPolyMaterial());
-}
-
-
-void RAS_MeshObject::SchedulePolygons(const MT_Transform &transform, int drawingmode)
-{
-// int nummaterials = m_materials.size();
- int i;
-
if (m_bModified)
{
- for (RAS_MaterialBucket::Set::iterator it = m_materials.begin();it!=m_materials.end();++it)
- {
- RAS_MaterialBucket* bucket = *it;
-
- bucket->SchedulePolygons(drawingmode);
- if (bucket->GetPolyMaterial()->IsZSort())
- m_zsort = true;
- }
-
- int numpolys = m_Polygons.size();
-
- if ((drawingmode > RAS_IRasterizer::KX_BOUNDINGBOX) &&
- (drawingmode < RAS_IRasterizer::KX_SOLID))
- {
- for (i=0;i<numpolys;i++)
- {
- RAS_Polygon* poly = m_Polygons[i];
- if (poly->IsVisible())
- ScheduleWireframePoly(poly->GetVertexIndexBase(),poly->VertexCount(),poly->GetEdgeCode()
- ,poly->GetMaterial()->GetPolyMaterial());
-
- }
- m_zsort = false;
- }
- else
- {
- if (!m_zsort)
- {
- for (i=0;i<numpolys;i++)
- {
- RAS_Polygon* poly = m_Polygons[i];
- if (poly->IsVisible())
- {
- SchedulePoly(poly->GetVertexIndexBase(),poly->VertexCount(),poly->GetMaterial()->GetPolyMaterial());
- }
- }
- }
- }
-
m_bModified = false;
-
- m_MeshMod = true;
+ m_bMeshModified = true;
}
}
+
diff --git a/source/gameengine/Rasterizer/RAS_MeshObject.h b/source/gameengine/Rasterizer/RAS_MeshObject.h
index 89c472cd0d4..0d35a2f402b 100644
--- a/source/gameengine/Rasterizer/RAS_MeshObject.h
+++ b/source/gameengine/Rasterizer/RAS_MeshObject.h
@@ -36,6 +36,7 @@
#include <vector>
#include <set>
+#include <list>
#include "RAS_Polygon.h"
#include "RAS_MaterialBucket.h"
@@ -43,221 +44,116 @@
#include "GEN_HashedPtr.h"
-/**
- * This class holds an array of vertices and indicies.
- */
-class KX_ArrayOptimizer
-{
-public:
- KX_ArrayOptimizer(int index)
- : m_index1(index)
- {};
- virtual ~KX_ArrayOptimizer();
-
- vector<KX_VertexArray*> m_VertexArrayCache1;
- vector<int> m_TriangleArrayCount;
- vector<KX_IndexArray*> m_IndexArrayCache1;
-
- /**
- order in which they are stored into the mesh
- */
- int m_index1;
-};
-
-/**
- * This struct holds a triangle.
- */
-struct RAS_TriangleIndex
-{
-public:
- int m_index[3];
- int m_array;
- RAS_IPolyMaterial* m_matid;
- bool m_collider;
-};
-
-/**
- * This class looks horribly broken. Only m_matid is used, and
- * m_matid is a (int) RAS_IPolyMaterial*.
- * --> m_matid == lhs.m_matid should be *m_matid == *lhs.m_matid
- */
-class RAS_MatArrayIndex
-{
-public:
-
- int m_arrayindex1;
- RAS_IPolyMaterial* m_matid;
- int m_array;
- int m_index;
+struct Mesh;
-/*
- inline bool Less(const RAS_MatArrayIndex& lhs) const {
- bool result =
- ( (m_matid < lhs.m_matid) ||
- ((m_matid == lhs.m_matid)&&(m_array < lhs.m_array)) ||
- ((m_matid == lhs.m_matid) && (m_array == lhs.m_array) &&
- (m_index < lhs.m_index))
-
- );
- return result;
-
- }
-*/
-
-};
-/*
-inline bool operator <( const RAS_MatArrayIndex& rhs,const RAS_MatArrayIndex& lhs)
-{
- return ( rhs.Less(lhs));
-}*/
+/* RAS_MeshObject is a mesh used for rendering. It stores polygons,
+ * but the actual vertices and index arrays are stored in material
+ * buckets, referenced by the list of RAS_MeshMaterials. */
-/**
- * RAS_MeshObject stores mesh data for the renderer.
- */
class RAS_MeshObject
{
-
- // GEN_Map<class RAS_IPolyMaterial,KX_ArrayOptimizer*> m_matVertexArrayS;
- //vector<class RAS_IPolyMaterial*,KX_ArrayOptimizer> m_vertexArrays;
- virtual KX_ArrayOptimizer* GetArrayOptimizer(RAS_IPolyMaterial* polymat);
- //vector<RAS_Polygon*> m_polygons;
-
+private:
unsigned int m_debugcolor;
- bool m_bModified;
int m_lightlayer;
-
- vector<class RAS_Polygon*> m_Polygons;
+
+ bool m_bModified;
+ bool m_bMeshModified;
+
STR_String m_name;
static STR_String s_emptyname;
- bool m_zsort;
- bool m_MeshMod;
+ vector<class RAS_Polygon*> m_Polygons;
+
+ /* polygon sorting */
struct polygonSlot;
struct backtofront;
struct fronttoback;
-
protected:
- enum { BUCKET_MAX_INDICES = 65535 };//2048};//8192};
- enum { BUCKET_MAX_TRIANGLES = 65535 };
-
- GEN_Map<class RAS_IPolyMaterial,KX_ArrayOptimizer*> m_matVertexArrayS;
-
- RAS_MaterialBucket::Set m_materials;
+ list<RAS_MeshMaterial> m_materials;
+ Mesh* m_mesh;
+ bool m_bDeformed;
+
public:
// for now, meshes need to be in a certain layer (to avoid sorting on lights in realtime)
- RAS_MeshObject(int lightlayer);
+ RAS_MeshObject(Mesh* mesh, int lightlayer);
virtual ~RAS_MeshObject();
- vector<RAS_IPolyMaterial*> m_sortedMaterials;
- vector<vector<RAS_MatArrayIndex> > m_xyz_index_to_vertex_index_mapping;
- vector<RAS_TriangleIndex > m_triangle_indices;
-
- int m_class;
- unsigned int GetLightLayer();
+ bool IsDeformed() { return m_bDeformed; }
+
+ /* materials */
int NumMaterials();
const STR_String& GetMaterialName(unsigned int matid);
- RAS_MaterialBucket* GetMaterialBucket(unsigned int matid);
const STR_String& GetTextureName(unsigned int matid);
- virtual void AddPolygon(RAS_Polygon* poly);
- void UpdateMaterialList();
-
- int NumPolygons();
- RAS_Polygon* GetPolygon(int num);
-
- virtual void Bucketize(
- double* oglmatrix,
- void* clientobj,
- bool useObjectColor,
- const MT_Vector4& rgbavec
- );
- void RemoveFromBuckets(
- double* oglmatrix,
- void* clientobj
- );
+ RAS_MeshMaterial* GetMeshMaterial(unsigned int matid);
+ RAS_MeshMaterial* GetMeshMaterial(RAS_IPolyMaterial *mat);
- void MarkVisible(
- double* oglmatrix,
- void* clientobj,
- bool visible,
- bool useObjectColor,
- const MT_Vector4& rgbavec
- );
+ list<RAS_MeshMaterial>::iterator GetFirstMaterial();
+ list<RAS_MeshMaterial>::iterator GetLastMaterial();
- void DebugColor(unsigned int abgr);
-
- /**
- * Sorts the polygons by their transformed z values.
- */
- void SortPolygons(const MT_Transform &transform);
+ unsigned int GetLightLayer();
- void SchedulePolygons(
- const MT_Transform &transform,
- int drawingmode
- );
+ /* name */
+ void SetName(STR_String name);
+ const STR_String& GetName();
- void ClearArrayData();
-
- RAS_MaterialBucket::Set::iterator GetFirstMaterial();
- RAS_MaterialBucket::Set::iterator GetLastMaterial();
-
- virtual RAS_TexVert* GetVertex(
- short array,
- unsigned int index,
- RAS_IPolyMaterial* polymat
- );
-
- virtual int FindVertexArray(
- int numverts,
- RAS_IPolyMaterial* polymat
- );
-
- void SchedulePoly(
- const KX_VertexIndex& idx,
- int numverts,
- RAS_IPolyMaterial* mat
- );
+ /* modification state */
+ bool MeshModified();
+ void SetMeshModified(bool v){m_bMeshModified = v;}
- void ScheduleWireframePoly(
- const KX_VertexIndex& idx,
- int numverts,
- int edgecode,
- RAS_IPolyMaterial* mat
- );
-
- // find (and share) or add vertices
- // for some speedup, only the last 20 added vertices are searched for equality
+ /* original blender mesh */
+ Mesh* GetMesh() { return m_mesh; }
+
+ /* mesh construction */
- virtual int FindOrAddVertex(
- int vtxarray,
+ virtual RAS_Polygon* AddPolygon(RAS_MaterialBucket *bucket, int numverts);
+ virtual void AddVertex(RAS_Polygon *poly, int i,
const MT_Point3& xyz,
const MT_Point2& uv,
const MT_Point2& uv2,
const MT_Vector4& tangent,
const unsigned int rgbacolor,
const MT_Vector3& normal,
- RAS_IPolyMaterial* mat,
- int orgindex
- );
-
- const vecVertexArray& GetVertexCache (RAS_IPolyMaterial* mat);
+ bool flat,
+ int origindex);
+
+ void SchedulePolygons(int drawingmode);
+
+ /* vertex and polygon acces */
+ int NumVertices(RAS_IPolyMaterial* mat);
+ RAS_TexVert* GetVertex(unsigned int matid, unsigned int index);
+
+ int NumPolygons();
+ RAS_Polygon* GetPolygon(int num) const;
- int GetVertexArrayLength(RAS_IPolyMaterial* mat);
+ /* buckets */
+ virtual void AddMeshUser(void *clientobj);
+ virtual void UpdateBuckets(
+ void* clientobj,
+ double* oglmatrix,
+ bool useObjectColor,
+ const MT_Vector4& rgbavec,
+ bool visible,
+ bool culled);
- RAS_TexVert* GetVertex(
- unsigned int matid,
- unsigned int index
- );
+ void RemoveFromBuckets(void *clientobj);
- const vecIndexArrays& GetIndexCache (RAS_IPolyMaterial* mat);
- void SetName(STR_String name);
- const STR_String& GetName();
+ /* colors */
+ void DebugColor(unsigned int abgr);
+ void SetVertexColor(RAS_IPolyMaterial* mat,MT_Vector4 rgba);
+
+ /* polygon sorting by Z for alpha */
+ void SortPolygons(RAS_MeshSlot& ms, const MT_Transform &transform);
- bool MeshModified();
- void SetMeshModified(bool v){m_MeshMod = v;}
+ /* for construction to find shared vertices */
+ struct SharedVertex {
+ RAS_DisplayArray *m_darray;
+ int m_offset;
+ };
+ vector<vector<SharedVertex> > m_sharedvertex_map;
};
#endif //__RAS_MESHOBJECT
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Blur2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Blur2DFilter.h
new file mode 100644
index 00000000000..81821639489
--- /dev/null
+++ b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Blur2DFilter.h
@@ -0,0 +1,51 @@
+/**
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __RAS_BLUR2DFILTER
+#define __RAS_BLUR2DFILTER
+
+const char * BlurFragmentShader=STRINGIFY(
+uniform sampler2D bgl_RenderedTexture;
+uniform vec2 bgl_TextureCoordinateOffset[9];
+
+void main(void)
+{
+ vec4 sample[9];
+
+ for (int i = 0; i < 9; i++)
+ {
+ sample[i] = texture2D(bgl_RenderedTexture,
+ gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]);
+ }
+
+ gl_FragColor = (sample[0] + (2.0*sample[1]) + sample[2] +
+ (2.0*sample[3]) + sample[4] + (2.0*sample[5]) +
+ sample[6] + (2.0*sample[7]) + sample[8]) / 13.0;
+}
+);
+#endif
+
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Dilation2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Dilation2DFilter.h
new file mode 100644
index 00000000000..2ee75396f42
--- /dev/null
+++ b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Dilation2DFilter.h
@@ -0,0 +1,51 @@
+/**
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __RAS_DILATION2DFILTER
+#define __RAS_DILATION2DFILTER
+
+const char * DilationFragmentShader=STRINGIFY(
+uniform sampler2D bgl_RenderedTexture;
+uniform vec2 bgl_TextureCoordinateOffset[9];
+
+void main(void)
+{
+ vec4 sample[9];
+ vec4 maxValue = vec4(0.0);
+
+ for (int i = 0; i < 9; i++)
+ {
+ sample[i] = texture2D(bgl_RenderedTexture,
+ gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]);
+ maxValue = max(sample[i], maxValue);
+ }
+
+ gl_FragColor = maxValue;
+}
+);
+#endif
+
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h
new file mode 100644
index 00000000000..d3ce829bab0
--- /dev/null
+++ b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h
@@ -0,0 +1,50 @@
+/**
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __RAS_EROSION2DFILTER
+#define __RAS_EROSION2DFILTER
+
+const char * ErosionFragmentShader=STRINGIFY(
+uniform sampler2D bgl_RenderedTexture;
+uniform vec2 bgl_TextureCoordinateOffset[9];
+
+void main(void)
+{
+ vec4 sample[9];
+ vec4 minValue = vec4(1.0);
+
+ for (int i = 0; i < 9; i++)
+ {
+ sample[i] = texture2D(bgl_RenderedTexture,
+ gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]);
+ minValue = min(sample[i], minValue);
+ }
+
+ gl_FragColor = minValue;
+}
+);
+#endif
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_GrayScale2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_GrayScale2DFilter.h
new file mode 100644
index 00000000000..ae51308e9a4
--- /dev/null
+++ b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_GrayScale2DFilter.h
@@ -0,0 +1,41 @@
+/**
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __RAS_GRAYSCALE2DFILTER
+#define __RAS_GRAYSCALE2DFILTER
+
+const char * GrayScaleFragmentShader=STRINGIFY(
+uniform sampler2D bgl_RenderedTexture;
+
+void main(void)
+{
+ vec4 texcolor = texture2D(bgl_RenderedTexture, gl_TexCoord[0].st);
+ float gray = dot(texcolor.rgb, vec3(0.299, 0.587, 0.114));
+ gl_FragColor = vec4(gray, gray, gray, texcolor.a);
+}
+);
+#endif
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Invert2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Invert2DFilter.h
new file mode 100644
index 00000000000..f723f619f68
--- /dev/null
+++ b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Invert2DFilter.h
@@ -0,0 +1,41 @@
+/**
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __RAS_INVERT2DFILTER
+#define __RAS_INVERT2DFILTER
+
+const char * InvertFragmentShader=STRINGIFY(
+uniform sampler2D bgl_RenderedTexture;
+
+void main(void)
+{
+ vec4 texcolor = texture2D(bgl_RenderedTexture, gl_TexCoord[0].st);
+ gl_FragColor.rgb = 1.0 - texcolor.rgb;
+ gl_FragColor.a = texcolor.a;
+}
+);
+#endif
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Laplacian2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Laplacian2DFilter.h
new file mode 100644
index 00000000000..bfbb40b2fc9
--- /dev/null
+++ b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Laplacian2DFilter.h
@@ -0,0 +1,53 @@
+/**
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __RAS_LAPLACION2DFILTER
+#define __RAS_LAPLACION2DFILTER
+
+const char * LaplacionFragmentShader=STRINGIFY(
+uniform sampler2D bgl_RenderedTexture;
+uniform vec2 bgl_TextureCoordinateOffset[9];
+
+void main(void)
+{
+ vec4 sample[9];
+
+ for (int i = 0; i < 9; i++)
+ {
+ sample[i] = texture2D(bgl_RenderedTexture,
+ gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]);
+ }
+
+ gl_FragColor = (sample[4] * 8.0) -
+ (sample[0] + sample[1] + sample[2] +
+ sample[3] + sample[5] +
+ sample[6] + sample[7] + sample[8]);
+ gl_FragColor = vec4(gl_FragColor.rgb, 1.0);
+}
+);
+#endif
+
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Prewitt2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Prewitt2DFilter.h
new file mode 100644
index 00000000000..0cbf8a7a802
--- /dev/null
+++ b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Prewitt2DFilter.h
@@ -0,0 +1,58 @@
+/**
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __RAS_PREWITT2DFILTER
+#define __RAS_PREWITT2DFILTER
+
+const char * PrewittFragmentShader=STRINGIFY(
+uniform sampler2D bgl_RenderedTexture;
+uniform vec2 bgl_TextureCoordinateOffset[9];
+
+void main(void)
+{
+ vec4 sample[9];
+
+ for (int i = 0; i < 9; i++)
+ {
+ sample[i] = texture2D(bgl_RenderedTexture,
+ gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]);
+ }
+
+ vec4 horizEdge = sample[2] + sample[5] + sample[8] -
+ (sample[0] + sample[3] + sample[6]);
+
+ vec4 vertEdge = sample[0] + sample[1] + sample[2] -
+ (sample[6] + sample[7] + sample[8]);
+
+ gl_FragColor.rgb = sqrt((horizEdge.rgb * horizEdge.rgb) +
+ (vertEdge.rgb * vertEdge.rgb));
+ gl_FragColor.a = 1.0;
+}
+
+);
+#endif
+
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sepia2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sepia2DFilter.h
new file mode 100644
index 00000000000..ca431af4cd7
--- /dev/null
+++ b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sepia2DFilter.h
@@ -0,0 +1,41 @@
+/**
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __RAS_SEPIA2DFILTER
+#define __RAS_SEPIA2DFILTER
+
+const char * SepiaFragmentShader=STRINGIFY(
+uniform sampler2D bgl_RenderedTexture;
+
+void main(void)
+{
+ vec4 texcolor = texture2D(bgl_RenderedTexture, gl_TexCoord[0].st);
+ float gray = dot(texcolor.rgb, vec3(0.299, 0.587, 0.114));
+ gl_FragColor = vec4(gray * vec3(1.2, 1.0, 0.8), texcolor.a);
+}
+);
+#endif
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sharpen2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sharpen2DFilter.h
new file mode 100644
index 00000000000..5a9661e2617
--- /dev/null
+++ b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sharpen2DFilter.h
@@ -0,0 +1,52 @@
+/**
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __RAS_SHARPEN2DFILTER
+#define __RAS_SHARPEN2DFILTER
+
+const char * SharpenFragmentShader=STRINGIFY(
+uniform sampler2D bgl_RenderedTexture;
+uniform vec2 bgl_TextureCoordinateOffset[9];
+
+void main(void)
+{
+ vec4 sample[9];
+
+ for (int i = 0; i < 9; i++)
+ {
+ sample[i] = texture2D(bgl_RenderedTexture,
+ gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]);
+ }
+
+ gl_FragColor = (sample[4] * 9.0) -
+ (sample[0] + sample[1] + sample[2] +
+ sample[3] + sample[5] +
+ sample[6] + sample[7] + sample[8]);
+}
+);
+#endif
+
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sobel2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sobel2DFilter.h
new file mode 100644
index 00000000000..142e4f0e3d4
--- /dev/null
+++ b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sobel2DFilter.h
@@ -0,0 +1,57 @@
+/**
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __RAS_SOBEL2DFILTER
+#define __RAS_SOBEL2DFILTER
+
+const char * SobelFragmentShader=STRINGIFY(
+uniform sampler2D bgl_RenderedTexture;
+uniform vec2 bgl_TextureCoordinateOffset[9];
+
+void main(void)
+{
+ vec4 sample[9];
+
+ for (int i = 0; i < 9; i++)
+ {
+ sample[i] = texture2D(bgl_RenderedTexture,
+ gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]);
+ }
+
+ vec4 horizEdge = sample[2] + (2.0*sample[5]) + sample[8] -
+ (sample[0] + (2.0*sample[3]) + sample[6]);
+
+ vec4 vertEdge = sample[0] + (2.0*sample[1]) + sample[2] -
+ (sample[6] + (2.0*sample[7]) + sample[8]);
+
+ gl_FragColor.rgb = sqrt((horizEdge.rgb * horizEdge.rgb) +
+ (vertEdge.rgb * vertEdge.rgb));
+ gl_FragColor.a = 1.0;
+}
+);
+#endif
+
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/ARB_multitexture.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/ARB_multitexture.h
deleted file mode 100644
index a2f27ce3361..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/ARB_multitexture.h
+++ /dev/null
@@ -1,150 +0,0 @@
-#ifndef __ARB_MULTITEXTURE_H__
-#define __ARB_MULTITEXTURE_H__
-
-/*
-*/
-
-/* ----------------------------------------------------------------------------
- GL_ARB_multitexture
----------------------------------------------------------------------------- */
-#ifdef GL_ARB_multitexture
- #define GL_TEXTURE0_ARB 0x84C0
- #define GL_TEXTURE1_ARB 0x84C1
- #define GL_TEXTURE2_ARB 0x84C2
- #define GL_TEXTURE3_ARB 0x84C3
- #define GL_TEXTURE4_ARB 0x84C4
- #define GL_TEXTURE5_ARB 0x84C5
- #define GL_TEXTURE6_ARB 0x84C6
- #define GL_TEXTURE7_ARB 0x84C7
- #define GL_TEXTURE8_ARB 0x84C8
- #define GL_TEXTURE9_ARB 0x84C9
- #define GL_TEXTURE10_ARB 0x84CA
- #define GL_ACTIVE_TEXTURE_ARB 0x84E0
- #define GL_CLIENT_ACTIVE_TEXTURE_ARB 0x84E1
- #define GL_MAX_TEXTURE_UNITS_ARB 0x84E2
-#endif
-
-
-/* ----------------------------------------------------------------------------
- GL_ARB_texture_env_combine
----------------------------------------------------------------------------- */
-#ifdef GL_ARB_texture_env_combine
- #define GL_COMBINE_ARB 0x8570
- #define GL_COMBINE_RGB_ARB 0x8571
- #define GL_COMBINE_ALPHA_ARB 0x8572
- #define GL_SOURCE0_RGB_ARB 0x8580
- #define GL_SOURCE1_RGB_ARB 0x8581
- #define GL_SOURCE2_RGB_ARB 0x8582
- #define GL_SOURCE0_ALPHA_ARB 0x8588
- #define GL_SOURCE1_ALPHA_ARB 0x8589
- #define GL_SOURCE2_ALPHA_ARB 0x858A
- #define GL_OPERAND0_RGB_ARB 0x8590
- #define GL_OPERAND1_RGB_ARB 0x8591
- #define GL_OPERAND2_RGB_ARB 0x8592
- #define GL_OPERAND0_ALPHA_ARB 0x8598
- #define GL_OPERAND1_ALPHA_ARB 0x8599
- #define GL_OPERAND2_ALPHA_ARB 0x859A
- #define GL_RGB_SCALE_ARB 0x8573
- #define GL_ADD_SIGNED_ARB 0x8574
- #define GL_INTERPOLATE_ARB 0x8575
- #define GL_SUBTRACT_ARB 0x84E7
- #define GL_CONSTANT_ARB 0x8576
- #define GL_PRIMARY_COLOR_ARB 0x8577
- #define GL_PREVIOUS_ARB 0x8578
-#endif
-
-/* ----------------------------------------------------------------------------
- GL_ARB_texture_cube_map
----------------------------------------------------------------------------- */
-#ifdef GL_ARB_texture_cube_map
- #define GL_NORMAL_MAP_ARB 0x8511
- #define GL_REFLECTION_MAP_ARB 0x8512
- #define GL_TEXTURE_CUBE_MAP_ARB 0x8513
- #define GL_TEXTURE_BINDING_CUBE_MAP_ARB 0x8514
- #define GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x8515
- #define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x8516
- #define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x8517
- #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x8518
- #define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x8519
- #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x851A
- #define GL_PROXY_TEXTURE_CUBE_MAP_ARB 0x851B
- #define GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB 0x851C
-#endif
-
-/* ----------------------------------------------------------------------------
- GL_ARB_shader_objects
----------------------------------------------------------------------------- */
-#ifdef GL_ARB_shader_objects
- #define GL_PROGRAM_OBJECT_ARB 0x8B40
- #define GL_SHADER_OBJECT_ARB 0x8B48
- #define GL_OBJECT_TYPE_ARB 0x8B4E
- #define GL_OBJECT_SUBTYPE_ARB 0x8B4F
- #define GL_FLOAT_VEC2_ARB 0x8B50
- #define GL_FLOAT_VEC3_ARB 0x8B51
- #define GL_FLOAT_VEC4_ARB 0x8B52
- #define GL_INT_VEC2_ARB 0x8B53
- #define GL_INT_VEC3_ARB 0x8B54
- #define GL_INT_VEC4_ARB 0x8B55
- #define GL_BOOL_ARB 0x8B56
- #define GL_BOOL_VEC2_ARB 0x8B57
- #define GL_BOOL_VEC3_ARB 0x8B58
- #define GL_BOOL_VEC4_ARB 0x8B59
- #define GL_FLOAT_MAT2_ARB 0x8B5A
- #define GL_FLOAT_MAT3_ARB 0x8B5B
- #define GL_FLOAT_MAT4_ARB 0x8B5C
- #define GL_SAMPLER_1D_ARB 0x8B5D
- #define GL_SAMPLER_2D_ARB 0x8B5E
- #define GL_SAMPLER_3D_ARB 0x8B5F
- #define GL_SAMPLER_CUBE_ARB 0x8B60
- #define GL_SAMPLER_1D_SHADOW_ARB 0x8B61
- #define GL_SAMPLER_2D_SHADOW_ARB 0x8B62
- #define GL_SAMPLER_2D_RECT_ARB 0x8B63
- #define GL_SAMPLER_2D_RECT_SHADOW_ARB 0x8B64
- #define GL_OBJECT_DELETE_STATUS_ARB 0x8B80
- #define GL_OBJECT_COMPILE_STATUS_ARB 0x8B81
- #define GL_OBJECT_LINK_STATUS_ARB 0x8B82
- #define GL_OBJECT_VALIDATE_STATUS_ARB 0x8B83
- #define GL_OBJECT_INFO_LOG_LENGTH_ARB 0x8B84
- #define GL_OBJECT_ATTACHED_OBJECTS_ARB 0x8B85
- #define GL_OBJECT_ACTIVE_UNIFORMS_ARB 0x8B86
- #define GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB 0x8B87
- #define GL_OBJECT_SHADER_SOURCE_LENGTH_ARB 0x8B88
-#endif
-
-/* ----------------------------------------------------------------------------
- GL_ARB_vertex_shader
----------------------------------------------------------------------------- */
-#ifdef GL_ARB_vertex_shader
- #define GL_VERTEX_SHADER_ARB 0x8B31
- #define GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB 0x8B4A
- #define GL_MAX_VARYING_FLOATS_ARB 0x8B4B
- #define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB 0x8B4C
- #define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB 0x8B4D
- #define GL_OBJECT_ACTIVE_ATTRIBUTES_ARB 0x8B89
- #define GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB 0x8B8A
-#endif
-
-
-/* ----------------------------------------------------------------------------
- GL_ARB_fragment_shader
----------------------------------------------------------------------------- */
-#ifdef GL_ARB_fragment_shader
- #define GL_FRAGMENT_SHADER_ARB 0x8B30
- #define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB 0x8B49
- #define GL_FRAGMENT_SHADER_DERIVATIVE_HINT_ARB 0x8B8B
-#endif
-
-
-/* ----------------------------------------------------------------------------
- GL_ARB_depth_texture
----------------------------------------------------------------------------- */
-#ifndef GL_ARB_depth_texture
- #define GL_DEPTH_COMPONENT16_ARB 0x81A5
- #define GL_DEPTH_COMPONENT24_ARB 0x81A6
- #define GL_DEPTH_COMPONENT32_ARB 0x81A7
- #define GL_TEXTURE_DEPTH_SIZE_ARB 0x884A
- #define GL_DEPTH_TEXTURE_MODE_ARB 0x884B
-#endif
-
-
-#endif//__ARB_MULTITEXTURE_H__
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt
index 5153834899b..e4403ace69f 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt
@@ -31,6 +31,8 @@ SET(INC
../../../../intern/string
../../../../intern/moto/include
../../../../source/gameengine/Rasterizer
+ ../../../../extern/glew/include
+ ../../../../source/blender/gpu
)
BLENDERLIB(bf_oglrasterizer "${SRC}" "${INC}")
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/EXT_separate_specular_color.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/EXT_separate_specular_color.h
deleted file mode 100644
index 5a9d8f32a87..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/EXT_separate_specular_color.h
+++ /dev/null
@@ -1,12 +0,0 @@
-#ifndef GL_EXT_separate_specular_color
-#define GL_EXT_separate_specular_color 1
-#define GL_LIGHT_MODEL_COLOR_CONTROL_EXT 0x81F8
-#define GL_SINGLE_COLOR_EXT 0x81F9
-#define GL_SEPARATE_SPECULAR_COLOR_EXT 0x81FA
-#endif
-
-#ifndef GL_VERSION_1_2
-#define GL_LIGHT_MODEL_COLOR_CONTROL 0x81F8
-#define GL_SINGLE_COLOR 0x81F9
-#define GL_SEPARATE_SPECULAR_COLOR 0x81FA
-#endif
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/Makefile b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/Makefile
index c0d12435b14..aee485a22be 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/Makefile
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/Makefile
@@ -36,11 +36,16 @@ include nan_compile.mk
CCFLAGS += $(LEVEL_1_CPP_WARNINGS)
+CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(OPENGL_HEADERS)
CPPFLAGS += -I$(NAN_STRING)/include
CPPFLAGS += -I$(NAN_MOTO)/include
CPPFLAGS += -I../../../kernel/gen_system
+CPPFLAGS += -I../../../blender/gpu
+CPPFLAGS += -I../../BlenderRoutines
CPPFLAGS += -I..
+
ifeq ($(OS),darwin)
CPPFLAGS += -fpascal-strings
endif
+
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_GLExtensionManager.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_GLExtensionManager.cpp
index c2b6e03fa02..d241bd1ee31 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_GLExtensionManager.cpp
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_GLExtensionManager.cpp
@@ -25,664 +25,43 @@
*
* ***** END GPL LICENSE BLOCK *****
*/
-/*
- The extension manager's job is to link at runtime OpenGL extension
- functions.
- Since the various platform have different methods of finding a fn
- pointer, this file attempts to encapsulate all that, so it gets a
- little messy. Hopefully we can
-*/
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-#ifdef WIN32
-# include <windows.h>
-
-# include <GL/gl.h>
-
-#elif defined(__APPLE__)
-# include <Carbon/Carbon.h>
-# define GL_GLEXT_LEGACY 1
-# include <OpenGL/gl.h>
-
-#else /* UNIX */
-# include <GL/gl.h>
-# include <GL/glx.h>
-
-# include <dlfcn.h>
-#endif
-
-#include <vector>
#include <iostream>
-#include <algorithm>
-#include <bitset>
-
-#include "STR_String.h"
#include "RAS_GLExtensionManager.h"
-/* -----------------------------------------------------------------------------
-
- Platform specific functions section.
-
- Required Functions:
- static void bglInitEntryPoints (void) -- Loads the GL library
- static void bglDeallocEntryPoints (void) -- Frees the GL library
- static void *bglGetProcAddress(const GLubyte* entry) -- Finds the address of
- the GL function entry
-
-*/
-#if defined(BGL_NO_EXTENSIONS)
-static void bglInitEntryPoints (void) {}
-static void bglDeallocEntryPoints (void) {}
-
-static void *bglGetProcAddress(const GLubyte* entry)
-{
- /* No Extensions! */
- return NULL;
-}
-#elif defined(__APPLE__)
-/* http://developer.apple.com/qa/qa2001/qa1188.html */
-CFBundleRef gBundleRefOpenGL = NULL;
-
-// -------------------------
-
-static OSStatus bglInitEntryPoints (void)
-{
- OSStatus err = noErr;
- const Str255 frameworkName = "\pOpenGL.framework";
- FSRefParam fileRefParam;
- FSRef fileRef;
- CFURLRef bundleURLOpenGL;
-
- memset(&fileRefParam, 0, sizeof(fileRefParam));
- memset(&fileRef, 0, sizeof(fileRef));
-
- fileRefParam.ioNamePtr = frameworkName;
- fileRefParam.newRef = &fileRef;
-
- // Frameworks directory/folder
- err = FindFolder (kSystemDomain, kFrameworksFolderType, false,
- &fileRefParam.ioVRefNum, (SInt32*)&fileRefParam.ioDirID);
- if (noErr != err) {
- DebugStr ((unsigned char *)"\pCould not find frameworks folder");
- return err;
- }
- err = PBMakeFSRefSync (&fileRefParam); // make FSRef for folder
- if (noErr != err) {
- DebugStr ((unsigned char *)"\pCould make FSref to frameworks folder");
- return err;
- }
- // create URL to folder
- bundleURLOpenGL = CFURLCreateFromFSRef (kCFAllocatorDefault,
- &fileRef);
- if (!bundleURLOpenGL) {
- DebugStr ((unsigned char *)"\pCould create OpenGL Framework bundle URL");
- return paramErr;
- }
- // create ref to GL's bundle
- gBundleRefOpenGL = CFBundleCreate (kCFAllocatorDefault,
- bundleURLOpenGL);
- if (!gBundleRefOpenGL) {
- DebugStr ((unsigned char *)"\pCould not create OpenGL Framework bundle");
- return paramErr;
- }
- CFRelease (bundleURLOpenGL); // release created bundle
- // if the code was successfully loaded, look for our function.
- if (!CFBundleLoadExecutable (gBundleRefOpenGL)) {
- DebugStr ((unsigned char *)"\pCould not load MachO executable");
- return paramErr;
- }
- return err;
-}
-
-// -------------------------
-
-static void bglDeallocEntryPoints (void)
-{
- if (gBundleRefOpenGL != NULL) {
- // unload the bundle's code.
- CFBundleUnloadExecutable (gBundleRefOpenGL);
- CFRelease (gBundleRefOpenGL);
- gBundleRefOpenGL = NULL;
- }
-}
-
-// -------------------------
-
-/*unused*/
-static void * bglGetProcAddress (const GLubyte * pszProc)
-{
- if (!gBundleRefOpenGL)
- return NULL;
-
- return CFBundleGetFunctionPointerForName (gBundleRefOpenGL,
- CFStringCreateWithCStringNoCopy (NULL,
- (const char *) pszProc, CFStringGetSystemEncoding (), NULL));
-}
-#elif defined(GLX_ARB_get_proc_address)
-/* Not all glx.h define PFNGLXGETPROCADDRESSARBPROC !
- We define our own if needed. */
-#ifdef HAVE_PFNGLXGETPROCADDRESSARBPROC
-#define PFNBGLXGETPROCADDRESSARBPROC PFNGLXGETPROCADDRESSARBPROC
-#else
-typedef void (*(*PFNBGLXGETPROCADDRESSARBPROC)(const GLubyte *procname))();
-#endif
-
-void *_getProcAddress(const GLubyte *procName) { return NULL; }
-PFNBGLXGETPROCADDRESSARBPROC bglGetProcAddress;
-
-
-//weird bug related to combination of pthreads,libGL and dlopen
-//cannot call dlclose in such environment, causes crashes
-//so try to keep a global handle to libGL
-void* libGL = 0;
-
-static void bglInitEntryPoints (void)
-{
- Display *dpy = glXGetCurrentDisplay();
- std::vector<STR_String> Xextensions = STR_String(glXQueryExtensionsString(dpy, DefaultScreen(dpy))).Explode(' ');
- if (std::find(Xextensions.begin(), Xextensions.end(), "GLX_ARB_get_proc_address") != Xextensions.end())
- {
- if (!libGL)
- {
- libGL = dlopen("libGL.so", RTLD_LAZY|RTLD_GLOBAL);
- if (libGL)
- bglGetProcAddress = (PFNBGLXGETPROCADDRESSARBPROC) (dlsym(libGL, "glXGetProcAddressARB"));
- else
- std::cout << "Error: " << dlerror() << std::endl;
-
- // dlclose(libGL);
- if (!bglGetProcAddress)
- bglGetProcAddress = (PFNBGLXGETPROCADDRESSARBPROC) _getProcAddress;
-
- // --
- if(!bglGetProcAddress)
- std::cout << "Error: unable to find _getProcAddress in libGL" << std::endl;
- }
- }
-}
-
-static void bglDeallocEntryPoints (void) {}
-
-#elif defined(WIN32)
-static void bglInitEntryPoints (void) {}
-static void bglDeallocEntryPoints (void) {}
-
-#define bglGetProcAddress(entry) wglGetProcAddress((LPCSTR) entry)
-
-#else /* Unknown Platform - disable extensions */
-static void bglInitEntryPoints (void) {}
-static void bglDeallocEntryPoints (void) {}
-
-static void *bglGetProcAddress(const GLubyte* entry)
-{
- /* No Extensions! */
- return NULL;
-}
-
-#endif /* End Platform Specific */
-
-/* -----------------------------------------------------------------------------
-
- GL Extension Manager.
-*/
- /* Bit array of available extensions */
-static std::bitset<bgl::NUM_EXTENSIONS> enabled_extensions;
-static std::vector<STR_String> extensions;
-static int m_debug;
-
-static void LinkExtensions();
-
-static void EnableExtension(bgl::ExtensionName name)
-{
- unsigned int num = (unsigned int) name;
- if (num < bgl::NUM_EXTENSIONS)
- enabled_extensions.set(num);
-}
-
-
-static bool QueryExtension(STR_String extension_name)
-{
- return std::find(extensions.begin(), extensions.end(), extension_name) != extensions.end();
-}
-
namespace bgl
{
-
-void InitExtensions(int debug)
-{
- m_debug = debug;
- bglInitEntryPoints (); //init bundle
- EnableExtension(_BGL_TEST);
- LinkExtensions();
- bglDeallocEntryPoints();
-}
-
-bool QueryExtension(ExtensionName name)
-{
- unsigned int num = (unsigned int) name;
- if (num < NUM_EXTENSIONS)
- return enabled_extensions[num];
-
- return false;
-}
-
-bool QueryVersion(int major, int minor)
-{
- static int gl_major = 0;
- static int gl_minor = 0;
-
- if (gl_major == 0)
+ void InitExtensions(bool debug)
{
- const char *gl_version_str = (const char *) glGetString(GL_VERSION);
- if (!gl_version_str)
- return false;
- STR_String gl_version = STR_String(gl_version_str);
- int i = gl_version.Find('.');
- gl_major = gl_version.Left(i).ToInt();
- gl_minor = gl_version.Mid(i+1, gl_version.FindOneOf(". ", i+1) - i - 1).ToInt();
-
- static bool doQueryVersion = m_debug;
- if (doQueryVersion)
- {
- doQueryVersion = false;
- std::cout << "GL_VERSION: " << gl_major << "." << gl_minor << " (" << gl_version << ")" << std::endl;
- }
- }
-
- if (gl_major > major)
- return true;
-
- if (gl_major == major && gl_minor >= minor)
- return true;
+ static bool firsttime = true;
- return false;
-}
-
-
-/*******************************************************************************
-1. Extension function entry points go here
-
-Need to #ifdef (compile time test for extension)
-Add null functions if appropriate
-
-Some extensions have been incorporated into the core GL, eg Multitexture was
-added in GL v1.1. If Blender calls one of these functions before they are
-linked, it will crash. Even worse, if Blender *indirectly* calls one of these
-functions, (ie the GL implementation calls them itself) Blender will crash.
-
-We fix this by adding them to the bgl namespace - the functions are now
-private to the gameengine. Code can transparently use extensions by adding:
-
-using namespace bgl;
-
-to their source. Cunning like a weasel.
-
- ******************************************************************************/
-
-#if defined(PFNGLPNTRIANGLESIATIPROC)
-PFNGLPNTRIANGLESIATIPROC glPNTrianglesiATI;
-PFNGLPNTRIANGLESFATIPROC glPNTrianglesfATI;
-#endif
-
-BL_EXTInfo RAS_EXT_support;
-
-
-#ifdef GL_ARB_multitexture
-int max_texture_units = 2;
- PFNGLACTIVETEXTUREARBPROC blActiveTextureARB;
- PFNGLCLIENTACTIVETEXTUREARBPROC blClientActiveTextureARB;
- PFNGLMULTITEXCOORD1DARBPROC blMultiTexCoord1dARB;
- PFNGLMULTITEXCOORD1DVARBPROC blMultiTexCoord1dvARB;
- PFNGLMULTITEXCOORD1FARBPROC blMultiTexCoord1fARB;
- PFNGLMULTITEXCOORD1FVARBPROC blMultiTexCoord1fvARB;
- PFNGLMULTITEXCOORD1IARBPROC blMultiTexCoord1iARB;
- PFNGLMULTITEXCOORD1IVARBPROC blMultiTexCoord1ivARB;
- PFNGLMULTITEXCOORD1SARBPROC blMultiTexCoord1sARB;
- PFNGLMULTITEXCOORD1SVARBPROC blMultiTexCoord1svARB;
- PFNGLMULTITEXCOORD2DARBPROC blMultiTexCoord2dARB;
- PFNGLMULTITEXCOORD2DVARBPROC blMultiTexCoord2dvARB;
- PFNGLMULTITEXCOORD2FARBPROC blMultiTexCoord2fARB;
- PFNGLMULTITEXCOORD2FVARBPROC blMultiTexCoord2fvARB;
- PFNGLMULTITEXCOORD2IARBPROC blMultiTexCoord2iARB;
- PFNGLMULTITEXCOORD2IVARBPROC blMultiTexCoord2ivARB;
- PFNGLMULTITEXCOORD2SARBPROC blMultiTexCoord2sARB;
- PFNGLMULTITEXCOORD2SVARBPROC blMultiTexCoord2svARB;
- PFNGLMULTITEXCOORD3DARBPROC blMultiTexCoord3dARB;
- PFNGLMULTITEXCOORD3DVARBPROC blMultiTexCoord3dvARB;
- PFNGLMULTITEXCOORD3FARBPROC blMultiTexCoord3fARB;
- PFNGLMULTITEXCOORD3FVARBPROC blMultiTexCoord3fvARB;
- PFNGLMULTITEXCOORD3IARBPROC blMultiTexCoord3iARB;
- PFNGLMULTITEXCOORD3IVARBPROC blMultiTexCoord3ivARB;
- PFNGLMULTITEXCOORD3SARBPROC blMultiTexCoord3sARB;
- PFNGLMULTITEXCOORD3SVARBPROC blMultiTexCoord3svARB;
- PFNGLMULTITEXCOORD4DARBPROC blMultiTexCoord4dARB;
- PFNGLMULTITEXCOORD4DVARBPROC blMultiTexCoord4dvARB;
- PFNGLMULTITEXCOORD4FARBPROC blMultiTexCoord4fARB;
- PFNGLMULTITEXCOORD4FVARBPROC blMultiTexCoord4fvARB;
- PFNGLMULTITEXCOORD4IARBPROC blMultiTexCoord4iARB;
- PFNGLMULTITEXCOORD4IVARBPROC blMultiTexCoord4ivARB;
- PFNGLMULTITEXCOORD4SARBPROC blMultiTexCoord4sARB;
- PFNGLMULTITEXCOORD4SVARBPROC blMultiTexCoord4svARB;
-#endif
-
-#ifdef GL_ARB_shader_objects
- PFNGLDELETEOBJECTARBPROC blDeleteObjectARB;
- PFNGLGETHANDLEARBPROC blGetHandleARB;
- PFNGLDETACHOBJECTARBPROC blDetachObjectARB;
- PFNGLCREATESHADEROBJECTARBPROC blCreateShaderObjectARB;
- PFNGLSHADERSOURCEARBPROC blShaderSourceARB;
- PFNGLCOMPILESHADERARBPROC blCompileShaderARB;
- PFNGLCREATEPROGRAMOBJECTARBPROC blCreateProgramObjectARB;
- PFNGLATTACHOBJECTARBPROC blAttachObjectARB;
- PFNGLLINKPROGRAMARBPROC blLinkProgramARB;
- PFNGLUSEPROGRAMOBJECTARBPROC blUseProgramObjectARB;
- PFNGLVALIDATEPROGRAMARBPROC blValidateProgramARB;
- PFNGLUNIFORM1FARBPROC blUniform1fARB;
- PFNGLUNIFORM2FARBPROC blUniform2fARB;
- PFNGLUNIFORM3FARBPROC blUniform3fARB;
- PFNGLUNIFORM4FARBPROC blUniform4fARB;
- PFNGLUNIFORM1IARBPROC blUniform1iARB;
- PFNGLUNIFORM2IARBPROC blUniform2iARB;
- PFNGLUNIFORM3IARBPROC blUniform3iARB;
- PFNGLUNIFORM4IARBPROC blUniform4iARB;
- PFNGLUNIFORM1FVARBPROC blUniform1fvARB;
- PFNGLUNIFORM2FVARBPROC blUniform2fvARB;
- PFNGLUNIFORM3FVARBPROC blUniform3fvARB;
- PFNGLUNIFORM4FVARBPROC blUniform4fvARB;
- PFNGLUNIFORM1IVARBPROC blUniform1ivARB;
- PFNGLUNIFORM2IVARBPROC blUniform2ivARB;
- PFNGLUNIFORM3IVARBPROC blUniform3ivARB;
- PFNGLUNIFORM4IVARBPROC blUniform4ivARB;
- PFNGLUNIFORMMATRIX2FVARBPROC blUniformMatrix2fvARB;
- PFNGLUNIFORMMATRIX3FVARBPROC blUniformMatrix3fvARB;
- PFNGLUNIFORMMATRIX4FVARBPROC blUniformMatrix4fvARB;
- PFNGLGETOBJECTPARAMETERFVARBPROC blGetObjectParameterfvARB;
- PFNGLGETOBJECTPARAMETERIVARBPROC blGetObjectParameterivARB;
- PFNGLGETINFOLOGARBPROC blGetInfoLogARB;
- PFNGLGETATTACHEDOBJECTSARBPROC blGetAttachedObjectsARB;
- PFNGLGETUNIFORMLOCATIONARBPROC blGetUniformLocationARB;
- PFNGLGETACTIVEUNIFORMARBPROC blGetActiveUniformARB;
- PFNGLGETUNIFORMFVARBPROC blGetUniformfvARB;
- PFNGLGETUNIFORMIVARBPROC blGetUniformivARB;
- PFNGLGETSHADERSOURCEARBPROC blGetShaderSourceARB;
-#endif
-
-#ifdef GL_ARB_vertex_shader
-PFNGLBINDATTRIBLOCATIONARBPROC blBindAttribLocationARB;
-PFNGLGETACTIVEATTRIBARBPROC blGetActiveAttribARB;
-PFNGLGETATTRIBLOCATIONARBPROC blGetAttribLocationARB;
-#endif
-
-#ifdef GL_ARB_vertex_program
- PFNGLVERTEXATTRIB1FARBPROC blVertexAttrib1fARB;
- PFNGLVERTEXATTRIB1FVARBPROC blVertexAttrib1fvARB;
- PFNGLVERTEXATTRIB2FARBPROC blVertexAttrib2fARB;
- PFNGLVERTEXATTRIB2FVARBPROC blVertexAttrib2fvARB;
- PFNGLVERTEXATTRIB3FARBPROC blVertexAttrib3fARB;
- PFNGLVERTEXATTRIB3FVARBPROC blVertexAttrib3fvARB;
- PFNGLVERTEXATTRIB4FARBPROC blVertexAttrib4fARB;
- PFNGLVERTEXATTRIB4FVARBPROC blVertexAttrib4fvARB;
- PFNGLGETPROGRAMSTRINGARBPROC blGetProgramStringARB;
- PFNGLGETVERTEXATTRIBDVARBPROC blGetVertexAttribdvARB;
- PFNGLGETVERTEXATTRIBFVARBPROC blGetVertexAttribfvARB;
- PFNGLGETVERTEXATTRIBIVARBPROC blGetVertexAttribivARB;
-#endif
-
- /*
-#ifdef GL_EXT_compiled_vertex_array
- PFNGLLOCKARRAYSEXTPROC blLockArraysEXT;
- PFNGLUNLOCKARRAYSEXTPROC blUnlockArraysEXT;
-#endif
-*/
-
-} // namespace bgl
-
-using namespace bgl;
-/*******************************************************************************
-2. Query extension functions here
-
-Need to #ifdef (compile time test for extension)
-Use QueryExtension("GL_EXT_name") to test at runtime.
-Use bglGetProcAddress to find entry point
-Use EnableExtension(_GL_EXT_...) to allow Blender to use the extension.
-
- ******************************************************************************/
-static void LinkExtensions()
-{
- static bool doDebugMessages = m_debug;
- extensions = STR_String((const char *) glGetString(GL_EXTENSIONS)).Explode(' ');
- RAS_EXT_support = BL_EXTInfo();
-
-#if defined(PFNGLPNTRIANGLESIATIPROC)
- if (QueryExtension("GL_ATI_pn_triangles"))
- {
- glPNTrianglesiATI = reinterpret_cast<PFNGLPNTRIANGLESIATIPROC>(bglGetProcAddress((const GLubyte *) "glPNTrianglesiATI"));
- glPNTrianglesfATI = reinterpret_cast<PFNGLPNTRIANGLESFATIPROC>(bglGetProcAddress((const GLubyte *) "glPNTrianglesfATI"));
- if (glPNTrianglesiATI && glPNTrianglesfATI) {
- EnableExtension(_GL_ATI_pn_triangles);
- if (doDebugMessages)
- std::cout << "Enabled GL_ATI_pn_triangles" << std::endl;
- } else {
- std::cout << "ERROR: GL_ATI_pn_triangles implementation is broken!" << std::endl;
- }
- }
-#endif
-
-#ifdef GL_ARB_texture_env_combine
- if (QueryExtension("GL_ARB_texture_env_combine"))
- {
- EnableExtension(_GL_ARB_texture_env_combine);
- RAS_EXT_support._ARB_texture_env_combine = 1;
- if (doDebugMessages)
- {
- std::cout << "Detected GL_ARB_texture_env_combine" << std::endl;
- }
- }
-#endif
-
-#ifdef GL_ARB_texture_cube_map
- if (QueryExtension("GL_ARB_texture_cube_map"))
- {
- EnableExtension(_GL_ARB_texture_cube_map);
- RAS_EXT_support._ARB_texture_cube_map = 1;
- if (doDebugMessages)
- std::cout << "Detected GL_ARB_texture_cube_map" << std::endl;
- }
-#endif
-
-#ifdef GL_ARB_multitexture
- if (QueryExtension("GL_ARB_multitexture"))
- {
- bgl::blActiveTextureARB = reinterpret_cast<PFNGLACTIVETEXTUREARBPROC>(bglGetProcAddress((const GLubyte *) "glActiveTextureARB"));
- bgl::blClientActiveTextureARB = reinterpret_cast<PFNGLCLIENTACTIVETEXTUREARBPROC>(bglGetProcAddress((const GLubyte *) "glClientActiveTextureARB"));
- bgl::blMultiTexCoord1dARB = reinterpret_cast<PFNGLMULTITEXCOORD1DARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord1dARB"));
- bgl::blMultiTexCoord1dvARB = reinterpret_cast<PFNGLMULTITEXCOORD1DVARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord1dvARB"));
- bgl::blMultiTexCoord1fARB = reinterpret_cast<PFNGLMULTITEXCOORD1FARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord1fARB"));
- bgl::blMultiTexCoord1fvARB = reinterpret_cast<PFNGLMULTITEXCOORD1FVARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord1fvARB"));
- bgl::blMultiTexCoord1iARB = reinterpret_cast<PFNGLMULTITEXCOORD1IARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord1iARB"));
- bgl::blMultiTexCoord1ivARB = reinterpret_cast<PFNGLMULTITEXCOORD1IVARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord1ivARB"));
- bgl::blMultiTexCoord1sARB = reinterpret_cast<PFNGLMULTITEXCOORD1SARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord1sARB"));
- bgl::blMultiTexCoord1svARB = reinterpret_cast<PFNGLMULTITEXCOORD1SVARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord1svARB"));
- bgl::blMultiTexCoord2dARB = reinterpret_cast<PFNGLMULTITEXCOORD2DARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord2dARB"));
- bgl::blMultiTexCoord2dvARB = reinterpret_cast<PFNGLMULTITEXCOORD2DVARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord2dvARB"));
- bgl::blMultiTexCoord2fARB = reinterpret_cast<PFNGLMULTITEXCOORD2FARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord2fARB"));
- bgl::blMultiTexCoord2fvARB = reinterpret_cast<PFNGLMULTITEXCOORD2FVARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord2fvARB"));
- bgl::blMultiTexCoord2iARB = reinterpret_cast<PFNGLMULTITEXCOORD2IARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord2iARB"));
- bgl::blMultiTexCoord2ivARB = reinterpret_cast<PFNGLMULTITEXCOORD2IVARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord2ivARB"));
- bgl::blMultiTexCoord2sARB = reinterpret_cast<PFNGLMULTITEXCOORD2SARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord2sARB"));
- bgl::blMultiTexCoord2svARB = reinterpret_cast<PFNGLMULTITEXCOORD2SVARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord2svARB"));
- bgl::blMultiTexCoord3dARB = reinterpret_cast<PFNGLMULTITEXCOORD3DARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord3dARB"));
- bgl::blMultiTexCoord3dvARB = reinterpret_cast<PFNGLMULTITEXCOORD3DVARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord3dvARB"));
- bgl::blMultiTexCoord3fARB = reinterpret_cast<PFNGLMULTITEXCOORD3FARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord3fARB"));
- bgl::blMultiTexCoord3fvARB = reinterpret_cast<PFNGLMULTITEXCOORD3FVARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord3fvARB"));
- bgl::blMultiTexCoord3iARB = reinterpret_cast<PFNGLMULTITEXCOORD3IARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord3iARB"));
- bgl::blMultiTexCoord3ivARB = reinterpret_cast<PFNGLMULTITEXCOORD3IVARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord3ivARB"));
- bgl::blMultiTexCoord3sARB = reinterpret_cast<PFNGLMULTITEXCOORD3SARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord3sARB"));
- bgl::blMultiTexCoord3svARB = reinterpret_cast<PFNGLMULTITEXCOORD3SVARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord3svARB"));
- bgl::blMultiTexCoord4dARB = reinterpret_cast<PFNGLMULTITEXCOORD4DARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord4dARB"));
- bgl::blMultiTexCoord4dvARB = reinterpret_cast<PFNGLMULTITEXCOORD4DVARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord4dvARB"));
- bgl::blMultiTexCoord4fARB = reinterpret_cast<PFNGLMULTITEXCOORD4FARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord4fARB"));
- bgl::blMultiTexCoord4fvARB = reinterpret_cast<PFNGLMULTITEXCOORD4FVARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord4fvARB"));
- bgl::blMultiTexCoord4iARB = reinterpret_cast<PFNGLMULTITEXCOORD4IARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord4iARB"));
- bgl::blMultiTexCoord4ivARB = reinterpret_cast<PFNGLMULTITEXCOORD4IVARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord4ivARB"));
- bgl::blMultiTexCoord4sARB = reinterpret_cast<PFNGLMULTITEXCOORD4SARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord4sARB"));
- bgl::blMultiTexCoord4svARB = reinterpret_cast<PFNGLMULTITEXCOORD4SVARBPROC>(bglGetProcAddress((const GLubyte *) "glMultiTexCoord4svARB"));
- if (bgl::blActiveTextureARB && bgl::blClientActiveTextureARB && bgl::blMultiTexCoord1dARB && bgl::blMultiTexCoord1dvARB && bgl::blMultiTexCoord1fARB && bgl::blMultiTexCoord1fvARB && bgl::blMultiTexCoord1iARB && bgl::blMultiTexCoord1ivARB && bgl::blMultiTexCoord1sARB && bgl::blMultiTexCoord1svARB && bgl::blMultiTexCoord2dARB && bgl::blMultiTexCoord2dvARB && bgl::blMultiTexCoord2fARB && bgl::blMultiTexCoord2fvARB && bgl::blMultiTexCoord2iARB && bgl::blMultiTexCoord2ivARB && bgl::blMultiTexCoord2sARB && bgl::blMultiTexCoord2svARB && bgl::blMultiTexCoord3dARB && bgl::blMultiTexCoord3dvARB && bgl::blMultiTexCoord3fARB && bgl::blMultiTexCoord3fvARB && bgl::blMultiTexCoord3iARB && bgl::blMultiTexCoord3ivARB && bgl::blMultiTexCoord3sARB && bgl::blMultiTexCoord3svARB && bgl::blMultiTexCoord4dARB && bgl::blMultiTexCoord4dvARB && bgl::blMultiTexCoord4fARB && bgl::blMultiTexCoord4fvARB && bgl::blMultiTexCoord4iARB && bgl::blMultiTexCoord4ivARB && bgl::blMultiTexCoord4sARB && bgl::blMultiTexCoord4svARB) {
- EnableExtension(_GL_ARB_multitexture);
- RAS_EXT_support._ARB_multitexture = 1;
- if (doDebugMessages)
- std::cout << "Enabled GL_ARB_multitexture" << std::endl;
- } else {
- std::cout << "ERROR: GL_ARB_multitexture implementation is broken!" << std::endl;
- }
- }
-#endif
-
-#if GL_ARB_shader_objects
- if (QueryExtension("GL_ARB_shader_objects"))
- {
- bgl::blDeleteObjectARB = reinterpret_cast<PFNGLDELETEOBJECTARBPROC>(bglGetProcAddress((const GLubyte *) "glDeleteObjectARB"));
- bgl::blGetHandleARB = reinterpret_cast<PFNGLGETHANDLEARBPROC>(bglGetProcAddress((const GLubyte *) "glGetHandleARB"));
- bgl::blDetachObjectARB = reinterpret_cast<PFNGLDETACHOBJECTARBPROC>(bglGetProcAddress((const GLubyte *) "glDetachObjectARB"));
- bgl::blCreateShaderObjectARB = reinterpret_cast<PFNGLCREATESHADEROBJECTARBPROC>(bglGetProcAddress((const GLubyte *) "glCreateShaderObjectARB"));
- bgl::blShaderSourceARB = reinterpret_cast<PFNGLSHADERSOURCEARBPROC>(bglGetProcAddress((const GLubyte *) "glShaderSourceARB"));
- bgl::blCompileShaderARB = reinterpret_cast<PFNGLCOMPILESHADERARBPROC>(bglGetProcAddress((const GLubyte *) "glCompileShaderARB"));
- bgl::blCreateProgramObjectARB = reinterpret_cast<PFNGLCREATEPROGRAMOBJECTARBPROC>(bglGetProcAddress((const GLubyte *) "glCreateProgramObjectARB"));
- bgl::blAttachObjectARB = reinterpret_cast<PFNGLATTACHOBJECTARBPROC>(bglGetProcAddress((const GLubyte *) "glAttachObjectARB"));
- bgl::blLinkProgramARB = reinterpret_cast<PFNGLLINKPROGRAMARBPROC>(bglGetProcAddress((const GLubyte *) "glLinkProgramARB"));
- bgl::blUseProgramObjectARB = reinterpret_cast<PFNGLUSEPROGRAMOBJECTARBPROC>(bglGetProcAddress((const GLubyte *) "glUseProgramObjectARB"));
- bgl::blValidateProgramARB = reinterpret_cast<PFNGLVALIDATEPROGRAMARBPROC>(bglGetProcAddress((const GLubyte *) "glValidateProgramARB"));
- bgl::blUniform1fARB = reinterpret_cast<PFNGLUNIFORM1FARBPROC>(bglGetProcAddress((const GLubyte *) "glUniform1fARB"));
- bgl::blUniform2fARB = reinterpret_cast<PFNGLUNIFORM2FARBPROC>(bglGetProcAddress((const GLubyte *) "glUniform2fARB"));
- bgl::blUniform3fARB = reinterpret_cast<PFNGLUNIFORM3FARBPROC>(bglGetProcAddress((const GLubyte *) "glUniform3fARB"));
- bgl::blUniform4fARB = reinterpret_cast<PFNGLUNIFORM4FARBPROC>(bglGetProcAddress((const GLubyte *) "glUniform4fARB"));
- bgl::blUniform1iARB = reinterpret_cast<PFNGLUNIFORM1IARBPROC>(bglGetProcAddress((const GLubyte *) "glUniform1iARB"));
- bgl::blUniform2iARB = reinterpret_cast<PFNGLUNIFORM2IARBPROC>(bglGetProcAddress((const GLubyte *) "glUniform2iARB"));
- bgl::blUniform3iARB = reinterpret_cast<PFNGLUNIFORM3IARBPROC>(bglGetProcAddress((const GLubyte *) "glUniform3iARB"));
- bgl::blUniform4iARB = reinterpret_cast<PFNGLUNIFORM4IARBPROC>(bglGetProcAddress((const GLubyte *) "glUniform4iARB"));
- bgl::blUniform1fvARB = reinterpret_cast<PFNGLUNIFORM1FVARBPROC>(bglGetProcAddress((const GLubyte *) "glUniform1fvARB"));
- bgl::blUniform2fvARB = reinterpret_cast<PFNGLUNIFORM2FVARBPROC>(bglGetProcAddress((const GLubyte *) "glUniform2fvARB"));
- bgl::blUniform3fvARB = reinterpret_cast<PFNGLUNIFORM3FVARBPROC>(bglGetProcAddress((const GLubyte *) "glUniform3fvARB"));
- bgl::blUniform4fvARB = reinterpret_cast<PFNGLUNIFORM4FVARBPROC>(bglGetProcAddress((const GLubyte *) "glUniform4fvARB"));
- bgl::blUniform1ivARB = reinterpret_cast<PFNGLUNIFORM1IVARBPROC>(bglGetProcAddress((const GLubyte *) "glUniform1ivARB"));
- bgl::blUniform2ivARB = reinterpret_cast<PFNGLUNIFORM2IVARBPROC>(bglGetProcAddress((const GLubyte *) "glUniform2ivARB"));
- bgl::blUniform3ivARB = reinterpret_cast<PFNGLUNIFORM3IVARBPROC>(bglGetProcAddress((const GLubyte *) "glUniform3ivARB"));
- bgl::blUniform4ivARB = reinterpret_cast<PFNGLUNIFORM4IVARBPROC>(bglGetProcAddress((const GLubyte *) "glUniform4ivARB"));
- bgl::blUniformMatrix2fvARB = reinterpret_cast<PFNGLUNIFORMMATRIX2FVARBPROC>(bglGetProcAddress((const GLubyte *) "glUniformMatrix2fvARB"));
- bgl::blUniformMatrix3fvARB = reinterpret_cast<PFNGLUNIFORMMATRIX3FVARBPROC>(bglGetProcAddress((const GLubyte *) "glUniformMatrix3fvARB"));
- bgl::blUniformMatrix4fvARB = reinterpret_cast<PFNGLUNIFORMMATRIX4FVARBPROC>(bglGetProcAddress((const GLubyte *) "glUniformMatrix4fvARB"));
- bgl::blGetObjectParameterfvARB = reinterpret_cast<PFNGLGETOBJECTPARAMETERFVARBPROC>(bglGetProcAddress((const GLubyte *) "glGetObjectParameterfvARB"));
- bgl::blGetObjectParameterivARB = reinterpret_cast<PFNGLGETOBJECTPARAMETERIVARBPROC>(bglGetProcAddress((const GLubyte *) "glGetObjectParameterivARB"));
- bgl::blGetInfoLogARB = reinterpret_cast<PFNGLGETINFOLOGARBPROC>(bglGetProcAddress((const GLubyte *) "glGetInfoLogARB"));
- bgl::blGetAttachedObjectsARB = reinterpret_cast<PFNGLGETATTACHEDOBJECTSARBPROC>(bglGetProcAddress((const GLubyte *) "glGetAttachedObjectsARB"));
- bgl::blGetUniformLocationARB = reinterpret_cast<PFNGLGETUNIFORMLOCATIONARBPROC>(bglGetProcAddress((const GLubyte *) "glGetUniformLocationARB"));
- bgl::blGetActiveUniformARB = reinterpret_cast<PFNGLGETACTIVEUNIFORMARBPROC>(bglGetProcAddress((const GLubyte *) "glGetActiveUniformARB"));
- bgl::blGetUniformfvARB = reinterpret_cast<PFNGLGETUNIFORMFVARBPROC>(bglGetProcAddress((const GLubyte *) "glGetUniformfvARB"));
- bgl::blGetUniformivARB = reinterpret_cast<PFNGLGETUNIFORMIVARBPROC>(bglGetProcAddress((const GLubyte *) "glGetUniformivARB"));
- bgl::blGetShaderSourceARB = reinterpret_cast<PFNGLGETSHADERSOURCEARBPROC>(bglGetProcAddress((const GLubyte *) "glGetShaderSourceARB"));
- if (bgl::blDeleteObjectARB && bgl::blGetHandleARB && bgl::blDetachObjectARB && bgl::blCreateShaderObjectARB && bgl::blShaderSourceARB && bgl::blCompileShaderARB && bgl::blCreateProgramObjectARB && bgl::blAttachObjectARB && bgl::blLinkProgramARB && bgl::blUseProgramObjectARB && bgl::blValidateProgramARB && bgl::blUniform1fARB && bgl::blUniform2fARB && bgl::blUniform3fARB && bgl::blUniform4fARB && bgl::blUniform1iARB && bgl::blUniform2iARB && bgl::blUniform3iARB && bgl::blUniform4iARB && bgl::blUniform1fvARB && bgl::blUniform2fvARB && bgl::blUniform3fvARB && bgl::blUniform4fvARB && bgl::blUniform1ivARB && bgl::blUniform2ivARB && bgl::blUniform3ivARB && bgl::blUniform4ivARB && bgl::blUniformMatrix2fvARB && bgl::blUniformMatrix3fvARB && bgl::blUniformMatrix4fvARB && bgl::blGetObjectParameterfvARB && bgl::blGetObjectParameterivARB && bgl::blGetInfoLogARB && bgl::blGetAttachedObjectsARB && bgl::blGetUniformLocationARB && bgl::blGetActiveUniformARB && bgl::blGetUniformfvARB && bgl::blGetUniformivARB && bgl::blGetShaderSourceARB) {
- EnableExtension(_GL_ARB_shader_objects);
- RAS_EXT_support._ARB_shader_objects =1;
- if (doDebugMessages)
- std::cout << "Enabled GL_ARB_shader_objects" << std::endl;
- } else {
- std::cout << "ERROR: GL_ARB_shader_objects implementation is broken!" << std::endl;
- }
- }
-#endif
-
-#if GL_ARB_vertex_shader
- if (QueryExtension("GL_ARB_vertex_shader"))
- {
- bgl::blBindAttribLocationARB = reinterpret_cast<PFNGLBINDATTRIBLOCATIONARBPROC>(bglGetProcAddress((const GLubyte *) "glBindAttribLocationARB"));
- bgl::blGetActiveAttribARB = reinterpret_cast<PFNGLGETACTIVEATTRIBARBPROC>(bglGetProcAddress((const GLubyte *) "glGetActiveAttribARB"));
- bgl::blGetAttribLocationARB = reinterpret_cast<PFNGLGETATTRIBLOCATIONARBPROC>(bglGetProcAddress((const GLubyte *) "glGetAttribLocationARB"));
- if (bgl::blBindAttribLocationARB && bgl::blGetActiveAttribARB && bgl::blGetAttribLocationARB) {
- EnableExtension(_GL_ARB_vertex_shader);
- RAS_EXT_support._ARB_vertex_shader = 1;
- if (doDebugMessages)
- std::cout << "Enabled GL_ARB_vertex_shader" << std::endl;
- } else {
- std::cout << "ERROR: GL_ARB_vertex_shader implementation is broken!" << std::endl;
- }
- }
-#endif
-
-#ifdef GL_ARB_fragment_shader
- if (QueryExtension("GL_ARB_fragment_shader"))
- {
- EnableExtension(_GL_ARB_fragment_shader);
- RAS_EXT_support._ARB_fragment_shader = 1;
- if (doDebugMessages)
- std::cout << "Detected GL_ARB_fragment_shader" << std::endl;
- }
-#endif
-
-#if defined(GL_ARB_vertex_program)
- if (QueryExtension("GL_ARB_vertex_program"))
- {
- bgl::blVertexAttrib1fARB = reinterpret_cast<PFNGLVERTEXATTRIB1FARBPROC>(bglGetProcAddress((const GLubyte *) "glVertexAttrib1fARB"));
- bgl::blVertexAttrib1fvARB = reinterpret_cast<PFNGLVERTEXATTRIB1FVARBPROC>(bglGetProcAddress((const GLubyte *) "glVertexAttrib1fvARB"));
- bgl::blVertexAttrib2fARB = reinterpret_cast<PFNGLVERTEXATTRIB2FARBPROC>(bglGetProcAddress((const GLubyte *) "glVertexAttrib2fARB"));
- bgl::blVertexAttrib2fvARB = reinterpret_cast<PFNGLVERTEXATTRIB2FVARBPROC>(bglGetProcAddress((const GLubyte *) "glVertexAttrib2fvARB"));
- bgl::blVertexAttrib3fARB = reinterpret_cast<PFNGLVERTEXATTRIB3FARBPROC>(bglGetProcAddress((const GLubyte *) "glVertexAttrib3fARB"));
- bgl::blVertexAttrib3fvARB = reinterpret_cast<PFNGLVERTEXATTRIB3FVARBPROC>(bglGetProcAddress((const GLubyte *) "glVertexAttrib3fvARB"));
- bgl::blVertexAttrib4fARB = reinterpret_cast<PFNGLVERTEXATTRIB4FARBPROC>(bglGetProcAddress((const GLubyte *) "glVertexAttrib4fARB"));
- bgl::blVertexAttrib4fvARB = reinterpret_cast<PFNGLVERTEXATTRIB4FVARBPROC>(bglGetProcAddress((const GLubyte *) "glVertexAttrib4fvARB"));
- bgl::blGetVertexAttribdvARB = reinterpret_cast<PFNGLGETVERTEXATTRIBDVARBPROC>(bglGetProcAddress((const GLubyte *) "glGetVertexAttribdvARB"));
- bgl::blGetVertexAttribfvARB = reinterpret_cast<PFNGLGETVERTEXATTRIBFVARBPROC>(bglGetProcAddress((const GLubyte *) "glGetVertexAttribfvARB"));
- bgl::blGetVertexAttribivARB = reinterpret_cast<PFNGLGETVERTEXATTRIBIVARBPROC>(bglGetProcAddress((const GLubyte *) "glGetVertexAttribivARB"));
- if (bgl::blVertexAttrib1fARB && bgl::blVertexAttrib1fvARB && bgl::blVertexAttrib2fARB && bgl::blVertexAttrib2fvARB && bgl::blVertexAttrib3fARB && bgl::blVertexAttrib3fvARB && bgl::blGetVertexAttribdvARB) {
- EnableExtension(_GL_ARB_vertex_program);
- RAS_EXT_support._ARB_vertex_program = 1;
- if (doDebugMessages)
- std::cout << "Enabled GL_ARB_vertex_program" << std::endl;
- } else {
- std::cout << "ERROR: GL_ARB_vertex_program implementation is broken!" << std::endl;
- }
- }
-#endif
-
-
-#ifdef GL_ARB_depth_texture
- if (QueryExtension("GL_ARB_depth_texture"))
- {
- EnableExtension(_GL_ARB_depth_texture);
- RAS_EXT_support._ARB_depth_texture = 1;
- if (doDebugMessages)
- {
- std::cout << "Detected GL_ARB_depth_texture" << std::endl;
- }
- }
-#endif
-/*
-#ifdef GL_EXT_compiled_vertex_array
- if (QueryExtension("GL_EXT_compiled_vertex_array"))
- {
- blLockArraysEXT = reinterpret_cast<PFNGLLOCKARRAYSEXTPROC>(bglGetProcAddress((const GLubyte *) "glLockArraysEXT"));
- blUnlockArraysEXT = reinterpret_cast<PFNGLUNLOCKARRAYSEXTPROC>(bglGetProcAddress((const GLubyte *) "glUnlockArraysEXT"));
- if (blLockArraysEXT && blUnlockArraysEXT) {
- EnableExtension(_GL_EXT_compiled_vertex_array);
- RAS_EXT_support._EXT_compiled_vertex_array = 1;
- if (doDebugMessages)
- std::cout << "Enabled GL_EXT_compiled_vertex_array" << std::endl;
- } else {
- std::cout << "ERROR: GL_EXT_compiled_vertex_array implementation is broken!" << std::endl;
- }
- }
-#endif
-*/
- if (QueryExtension("GL_EXT_separate_specular_color"))
- {
- EnableExtension(_GL_EXT_separate_specular_color);
- if (doDebugMessages)
+ if(firsttime) {
+ firsttime = false;
+
+ if(debug) {
+ if(GLEW_ATI_pn_triangles)
+ std::cout << "Enabled GL_ATI_pn_triangles" << std::endl;
+ if(GLEW_ARB_texture_env_combine)
+ std::cout << "Detected GL_ARB_texture_env_combine" << std::endl;
+ if(GLEW_ARB_texture_cube_map)
+ std::cout << "Detected GL_ARB_texture_cube_map" << std::endl;
+ if(GLEW_ARB_multitexture)
+ std::cout << "Detected GL_ARB_multitexture" << std::endl;
+ if(GLEW_ARB_shader_objects)
+ std::cout << "Detected GL_ARB_shader_objects" << std::endl;
+ if(GLEW_ARB_vertex_shader)
+ std::cout << "Detected GL_ARB_vertex_shader" << std::endl;
+ if(GLEW_ARB_fragment_shader)
+ std::cout << "Detected GL_ARB_fragment_shader" << std::endl;
+ if(GLEW_ARB_vertex_program)
+ std::cout << "Detected GL_ARB_vertex_program" << std::endl;
+ if(GLEW_ARB_depth_texture)
+ std::cout << "Detected GL_ARB_depth_texture" << std::endl;
+ if(GLEW_EXT_separate_specular_color)
std::cout << "Detected GL_EXT_separate_specular_color" << std::endl;
+ }
+ }
}
-
- doDebugMessages = false;
-}
+} // namespace bgl
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_GLExtensionManager.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_GLExtensionManager.h
index a09294f723d..2265becbdad 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_GLExtensionManager.h
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_GLExtensionManager.h
@@ -29,506 +29,14 @@
#ifndef __RAS_GLEXTENSIONMANAGER_H__
#define __RAS_GLEXTENSIONMANAGER_H__
+#include "GL/glew.h"
-#ifdef WIN32
-# include <windows.h>
-# include <GL/gl.h>
+/* Note: this used to have a lot more code, but now extension handling
+ * is done by GLEW, so it does mostly debug stuff */
-#elif defined(__APPLE__)
-# define __glext_h_
-# define GL_GLEXT_LEGACY 1
-# include <OpenGL/gl.h>
-# include <OpenGL/glu.h>
-# undef __glext_h_
-
-#else /* UNIX */
-# define __glext_h_
-# include <GL/gl.h>
-# include <GL/glx.h>
-# undef GL_ARB_multitexture // (ubuntu)
-# undef __glext_h_
-#endif
-
-#ifdef __sgi
-# undef GL_ARB_vertex_program
-#endif
-
-#include "glext.h"
-
-#include "EXT_separate_specular_color.h"
-#include "ARB_multitexture.h"
namespace bgl
{
- /**
- * This is a list of all registered OpenGL extensions.
- * It is available from:
- * http://oss.sgi.com/projects/ogl-sample/registry/
- */
- typedef enum {
- /* ARB Extensions */
- _GL_ARB_imaging,
- _GL_ARB_multitexture ,
- _GLX_ARB_get_proc_address ,
- _GL_ARB_transpose_matrix ,
- _WGL_ARB_buffer_region ,
- _GL_ARB_multisample ,
- _GL_ARB_texture_env_add ,
- _GL_ARB_texture_cube_map ,
- _WGL_ARB_extensions_string ,
- _WGL_ARB_pixel_format ,
- _WGL_ARB_make_current_read ,
- _WGL_ARB_pbuffer ,
- _GL_ARB_texture_compression ,
- _GL_ARB_texture_border_clamp ,
- _GL_ARB_point_parameters ,
- _GL_ARB_vertex_blend ,
- _GL_ARB_matrix_palette ,
- _GL_ARB_texture_env_combine ,
- _GL_ARB_texture_env_crossbar ,
- _GL_ARB_texture_env_dot3 ,
- _WGL_ARB_render_texture ,
- _GL_ARB_texture_mirrored_repeat ,
- _GL_ARB_depth_texture ,
- _GL_ARB_shadow ,
- _GL_ARB_shadow_ambient ,
- _GL_ARB_window_pos ,
- _GL_ARB_vertex_program ,
- _GL_ARB_fragment_program ,
- _GL_ARB_vertex_buffer_object ,
- _GL_ARB_occlusion_query ,
- _GL_ARB_shader_objects ,
- _GL_ARB_vertex_shader ,
- _GL_ARB_fragment_shader ,
- _GL_ARB_shading_language_100 ,
- _GL_ARB_texture_non_power_of_two ,
- _GL_ARB_point_sprite ,
- _GL_ARB_fragment_program_shadow ,
-
- /* Non ARB Extensions */
- _GL_EXT_abgr ,
- _GL_EXT_blend_color ,
- _GL_EXT_polygon_offset ,
- _GL_EXT_texture ,
- _GL_EXT_texture3D ,
- _GL_SGIS_texture_filter4 ,
- _GL_EXT_subtexture ,
- _GL_EXT_copy_texture ,
- _GL_EXT_histogram ,
- _GL_EXT_convolution ,
- _GL_SGI_color_matrix ,
- _GL_SGI_color_table ,
- _GL_SGIS_pixel_texture ,
- _GL_SGIS_texture4D ,
- _GL_SGI_texture_color_table ,
- _GL_EXT_cmyka ,
- _GL_EXT_texture_object ,
- _GL_SGIS_detail_texture ,
- _GL_SGIS_sharpen_texture ,
- _GL_EXT_packed_pixels ,
- _GL_SGIS_texture_lod ,
- _GL_SGIS_multisample ,
- _GL_EXT_rescale_normal ,
- _GLX_EXT_visual_info ,
- _GL_EXT_vertex_array ,
- _GL_EXT_misc_attribute ,
- _GL_SGIS_generate_mipmap ,
- _GL_SGIX_clipmap ,
- _GL_SGIX_shadow ,
- _GL_SGIS_texture_edge_clamp ,
- _GL_SGIS_texture_border_clamp ,
- _GL_EXT_blend_minmax ,
- _GL_EXT_blend_subtract ,
- _GL_EXT_blend_logic_op ,
- _GLX_SGI_swap_control ,
- _GLX_SGI_video_sync ,
- _GLX_SGI_make_current_read ,
- _GLX_SGIX_video_source ,
- _GLX_EXT_visual_rating ,
- _GL_SGIX_interlace ,
- _GLX_EXT_import_context ,
- _GLX_SGIX_fbconfig ,
- _GLX_SGIX_pbuffer ,
- _GL_SGIS_texture_select ,
- _GL_SGIX_sprite ,
- _GL_SGIX_texture_multi_buffer ,
- _GL_EXT_point_parameters ,
- _GL_SGIX_instruments ,
- _GL_SGIX_texture_scale_bias ,
- _GL_SGIX_framezoom ,
- _GL_SGIX_tag_sample_buffer ,
- _GL_SGIX_reference_plane ,
- _GL_SGIX_flush_raster ,
- _GLX_SGI_cushion ,
- _GL_SGIX_depth_texture ,
- _GL_SGIS_fog_function ,
- _GL_SGIX_fog_offset ,
- _GL_HP_image_transform ,
- _GL_HP_convolution_border_modes ,
- _GL_SGIX_texture_add_env ,
- _GL_EXT_color_subtable ,
- _GLU_EXT_object_space_tess ,
- _GL_PGI_vertex_hints ,
- _GL_PGI_misc_hints ,
- _GL_EXT_paletted_texture ,
- _GL_EXT_clip_volume_hint ,
- _GL_SGIX_list_priority ,
- _GL_SGIX_ir_instrument1 ,
- _GLX_SGIX_video_resize ,
- _GL_SGIX_texture_lod_bias ,
- _GLU_SGI_filter4_parameters ,
- _GLX_SGIX_dm_buffer ,
- _GL_SGIX_shadow_ambient ,
- _GLX_SGIX_swap_group ,
- _GLX_SGIX_swap_barrier ,
- _GL_EXT_index_texture ,
- _GL_EXT_index_material ,
- _GL_EXT_index_func ,
- _GL_EXT_index_array_formats ,
- _GL_EXT_compiled_vertex_array ,
- _GL_EXT_cull_vertex ,
- _GLU_EXT_nurbs_tessellator ,
- _GL_SGIX_ycrcb ,
- _GL_EXT_fragment_lighting ,
- _GL_IBM_rasterpos_clip ,
- _GL_HP_texture_lighting ,
- _GL_EXT_draw_range_elements ,
- _GL_WIN_phong_shading ,
- _GL_WIN_specular_fog ,
- _GLX_SGIS_color_range ,
- _GL_EXT_light_texture ,
- _GL_SGIX_blend_alpha_minmax ,
- _GL_EXT_scene_marker ,
- _GL_SGIX_pixel_texture_bits ,
- _GL_EXT_bgra ,
- _GL_SGIX_async ,
- _GL_SGIX_async_pixel ,
- _GL_SGIX_async_histogram ,
- _GL_INTEL_texture_scissor ,
- _GL_INTEL_parallel_arrays ,
- _GL_HP_occlusion_test ,
- _GL_EXT_pixel_transform ,
- _GL_EXT_pixel_transform_color_table ,
- _GL_EXT_shared_texture_palette ,
- _GLX_SGIS_blended_overlay ,
- _GL_EXT_separate_specular_color ,
- _GL_EXT_secondary_color ,
- _GL_EXT_texture_env ,
- _GL_EXT_texture_perturb_normal ,
- _GL_EXT_multi_draw_arrays ,
- _GL_EXT_fog_coord ,
- _GL_REND_screen_coordinates ,
- _GL_EXT_coordinate_frame ,
- _GL_EXT_texture_env_combine ,
- _GL_APPLE_specular_vector ,
- _GL_SGIX_pixel_texture ,
- _GL_APPLE_transform_hint ,
- _GL_SUNX_constant_data ,
- _GL_SUN_global_alpha ,
- _GL_SUN_triangle_list ,
- _GL_SUN_vertex ,
- _WGL_EXT_display_color_table ,
- _WGL_EXT_extensions_string ,
- _WGL_EXT_make_current_read ,
- _WGL_EXT_pixel_format ,
- _WGL_EXT_pbuffer ,
- _WGL_EXT_swap_control ,
- _GL_EXT_blend_func_separate ,
- _GL_INGR_color_clamp ,
- _GL_INGR_interlace_read ,
- _GL_EXT_stencil_wrap ,
- _WGL_EXT_depth_float ,
- _GL_EXT_422_pixels ,
- _GL_NV_texgen_reflection ,
- _GL_SGIX_texture_range ,
- _GL_SUN_convolution_border_modes ,
- _GLX_SUN_get_transparent_index ,
- _GL_EXT_texture_env_add ,
- _GL_EXT_texture_lod_bias ,
- _GL_EXT_texture_filter_anisotropic ,
- _GL_EXT_vertex_weighting ,
- _GL_NV_light_max_exponent ,
- _GL_NV_vertex_array_range ,
- _GL_NV_register_combiners ,
- _GL_NV_fog_distance ,
- _GL_NV_texgen_emboss ,
- _GL_NV_blend_square ,
- _GL_NV_texture_env_combine4 ,
- _GL_MESA_resize_buffers ,
- _GL_MESA_window_pos ,
- _GL_EXT_texture_compression_s3tc ,
- _GL_IBM_cull_vertex ,
- _GL_IBM_multimode_draw_arrays ,
- _GL_IBM_vertex_array_lists ,
- _GL_3DFX_texture_compression_FXT1 ,
- _GL_3DFX_multisample ,
- _GL_3DFX_tbuffer ,
- _WGL_EXT_multisample ,
- _GL_SGIX_vertex_preclip ,
- _GL_SGIX_resample ,
- _GL_SGIS_texture_color_mask ,
- _GLX_MESA_copy_sub_buffer ,
- _GLX_MESA_pixmap_colormap ,
- _GLX_MESA_release_buffers ,
- _GLX_MESA_set_3dfx_mode ,
- _GL_EXT_texture_env_dot3 ,
- _GL_ATI_texture_mirror_once ,
- _GL_NV_fence ,
- _GL_IBM_static_data ,
- _GL_IBM_texture_mirrored_repeat ,
- _GL_NV_evaluators ,
- _GL_NV_packed_depth_stencil ,
- _GL_NV_register_combiners2 ,
- _GL_NV_texture_compression_vtc ,
- _GL_NV_texture_rectangle ,
- _GL_NV_texture_shader ,
- _GL_NV_texture_shader2 ,
- _GL_NV_vertex_array_range2 ,
- _GL_NV_vertex_program ,
- _GLX_SGIX_visual_select_group ,
- _GL_SGIX_texture_coordinate_clamp ,
- _GLX_OML_swap_method ,
- _GLX_OML_sync_control ,
- _GL_OML_interlace ,
- _GL_OML_subsample ,
- _GL_OML_resample ,
- _WGL_OML_sync_control ,
- _GL_NV_copy_depth_to_color ,
- _GL_ATI_envmap_bumpmap ,
- _GL_ATI_fragment_shader ,
- _GL_ATI_pn_triangles ,
- _GL_ATI_vertex_array_object ,
- _GL_EXT_vertex_shader ,
- _GL_ATI_vertex_streams ,
- _WGL_I3D_digital_video_control ,
- _WGL_I3D_gamma ,
- _WGL_I3D_genlock ,
- _WGL_I3D_image_buffer ,
- _WGL_I3D_swap_frame_lock ,
- _WGL_I3D_swap_frame_usage ,
- _GL_ATI_element_array ,
- _GL_SUN_mesh_array ,
- _GL_SUN_slice_accum ,
- _GL_NV_multisample_filter_hint ,
- _GL_NV_depth_clamp ,
- _GL_NV_occlusion_query ,
- _GL_NV_point_sprite ,
- _WGL_NV_render_depth_texture ,
- _WGL_NV_render_texture_rectangle ,
- _GL_NV_texture_shader3 ,
- _GL_NV_vertex_program1_1 ,
- _GL_EXT_shadow_funcs ,
- _GL_EXT_stencil_two_side ,
- _GL_ATI_text_fragment_shader ,
- _GL_APPLE_client_storage ,
- _GL_APPLE_element_array ,
- _GL_APPLE_fence ,
- _GL_APPLE_vertex_array_object ,
- _GL_APPLE_vertex_array_range ,
- _GL_APPLE_ycbcr_422 ,
- _GL_S3_s3tc ,
- _GL_ATI_draw_buffers ,
- _WGL_ATI_pixel_format_float ,
- _GL_ATI_texture_env_combine3 ,
- _GL_ATI_texture_float ,
- _GL_NV_float_buffer ,
- _GL_NV_fragment_program ,
- _GL_NV_half_float ,
- _GL_NV_pixel_data_range ,
- _GL_NV_primitive_restart ,
- _GL_NV_texture_expand_normal ,
- _GL_NV_vertex_program2 ,
- _GL_ATI_map_object_buffer ,
- _GL_ATI_separate_stencil ,
- _GL_ATI_vertex_attrib_array_object ,
- _GL_OES_byte_coordinates ,
- _GL_OES_fixed_point ,
- _GL_OES_single_precision ,
- _GL_OES_compressed_paletted_texture ,
- _GL_OES_read_format ,
- _GL_OES_query_matrix ,
- _GL_EXT_depth_bounds_test ,
- _GL_EXT_texture_mirror_clamp ,
- _GL_EXT_blend_equation_separate ,
- _GL_MESA_pack_invert ,
- _GL_MESA_ycbcr_texture,
-
- /* Finished */
- _BGL_TEST,
- NUM_EXTENSIONS
- } ExtensionName;
-
- /**
- * Checks at runtime whether OpenGL supports the named extension.
- * Returns true if OpenGL supports the given extension.
- *
- * @param name The extension name to check.
- */
- bool QueryExtension(ExtensionName name);
- /**
- * Checks the OpenGL version.
- * Returns true if OpenGL is at least the given version.
- *
- * @param major The major version required
- * @param minor The minor version required
- */
- bool QueryVersion(int major, int minor);
- /**
- * This will dynamically link all runtime supported extensions into
- * the binary.
- *
- * @param debug Enable debug printing. This will print debugging info
- * when extensions are loaded.
- */
- void InitExtensions(int debug);
-
-#if defined(PFNGLPNTRIANGLESIATIPROC)
-extern PFNGLPNTRIANGLESIATIPROC blPNTrianglesiATI;
-extern PFNGLPNTRIANGLESFATIPROC blPNTrianglesfATI;
-#endif
-
-
-// quick runtime checks
-typedef struct BL_EXTInfo
-{
- BL_EXTInfo():
- _ARB_multitexture(0),
- _ARB_texture_env_combine(0),
- _EXT_blend_color(0),
- _ARB_texture_cube_map(0),
- _ARB_shader_objects(0),
- _ARB_vertex_shader(0),
- _ARB_fragment_shader(0),
- _EXT_texture3D(0),
- _ARB_vertex_program(0),
- _ARB_depth_texture(0),
- _EXT_compiled_vertex_array(0)
- {
- //
- }
- bool _ARB_multitexture;
- bool _ARB_texture_env_combine;
- bool _EXT_blend_color;
- bool _ARB_texture_cube_map;
- bool _ARB_shader_objects;
- bool _ARB_vertex_shader;
- bool _ARB_fragment_shader;
- bool _EXT_texture3D;
- bool _ARB_vertex_program;
- bool _ARB_depth_texture;
- bool _EXT_compiled_vertex_array;
-}BL_EXTInfo;
-
-extern BL_EXTInfo RAS_EXT_support;
-
-#ifdef GL_ARB_multitexture // defined in glext.h now...
-extern int max_texture_units;
-extern PFNGLACTIVETEXTUREARBPROC blActiveTextureARB;
-extern PFNGLCLIENTACTIVETEXTUREARBPROC blClientActiveTextureARB;
-extern PFNGLMULTITEXCOORD1DARBPROC blMultiTexCoord1dARB;
-extern PFNGLMULTITEXCOORD1DVARBPROC blMultiTexCoord1dvARB;
-extern PFNGLMULTITEXCOORD1FARBPROC blMultiTexCoord1fARB;
-extern PFNGLMULTITEXCOORD1FVARBPROC blMultiTexCoord1fvARB;
-extern PFNGLMULTITEXCOORD1IARBPROC blMultiTexCoord1iARB;
-extern PFNGLMULTITEXCOORD1IVARBPROC blMultiTexCoord1ivARB;
-extern PFNGLMULTITEXCOORD1SARBPROC blMultiTexCoord1sARB;
-extern PFNGLMULTITEXCOORD1SVARBPROC blMultiTexCoord1svARB;
-extern PFNGLMULTITEXCOORD2DARBPROC blMultiTexCoord2dARB;
-extern PFNGLMULTITEXCOORD2DVARBPROC blMultiTexCoord2dvARB;
-extern PFNGLMULTITEXCOORD2FARBPROC blMultiTexCoord2fARB;
-extern PFNGLMULTITEXCOORD2FVARBPROC blMultiTexCoord2fvARB;
-extern PFNGLMULTITEXCOORD2IARBPROC blMultiTexCoord2iARB;
-extern PFNGLMULTITEXCOORD2IVARBPROC blMultiTexCoord2ivARB;
-extern PFNGLMULTITEXCOORD2SARBPROC blMultiTexCoord2sARB;
-extern PFNGLMULTITEXCOORD2SVARBPROC blMultiTexCoord2svARB;
-extern PFNGLMULTITEXCOORD3DARBPROC blMultiTexCoord3dARB;
-extern PFNGLMULTITEXCOORD3DVARBPROC blMultiTexCoord3dvARB;
-extern PFNGLMULTITEXCOORD3FARBPROC blMultiTexCoord3fARB;
-extern PFNGLMULTITEXCOORD3FVARBPROC blMultiTexCoord3fvARB;
-extern PFNGLMULTITEXCOORD3IARBPROC blMultiTexCoord3iARB;
-extern PFNGLMULTITEXCOORD3IVARBPROC blMultiTexCoord3ivARB;
-extern PFNGLMULTITEXCOORD3SARBPROC blMultiTexCoord3sARB;
-extern PFNGLMULTITEXCOORD3SVARBPROC blMultiTexCoord3svARB;
-extern PFNGLMULTITEXCOORD4DARBPROC blMultiTexCoord4dARB;
-extern PFNGLMULTITEXCOORD4DVARBPROC blMultiTexCoord4dvARB;
-extern PFNGLMULTITEXCOORD4FARBPROC blMultiTexCoord4fARB;
-extern PFNGLMULTITEXCOORD4FVARBPROC blMultiTexCoord4fvARB;
-extern PFNGLMULTITEXCOORD4IARBPROC blMultiTexCoord4iARB;
-extern PFNGLMULTITEXCOORD4IVARBPROC blMultiTexCoord4ivARB;
-extern PFNGLMULTITEXCOORD4SARBPROC blMultiTexCoord4sARB;
-extern PFNGLMULTITEXCOORD4SVARBPROC blMultiTexCoord4svARB;
-#endif
-
-
-#ifdef GL_ARB_shader_objects
-extern PFNGLDELETEOBJECTARBPROC blDeleteObjectARB;
-extern PFNGLGETHANDLEARBPROC blGetHandleARB;
-extern PFNGLDETACHOBJECTARBPROC blDetachObjectARB;
-extern PFNGLCREATESHADEROBJECTARBPROC blCreateShaderObjectARB;
-extern PFNGLSHADERSOURCEARBPROC blShaderSourceARB;
-extern PFNGLCOMPILESHADERARBPROC blCompileShaderARB;
-extern PFNGLCREATEPROGRAMOBJECTARBPROC blCreateProgramObjectARB;
-extern PFNGLATTACHOBJECTARBPROC blAttachObjectARB;
-extern PFNGLLINKPROGRAMARBPROC blLinkProgramARB;
-extern PFNGLUSEPROGRAMOBJECTARBPROC blUseProgramObjectARB;
-extern PFNGLVALIDATEPROGRAMARBPROC blValidateProgramARB;
-extern PFNGLUNIFORM1FARBPROC blUniform1fARB;
-extern PFNGLUNIFORM2FARBPROC blUniform2fARB;
-extern PFNGLUNIFORM3FARBPROC blUniform3fARB;
-extern PFNGLUNIFORM4FARBPROC blUniform4fARB;
-extern PFNGLUNIFORM1IARBPROC blUniform1iARB;
-extern PFNGLUNIFORM2IARBPROC blUniform2iARB;
-extern PFNGLUNIFORM3IARBPROC blUniform3iARB;
-extern PFNGLUNIFORM4IARBPROC blUniform4iARB;
-extern PFNGLUNIFORM1FVARBPROC blUniform1fvARB;
-extern PFNGLUNIFORM2FVARBPROC blUniform2fvARB;
-extern PFNGLUNIFORM3FVARBPROC blUniform3fvARB;
-extern PFNGLUNIFORM4FVARBPROC blUniform4fvARB;
-extern PFNGLUNIFORM1IVARBPROC blUniform1ivARB;
-extern PFNGLUNIFORM2IVARBPROC blUniform2ivARB;
-extern PFNGLUNIFORM3IVARBPROC blUniform3ivARB;
-extern PFNGLUNIFORM4IVARBPROC blUniform4ivARB;
-extern PFNGLUNIFORMMATRIX2FVARBPROC blUniformMatrix2fvARB;
-extern PFNGLUNIFORMMATRIX3FVARBPROC blUniformMatrix3fvARB;
-extern PFNGLUNIFORMMATRIX4FVARBPROC blUniformMatrix4fvARB;
-extern PFNGLGETOBJECTPARAMETERFVARBPROC blGetObjectParameterfvARB;
-extern PFNGLGETOBJECTPARAMETERIVARBPROC blGetObjectParameterivARB;
-extern PFNGLGETINFOLOGARBPROC blGetInfoLogARB;
-extern PFNGLGETATTACHEDOBJECTSARBPROC blGetAttachedObjectsARB;
-extern PFNGLGETUNIFORMLOCATIONARBPROC blGetUniformLocationARB;
-extern PFNGLGETACTIVEUNIFORMARBPROC blGetActiveUniformARB;
-extern PFNGLGETUNIFORMFVARBPROC blGetUniformfvARB;
-extern PFNGLGETUNIFORMIVARBPROC blGetUniformivARB;
-extern PFNGLGETSHADERSOURCEARBPROC blGetShaderSourceARB;
-#endif
-
-#ifdef GL_ARB_vertex_shader
-extern PFNGLBINDATTRIBLOCATIONARBPROC blBindAttribLocationARB;
-extern PFNGLGETACTIVEATTRIBARBPROC blGetActiveAttribARB;
-extern PFNGLGETATTRIBLOCATIONARBPROC blGetAttribLocationARB;
-#endif
-
-#ifdef GL_ARB_vertex_program
-extern PFNGLVERTEXATTRIB1FARBPROC blVertexAttrib1fARB;
-extern PFNGLVERTEXATTRIB1FVARBPROC blVertexAttrib1fvARB;
-extern PFNGLVERTEXATTRIB2FARBPROC blVertexAttrib2fARB;
-extern PFNGLVERTEXATTRIB2FVARBPROC blVertexAttrib2fvARB;
-extern PFNGLVERTEXATTRIB3FARBPROC blVertexAttrib3fARB;
-extern PFNGLVERTEXATTRIB3FVARBPROC blVertexAttrib3fvARB;
-extern PFNGLVERTEXATTRIB4FARBPROC blVertexAttrib4fARB;
-extern PFNGLVERTEXATTRIB4FVARBPROC blVertexAttrib4fvARB;
-extern PFNGLGETPROGRAMSTRINGARBPROC blGetProgramStringARB;
-extern PFNGLGETVERTEXATTRIBDVARBPROC blGetVertexAttribdvARB;
-extern PFNGLGETVERTEXATTRIBFVARBPROC blGetVertexAttribfvARB;
-extern PFNGLGETVERTEXATTRIBIVARBPROC blGetVertexAttribivARB;
-#endif
-
-/*
-#ifdef GL_EXT_compiled_vertex_array
-extern PFNGLLOCKARRAYSEXTPROC blLockArraysEXT;
-extern PFNGLUNLOCKARRAYSEXTPROC blUnlockArraysEXT;
-#endif
-*/
+ void InitExtensions(bool debug);
} /* namespace bgl */
-
#endif /* __RAS_GLEXTENSIONMANAGER_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp
index ed4cfb2ae42..2c4b55ff964 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp
@@ -6,15 +6,11 @@
#ifdef WIN32
#include <windows.h>
#endif // WIN32
-#ifdef __APPLE__
-#define GL_GLEXT_LEGACY 1
-#include <OpenGL/gl.h>
-#else
-#include <GL/gl.h>
-#endif
+#include "GL/glew.h"
+
+#include "RAS_MaterialBucket.h"
#include "RAS_TexVert.h"
-#include "RAS_GLExtensionManager.h"
#include "MT_assert.h"
//#ifndef NDEBUG
@@ -25,11 +21,21 @@
#define spit(x)
//#endif
-RAS_ListSlot::RAS_ListSlot()
+RAS_ListSlot::RAS_ListSlot(RAS_ListRasterizer* rasty)
: KX_ListSlot(),
+ m_list(0),
m_flag(LIST_MODIFY|LIST_CREATE),
- m_list(0)
+ m_rasty(rasty)
+{
+}
+
+int RAS_ListSlot::Release()
{
+ if (--m_refcount > 0)
+ return m_refcount;
+ m_rasty->RemoveListSlot(this);
+ delete this;
+ return 0;
}
RAS_ListSlot::~RAS_ListSlot()
@@ -96,8 +102,9 @@ bool RAS_ListSlot::End()
-RAS_ListRasterizer::RAS_ListRasterizer(RAS_ICanvas* canvas)
-: RAS_OpenGLRasterizer(canvas)
+RAS_ListRasterizer::RAS_ListRasterizer(RAS_ICanvas* canvas, bool useVertexArrays, bool lock)
+: RAS_VAOpenGLRasterizer(canvas, lock),
+ mUseVertexArrays(useVertexArrays)
{
// --
}
@@ -107,22 +114,34 @@ RAS_ListRasterizer::~RAS_ListRasterizer()
ReleaseAlloc();
}
-RAS_ListSlot* RAS_ListRasterizer::FindOrAdd(const vecVertexArray& vertexarrays, KX_ListSlot** slot)
+void RAS_ListRasterizer::RemoveListSlot(RAS_ListSlot* list)
+{
+ RAS_Lists::iterator it = mLists.begin();
+ while(it != mLists.end()) {
+ if (it->second == list) {
+ mLists.erase(it);
+ break;
+ }
+ it++;
+ }
+}
+
+RAS_ListSlot* RAS_ListRasterizer::FindOrAdd(RAS_MeshSlot& ms)
{
/*
Keep a copy of constant lists submitted for rendering,
this guards against (replicated)new...delete every frame,
and we can reuse lists!
- :: sorted by vertex array
+ :: sorted by mesh slot
*/
- RAS_ListSlot* localSlot = (RAS_ListSlot*)*slot;
+ RAS_ListSlot* localSlot = (RAS_ListSlot*)ms.m_DisplayList;
if(!localSlot) {
- RAS_Lists::iterator it = mLists.find(vertexarrays);
+ RAS_Lists::iterator it = mLists.find(&ms);
if(it == mLists.end()) {
- localSlot = new RAS_ListSlot();
- mLists.insert(std::pair<vecVertexArray, RAS_ListSlot*>(vertexarrays, localSlot));
+ localSlot = new RAS_ListSlot(this);
+ mLists.insert(std::pair<RAS_MeshSlot*, RAS_ListSlot*>(&ms, localSlot));
} else {
- localSlot = it->second;
+ localSlot = static_cast<RAS_ListSlot*>(it->second->AddRef());
}
}
MT_assert(localSlot);
@@ -139,71 +158,87 @@ void RAS_ListRasterizer::ReleaseAlloc()
mLists.clear();
}
-
-void RAS_ListRasterizer::IndexPrimitives(
- const vecVertexArray & vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
- class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor,
- class KX_ListSlot** slot)
+void RAS_ListRasterizer::IndexPrimitives(RAS_MeshSlot& ms)
{
RAS_ListSlot* localSlot =0;
- // useObjectColor(are we updating every frame?)
- if(!useObjectColor) {
- localSlot = FindOrAdd(vertexarrays, slot);
+ if(ms.m_bDisplayList) {
+ localSlot = FindOrAdd(ms);
localSlot->DrawList();
- if(localSlot->End())
+ if(localSlot->End()) {
+ // save slot here too, needed for replicas and object using same mesh
+ // => they have the same vertexarray but different mesh slot
+ ms.m_DisplayList = localSlot;
return;
+ }
}
+
+ if (mUseVertexArrays)
+ RAS_VAOpenGLRasterizer::IndexPrimitives(ms);
+ else
+ RAS_OpenGLRasterizer::IndexPrimitives(ms);
- RAS_OpenGLRasterizer::IndexPrimitives(
- vertexarrays, indexarrays,
- mode, polymat,
- rendertools, useObjectColor,
- rgbacolor,slot
- );
-
- if(!useObjectColor) {
+ if(ms.m_bDisplayList) {
localSlot->EndList();
- *slot = localSlot;
+ ms.m_DisplayList = localSlot;
}
}
-void RAS_ListRasterizer::IndexPrimitivesMulti(
- const vecVertexArray& vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
- class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor,
- class KX_ListSlot** slot)
+void RAS_ListRasterizer::IndexPrimitivesMulti(RAS_MeshSlot& ms)
{
RAS_ListSlot* localSlot =0;
- // useObjectColor(are we updating every frame?)
- if(!useObjectColor) {
- localSlot = FindOrAdd(vertexarrays, slot);
+ if(ms.m_bDisplayList) {
+ localSlot = FindOrAdd(ms);
localSlot->DrawList();
- if(localSlot->End())
+ if(localSlot->End()) {
+ // save slot here too, needed for replicas and object using same mesh
+ // => they have the same vertexarray but different mesh slot
+ ms.m_DisplayList = localSlot;
return;
+ }
}
- RAS_OpenGLRasterizer::IndexPrimitivesMulti(
- vertexarrays, indexarrays,
- mode, polymat,
- rendertools, useObjectColor,
- rgbacolor,slot
- );
- if(!useObjectColor) {
+ // workaround: note how we do not use vertex arrays for making display
+ // lists, since glVertexAttribPointerARB doesn't seem to work correct
+ // in display lists on ATI? either a bug in the driver or in Blender ..
+ if (mUseVertexArrays && !localSlot)
+ RAS_VAOpenGLRasterizer::IndexPrimitivesMulti(ms);
+ else
+ RAS_OpenGLRasterizer::IndexPrimitivesMulti(ms);
+
+ if(ms.m_bDisplayList) {
localSlot->EndList();
- *slot = localSlot;
+ ms.m_DisplayList = localSlot;
+ }
+}
+
+bool RAS_ListRasterizer::Init(void)
+{
+ if (mUseVertexArrays) {
+ return RAS_VAOpenGLRasterizer::Init();
+ } else {
+ return RAS_OpenGLRasterizer::Init();
+ }
+}
+
+void RAS_ListRasterizer::SetDrawingMode(int drawingmode)
+{
+ if (mUseVertexArrays) {
+ RAS_VAOpenGLRasterizer::SetDrawingMode(drawingmode);
+ } else {
+ RAS_OpenGLRasterizer::SetDrawingMode(drawingmode);
+ }
+}
+
+void RAS_ListRasterizer::Exit()
+{
+ if (mUseVertexArrays) {
+ RAS_VAOpenGLRasterizer::Exit();
+ } else {
+ RAS_OpenGLRasterizer::Exit();
}
}
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h
index 82840cd1399..96d6d2a995d 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h
@@ -2,17 +2,21 @@
#define __RAS_LISTRASTERIZER_H__
#include "RAS_MaterialBucket.h"
-#include "RAS_OpenGLRasterizer.h"
+#include "RAS_VAOpenGLRasterizer.h"
#include <vector>
+#include <map>
+class RAS_ListRasterizer;
class RAS_ListSlot : public KX_ListSlot
{
unsigned int m_list;
unsigned int m_flag;
+ RAS_ListRasterizer* m_rasty;
public:
- RAS_ListSlot();
+ RAS_ListSlot(RAS_ListRasterizer* rasty);
virtual ~RAS_ListSlot();
virtual void SetModified(bool mod);
+ virtual int Release();
void RemoveList();
void DrawList();
@@ -31,40 +35,28 @@ enum RAS_ListSlotFlags {
LIST_REGEN =64
};
-typedef std::map<const vecVertexArray, RAS_ListSlot*> RAS_Lists;
+typedef std::map<class RAS_MeshSlot*, RAS_ListSlot*> RAS_Lists;
-class RAS_ListRasterizer : public RAS_OpenGLRasterizer
+class RAS_ListRasterizer : public RAS_VAOpenGLRasterizer
{
+ bool mUseVertexArrays;
RAS_Lists mLists;
- RAS_ListSlot* FindOrAdd(const vecVertexArray& vertexarrays, KX_ListSlot** slot);
+ RAS_ListSlot* FindOrAdd(class RAS_MeshSlot& ms);
void ReleaseAlloc();
public:
- RAS_ListRasterizer(RAS_ICanvas* canvas);
+ void RemoveListSlot(RAS_ListSlot* list);
+ RAS_ListRasterizer(RAS_ICanvas* canvas, bool useVertexArrays=false, bool lock=false);
virtual ~RAS_ListRasterizer();
- virtual void IndexPrimitives(
- const vecVertexArray& vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
- class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor,
- class KX_ListSlot** slot
- );
+ virtual void IndexPrimitives(class RAS_MeshSlot& ms);
+ virtual void IndexPrimitivesMulti(class RAS_MeshSlot& ms);
- virtual void IndexPrimitivesMulti(
- const vecVertexArray& vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
- class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor,
- class KX_ListSlot** slot
- );
+ virtual bool Init();
+ virtual void Exit();
+
+ virtual void SetDrawingMode(int drawingmode);
virtual bool QueryLists(){return true;}
};
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp
index 7988bab337f..87a0a1d8b9e 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp
@@ -27,35 +27,19 @@
*/
#include <math.h>
+#include <stdlib.h>
#include "RAS_OpenGLRasterizer.h"
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-#ifdef WIN32
-#include <windows.h>
-#endif // WIN32
-#ifdef __APPLE__
-#define GL_GLEXT_LEGACY 1
-#include <OpenGL/gl.h>
-#include <OpenGL/glu.h>
-#else
-#include <GL/gl.h>
-#if defined(__sun__) && !defined(__sparc__)
-#include <mesa/glu.h>
-#else
-#include <GL/glu.h>
-#endif
-#endif
+#include "GL/glew.h"
#include "RAS_Rect.h"
#include "RAS_TexVert.h"
#include "MT_CmMatrix4x4.h"
#include "RAS_IRenderTools.h" // rendering text
-#include "RAS_GLExtensionManager.h"
+#include "GPU_draw.h"
+#include "GPU_material.h"
/**
* 32x32 bit masks for vinterlace stereo mode
@@ -82,12 +66,16 @@ RAS_OpenGLRasterizer::RAS_OpenGLRasterizer(RAS_ICanvas* canvas)
m_focallength(0.0),
m_setfocallength(false),
m_noOfScanlines(32),
- m_useTang(false),
- m_materialCachingInfo(0),
m_motionblur(0),
- m_motionblurvalue(-1.0)
-{
- m_viewmatrix.Identity();
+ m_motionblurvalue(-1.0),
+ m_texco_num(0),
+ m_attrib_num(0),
+ m_last_blendmode(GPU_BLEND_SOLID),
+ m_last_frontface(true),
+ m_materialCachingInfo(0)
+{
+ m_viewmatrix.setIdentity();
+ m_viewinvmatrix.setIdentity();
for (int i = 0; i < 32; i++)
{
@@ -104,78 +92,9 @@ RAS_OpenGLRasterizer::~RAS_OpenGLRasterizer()
{
}
-
-
-static void Myinit_gl_stuff(void)
-{
- float mat_specular[] = { 0.5, 0.5, 0.5, 1.0 };
- float mat_shininess[] = { 35.0 };
-/* float one= 1.0; */
- int a, x, y;
- GLubyte pat[32*32];
- const GLubyte *patc= pat;
-
- glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_specular);
- glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
- glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess);
-
-
-#if defined(__FreeBSD) || defined(__linux__)
- glDisable(GL_DITHER); /* op sgi/sun hardware && 12 bits */
-#endif
-
- /* no local viewer, looks ugly in ortho mode */
- /* glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, &one); */
-
- glDepthFunc(GL_LEQUAL);
- /* scaling matrices */
- glEnable(GL_NORMALIZE);
-
- glShadeModel(GL_FLAT);
-
- glDisable(GL_ALPHA_TEST);
- glDisable(GL_BLEND);
- glDisable(GL_DEPTH_TEST);
- glDisable(GL_FOG);
- glDisable(GL_LIGHTING);
- glDisable(GL_LOGIC_OP);
- glDisable(GL_STENCIL_TEST);
- glDisable(GL_TEXTURE_1D);
- glDisable(GL_TEXTURE_2D);
-
- glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
- glPixelTransferi(GL_RED_SCALE, 1);
- glPixelTransferi(GL_RED_BIAS, 0);
- glPixelTransferi(GL_GREEN_SCALE, 1);
- glPixelTransferi(GL_GREEN_BIAS, 0);
- glPixelTransferi(GL_BLUE_SCALE, 1);
- glPixelTransferi(GL_BLUE_BIAS, 0);
- glPixelTransferi(GL_ALPHA_SCALE, 1);
- glPixelTransferi(GL_ALPHA_BIAS, 0);
-
- a = 0;
- for(x=0; x<32; x++)
- {
- for(y=0; y<4; y++)
- {
- if( (x) & 1) pat[a++]= 0x88;
- else pat[a++]= 0x22;
- }
- }
-
- glPolygonStipple(patc);
-
- glFrontFace(GL_CCW);
- glCullFace(GL_BACK);
- glEnable(GL_CULL_FACE);
-}
-
-
-
bool RAS_OpenGLRasterizer::Init()
{
-
- Myinit_gl_stuff();
+ GPU_state_init();
m_redback = 0.4375;
m_greenback = 0.4375;
@@ -186,6 +105,13 @@ bool RAS_OpenGLRasterizer::Init()
m_ambg = 0.0f;
m_ambb = 0.0f;
+ glDisable(GL_BLEND);
+ glDisable(GL_ALPHA_TEST);
+ m_last_blendmode = GPU_BLEND_SOLID;
+
+ glFrontFace(GL_CCW);
+ m_last_frontface = true;
+
glClearColor(m_redback,m_greenback,m_blueback,m_alphaback);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
@@ -204,18 +130,6 @@ void RAS_OpenGLRasterizer::SetAmbientColor(float red, float green, float blue)
}
-void RAS_OpenGLRasterizer::SetAlphaTest(bool enable)
-{
- if (enable)
- {
- glEnable(GL_ALPHA_TEST);
- glAlphaFunc(GL_GREATER, 0.6f);
- }
- else glDisable(GL_ALPHA_TEST);
-}
-
-
-
void RAS_OpenGLRasterizer::SetAmbient(float factor)
{
float ambient[] = { m_ambr*factor, m_ambg*factor, m_ambb*factor, 1.0f };
@@ -334,27 +248,16 @@ void RAS_OpenGLRasterizer::Exit()
glDisable(GL_POLYGON_STIPPLE);
glDisable(GL_LIGHTING);
- if (bgl::QueryExtension(bgl::_GL_EXT_separate_specular_color) || bgl::QueryVersion(1, 2))
+ if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2)
glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
EndFrame();
}
-bool RAS_OpenGLRasterizer::InterlacedStereo() const
-{
- return m_stereomode == RAS_STEREO_VINTERLACE || m_stereomode == RAS_STEREO_INTERLACED;
-}
-
bool RAS_OpenGLRasterizer::BeginFrame(int drawingmode, double time)
{
m_time = time;
m_drawingmode = drawingmode;
-
- if (!InterlacedStereo() || m_curreye == RAS_STEREO_LEFTEYE)
- {
- m_2DCanvas->ClearColor(m_redback,m_greenback,m_blueback,m_alphaback);
- m_2DCanvas->ClearBuffer(RAS_ICanvas::COLOR_BUFFER);
- }
// Blender camera routine destroys the settings
if (m_drawingmode < KX_SOLID)
@@ -368,6 +271,13 @@ bool RAS_OpenGLRasterizer::BeginFrame(int drawingmode, double time)
glEnable (GL_CULL_FACE);
}
+ glDisable(GL_BLEND);
+ glDisable(GL_ALPHA_TEST);
+ m_last_blendmode = GPU_BLEND_SOLID;
+
+ glFrontFace(GL_CCW);
+ m_last_frontface = true;
+
glShadeModel(GL_SMOOTH);
m_2DCanvas->BeginFrame();
@@ -381,46 +291,28 @@ void RAS_OpenGLRasterizer::SetDrawingMode(int drawingmode)
{
m_drawingmode = drawingmode;
- switch (m_drawingmode)
- {
- case KX_BOUNDINGBOX:
- {
- }
- case KX_WIREFRAME:
- {
- glDisable (GL_CULL_FACE);
- break;
- }
- case KX_TEXTURED:
- {
- }
- case KX_SHADED:
- {
- }
- case KX_SOLID:
- {
- }
- default:
- {
- }
- }
+ if(m_drawingmode == KX_WIREFRAME)
+ glDisable(GL_CULL_FACE);
}
-
-
int RAS_OpenGLRasterizer::GetDrawingMode()
{
return m_drawingmode;
}
-
void RAS_OpenGLRasterizer::SetDepthMask(DepthMask depthmask)
{
glDepthMask(depthmask == KX_DEPTHMASK_DISABLED ? GL_FALSE : GL_TRUE);
}
+void RAS_OpenGLRasterizer::ClearColorBuffer()
+{
+ m_2DCanvas->ClearColor(m_redback,m_greenback,m_blueback,m_alphaback);
+ m_2DCanvas->ClearBuffer(RAS_ICanvas::COLOR_BUFFER);
+}
+
void RAS_OpenGLRasterizer::ClearDepthBuffer()
{
@@ -531,6 +423,10 @@ bool RAS_OpenGLRasterizer::Stereo()
return true;
}
+bool RAS_OpenGLRasterizer::InterlacedStereo()
+{
+ return m_stereomode == RAS_STEREO_VINTERLACE || m_stereomode == RAS_STEREO_INTERLACED;
+}
void RAS_OpenGLRasterizer::SetEye(const StereoEye eye)
{
@@ -607,1172 +503,251 @@ void RAS_OpenGLRasterizer::SwapBuffers()
-void RAS_OpenGLRasterizer::GetViewMatrix(MT_Matrix4x4 &mat) const
+const MT_Matrix4x4& RAS_OpenGLRasterizer::GetViewMatrix() const
{
- float viewmat[16];
- glGetFloatv(GL_MODELVIEW_MATRIX, viewmat);
- mat.setValue(viewmat);
+ return m_viewmatrix;
}
+const MT_Matrix4x4& RAS_OpenGLRasterizer::GetViewInvMatrix() const
+{
+ return m_viewinvmatrix;
+}
-
-void RAS_OpenGLRasterizer::IndexPrimitives(const vecVertexArray & vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
+void RAS_OpenGLRasterizer::IndexPrimitives_3DText(RAS_MeshSlot& ms,
class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor,
- class KX_ListSlot** slot
- )
+ class RAS_IRenderTools* rendertools)
{
- GLenum drawmode;
- switch (mode)
- {
- case 0:
- drawmode = GL_TRIANGLES;
- break;
- case 1:
- drawmode = GL_LINES;
- break;
- case 2:
- drawmode = GL_QUADS;
- break;
- default:
- drawmode = GL_LINES;
- break;
+ bool obcolor = ms.m_bObjectColor;
+ MT_Vector4& rgba = ms.m_RGBAcolor;
+ RAS_MeshSlot::iterator it;
+
+ // handle object color
+ if (obcolor) {
+ glDisableClientState(GL_COLOR_ARRAY);
+ glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
}
-
- const RAS_TexVert* vertexarray ;
- unsigned int numindices,vt;
+ else
+ glEnableClientState(GL_COLOR_ARRAY);
- for (vt=0;vt<vertexarrays.size();vt++)
- {
- vertexarray = &((*vertexarrays[vt]) [0]);
- const KX_IndexArray & indexarray = (*indexarrays[vt]);
- numindices = indexarray.size();
+ for(ms.begin(it); !ms.end(it); ms.next(it)) {
+ RAS_TexVert *vertex;
+ size_t i, j, numvert;
- if (!numindices)
- break;
-
- int vindex=0;
- switch (mode)
- {
- case 1:
- {
- glBegin(GL_LINES);
- vindex=0;
- for (unsigned int i=0;i<numindices;i+=2)
- {
- glVertex3fv(vertexarray[(indexarray[vindex++])].getLocalXYZ());
- glVertex3fv(vertexarray[(indexarray[vindex++])].getLocalXYZ());
- }
- glEnd();
- }
- break;
- case 2:
- {
- glBegin(GL_QUADS);
- vindex=0;
- if (useObjectColor)
- {
- for (unsigned int i=0;i<numindices;i+=4)
- {
-
- glColor4d(rgbacolor[0], rgbacolor[1], rgbacolor[2], rgbacolor[3]);
-
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
- }
- }
- else
- {
- for (unsigned int i=0;i<numindices;i+=4)
- {
- // This looks curiously endian unsafe to me.
- // However it depends on the way the colors are packed into
- // the m_rgba field of RAS_TexVert
-
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
- }
- }
- glEnd();
- break;
- }
- case 0:
- {
- glBegin(GL_TRIANGLES);
- vindex=0;
- if (useObjectColor)
- {
- for (unsigned int i=0;i<numindices;i+=3)
- {
-
- glColor4d(rgbacolor[0], rgbacolor[1], rgbacolor[2], rgbacolor[3]);
-
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
- }
- }
- else
- {
- for (unsigned int i=0;i<numindices;i+=3)
- {
-
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
- }
- }
- glEnd();
- break;
- }
- default:
- {
- }
-
- } // switch
- } // for each vertexarray
+ numvert = it.array->m_type;
-}
+ if(it.array->m_type == RAS_DisplayArray::LINE) {
+ // line drawing, no text
+ glBegin(GL_LINES);
-void RAS_OpenGLRasterizer::IndexPrimitives_Ex(const vecVertexArray & vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
- class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor
- )
-{
- bool recalc;
- GLenum drawmode;
- switch (mode)
- {
- case 0:
- drawmode = GL_TRIANGLES;
- break;
- case 1:
- drawmode = GL_LINES;
- break;
- case 2:
- drawmode = GL_QUADS;
- break;
- default:
- drawmode = GL_LINES;
- break;
- }
-
- const RAS_TexVert* vertexarray ;
- unsigned int numindices,vt;
-
- for (vt=0;vt<vertexarrays.size();vt++)
- {
- vertexarray = &((*vertexarrays[vt]) [0]);
- const KX_IndexArray & indexarray = (*indexarrays[vt]);
- numindices = indexarray.size();
-
- if (!numindices)
- continue;
-
- int vindex=0;
- switch (mode)
- {
- case 1:
+ for(i=0; i<it.totindex; i+=2)
{
- glBegin(GL_LINES);
- vindex=0;
- for (unsigned int i=0;i<numindices;i+=2)
- {
- glVertex3fv(vertexarray[(indexarray[vindex++])].getLocalXYZ());
- glVertex3fv(vertexarray[(indexarray[vindex++])].getLocalXYZ());
- }
- glEnd();
- }
- break;
- case 2:
- {
- glBegin(GL_QUADS);
- vindex=0;
- if (useObjectColor)
- {
- for (unsigned int i=0;i<numindices;i+=4)
- {
- MT_Point3 mv1, mv2, mv3, mv4, fnor;
- /* Calc a new face normal */
+ vertex = &it.vertex[it.index[i]];
+ glVertex3fv(vertex->getXYZ());
- if (vertexarray[(indexarray[vindex])].getFlag() & TV_CALCFACENORMAL)
- recalc= true;
- else
- recalc=false;
-
- if (recalc){
- mv1 = MT_Point3(vertexarray[(indexarray[vindex])].getLocalXYZ());
- mv2 = MT_Point3(vertexarray[(indexarray[vindex+1])].getLocalXYZ());
- mv3 = MT_Point3(vertexarray[(indexarray[vindex+2])].getLocalXYZ());
- mv4 = MT_Point3(vertexarray[(indexarray[vindex+2])].getLocalXYZ());
-
- fnor = (((mv2-mv1).cross(mv3-mv2))+((mv4-mv3).cross(mv1-mv4))).safe_normalized();
-
- glNormal3f(fnor[0], fnor[1], fnor[2]);
- }
-
- glColor4d(rgbacolor[0], rgbacolor[1], rgbacolor[2], rgbacolor[3]);
-
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
- }
- }
- else
- {
- for (unsigned int i=0;i<numindices;i+=4)
- {
- // This looks curiously endian unsafe to me.
- // However it depends on the way the colors are packed into
- // the m_rgba field of RAS_TexVert
- MT_Point3 mv1, mv2, mv3, mv4, fnor;
- /* Calc a new face normal */
-
- if (vertexarray[(indexarray[vindex])].getFlag() & TV_CALCFACENORMAL)
- recalc= true;
- else
- recalc=false;
-
-
- if (recalc){
- mv1 = MT_Point3(vertexarray[(indexarray[vindex])].getLocalXYZ());
- mv2 = MT_Point3(vertexarray[(indexarray[vindex+1])].getLocalXYZ());
- mv3 = MT_Point3(vertexarray[(indexarray[vindex+2])].getLocalXYZ());
- mv4 = MT_Point3(vertexarray[(indexarray[vindex+3])].getLocalXYZ());
-
- fnor = (((mv2-mv1).cross(mv3-mv2))+((mv4-mv3).cross(mv1-mv4))).safe_normalized();
-
- glNormal3f(fnor[0], fnor[1], fnor[2]);
- }
-
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
- }
- }
- glEnd();
- break;
+ vertex = &it.vertex[it.index[i+1]];
+ glVertex3fv(vertex->getXYZ());
}
- case 0:
+
+ glEnd();
+ }
+ else {
+ // triangle and quad text drawing
+ for(i=0; i<it.totindex; i+=numvert)
{
- glBegin(GL_TRIANGLES);
- vindex=0;
- if (useObjectColor)
- {
- for (unsigned int i=0;i<numindices;i+=3)
- {
- MT_Point3 mv1, mv2, mv3, fnor;
- /* Calc a new face normal */
+ float v[4][3];
+ int glattrib, unit;
- if (vertexarray[(indexarray[vindex])].getFlag() & TV_CALCFACENORMAL)
- recalc= true;
- else
- recalc=false;
-
- if (recalc){
- mv1 = MT_Point3(vertexarray[(indexarray[vindex])].getLocalXYZ());
- mv2 = MT_Point3(vertexarray[(indexarray[vindex+1])].getLocalXYZ());
- mv3 = MT_Point3(vertexarray[(indexarray[vindex+2])].getLocalXYZ());
-
- fnor = ((mv2-mv1).cross(mv3-mv2)).safe_normalized();
- glNormal3f(fnor[0], fnor[1], fnor[2]);
- }
-
- glColor4d(rgbacolor[0], rgbacolor[1], rgbacolor[2], rgbacolor[3]);
-
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
- }
- }
- else
- {
- for (unsigned int i=0;i<numindices;i+=3)
- {
- MT_Point3 mv1, mv2, mv3, fnor;
- /* Calc a new face normal */
+ for(j=0; j<numvert; j++) {
+ vertex = &it.vertex[it.index[i+j]];
- if (vertexarray[(indexarray[vindex])].getFlag() & TV_CALCFACENORMAL)
- recalc= true;
- else
- recalc=false;
-
-
- if (recalc){
- mv1 = MT_Point3(vertexarray[(indexarray[vindex])].getLocalXYZ());
- mv2 = MT_Point3(vertexarray[(indexarray[vindex+1])].getLocalXYZ());
- mv3 = MT_Point3(vertexarray[(indexarray[vindex+2])].getLocalXYZ());
-
- fnor = ((mv2-mv1).cross(mv3-mv2)).safe_normalized();
- glNormal3f(fnor[0], fnor[1], fnor[2]);
- }
-
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
- }
+ v[j][0] = vertex->getXYZ()[0];
+ v[j][1] = vertex->getXYZ()[1];
+ v[j][2] = vertex->getXYZ()[2];
}
- glEnd();
- break;
- }
- default:
- {
+
+ // find the right opengl attribute
+ glattrib = -1;
+ if(GLEW_ARB_vertex_program)
+ for(unit=0; unit<m_attrib_num; unit++)
+ if(m_attrib[unit] == RAS_TEXCO_UV1)
+ glattrib = unit;
+
+ rendertools->RenderText(polymat->GetDrawingMode(), polymat,
+ v[0], v[1], v[2], (numvert == 4)? v[3]: NULL, glattrib);
+
+ ClearCachingInfo();
}
-
- } // switch
- } // for each vertexarray
+ }
+ }
+ glDisableClientState(GL_COLOR_ARRAY);
}
+void RAS_OpenGLRasterizer::SetTexCoordNum(int num)
+{
+ m_texco_num = num;
+ if(m_texco_num > RAS_MAX_TEXCO)
+ m_texco_num = RAS_MAX_TEXCO;
+}
-
-void RAS_OpenGLRasterizer::IndexPrimitives_3DText(const vecVertexArray & vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
- class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor
- )
-{
- GLenum drawmode;
- switch (mode)
- {
- case 0:
- drawmode = GL_TRIANGLES;
- break;
- case 1:
- drawmode = GL_LINES;
- break;
- case 2:
- drawmode = GL_QUADS;
- break;
- default:
- drawmode = GL_LINES;
- break;
- }
-
- const RAS_TexVert* vertexarray ;
-
- unsigned int numindices, vt;
-
- if (useObjectColor)
- {
- glDisableClientState(GL_COLOR_ARRAY);
- glColor4d(rgbacolor[0], rgbacolor[1], rgbacolor[2], rgbacolor[3]);
- }
- else
- {
- glEnableClientState(GL_COLOR_ARRAY);
- }
-
- for (vt=0;vt<vertexarrays.size();vt++)
- {
- vertexarray = &((*vertexarrays[vt]) [0]);
- const KX_IndexArray & indexarray = (*indexarrays[vt]);
- numindices = indexarray.size();
-
- if (!numindices)
- break;
-
- int vindex=0;
- switch (mode)
- {
- case 1:
- {
- glBegin(GL_LINES);
- vindex=0;
- for (unsigned int i=0;i<numindices;i+=2)
- {
- glVertex3fv(vertexarray[(indexarray[vindex++])].getLocalXYZ());
- glVertex3fv(vertexarray[(indexarray[vindex++])].getLocalXYZ());
- }
- glEnd();
- }
- break;
- case 2:
- {
- vindex=0;
- for (unsigned int i=0;i<numindices;i+=4)
- {
- float v1[3],v2[3],v3[3],v4[3];
-
- v1[0] = vertexarray[(indexarray[vindex])].getLocalXYZ()[0];
- v1[1] = vertexarray[(indexarray[vindex])].getLocalXYZ()[1];
- v1[2] = vertexarray[(indexarray[vindex])].getLocalXYZ()[2];
- vindex++;
-
- v2[0] = vertexarray[(indexarray[vindex])].getLocalXYZ()[0];
- v2[1] = vertexarray[(indexarray[vindex])].getLocalXYZ()[1];
- v2[2] = vertexarray[(indexarray[vindex])].getLocalXYZ()[2];
- vindex++;
-
- v3[0] = vertexarray[(indexarray[vindex])].getLocalXYZ()[0];
- v3[1] = vertexarray[(indexarray[vindex])].getLocalXYZ()[1];
- v3[2] = vertexarray[(indexarray[vindex])].getLocalXYZ()[2];
- vindex++;
-
- v4[0] = vertexarray[(indexarray[vindex])].getLocalXYZ()[0];
- v4[1] = vertexarray[(indexarray[vindex])].getLocalXYZ()[1];
- v4[2] = vertexarray[(indexarray[vindex])].getLocalXYZ()[2];
-
- vindex++;
-
- rendertools->RenderText(polymat->GetDrawingMode(),polymat,v1,v2,v3,v4);
- ClearCachingInfo();
- }
- break;
- }
- case 0:
- {
- glBegin(GL_TRIANGLES);
- vindex=0;
- for (unsigned int i=0;i<numindices;i+=3)
- {
- float v1[3],v2[3],v3[3];
-
- v1[0] = vertexarray[(indexarray[vindex])].getLocalXYZ()[0];
- v1[1] = vertexarray[(indexarray[vindex])].getLocalXYZ()[1];
- v1[2] = vertexarray[(indexarray[vindex])].getLocalXYZ()[2];
- vindex++;
-
- v2[0] = vertexarray[(indexarray[vindex])].getLocalXYZ()[0];
- v2[1] = vertexarray[(indexarray[vindex])].getLocalXYZ()[1];
- v2[2] = vertexarray[(indexarray[vindex])].getLocalXYZ()[2];
- vindex++;
-
- v3[0] = vertexarray[(indexarray[vindex])].getLocalXYZ()[0];
- v3[1] = vertexarray[(indexarray[vindex])].getLocalXYZ()[1];
- v3[2] = vertexarray[(indexarray[vindex])].getLocalXYZ()[2];
- vindex++;
-
- rendertools->RenderText(polymat->GetDrawingMode(),polymat,v1,v2,v3,NULL);
- ClearCachingInfo();
- }
- glEnd();
- break;
- }
- default:
- {
- }
- } //switch
- } //for each vertexarray
+void RAS_OpenGLRasterizer::SetAttribNum(int num)
+{
+ m_attrib_num = num;
+ if(m_attrib_num > RAS_MAX_ATTRIB)
+ m_attrib_num = RAS_MAX_ATTRIB;
}
-void RAS_OpenGLRasterizer::SetTexCoords(TexCoGen coords,int unit)
+void RAS_OpenGLRasterizer::SetTexCoord(TexCoGen coords, int unit)
{
// this changes from material to material
- if(unit < RAS_MAX)
+ if(unit < RAS_MAX_TEXCO)
m_texco[unit] = coords;
}
-void RAS_OpenGLRasterizer::SetAttrib(int type)
+void RAS_OpenGLRasterizer::SetAttrib(TexCoGen coords, int unit)
{
- if(type == RAS_TEXTANGENT) m_useTang=true;
+ // this changes from material to material
+ if(unit < RAS_MAX_ATTRIB)
+ m_attrib[unit] = coords;
}
-void RAS_OpenGLRasterizer::TexCoord(const RAS_TexVert &tv, int enabled)
+void RAS_OpenGLRasterizer::TexCoord(const RAS_TexVert &tv)
{
-#ifdef GL_ARB_multitexture
- if(bgl::RAS_EXT_support._ARB_multitexture)
- {
- for(int unit=0; unit<enabled; unit++)
- {
- if( tv.getFlag() & TV_2NDUV && tv.getUnit() == unit ) {
- bgl::blMultiTexCoord2fvARB(GL_TEXTURE0_ARB+unit, tv.getUV2());
+ int unit;
+
+ if(GLEW_ARB_multitexture) {
+ for(unit=0; unit<m_texco_num; unit++) {
+ if(tv.getFlag() & RAS_TexVert::SECOND_UV && (int)tv.getUnit() == unit) {
+ glMultiTexCoord2fvARB(GL_TEXTURE0_ARB+unit, tv.getUV2());
continue;
}
- switch(m_texco[unit])
- {
- case RAS_TEXCO_DISABLE:
- case RAS_TEXCO_OBJECT:
- case RAS_TEXCO_GEN:
- break;
+ switch(m_texco[unit]) {
case RAS_TEXCO_ORCO:
case RAS_TEXCO_GLOB:
- bgl::blMultiTexCoord3fvARB(GL_TEXTURE0_ARB+unit, tv.getLocalXYZ());
+ glMultiTexCoord3fvARB(GL_TEXTURE0_ARB+unit, tv.getXYZ());
break;
case RAS_TEXCO_UV1:
- bgl::blMultiTexCoord2fvARB(GL_TEXTURE0_ARB+unit, tv.getUV1());
+ glMultiTexCoord2fvARB(GL_TEXTURE0_ARB+unit, tv.getUV1());
break;
case RAS_TEXCO_NORM:
- bgl::blMultiTexCoord3fvARB(GL_TEXTURE0_ARB+unit, tv.getNormal());
+ glMultiTexCoord3fvARB(GL_TEXTURE0_ARB+unit, tv.getNormal());
break;
case RAS_TEXTANGENT:
- bgl::blMultiTexCoord4fvARB(GL_TEXTURE0_ARB+unit, tv.getTangent());
+ glMultiTexCoord4fvARB(GL_TEXTURE0_ARB+unit, tv.getTangent());
break;
case RAS_TEXCO_UV2:
- bgl::blMultiTexCoord2fvARB(GL_TEXTURE0_ARB+unit, tv.getUV2());
+ glMultiTexCoord2fvARB(GL_TEXTURE0_ARB+unit, tv.getUV2());
+ break;
+ default:
break;
}
}
}
-#endif
-#ifdef GL_ARB_vertex_program
- if(m_useTang && bgl::RAS_EXT_support._ARB_vertex_program)
- bgl::blVertexAttrib4fvARB(1/*tangent*/, tv.getTangent());
-#endif
+ if(GLEW_ARB_vertex_program) {
+ for(unit=0; unit<m_attrib_num; unit++) {
+ switch(m_attrib[unit]) {
+ case RAS_TEXCO_ORCO:
+ case RAS_TEXCO_GLOB:
+ glVertexAttrib3fvARB(unit, tv.getXYZ());
+ break;
+ case RAS_TEXCO_UV1:
+ glVertexAttrib2fvARB(unit, tv.getUV1());
+ break;
+ case RAS_TEXCO_NORM:
+ glVertexAttrib3fvARB(unit, tv.getNormal());
+ break;
+ case RAS_TEXTANGENT:
+ glVertexAttrib4fvARB(unit, tv.getTangent());
+ break;
+ case RAS_TEXCO_UV2:
+ glVertexAttrib2fvARB(unit, tv.getUV2());
+ break;
+ case RAS_TEXCO_VCOL:
+ glVertexAttrib4ubvARB(unit, tv.getRGBA());
+ break;
+ default:
+ break;
+ }
+ }
+ }
}
-void RAS_OpenGLRasterizer::Tangent( const RAS_TexVert& v1,
- const RAS_TexVert& v2,
- const RAS_TexVert& v3,
- const MT_Vector3 &no)
+
+void RAS_OpenGLRasterizer::IndexPrimitives(RAS_MeshSlot& ms)
{
-#ifdef GL_ARB_multitexture
- // TODO: set for deformer...
- MT_Vector3 x1(v1.getLocalXYZ()), x2(v2.getLocalXYZ()), x3(v3.getLocalXYZ());
- MT_Vector2 uv1(v1.getUV1()), uv2(v2.getUV1()), uv3(v3.getUV1());
- MT_Vector3 dx1(x2 - x1), dx2(x3 - x1);
- MT_Vector2 duv1(uv2 - uv1), duv2(uv3 - uv1);
-
- MT_Scalar r = 1.0 / (duv1.x() * duv2.y() - duv2.x() * duv1.y());
- duv1 *= r;
- duv2 *= r;
- MT_Vector3 sdir(duv2.y() * dx1 - duv1.y() * dx2);
- MT_Vector3 tdir(duv1.x() * dx2 - duv2.x() * dx1);
-
- // Gram-Schmidt orthogonalize
- MT_Vector3 t(sdir - no.cross(no.cross(sdir)));
- if (!MT_fuzzyZero(t))
- t /= t.length();
-
- float tangent[4];
- t.getValue(tangent);
- // Calculate handedness
- tangent[3] = no.dot(sdir.cross(tdir)) < 0.0 ? -1.0 : 1.0;
-#endif
+ IndexPrimitivesInternal(ms, false);
}
+void RAS_OpenGLRasterizer::IndexPrimitivesMulti(RAS_MeshSlot& ms)
+{
+ IndexPrimitivesInternal(ms, true);
+}
-void RAS_OpenGLRasterizer::IndexPrimitivesMulti(
- const vecVertexArray& vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
- class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor,
- class KX_ListSlot** slot
- )
+void RAS_OpenGLRasterizer::IndexPrimitivesInternal(RAS_MeshSlot& ms, bool multi)
{
-#ifdef GL_ARB_multitexture
-
- GLenum drawmode;
- switch (mode)
- {
- case 0:
- drawmode = GL_TRIANGLES;
- break;
- case 1:
- drawmode = GL_LINES;
- break;
- case 2:
- drawmode = GL_QUADS;
- break;
- default:
- drawmode = GL_LINES;
- break;
- }
-
- const RAS_TexVert* vertexarray ;
- unsigned int numindices,vt;
+ bool obcolor = ms.m_bObjectColor;
+ bool wireframe = m_drawingmode <= KX_WIREFRAME;
+ MT_Vector4& rgba = ms.m_RGBAcolor;
+ RAS_MeshSlot::iterator it;
+
+ // iterate over display arrays, each containing an index + vertex array
+ for(ms.begin(it); !ms.end(it); ms.next(it)) {
+ RAS_TexVert *vertex;
+ size_t i, j, numvert;
+
+ numvert = it.array->m_type;
- for (vt=0;vt<vertexarrays.size();vt++)
- {
- vertexarray = &((*vertexarrays[vt]) [0]);
- const KX_IndexArray & indexarray = (*indexarrays[vt]);
- numindices = indexarray.size();
- const unsigned int enabled = polymat->GetEnabled();
+ if(it.array->m_type == RAS_DisplayArray::LINE) {
+ // line drawing
+ glBegin(GL_LINES);
- if (!numindices)
- break;
-
- int vindex=0;
- switch (mode)
- {
- case 1:
- {
- glBegin(GL_LINES);
- vindex=0;
- for (unsigned int i=0;i<numindices;i+=2)
- {
- glVertex3fv(vertexarray[(indexarray[vindex++])].getLocalXYZ());
- glVertex3fv(vertexarray[(indexarray[vindex++])].getLocalXYZ());
- }
- glEnd();
- }
- break;
- case 2:
+ for(i=0; i<it.totindex; i+=2)
{
- glBegin(GL_QUADS);
- vindex=0;
- if (useObjectColor)
- {
- for (unsigned int i=0;i<numindices;i+=4)
- {
-
- glColor4d(rgbacolor[0], rgbacolor[1], rgbacolor[2], rgbacolor[3]);
-
- //
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- //
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- //
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- //
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
- }
- }
- else
- {
- for (unsigned int i=0;i<numindices;i+=4)
- {
- // This looks curiously endian unsafe to me.
- // However it depends on the way the colors are packed into
- // the m_rgba field of RAS_TexVert
-
- //
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
-
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- //
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- //
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- //
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
- }
- }
- glEnd();
- break;
+ vertex = &it.vertex[it.index[i]];
+ glVertex3fv(vertex->getXYZ());
+
+ vertex = &it.vertex[it.index[i+1]];
+ glVertex3fv(vertex->getXYZ());
}
- case 0:
- {
+
+ glEnd();
+ }
+ else {
+ // triangle and quad drawing
+ if(it.array->m_type == RAS_DisplayArray::TRIANGLE)
glBegin(GL_TRIANGLES);
- vindex=0;
- if (useObjectColor)
- {
- for (unsigned int i=0;i<numindices;i+=3)
- {
-
- glColor4d(rgbacolor[0], rgbacolor[1], rgbacolor[2], rgbacolor[3]);
- //
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- //
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- //
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
- }
- }
- else
- {
- for (unsigned int i=0;i<numindices;i+=3)
- {
- //
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- //
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- //
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
- }
- }
- glEnd();
- break;
- }
- default:
+ else
+ glBegin(GL_QUADS);
+
+ for(i=0; i<it.totindex; i+=numvert)
{
- }
- } // switch
- } // for each vertexarray
-#endif// GL_ARB_multitexture
+ if(obcolor)
+ glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
-}
+ for(j=0; j<numvert; j++) {
+ vertex = &it.vertex[it.index[i+j]];
-void RAS_OpenGLRasterizer::IndexPrimitivesMulti_Ex(
- const vecVertexArray & vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
- class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor)
-{
-#ifdef GL_ARB_multitexture
- bool recalc;
- GLenum drawmode;
- switch (mode)
- {
- case 0:
- drawmode = GL_TRIANGLES;
- break;
- case 1:
- drawmode = GL_LINES;
- break;
- case 2:
- drawmode = GL_QUADS;
- break;
- default:
- drawmode = GL_LINES;
- break;
- }
-
- const RAS_TexVert* vertexarray ;
- unsigned int numindices,vt;
+ if(!wireframe) {
+ if(!obcolor)
+ glColor4ubv((const GLubyte *)(vertex->getRGBA()));
- for (vt=0;vt<vertexarrays.size();vt++)
- {
- vertexarray = &((*vertexarrays[vt]) [0]);
- const KX_IndexArray & indexarray = (*indexarrays[vt]);
- numindices = indexarray.size();
- const unsigned int enabled = polymat->GetEnabled();
-
- if (!numindices)
- continue;
-
- int vindex=0;
- switch (mode)
- {
- case 1:
- {
- glBegin(GL_LINES);
- vindex=0;
- for (unsigned int i=0;i<numindices;i+=2)
- {
- glVertex3fv(vertexarray[(indexarray[vindex++])].getLocalXYZ());
- glVertex3fv(vertexarray[(indexarray[vindex++])].getLocalXYZ());
- }
- glEnd();
- }
- break;
- case 2:
- {
- glBegin(GL_QUADS);
- vindex=0;
- if (useObjectColor)
- {
- for (unsigned int i=0;i<numindices;i+=4)
- {
- MT_Point3 mv1, mv2, mv3, mv4, fnor;
- /* Calc a new face normal */
+ glNormal3fv(vertex->getNormal());
- if (vertexarray[(indexarray[vindex])].getFlag() & TV_CALCFACENORMAL)
- recalc= true;
- else
- recalc=false;
-
- if (recalc){
- mv1 = MT_Point3(vertexarray[(indexarray[vindex])].getLocalXYZ());
- mv2 = MT_Point3(vertexarray[(indexarray[vindex+1])].getLocalXYZ());
- mv3 = MT_Point3(vertexarray[(indexarray[vindex+2])].getLocalXYZ());
- mv4 = MT_Point3(vertexarray[(indexarray[vindex+2])].getLocalXYZ());
-
- fnor = (((mv2-mv1).cross(mv3-mv2))+((mv4-mv3).cross(mv1-mv4))).safe_normalized();
-
- glNormal3f(fnor[0], fnor[1], fnor[2]);
- }
-
- glColor4d(rgbacolor[0], rgbacolor[1], rgbacolor[2], rgbacolor[3]);
-
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
-
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
-
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
-
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
- }
- }
- else
- {
- for (unsigned int i=0;i<numindices;i+=4)
- {
- // This looks curiously endian unsafe to me.
- // However it depends on the way the colors are packed into
- // the m_rgba field of RAS_TexVert
- MT_Point3 mv1, mv2, mv3, mv4, fnor;
- /* Calc a new face normal */
-
- if (vertexarray[(indexarray[vindex])].getFlag() & TV_CALCFACENORMAL)
- recalc= true;
+ if(multi)
+ TexCoord(*vertex);
else
- recalc=false;
-
-
- if (recalc){
- mv1 = MT_Point3(vertexarray[(indexarray[vindex])].getLocalXYZ());
- mv2 = MT_Point3(vertexarray[(indexarray[vindex+1])].getLocalXYZ());
- mv3 = MT_Point3(vertexarray[(indexarray[vindex+2])].getLocalXYZ());
- mv4 = MT_Point3(vertexarray[(indexarray[vindex+3])].getLocalXYZ());
-
- fnor = (((mv2-mv1).cross(mv3-mv2))+((mv4-mv3).cross(mv1-mv4))).safe_normalized();
-
- glNormal3f(fnor[0], fnor[1], fnor[2]);
- }
-
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
-
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
-
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
-
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
-
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
+ glTexCoord2fv(vertex->getUV1());
}
- }
- glEnd();
- break;
- }
- case 0:
- {
- glBegin(GL_TRIANGLES);
- vindex=0;
- if (useObjectColor)
- {
- for (unsigned int i=0;i<numindices;i+=3)
- {
- MT_Point3 mv1, mv2, mv3, fnor;
- /* Calc a new face normal */
- if (vertexarray[(indexarray[vindex])].getFlag() & TV_CALCFACENORMAL)
- recalc= true;
- else
- recalc=false;
-
- if (recalc){
- mv1 = MT_Point3(vertexarray[(indexarray[vindex])].getLocalXYZ());
- mv2 = MT_Point3(vertexarray[(indexarray[vindex+1])].getLocalXYZ());
- mv3 = MT_Point3(vertexarray[(indexarray[vindex+2])].getLocalXYZ());
-
- fnor = ((mv2-mv1).cross(mv3-mv2)).safe_normalized();
- glNormal3f(fnor[0], fnor[1], fnor[2]);
- }
-
- glColor4d(rgbacolor[0], rgbacolor[1], rgbacolor[2], rgbacolor[3]);
-
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
- }
+ glVertex3fv(vertex->getXYZ());
}
- else
- {
- for (unsigned int i=0;i<numindices;i+=3)
- {
- MT_Point3 mv1, mv2, mv3, fnor;
- /* Calc a new face normal */
-
- if (vertexarray[(indexarray[vindex])].getFlag() & TV_CALCFACENORMAL)
- recalc= true;
- else
- recalc=false;
-
-
- if (recalc){
- mv1 = MT_Point3(vertexarray[(indexarray[vindex])].getLocalXYZ());
- mv2 = MT_Point3(vertexarray[(indexarray[vindex+1])].getLocalXYZ());
- mv3 = MT_Point3(vertexarray[(indexarray[vindex+2])].getLocalXYZ());
-
- fnor = ((mv2-mv1).cross(mv3-mv2)).safe_normalized();
- glNormal3f(fnor[0], fnor[1], fnor[2]);
- }
-
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
-
- glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
- if (!recalc)
- glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
- TexCoord(vertexarray[(indexarray[vindex])],enabled );
- glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
- vindex++;
- }
- }
- glEnd();
- break;
}
- default:
- {
- }
-
- } // switch
- } // for each vertexarray
-#endif
-}
-
+ glEnd();
+ }
+ }
+}
void RAS_OpenGLRasterizer::SetProjectionMatrix(MT_CmMatrix4x4 &mat)
{
@@ -1799,6 +774,7 @@ MT_Matrix4x4 RAS_OpenGLRasterizer::GetFrustumMatrix(
float top,
float frustnear,
float frustfar,
+ float focallength,
bool
){
MT_Matrix4x4 result;
@@ -1810,9 +786,10 @@ MT_Matrix4x4 RAS_OpenGLRasterizer::GetFrustumMatrix(
float near_div_focallength;
// next 2 params should be specified on command line and in Blender publisher
if (!m_setfocallength)
- m_focallength = 1.5 * right; // derived from example
+ m_focallength = (focallength == 0.f) ? 1.5 * right // derived from example
+ : focallength;
if (!m_seteyesep)
- m_eyeseparation = 0.18 * right; // just a guess...
+ m_eyeseparation = m_focallength/30; // reasonable value...
near_div_focallength = frustnear / m_focallength;
switch(m_curreye)
@@ -1844,7 +821,7 @@ MT_Matrix4x4 RAS_OpenGLRasterizer::GetFrustumMatrix(
void RAS_OpenGLRasterizer::SetViewMatrix(const MT_Matrix4x4 &mat, const MT_Vector3& campos,
const MT_Point3 &, const MT_Quaternion &camOrientQuat)
{
- MT_Matrix4x4 viewMat = mat;
+ m_viewmatrix = mat;
// correction for stereo
if(m_stereomode != RAS_STEREO_NOSTEREO)
@@ -1871,7 +848,7 @@ void RAS_OpenGLRasterizer::SetViewMatrix(const MT_Matrix4x4 &mat, const MT_Vecto
MT_Transform transform;
transform.setIdentity();
transform.translate(-(eyeline * m_eyeseparation / 2.0));
- viewMat *= transform;
+ m_viewmatrix *= transform;
}
break;
case RAS_STEREO_RIGHTEYE:
@@ -1880,20 +857,21 @@ void RAS_OpenGLRasterizer::SetViewMatrix(const MT_Matrix4x4 &mat, const MT_Vecto
MT_Transform transform;
transform.setIdentity();
transform.translate(eyeline * m_eyeseparation / 2.0);
- viewMat *= transform;
+ m_viewmatrix *= transform;
}
break;
}
}
- // convert row major matrix 'viewMat' to column major for OpenGL
- MT_Scalar cammat[16];
- viewMat.getValue(cammat);
- MT_CmMatrix4x4 viewCmmat = cammat;
+ m_viewinvmatrix = m_viewmatrix;
+ m_viewinvmatrix.invert();
+
+ // note: getValue gives back column major as needed by OpenGL
+ MT_Scalar glviewmat[16];
+ m_viewmatrix.getValue(glviewmat);
glMatrixMode(GL_MODELVIEW);
- m_viewmatrix = viewCmmat;
- glLoadMatrixd(&m_viewmatrix(0,0));
+ glLoadMatrixd(glviewmat);
m_campos = campos;
}
@@ -1904,20 +882,6 @@ const MT_Point3& RAS_OpenGLRasterizer::GetCameraPosition()
}
-
-void RAS_OpenGLRasterizer::LoadViewMatrix()
-{
- glLoadMatrixd(&m_viewmatrix(0,0));
-}
-
-
-
-void RAS_OpenGLRasterizer::EnableTextures(bool enable)
-{
-}
-
-
-
void RAS_OpenGLRasterizer::SetCullFace(bool enable)
{
if (enable)
@@ -1985,7 +949,10 @@ void RAS_OpenGLRasterizer::SetPolygonOffset(float mult, float add)
void RAS_OpenGLRasterizer::EnableMotionBlur(float motionblurvalue)
{
- m_motionblur = 1;
+ /* don't just set m_motionblur to 1, but check if it is 0 so
+ * we don't reset a motion blur that is already enabled */
+ if(m_motionblur == 0)
+ m_motionblur = 1;
m_motionblurvalue = motionblurvalue;
}
@@ -1994,3 +961,47 @@ void RAS_OpenGLRasterizer::DisableMotionBlur()
m_motionblur = 0;
m_motionblurvalue = -1.0;
}
+
+void RAS_OpenGLRasterizer::SetBlendingMode(int blendmode)
+{
+ if(blendmode == m_last_blendmode)
+ return;
+
+ if(blendmode == GPU_BLEND_SOLID) {
+ glDisable(GL_BLEND);
+ glDisable(GL_ALPHA_TEST);
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ }
+ else if(blendmode == GPU_BLEND_ADD) {
+ glBlendFunc(GL_ONE, GL_ONE);
+ glEnable(GL_BLEND);
+ glDisable(GL_ALPHA_TEST);
+ }
+ else if(blendmode == GPU_BLEND_ALPHA) {
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ glEnable(GL_BLEND);
+ glEnable(GL_ALPHA_TEST);
+ glAlphaFunc(GL_GREATER, 0.0f);
+ }
+ else if(blendmode == GPU_BLEND_CLIP) {
+ glDisable(GL_BLEND);
+ glEnable(GL_ALPHA_TEST);
+ glAlphaFunc(GL_GREATER, 0.5f);
+ }
+
+ m_last_blendmode = blendmode;
+}
+
+void RAS_OpenGLRasterizer::SetFrontFace(bool ccw)
+{
+ if(m_last_frontface == ccw)
+ return;
+
+ if(ccw)
+ glFrontFace(GL_CCW);
+ else
+ glFrontFace(GL_CW);
+
+ m_last_frontface = ccw;
+}
+
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h
index c63a7b80b7c..0717cce0ce8 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h
@@ -41,7 +41,8 @@ using namespace std;
#include "RAS_MaterialBucket.h"
#include "RAS_ICanvas.h"
-#define RAS_MAX 3// match in BL_Material
+#define RAS_MAX_TEXCO 8 // match in BL_Material
+#define RAS_MAX_ATTRIB 16 // match in BL_BlenderShader
struct OglDebugLine
{
@@ -76,7 +77,8 @@ class RAS_OpenGLRasterizer : public RAS_IRasterizer
float m_ambb;
double m_time;
- MT_CmMatrix4x4 m_viewmatrix;
+ MT_Matrix4x4 m_viewmatrix;
+ MT_Matrix4x4 m_viewinvmatrix;
MT_Point3 m_campos;
StereoMode m_stereomode;
@@ -86,7 +88,6 @@ class RAS_OpenGLRasterizer : public RAS_IRasterizer
float m_focallength;
bool m_setfocallength;
int m_noOfScanlines;
- bool InterlacedStereo() const;
//motion blur
int m_motionblur;
@@ -94,8 +95,12 @@ class RAS_OpenGLRasterizer : public RAS_IRasterizer
protected:
int m_drawingmode;
- TexCoGen m_texco[RAS_MAX];
- bool m_useTang;
+ TexCoGen m_texco[RAS_MAX_TEXCO];
+ TexCoGen m_attrib[RAS_MAX_ATTRIB];
+ int m_texco_num;
+ int m_attrib_num;
+ int m_last_blendmode;
+ bool m_last_frontface;
/** Stores the caching information for the last material activated. */
RAS_IPolyMaterial::TCachingInfo m_materialCachingInfo;
@@ -125,6 +130,7 @@ public:
virtual bool Init();
virtual void Exit();
virtual bool BeginFrame(int drawingmode, double time);
+ virtual void ClearColorBuffer();
virtual void ClearDepthBuffer();
virtual void ClearCachingInfo(void);
virtual void EndFrame();
@@ -132,6 +138,7 @@ public:
virtual void SetStereoMode(const StereoMode stereomode);
virtual bool Stereo();
+ virtual bool InterlacedStereo();
virtual void SetEye(const StereoEye eye);
virtual StereoEye GetEye();
virtual void SetEyeSeparation(const float eyeseparation);
@@ -139,59 +146,16 @@ public:
virtual void SetFocalLength(const float focallength);
virtual float GetFocalLength();
- virtual void SetAlphaTest(bool enable);
-
virtual void SwapBuffers();
- virtual void IndexPrimitives(
- const vecVertexArray& vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
- class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor,
- class KX_ListSlot** slot
- );
-
- virtual void IndexPrimitives_Ex(
- const vecVertexArray& vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
- class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor
- );
+ virtual void IndexPrimitives(class RAS_MeshSlot& ms);
+ virtual void IndexPrimitivesMulti(class RAS_MeshSlot& ms);
virtual void IndexPrimitives_3DText(
- const vecVertexArray& vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
+ class RAS_MeshSlot& ms,
class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor
- );
-
- virtual void IndexPrimitivesMulti(
- const vecVertexArray& vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
- class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor,
- class KX_ListSlot** slot);
-
- virtual void IndexPrimitivesMulti_Ex(
- const vecVertexArray& vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
- class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor);
+ class RAS_IRenderTools* rendertools);
+ void IndexPrimitivesInternal(RAS_MeshSlot& ms, bool multi);
virtual void SetProjectionMatrix(MT_CmMatrix4x4 & mat);
virtual void SetProjectionMatrix(const MT_Matrix4x4 & mat);
@@ -203,7 +167,6 @@ public:
);
virtual const MT_Point3& GetCameraPosition();
- virtual void LoadViewMatrix();
virtual void SetFog(
float start,
@@ -235,7 +198,6 @@ public:
virtual void SetDrawingMode(int drawingmode);
virtual int GetDrawingMode();
- virtual void EnableTextures(bool enable);
virtual void SetCullFace(bool enable);
virtual void SetLines(bool enable);
@@ -246,6 +208,7 @@ public:
float top,
float frustnear,
float frustfar,
+ float focallength,
bool perspective
);
@@ -285,21 +248,21 @@ public:
std::vector <OglDebugLine> m_debugLines;
- virtual void SetTexCoords(TexCoGen coords,int enabled);
- virtual void SetAttrib(int type);
- void TexCoord(const RAS_TexVert &tv, int unit);
- virtual void GetViewMatrix(MT_Matrix4x4 &mat) const;
+ virtual void SetTexCoordNum(int num);
+ virtual void SetAttribNum(int num);
+ virtual void SetTexCoord(TexCoGen coords, int unit);
+ virtual void SetAttrib(TexCoGen coords, int unit);
+
+ void TexCoord(const RAS_TexVert &tv);
- void Tangent(const RAS_TexVert& v1,
- const RAS_TexVert& v2,
- const RAS_TexVert& v3,
- const MT_Vector3 &no);
+ const MT_Matrix4x4& GetViewMatrix() const;
+ const MT_Matrix4x4& GetViewInvMatrix() const;
virtual void EnableMotionBlur(float motionblurvalue);
virtual void DisableMotionBlur();
virtual float GetMotionBlurValue(){return m_motionblurvalue;};
- virtual int GetMotionBlurState(){return m_motionblur;};
- virtual void SetMotionBlurState(int newstate)
+ virtual int GetMotionBlurState(){return m_motionblur;};
+ virtual void SetMotionBlurState(int newstate)
{
if(newstate<0)
m_motionblur = 0;
@@ -308,6 +271,9 @@ public:
else
m_motionblur = newstate;
};
+
+ virtual void SetBlendingMode(int blendmode);
+ virtual void SetFrontFace(bool ccw);
};
#endif //__RAS_OPENGLRASTERIZER
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.cpp
index 3e4eef5bd45..2cb3b52adfb 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.cpp
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.cpp
@@ -30,35 +30,24 @@
#endif
#include "RAS_VAOpenGLRasterizer.h"
+#include <stdlib.h>
-#ifdef WIN32
-#include <windows.h>
-#endif // WIN32
-#ifdef __APPLE__
-#define GL_GLEXT_LEGACY 1
-#include <OpenGL/gl.h>
-#else
-#include <GL/gl.h>
-#endif
+#include "GL/glew.h"
+#include "GPU_extensions.h"
#include "STR_String.h"
#include "RAS_TexVert.h"
#include "MT_CmMatrix4x4.h"
#include "RAS_IRenderTools.h" // rendering text
-
-#include "RAS_GLExtensionManager.h"
-
-using namespace bgl;
-
RAS_VAOpenGLRasterizer::RAS_VAOpenGLRasterizer(RAS_ICanvas* canvas, bool lock)
: RAS_OpenGLRasterizer(canvas),
- m_Lock(lock && RAS_EXT_support._EXT_compiled_vertex_array)
+ m_Lock(lock && GLEW_EXT_compiled_vertex_array),
+ m_last_texco_num(0),
+ m_last_attrib_num(0)
{
}
-
-
RAS_VAOpenGLRasterizer::~RAS_VAOpenGLRasterizer()
{
}
@@ -71,9 +60,9 @@ bool RAS_VAOpenGLRasterizer::Init(void)
if (result)
{
glEnableClientState(GL_VERTEX_ARRAY);
- glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
+ glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
@@ -81,238 +70,175 @@ bool RAS_VAOpenGLRasterizer::Init(void)
return result;
}
-
-
void RAS_VAOpenGLRasterizer::SetDrawingMode(int drawingmode)
{
m_drawingmode = drawingmode;
- switch (m_drawingmode)
+ switch (m_drawingmode)
{
- case KX_BOUNDINGBOX:
- {
- }
- case KX_WIREFRAME:
- {
- glDisable (GL_CULL_FACE);
+ case KX_BOUNDINGBOX:
+ case KX_WIREFRAME:
+ //glDisableClientState(GL_COLOR_ARRAY);
+ //glDisable(GL_CULL_FACE);
break;
- }
- case KX_TEXTURED:
- {
- }
- case KX_SHADED:
- {
- glEnableClientState(GL_COLOR_ARRAY);
- }
- case KX_SOLID:
- {
+ case KX_SOLID:
+ //glDisableClientState(GL_COLOR_ARRAY);
+ break;
+ case KX_TEXTURED:
+ case KX_SHADED:
+ case KX_SHADOW:
+ //glEnableClientState(GL_COLOR_ARRAY);
+ default:
break;
- }
- default:
- {
- }
}
}
-
-
void RAS_VAOpenGLRasterizer::Exit()
{
- glDisableClientState(GL_VERTEX_ARRAY);
+ glEnableClientState(GL_VERTEX_ARRAY);
+ glEnableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
- glDisableClientState(GL_NORMAL_ARRAY);
RAS_OpenGLRasterizer::Exit();
}
-
-
-void RAS_VAOpenGLRasterizer::IndexPrimitives( const vecVertexArray& vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
- class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor,
- class KX_ListSlot** slot)
+void RAS_VAOpenGLRasterizer::IndexPrimitives(RAS_MeshSlot& ms)
{
- static const GLsizei vtxstride = sizeof(RAS_TexVert);
+ static const GLsizei stride = sizeof(RAS_TexVert);
+ bool wireframe = m_drawingmode <= KX_WIREFRAME;
+ RAS_MeshSlot::iterator it;
GLenum drawmode;
- switch (mode)
- {
- case 0:
- {
- drawmode = GL_TRIANGLES;
- break;
- }
- case 2:
- {
- drawmode = GL_QUADS;
- break;
- }
- case 1: //lines
- {
- }
- default:
- {
- drawmode = GL_LINES;
- break;
- }
- }
- const RAS_TexVert* vertexarray;
- unsigned int numindices, vt;
- if (drawmode != GL_LINES)
- {
- if (useObjectColor)
- {
- glDisableClientState(GL_COLOR_ARRAY);
- glColor4d(rgbacolor[0], rgbacolor[1], rgbacolor[2], rgbacolor[3]);
- } else
- {
- glColor4d(0,0,0,1.0);
- glEnableClientState(GL_COLOR_ARRAY);
- }
- }
- else
- {
- glColor3d(0,0,0);
- }
- // use glDrawElements to draw each vertexarray
- for (vt=0;vt<vertexarrays.size();vt++)
- {
- vertexarray = &((*vertexarrays[vt]) [0]);
- const KX_IndexArray & indexarray = (*indexarrays[vt]);
- numindices = indexarray.size();
+ if(!wireframe)
+ glEnableClientState(GL_TEXTURE_COORD_ARRAY);
- if (!numindices)
+ // use glDrawElements to draw each vertexarray
+ for(ms.begin(it); !ms.end(it); ms.next(it)) {
+ if(it.totindex == 0)
continue;
-
- glVertexPointer(3,GL_FLOAT,vtxstride,vertexarray->getLocalXYZ());
- glTexCoordPointer(2,GL_FLOAT,vtxstride,vertexarray->getUV1());
- glColorPointer(4,GL_UNSIGNED_BYTE,vtxstride,vertexarray->getRGBA());
- glNormalPointer(GL_FLOAT,vtxstride,vertexarray->getNormal());
- //if(m_Lock)
- // local->Begin(vertexarrays[vt]->size());
+ // drawing mode
+ if(it.array->m_type == RAS_DisplayArray::TRIANGLE)
+ drawmode = GL_TRIANGLES;
+ else if(it.array->m_type == RAS_DisplayArray::QUAD)
+ drawmode = GL_QUADS;
+ else
+ drawmode = GL_LINES;
+
+ // colors
+ if (drawmode != GL_LINES && !wireframe) {
+ if (ms.m_bObjectColor) {
+ const MT_Vector4& rgba = ms.m_RGBAcolor;
+
+ glDisableClientState(GL_COLOR_ARRAY);
+ glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
+ }
+ else {
+ glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
+ glEnableClientState(GL_COLOR_ARRAY);
+ }
+ }
+ else
+ glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
+
+ glVertexPointer(3, GL_FLOAT, stride, it.vertex->getXYZ());
+ glNormalPointer(GL_FLOAT, stride, it.vertex->getNormal());
+ if(!wireframe) {
+ glTexCoordPointer(2, GL_FLOAT, stride, it.vertex->getUV1());
+ if(glIsEnabled(GL_COLOR_ARRAY))
+ glColorPointer(4, GL_UNSIGNED_BYTE, stride, it.vertex->getRGBA());
+ }
// here the actual drawing takes places
- glDrawElements(drawmode,numindices,GL_UNSIGNED_SHORT,&(indexarray[0]));
-
- //if(m_Lock)
- // local->End();
-
+ glDrawElements(drawmode, it.totindex, GL_UNSIGNED_SHORT, it.index);
+ }
+ if(!wireframe) {
+ glDisableClientState(GL_TEXTURE_COORD_ARRAY);
+ glDisableClientState(GL_COLOR_ARRAY);
}
}
-
-void RAS_VAOpenGLRasterizer::IndexPrimitivesMulti( const vecVertexArray& vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
- class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor,
- class KX_ListSlot** slot)
+void RAS_VAOpenGLRasterizer::IndexPrimitivesMulti(RAS_MeshSlot& ms)
{
- static const GLsizei vtxstride = sizeof(RAS_TexVert);
+ static const GLsizei stride = sizeof(RAS_TexVert);
+ bool wireframe = m_drawingmode <= KX_WIREFRAME;
+ RAS_MeshSlot::iterator it;
GLenum drawmode;
- switch (mode)
- {
- case 0:
- {
- drawmode = GL_TRIANGLES;
- break;
- }
- case 2:
- {
- drawmode = GL_QUADS;
- break;
- }
- case 1: //lines
- {
- }
- default:
- {
- drawmode = GL_LINES;
- break;
- }
- }
- const RAS_TexVert* vertexarray;
- unsigned int numindices, vt;
- const unsigned int enabled = polymat->GetEnabled();
- if (drawmode != GL_LINES)
- {
- if (useObjectColor)
- {
- glDisableClientState(GL_COLOR_ARRAY);
- glColor4d(rgbacolor[0], rgbacolor[1], rgbacolor[2], rgbacolor[3]);
- } else
- {
- glColor4d(0,0,0,1.0);
- glEnableClientState(GL_COLOR_ARRAY);
- }
- }
- else
- {
- glColor3d(0,0,0);
- }
+ if(!wireframe)
+ EnableTextures(true);
// use glDrawElements to draw each vertexarray
- for (vt=0;vt<vertexarrays.size();vt++)
- {
- vertexarray = &((*vertexarrays[vt]) [0]);
- const KX_IndexArray & indexarray = (*indexarrays[vt]);
- numindices = indexarray.size();
-
- if (!numindices)
+ for(ms.begin(it); !ms.end(it); ms.next(it)) {
+ if(it.totindex == 0)
continue;
-
- glVertexPointer(3,GL_FLOAT,vtxstride,vertexarray->getLocalXYZ());
- TexCoordPtr(vertexarray, enabled);
- //glTexCoordPointer(2,GL_FLOAT,vtxstride,vertexarray->getUV1());
- glColorPointer(4,GL_UNSIGNED_BYTE,vtxstride,vertexarray->getRGBA());
- glNormalPointer(GL_FLOAT,vtxstride,vertexarray->getNormal());
-
- //if(m_Lock)
- // local->Begin(vertexarrays[vt]->size());
+ // drawing mode
+ if(it.array->m_type == RAS_DisplayArray::TRIANGLE)
+ drawmode = GL_TRIANGLES;
+ else if(it.array->m_type == RAS_DisplayArray::QUAD)
+ drawmode = GL_QUADS;
+ else
+ drawmode = GL_LINES;
+
+ // colors
+ if (drawmode != GL_LINES && !wireframe) {
+ if (ms.m_bObjectColor) {
+ const MT_Vector4& rgba = ms.m_RGBAcolor;
+
+ glDisableClientState(GL_COLOR_ARRAY);
+ glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
+ }
+ else {
+ glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
+ glEnableClientState(GL_COLOR_ARRAY);
+ }
+ }
+ else
+ glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
+
+ glVertexPointer(3, GL_FLOAT, stride, it.vertex->getXYZ());
+ glNormalPointer(GL_FLOAT, stride, it.vertex->getNormal());
+ if(!wireframe) {
+ TexCoordPtr(it.vertex);
+ if(glIsEnabled(GL_COLOR_ARRAY))
+ glColorPointer(4, GL_UNSIGNED_BYTE, stride, it.vertex->getRGBA());
+ }
// here the actual drawing takes places
- glDrawElements(drawmode,numindices,GL_UNSIGNED_SHORT,&(indexarray[0]));
-
- //if(m_Lock)
- // local->End();
+ glDrawElements(drawmode, it.totindex, GL_UNSIGNED_SHORT, it.index);
+ }
+
+ if(!wireframe) {
+ glDisableClientState(GL_COLOR_ARRAY);
+ EnableTextures(false);
}
}
-void RAS_VAOpenGLRasterizer::TexCoordPtr(const RAS_TexVert *tv, int enabled)
+void RAS_VAOpenGLRasterizer::TexCoordPtr(const RAS_TexVert *tv)
{
-#ifdef GL_ARB_multitexture
- if(bgl::RAS_EXT_support._ARB_multitexture)
+ /* note: this function must closely match EnableTextures to enable/disable
+ * the right arrays, otherwise coordinate and attribute pointers from other
+ * materials can still be used and cause crashes */
+ int unit;
+
+ if(GLEW_ARB_multitexture)
{
- for(int unit=0; unit<enabled; unit++)
+ for(unit=0; unit<m_texco_num; unit++)
{
- bgl::blClientActiveTextureARB(GL_TEXTURE0_ARB+unit);
-
- glEnableClientState(GL_TEXTURE_COORD_ARRAY);
- if( tv->getFlag() & TV_2NDUV && tv->getUnit() == unit ) {
+ glClientActiveTextureARB(GL_TEXTURE0_ARB+unit);
+ if(tv->getFlag() & RAS_TexVert::SECOND_UV && (int)tv->getUnit() == unit) {
+ glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, sizeof(RAS_TexVert), tv->getUV2());
continue;
}
switch(m_texco[unit])
{
- case RAS_TEXCO_DISABLE:
- case RAS_TEXCO_OBJECT:
- case RAS_TEXCO_GEN:
- glDisableClientState(GL_TEXTURE_COORD_ARRAY);
- break;
case RAS_TEXCO_ORCO:
case RAS_TEXCO_GLOB:
- glTexCoordPointer(3, GL_FLOAT, sizeof(RAS_TexVert),tv->getLocalXYZ());
+ glTexCoordPointer(3, GL_FLOAT, sizeof(RAS_TexVert),tv->getXYZ());
break;
case RAS_TEXCO_UV1:
glTexCoordPointer(2, GL_FLOAT, sizeof(RAS_TexVert),tv->getUV1());
@@ -326,24 +252,121 @@ void RAS_VAOpenGLRasterizer::TexCoordPtr(const RAS_TexVert *tv, int enabled)
case RAS_TEXCO_UV2:
glTexCoordPointer(2, GL_FLOAT, sizeof(RAS_TexVert),tv->getUV2());
break;
+ default:
+ break;
}
}
- }
-#ifdef GL_ARB_vertex_program
- if(m_useTang && bgl::RAS_EXT_support._ARB_vertex_program)
- bgl::blVertexAttrib4fvARB(1/*tangent*/, tv->getTangent());
-#endif
+ glClientActiveTextureARB(GL_TEXTURE0_ARB);
+ }
-#endif
+ if(GLEW_ARB_vertex_program) {
+ for(unit=0; unit<m_attrib_num; unit++) {
+ switch(m_attrib[unit]) {
+ case RAS_TEXCO_ORCO:
+ case RAS_TEXCO_GLOB:
+ glVertexAttribPointerARB(unit, 3, GL_FLOAT, GL_FALSE, sizeof(RAS_TexVert), tv->getXYZ());
+ break;
+ case RAS_TEXCO_UV1:
+ glVertexAttribPointerARB(unit, 2, GL_FLOAT, GL_FALSE, sizeof(RAS_TexVert), tv->getUV1());
+ break;
+ case RAS_TEXCO_NORM:
+ glVertexAttribPointerARB(unit, 3, GL_FLOAT, GL_FALSE, sizeof(RAS_TexVert), tv->getNormal());
+ break;
+ case RAS_TEXTANGENT:
+ glVertexAttribPointerARB(unit, 4, GL_FLOAT, GL_FALSE, sizeof(RAS_TexVert), tv->getTangent());
+ break;
+ case RAS_TEXCO_UV2:
+ glVertexAttribPointerARB(unit, 2, GL_FLOAT, GL_FALSE, sizeof(RAS_TexVert), tv->getUV2());
+ break;
+ case RAS_TEXCO_VCOL:
+ glVertexAttribPointerARB(unit, 4, GL_UNSIGNED_BYTE, GL_FALSE, sizeof(RAS_TexVert), tv->getRGBA());
+ break;
+ default:
+ break;
+ }
+ }
+ }
}
-
void RAS_VAOpenGLRasterizer::EnableTextures(bool enable)
{
- if (enable)
- glEnableClientState(GL_TEXTURE_COORD_ARRAY);
- else
- glDisableClientState(GL_TEXTURE_COORD_ARRAY);
+ TexCoGen *texco, *attrib;
+ int unit, texco_num, attrib_num;
+
+ /* we cache last texcoords and attribs to ensure we disable the ones that
+ * were actually last set */
+ if(enable) {
+ texco = m_texco;
+ texco_num = m_texco_num;
+ attrib = m_attrib;
+ attrib_num = m_attrib_num;
+
+ memcpy(m_last_texco, m_texco, sizeof(TexCoGen)*m_texco_num);
+ m_last_texco_num = m_texco_num;
+ memcpy(m_last_attrib, m_attrib, sizeof(TexCoGen)*m_attrib_num);
+ m_last_attrib_num = m_attrib_num;
+ }
+ else {
+ texco = m_last_texco;
+ texco_num = m_last_texco_num;
+ attrib = m_last_attrib;
+ attrib_num = m_last_attrib_num;
+ }
+
+ if(GLEW_ARB_multitexture) {
+ for(unit=0; unit<texco_num; unit++) {
+ glClientActiveTextureARB(GL_TEXTURE0_ARB+unit);
+
+ switch(texco[unit])
+ {
+ case RAS_TEXCO_ORCO:
+ case RAS_TEXCO_GLOB:
+ case RAS_TEXCO_UV1:
+ case RAS_TEXCO_NORM:
+ case RAS_TEXTANGENT:
+ case RAS_TEXCO_UV2:
+ if(enable) glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+ else glDisableClientState(GL_TEXTURE_COORD_ARRAY);
+ break;
+ default:
+ glDisableClientState(GL_TEXTURE_COORD_ARRAY);
+ break;
+ }
+ }
+
+ glClientActiveTextureARB(GL_TEXTURE0_ARB);
+ }
+ else {
+ if(texco_num) {
+ if(enable) glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+ else glDisableClientState(GL_TEXTURE_COORD_ARRAY);
+ }
+ }
+
+ if(GLEW_ARB_vertex_program) {
+ for(unit=0; unit<attrib_num; unit++) {
+ switch(attrib[unit]) {
+ case RAS_TEXCO_ORCO:
+ case RAS_TEXCO_GLOB:
+ case RAS_TEXCO_UV1:
+ case RAS_TEXCO_NORM:
+ case RAS_TEXTANGENT:
+ case RAS_TEXCO_UV2:
+ case RAS_TEXCO_VCOL:
+ if(enable) glEnableVertexAttribArrayARB(unit);
+ else glDisableVertexAttribArrayARB(unit);
+ break;
+ default:
+ glDisableVertexAttribArrayARB(unit);
+ break;
+ }
+ }
+ }
+
+ if(!enable) {
+ m_last_texco_num = 0;
+ m_last_attrib_num = 0;
+ }
}
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.h
index 4d478b0171f..766bbfbed0e 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.h
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.h
@@ -33,9 +33,14 @@
class RAS_VAOpenGLRasterizer : public RAS_OpenGLRasterizer
{
- void TexCoordPtr(const RAS_TexVert *tv, int unit);
+ void TexCoordPtr(const RAS_TexVert *tv);
bool m_Lock;
+ TexCoGen m_last_texco[RAS_MAX_TEXCO];
+ TexCoGen m_last_attrib[RAS_MAX_ATTRIB];
+ int m_last_texco_num;
+ int m_last_attrib_num;
+
public:
RAS_VAOpenGLRasterizer(RAS_ICanvas* canvas, bool lock=false);
virtual ~RAS_VAOpenGLRasterizer();
@@ -45,26 +50,10 @@ public:
virtual void SetDrawingMode(int drawingmode);
- virtual void IndexPrimitives( const vecVertexArray& vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
- class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor,
- class KX_ListSlot** slot);
-
- virtual void IndexPrimitivesMulti(
- const vecVertexArray& vertexarrays,
- const vecIndexArrays & indexarrays,
- int mode,
- class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools,
- bool useObjectColor,
- const MT_Vector4& rgbacolor,
- class KX_ListSlot** slot);
-
+ virtual void IndexPrimitives(class RAS_MeshSlot& ms);
+ virtual void IndexPrimitivesMulti(class RAS_MeshSlot& ms);
+private:
virtual void EnableTextures(bool enable);
//virtual bool QueryArrays(){return true;}
//virtual bool QueryLists(){return m_Lock;}
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/SConscript b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/SConscript
index b2b75ecb196..0f2a537265a 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/SConscript
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/SConscript
@@ -1,9 +1,9 @@
#!/usr/bin/python
Import ('env')
-sources = env.Glob('*.cpp') #'RAS_GLExtensionManager.cpp RAS_ListRasterizer.cpp RAS_OpenGLRasterizer.cpp RAS_VAOpenGLRasterizer.cpp'
+sources = env.Glob('*.cpp')
-incs = '. #source/kernel/gen_system #intern/string #intern/moto/include #source/gameengine/Rasterizer'
-incs += ' ' + env['BF_OPENGL_INC']
+incs = '. #source/kernel/gen_system #intern/string #intern/moto/include #source/gameengine/Rasterizer #source/gameengine/BlenderRoutines '
+incs += ' #source/blender/gpu #extern/glew/include ' + env['BF_OPENGL_INC']
env.BlenderLib ( 'bf_oglrasterizer', Split(sources), Split(incs), [], libtype=['game','player'], priority=[40, 115] )
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/glext.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/glext.h
deleted file mode 100644
index 7bb8e6e7cc7..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/glext.h
+++ /dev/null
@@ -1,6495 +0,0 @@
-#ifndef __glext_h_
-#define __glext_h_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
-** License Applicability. Except to the extent portions of this file are
-** made subject to an alternative license as permitted in the SGI Free
-** Software License B, Version 1.1 (the "License"), the contents of this
-** file are subject only to the provisions of the License. You may not use
-** this file except in compliance with the License. You may obtain a copy
-** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
-** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
-**
-** http://oss.sgi.com/projects/FreeB
-**
-** Note that, as provided in the License, the Software is distributed on an
-** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
-** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
-** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
-** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
-**
-** Original Code. The Original Code is: OpenGL Sample Implementation,
-** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
-** Inc. The Original Code is Copyright (c) 1991-2004 Silicon Graphics, Inc.
-** Copyright in any portions created by third parties is as indicated
-** elsewhere herein. All Rights Reserved.
-**
-** Additional Notice Provisions: This software was created using the
-** OpenGL(R) version 1.2.1 Sample Implementation published by SGI, but has
-** not been independently verified as being compliant with the OpenGL(R)
-** version 1.2.1 Specification.
-*/
-
-#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
-#define WIN32_LEAN_AND_MEAN 1
-#include <windows.h>
-#endif
-
-#ifndef APIENTRY
-#define APIENTRY
-#endif
-#ifndef APIENTRYP
-#define APIENTRYP APIENTRY *
-#endif
-#ifndef GLAPI
-#define GLAPI extern
-#endif
-
-/*************************************************************/
-
-/* Header file version number, required by OpenGL ABI for Linux */
-/* glext.h last updated 2005/06/20 */
-/* Current version at http://oss.sgi.com/projects/ogl-sample/registry/ */
-#define GL_GLEXT_VERSION 29
-
-#ifndef GL_VERSION_1_2
-#define GL_UNSIGNED_BYTE_3_3_2 0x8032
-#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033
-#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034
-#define GL_UNSIGNED_INT_8_8_8_8 0x8035
-#define GL_UNSIGNED_INT_10_10_10_2 0x8036
-#define GL_RESCALE_NORMAL 0x803A
-#define GL_TEXTURE_BINDING_3D 0x806A
-#define GL_PACK_SKIP_IMAGES 0x806B
-#define GL_PACK_IMAGE_HEIGHT 0x806C
-#define GL_UNPACK_SKIP_IMAGES 0x806D
-#define GL_UNPACK_IMAGE_HEIGHT 0x806E
-#define GL_TEXTURE_3D 0x806F
-#define GL_PROXY_TEXTURE_3D 0x8070
-#define GL_TEXTURE_DEPTH 0x8071
-#define GL_TEXTURE_WRAP_R 0x8072
-#define GL_MAX_3D_TEXTURE_SIZE 0x8073
-#define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362
-#define GL_UNSIGNED_SHORT_5_6_5 0x8363
-#define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364
-#define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365
-#define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366
-#define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
-#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368
-#define GL_BGR 0x80E0
-#define GL_BGRA 0x80E1
-#define GL_MAX_ELEMENTS_VERTICES 0x80E8
-#define GL_MAX_ELEMENTS_INDICES 0x80E9
-#define GL_CLAMP_TO_EDGE 0x812F
-#define GL_TEXTURE_MIN_LOD 0x813A
-#define GL_TEXTURE_MAX_LOD 0x813B
-#define GL_TEXTURE_BASE_LEVEL 0x813C
-#define GL_TEXTURE_MAX_LEVEL 0x813D
-#define GL_LIGHT_MODEL_COLOR_CONTROL 0x81F8
-#define GL_SINGLE_COLOR 0x81F9
-#define GL_SEPARATE_SPECULAR_COLOR 0x81FA
-#define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12
-#define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13
-#define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22
-#define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23
-#define GL_ALIASED_POINT_SIZE_RANGE 0x846D
-#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E
-#endif
-
-#ifndef GL_ARB_imaging
-#define GL_CONSTANT_COLOR 0x8001
-#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002
-#define GL_CONSTANT_ALPHA 0x8003
-#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004
-#define GL_BLEND_COLOR 0x8005
-#define GL_FUNC_ADD 0x8006
-#define GL_MIN 0x8007
-#define GL_MAX 0x8008
-#define GL_BLEND_EQUATION 0x8009
-#define GL_FUNC_SUBTRACT 0x800A
-#define GL_FUNC_REVERSE_SUBTRACT 0x800B
-#define GL_CONVOLUTION_1D 0x8010
-#define GL_CONVOLUTION_2D 0x8011
-#define GL_SEPARABLE_2D 0x8012
-#define GL_CONVOLUTION_BORDER_MODE 0x8013
-#define GL_CONVOLUTION_FILTER_SCALE 0x8014
-#define GL_CONVOLUTION_FILTER_BIAS 0x8015
-#define GL_REDUCE 0x8016
-#define GL_CONVOLUTION_FORMAT 0x8017
-#define GL_CONVOLUTION_WIDTH 0x8018
-#define GL_CONVOLUTION_HEIGHT 0x8019
-#define GL_MAX_CONVOLUTION_WIDTH 0x801A
-#define GL_MAX_CONVOLUTION_HEIGHT 0x801B
-#define GL_POST_CONVOLUTION_RED_SCALE 0x801C
-#define GL_POST_CONVOLUTION_GREEN_SCALE 0x801D
-#define GL_POST_CONVOLUTION_BLUE_SCALE 0x801E
-#define GL_POST_CONVOLUTION_ALPHA_SCALE 0x801F
-#define GL_POST_CONVOLUTION_RED_BIAS 0x8020
-#define GL_POST_CONVOLUTION_GREEN_BIAS 0x8021
-#define GL_POST_CONVOLUTION_BLUE_BIAS 0x8022
-#define GL_POST_CONVOLUTION_ALPHA_BIAS 0x8023
-#define GL_HISTOGRAM 0x8024
-#define GL_PROXY_HISTOGRAM 0x8025
-#define GL_HISTOGRAM_WIDTH 0x8026
-#define GL_HISTOGRAM_FORMAT 0x8027
-#define GL_HISTOGRAM_RED_SIZE 0x8028
-#define GL_HISTOGRAM_GREEN_SIZE 0x8029
-#define GL_HISTOGRAM_BLUE_SIZE 0x802A
-#define GL_HISTOGRAM_ALPHA_SIZE 0x802B
-#define GL_HISTOGRAM_LUMINANCE_SIZE 0x802C
-#define GL_HISTOGRAM_SINK 0x802D
-#define GL_MINMAX 0x802E
-#define GL_MINMAX_FORMAT 0x802F
-#define GL_MINMAX_SINK 0x8030
-#define GL_TABLE_TOO_LARGE 0x8031
-#define GL_COLOR_MATRIX 0x80B1
-#define GL_COLOR_MATRIX_STACK_DEPTH 0x80B2
-#define GL_MAX_COLOR_MATRIX_STACK_DEPTH 0x80B3
-#define GL_POST_COLOR_MATRIX_RED_SCALE 0x80B4
-#define GL_POST_COLOR_MATRIX_GREEN_SCALE 0x80B5
-#define GL_POST_COLOR_MATRIX_BLUE_SCALE 0x80B6
-#define GL_POST_COLOR_MATRIX_ALPHA_SCALE 0x80B7
-#define GL_POST_COLOR_MATRIX_RED_BIAS 0x80B8
-#define GL_POST_COLOR_MATRIX_GREEN_BIAS 0x80B9
-#define GL_POST_COLOR_MATRIX_BLUE_BIAS 0x80BA
-#define GL_POST_COLOR_MATRIX_ALPHA_BIAS 0x80BB
-#define GL_COLOR_TABLE 0x80D0
-#define GL_POST_CONVOLUTION_COLOR_TABLE 0x80D1
-#define GL_POST_COLOR_MATRIX_COLOR_TABLE 0x80D2
-#define GL_PROXY_COLOR_TABLE 0x80D3
-#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE 0x80D4
-#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE 0x80D5
-#define GL_COLOR_TABLE_SCALE 0x80D6
-#define GL_COLOR_TABLE_BIAS 0x80D7
-#define GL_COLOR_TABLE_FORMAT 0x80D8
-#define GL_COLOR_TABLE_WIDTH 0x80D9
-#define GL_COLOR_TABLE_RED_SIZE 0x80DA
-#define GL_COLOR_TABLE_GREEN_SIZE 0x80DB
-#define GL_COLOR_TABLE_BLUE_SIZE 0x80DC
-#define GL_COLOR_TABLE_ALPHA_SIZE 0x80DD
-#define GL_COLOR_TABLE_LUMINANCE_SIZE 0x80DE
-#define GL_COLOR_TABLE_INTENSITY_SIZE 0x80DF
-#define GL_CONSTANT_BORDER 0x8151
-#define GL_REPLICATE_BORDER 0x8153
-#define GL_CONVOLUTION_BORDER_COLOR 0x8154
-#endif
-
-#ifndef GL_VERSION_1_3
-#define GL_TEXTURE0 0x84C0
-#define GL_TEXTURE1 0x84C1
-#define GL_TEXTURE2 0x84C2
-#define GL_TEXTURE3 0x84C3
-#define GL_TEXTURE4 0x84C4
-#define GL_TEXTURE5 0x84C5
-#define GL_TEXTURE6 0x84C6
-#define GL_TEXTURE7 0x84C7
-#define GL_TEXTURE8 0x84C8
-#define GL_TEXTURE9 0x84C9
-#define GL_TEXTURE10 0x84CA
-#define GL_TEXTURE11 0x84CB
-#define GL_TEXTURE12 0x84CC
-#define GL_TEXTURE13 0x84CD
-#define GL_TEXTURE14 0x84CE
-#define GL_TEXTURE15 0x84CF
-#define GL_TEXTURE16 0x84D0
-#define GL_TEXTURE17 0x84D1
-#define GL_TEXTURE18 0x84D2
-#define GL_TEXTURE19 0x84D3
-#define GL_TEXTURE20 0x84D4
-#define GL_TEXTURE21 0x84D5
-#define GL_TEXTURE22 0x84D6
-#define GL_TEXTURE23 0x84D7
-#define GL_TEXTURE24 0x84D8
-#define GL_TEXTURE25 0x84D9
-#define GL_TEXTURE26 0x84DA
-#define GL_TEXTURE27 0x84DB
-#define GL_TEXTURE28 0x84DC
-#define GL_TEXTURE29 0x84DD
-#define GL_TEXTURE30 0x84DE
-#define GL_TEXTURE31 0x84DF
-#define GL_ACTIVE_TEXTURE 0x84E0
-#define GL_CLIENT_ACTIVE_TEXTURE 0x84E1
-#define GL_MAX_TEXTURE_UNITS 0x84E2
-#define GL_TRANSPOSE_MODELVIEW_MATRIX 0x84E3
-#define GL_TRANSPOSE_PROJECTION_MATRIX 0x84E4
-#define GL_TRANSPOSE_TEXTURE_MATRIX 0x84E5
-#define GL_TRANSPOSE_COLOR_MATRIX 0x84E6
-#define GL_MULTISAMPLE 0x809D
-#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E
-#define GL_SAMPLE_ALPHA_TO_ONE 0x809F
-#define GL_SAMPLE_COVERAGE 0x80A0
-#define GL_SAMPLE_BUFFERS 0x80A8
-#define GL_SAMPLES 0x80A9
-#define GL_SAMPLE_COVERAGE_VALUE 0x80AA
-#define GL_SAMPLE_COVERAGE_INVERT 0x80AB
-#define GL_MULTISAMPLE_BIT 0x20000000
-#define GL_NORMAL_MAP 0x8511
-#define GL_REFLECTION_MAP 0x8512
-#define GL_TEXTURE_CUBE_MAP 0x8513
-#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515
-#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517
-#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519
-#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A
-#define GL_PROXY_TEXTURE_CUBE_MAP 0x851B
-#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C
-#define GL_COMPRESSED_ALPHA 0x84E9
-#define GL_COMPRESSED_LUMINANCE 0x84EA
-#define GL_COMPRESSED_LUMINANCE_ALPHA 0x84EB
-#define GL_COMPRESSED_INTENSITY 0x84EC
-#define GL_COMPRESSED_RGB 0x84ED
-#define GL_COMPRESSED_RGBA 0x84EE
-#define GL_TEXTURE_COMPRESSION_HINT 0x84EF
-#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0
-#define GL_TEXTURE_COMPRESSED 0x86A1
-#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2
-#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3
-#define GL_CLAMP_TO_BORDER 0x812D
-#define GL_COMBINE 0x8570
-#define GL_COMBINE_RGB 0x8571
-#define GL_COMBINE_ALPHA 0x8572
-#define GL_SOURCE0_RGB 0x8580
-#define GL_SOURCE1_RGB 0x8581
-#define GL_SOURCE2_RGB 0x8582
-#define GL_SOURCE0_ALPHA 0x8588
-#define GL_SOURCE1_ALPHA 0x8589
-#define GL_SOURCE2_ALPHA 0x858A
-#define GL_OPERAND0_RGB 0x8590
-#define GL_OPERAND1_RGB 0x8591
-#define GL_OPERAND2_RGB 0x8592
-#define GL_OPERAND0_ALPHA 0x8598
-#define GL_OPERAND1_ALPHA 0x8599
-#define GL_OPERAND2_ALPHA 0x859A
-#define GL_RGB_SCALE 0x8573
-#define GL_ADD_SIGNED 0x8574
-#define GL_INTERPOLATE 0x8575
-#define GL_SUBTRACT 0x84E7
-#define GL_CONSTANT 0x8576
-#define GL_PRIMARY_COLOR 0x8577
-#define GL_PREVIOUS 0x8578
-#define GL_DOT3_RGB 0x86AE
-#define GL_DOT3_RGBA 0x86AF
-#endif
-
-#ifndef GL_VERSION_1_4
-#define GL_BLEND_DST_RGB 0x80C8
-#define GL_BLEND_SRC_RGB 0x80C9
-#define GL_BLEND_DST_ALPHA 0x80CA
-#define GL_BLEND_SRC_ALPHA 0x80CB
-#define GL_POINT_SIZE_MIN 0x8126
-#define GL_POINT_SIZE_MAX 0x8127
-#define GL_POINT_FADE_THRESHOLD_SIZE 0x8128
-#define GL_POINT_DISTANCE_ATTENUATION 0x8129
-#define GL_GENERATE_MIPMAP 0x8191
-#define GL_GENERATE_MIPMAP_HINT 0x8192
-#define GL_DEPTH_COMPONENT16 0x81A5
-#define GL_DEPTH_COMPONENT24 0x81A6
-#define GL_DEPTH_COMPONENT32 0x81A7
-#define GL_MIRRORED_REPEAT 0x8370
-#define GL_FOG_COORDINATE_SOURCE 0x8450
-#define GL_FOG_COORDINATE 0x8451
-#define GL_FRAGMENT_DEPTH 0x8452
-#define GL_CURRENT_FOG_COORDINATE 0x8453
-#define GL_FOG_COORDINATE_ARRAY_TYPE 0x8454
-#define GL_FOG_COORDINATE_ARRAY_STRIDE 0x8455
-#define GL_FOG_COORDINATE_ARRAY_POINTER 0x8456
-#define GL_FOG_COORDINATE_ARRAY 0x8457
-#define GL_COLOR_SUM 0x8458
-#define GL_CURRENT_SECONDARY_COLOR 0x8459
-#define GL_SECONDARY_COLOR_ARRAY_SIZE 0x845A
-#define GL_SECONDARY_COLOR_ARRAY_TYPE 0x845B
-#define GL_SECONDARY_COLOR_ARRAY_STRIDE 0x845C
-#define GL_SECONDARY_COLOR_ARRAY_POINTER 0x845D
-#define GL_SECONDARY_COLOR_ARRAY 0x845E
-#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD
-#define GL_TEXTURE_FILTER_CONTROL 0x8500
-#define GL_TEXTURE_LOD_BIAS 0x8501
-#define GL_INCR_WRAP 0x8507
-#define GL_DECR_WRAP 0x8508
-#define GL_TEXTURE_DEPTH_SIZE 0x884A
-#define GL_DEPTH_TEXTURE_MODE 0x884B
-#define GL_TEXTURE_COMPARE_MODE 0x884C
-#define GL_TEXTURE_COMPARE_FUNC 0x884D
-#define GL_COMPARE_R_TO_TEXTURE 0x884E
-#endif
-
-#ifndef GL_VERSION_1_5
-#define GL_BUFFER_SIZE 0x8764
-#define GL_BUFFER_USAGE 0x8765
-#define GL_QUERY_COUNTER_BITS 0x8864
-#define GL_CURRENT_QUERY 0x8865
-#define GL_QUERY_RESULT 0x8866
-#define GL_QUERY_RESULT_AVAILABLE 0x8867
-#define GL_ARRAY_BUFFER 0x8892
-#define GL_ELEMENT_ARRAY_BUFFER 0x8893
-#define GL_ARRAY_BUFFER_BINDING 0x8894
-#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895
-#define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896
-#define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897
-#define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898
-#define GL_INDEX_ARRAY_BUFFER_BINDING 0x8899
-#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A
-#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B
-#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C
-#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D
-#define GL_WEIGHT_ARRAY_BUFFER_BINDING 0x889E
-#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F
-#define GL_READ_ONLY 0x88B8
-#define GL_WRITE_ONLY 0x88B9
-#define GL_READ_WRITE 0x88BA
-#define GL_BUFFER_ACCESS 0x88BB
-#define GL_BUFFER_MAPPED 0x88BC
-#define GL_BUFFER_MAP_POINTER 0x88BD
-#define GL_STREAM_DRAW 0x88E0
-#define GL_STREAM_READ 0x88E1
-#define GL_STREAM_COPY 0x88E2
-#define GL_STATIC_DRAW 0x88E4
-#define GL_STATIC_READ 0x88E5
-#define GL_STATIC_COPY 0x88E6
-#define GL_DYNAMIC_DRAW 0x88E8
-#define GL_DYNAMIC_READ 0x88E9
-#define GL_DYNAMIC_COPY 0x88EA
-#define GL_SAMPLES_PASSED 0x8914
-#define GL_FOG_COORD_SRC GL_FOG_COORDINATE_SOURCE
-#define GL_FOG_COORD GL_FOG_COORDINATE
-#define GL_CURRENT_FOG_COORD GL_CURRENT_FOG_COORDINATE
-#define GL_FOG_COORD_ARRAY_TYPE GL_FOG_COORDINATE_ARRAY_TYPE
-#define GL_FOG_COORD_ARRAY_STRIDE GL_FOG_COORDINATE_ARRAY_STRIDE
-#define GL_FOG_COORD_ARRAY_POINTER GL_FOG_COORDINATE_ARRAY_POINTER
-#define GL_FOG_COORD_ARRAY GL_FOG_COORDINATE_ARRAY
-#define GL_FOG_COORD_ARRAY_BUFFER_BINDING GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING
-#define GL_SRC0_RGB GL_SOURCE0_RGB
-#define GL_SRC1_RGB GL_SOURCE1_RGB
-#define GL_SRC2_RGB GL_SOURCE2_RGB
-#define GL_SRC0_ALPHA GL_SOURCE0_ALPHA
-#define GL_SRC1_ALPHA GL_SOURCE1_ALPHA
-#define GL_SRC2_ALPHA GL_SOURCE2_ALPHA
-#endif
-
-#ifndef GL_VERSION_2_0
-#define GL_BLEND_EQUATION_RGB GL_BLEND_EQUATION
-#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622
-#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623
-#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624
-#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625
-#define GL_CURRENT_VERTEX_ATTRIB 0x8626
-#define GL_VERTEX_PROGRAM_POINT_SIZE 0x8642
-#define GL_VERTEX_PROGRAM_TWO_SIDE 0x8643
-#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645
-#define GL_STENCIL_BACK_FUNC 0x8800
-#define GL_STENCIL_BACK_FAIL 0x8801
-#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802
-#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803
-#define GL_MAX_DRAW_BUFFERS 0x8824
-#define GL_DRAW_BUFFER0 0x8825
-#define GL_DRAW_BUFFER1 0x8826
-#define GL_DRAW_BUFFER2 0x8827
-#define GL_DRAW_BUFFER3 0x8828
-#define GL_DRAW_BUFFER4 0x8829
-#define GL_DRAW_BUFFER5 0x882A
-#define GL_DRAW_BUFFER6 0x882B
-#define GL_DRAW_BUFFER7 0x882C
-#define GL_DRAW_BUFFER8 0x882D
-#define GL_DRAW_BUFFER9 0x882E
-#define GL_DRAW_BUFFER10 0x882F
-#define GL_DRAW_BUFFER11 0x8830
-#define GL_DRAW_BUFFER12 0x8831
-#define GL_DRAW_BUFFER13 0x8832
-#define GL_DRAW_BUFFER14 0x8833
-#define GL_DRAW_BUFFER15 0x8834
-#define GL_BLEND_EQUATION_ALPHA 0x883D
-#define GL_POINT_SPRITE 0x8861
-#define GL_COORD_REPLACE 0x8862
-#define GL_MAX_VERTEX_ATTRIBS 0x8869
-#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A
-#define GL_MAX_TEXTURE_COORDS 0x8871
-#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872
-#define GL_FRAGMENT_SHADER 0x8B30
-#define GL_VERTEX_SHADER 0x8B31
-#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49
-#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A
-#define GL_MAX_VARYING_FLOATS 0x8B4B
-#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C
-#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D
-#define GL_SHADER_TYPE 0x8B4F
-#define GL_FLOAT_VEC2 0x8B50
-#define GL_FLOAT_VEC3 0x8B51
-#define GL_FLOAT_VEC4 0x8B52
-#define GL_INT_VEC2 0x8B53
-#define GL_INT_VEC3 0x8B54
-#define GL_INT_VEC4 0x8B55
-#define GL_BOOL 0x8B56
-#define GL_BOOL_VEC2 0x8B57
-#define GL_BOOL_VEC3 0x8B58
-#define GL_BOOL_VEC4 0x8B59
-#define GL_FLOAT_MAT2 0x8B5A
-#define GL_FLOAT_MAT3 0x8B5B
-#define GL_FLOAT_MAT4 0x8B5C
-#define GL_SAMPLER_1D 0x8B5D
-#define GL_SAMPLER_2D 0x8B5E
-#define GL_SAMPLER_3D 0x8B5F
-#define GL_SAMPLER_CUBE 0x8B60
-#define GL_SAMPLER_1D_SHADOW 0x8B61
-#define GL_SAMPLER_2D_SHADOW 0x8B62
-#define GL_DELETE_STATUS 0x8B80
-#define GL_COMPILE_STATUS 0x8B81
-#define GL_LINK_STATUS 0x8B82
-#define GL_VALIDATE_STATUS 0x8B83
-#define GL_INFO_LOG_LENGTH 0x8B84
-#define GL_ATTACHED_SHADERS 0x8B85
-#define GL_ACTIVE_UNIFORMS 0x8B86
-#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87
-#define GL_SHADER_SOURCE_LENGTH 0x8B88
-#define GL_ACTIVE_ATTRIBUTES 0x8B89
-#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A
-#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B
-#define GL_SHADING_LANGUAGE_VERSION 0x8B8C
-#define GL_CURRENT_PROGRAM 0x8B8D
-#define GL_POINT_SPRITE_COORD_ORIGIN 0x8CA0
-#define GL_LOWER_LEFT 0x8CA1
-#define GL_UPPER_LEFT 0x8CA2
-#define GL_STENCIL_BACK_REF 0x8CA3
-#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4
-#define GL_STENCIL_BACK_WRITEMASK 0x8CA5
-#endif
-
-#ifndef GL_ARB_multitexture
-#define GL_TEXTURE0_ARB 0x84C0
-#define GL_TEXTURE1_ARB 0x84C1
-#define GL_TEXTURE2_ARB 0x84C2
-#define GL_TEXTURE3_ARB 0x84C3
-#define GL_TEXTURE4_ARB 0x84C4
-#define GL_TEXTURE5_ARB 0x84C5
-#define GL_TEXTURE6_ARB 0x84C6
-#define GL_TEXTURE7_ARB 0x84C7
-#define GL_TEXTURE8_ARB 0x84C8
-#define GL_TEXTURE9_ARB 0x84C9
-#define GL_TEXTURE10_ARB 0x84CA
-#define GL_TEXTURE11_ARB 0x84CB
-#define GL_TEXTURE12_ARB 0x84CC
-#define GL_TEXTURE13_ARB 0x84CD
-#define GL_TEXTURE14_ARB 0x84CE
-#define GL_TEXTURE15_ARB 0x84CF
-#define GL_TEXTURE16_ARB 0x84D0
-#define GL_TEXTURE17_ARB 0x84D1
-#define GL_TEXTURE18_ARB 0x84D2
-#define GL_TEXTURE19_ARB 0x84D3
-#define GL_TEXTURE20_ARB 0x84D4
-#define GL_TEXTURE21_ARB 0x84D5
-#define GL_TEXTURE22_ARB 0x84D6
-#define GL_TEXTURE23_ARB 0x84D7
-#define GL_TEXTURE24_ARB 0x84D8
-#define GL_TEXTURE25_ARB 0x84D9
-#define GL_TEXTURE26_ARB 0x84DA
-#define GL_TEXTURE27_ARB 0x84DB
-#define GL_TEXTURE28_ARB 0x84DC
-#define GL_TEXTURE29_ARB 0x84DD
-#define GL_TEXTURE30_ARB 0x84DE
-#define GL_TEXTURE31_ARB 0x84DF
-#define GL_ACTIVE_TEXTURE_ARB 0x84E0
-#define GL_CLIENT_ACTIVE_TEXTURE_ARB 0x84E1
-#define GL_MAX_TEXTURE_UNITS_ARB 0x84E2
-#endif
-
-#ifndef GL_ARB_transpose_matrix
-#define GL_TRANSPOSE_MODELVIEW_MATRIX_ARB 0x84E3
-#define GL_TRANSPOSE_PROJECTION_MATRIX_ARB 0x84E4
-#define GL_TRANSPOSE_TEXTURE_MATRIX_ARB 0x84E5
-#define GL_TRANSPOSE_COLOR_MATRIX_ARB 0x84E6
-#endif
-
-#ifndef GL_ARB_multisample
-#define GL_MULTISAMPLE_ARB 0x809D
-#define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB 0x809E
-#define GL_SAMPLE_ALPHA_TO_ONE_ARB 0x809F
-#define GL_SAMPLE_COVERAGE_ARB 0x80A0
-#define GL_SAMPLE_BUFFERS_ARB 0x80A8
-#define GL_SAMPLES_ARB 0x80A9
-#define GL_SAMPLE_COVERAGE_VALUE_ARB 0x80AA
-#define GL_SAMPLE_COVERAGE_INVERT_ARB 0x80AB
-#define GL_MULTISAMPLE_BIT_ARB 0x20000000
-#endif
-
-#ifndef GL_ARB_texture_env_add
-#endif
-
-#ifndef GL_ARB_texture_cube_map
-#define GL_NORMAL_MAP_ARB 0x8511
-#define GL_REFLECTION_MAP_ARB 0x8512
-#define GL_TEXTURE_CUBE_MAP_ARB 0x8513
-#define GL_TEXTURE_BINDING_CUBE_MAP_ARB 0x8514
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x8515
-#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x8516
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x8517
-#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x8518
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x8519
-#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x851A
-#define GL_PROXY_TEXTURE_CUBE_MAP_ARB 0x851B
-#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB 0x851C
-#endif
-
-#ifndef GL_ARB_texture_compression
-#define GL_COMPRESSED_ALPHA_ARB 0x84E9
-#define GL_COMPRESSED_LUMINANCE_ARB 0x84EA
-#define GL_COMPRESSED_LUMINANCE_ALPHA_ARB 0x84EB
-#define GL_COMPRESSED_INTENSITY_ARB 0x84EC
-#define GL_COMPRESSED_RGB_ARB 0x84ED
-#define GL_COMPRESSED_RGBA_ARB 0x84EE
-#define GL_TEXTURE_COMPRESSION_HINT_ARB 0x84EF
-#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB 0x86A0
-#define GL_TEXTURE_COMPRESSED_ARB 0x86A1
-#define GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A2
-#define GL_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A3
-#endif
-
-#ifndef GL_ARB_texture_border_clamp
-#define GL_CLAMP_TO_BORDER_ARB 0x812D
-#endif
-
-#ifndef GL_ARB_point_parameters
-#define GL_POINT_SIZE_MIN_ARB 0x8126
-#define GL_POINT_SIZE_MAX_ARB 0x8127
-#define GL_POINT_FADE_THRESHOLD_SIZE_ARB 0x8128
-#define GL_POINT_DISTANCE_ATTENUATION_ARB 0x8129
-#endif
-
-#ifndef GL_ARB_vertex_blend
-#define GL_MAX_VERTEX_UNITS_ARB 0x86A4
-#define GL_ACTIVE_VERTEX_UNITS_ARB 0x86A5
-#define GL_WEIGHT_SUM_UNITY_ARB 0x86A6
-#define GL_VERTEX_BLEND_ARB 0x86A7
-#define GL_CURRENT_WEIGHT_ARB 0x86A8
-#define GL_WEIGHT_ARRAY_TYPE_ARB 0x86A9
-#define GL_WEIGHT_ARRAY_STRIDE_ARB 0x86AA
-#define GL_WEIGHT_ARRAY_SIZE_ARB 0x86AB
-#define GL_WEIGHT_ARRAY_POINTER_ARB 0x86AC
-#define GL_WEIGHT_ARRAY_ARB 0x86AD
-#define GL_MODELVIEW0_ARB 0x1700
-#define GL_MODELVIEW1_ARB 0x850A
-#define GL_MODELVIEW2_ARB 0x8722
-#define GL_MODELVIEW3_ARB 0x8723
-#define GL_MODELVIEW4_ARB 0x8724
-#define GL_MODELVIEW5_ARB 0x8725
-#define GL_MODELVIEW6_ARB 0x8726
-#define GL_MODELVIEW7_ARB 0x8727
-#define GL_MODELVIEW8_ARB 0x8728
-#define GL_MODELVIEW9_ARB 0x8729
-#define GL_MODELVIEW10_ARB 0x872A
-#define GL_MODELVIEW11_ARB 0x872B
-#define GL_MODELVIEW12_ARB 0x872C
-#define GL_MODELVIEW13_ARB 0x872D
-#define GL_MODELVIEW14_ARB 0x872E
-#define GL_MODELVIEW15_ARB 0x872F
-#define GL_MODELVIEW16_ARB 0x8730
-#define GL_MODELVIEW17_ARB 0x8731
-#define GL_MODELVIEW18_ARB 0x8732
-#define GL_MODELVIEW19_ARB 0x8733
-#define GL_MODELVIEW20_ARB 0x8734
-#define GL_MODELVIEW21_ARB 0x8735
-#define GL_MODELVIEW22_ARB 0x8736
-#define GL_MODELVIEW23_ARB 0x8737
-#define GL_MODELVIEW24_ARB 0x8738
-#define GL_MODELVIEW25_ARB 0x8739
-#define GL_MODELVIEW26_ARB 0x873A
-#define GL_MODELVIEW27_ARB 0x873B
-#define GL_MODELVIEW28_ARB 0x873C
-#define GL_MODELVIEW29_ARB 0x873D
-#define GL_MODELVIEW30_ARB 0x873E
-#define GL_MODELVIEW31_ARB 0x873F
-#endif
-
-#ifndef GL_ARB_matrix_palette
-#define GL_MATRIX_PALETTE_ARB 0x8840
-#define GL_MAX_MATRIX_PALETTE_STACK_DEPTH_ARB 0x8841
-#define GL_MAX_PALETTE_MATRICES_ARB 0x8842
-#define GL_CURRENT_PALETTE_MATRIX_ARB 0x8843
-#define GL_MATRIX_INDEX_ARRAY_ARB 0x8844
-#define GL_CURRENT_MATRIX_INDEX_ARB 0x8845
-#define GL_MATRIX_INDEX_ARRAY_SIZE_ARB 0x8846
-#define GL_MATRIX_INDEX_ARRAY_TYPE_ARB 0x8847
-#define GL_MATRIX_INDEX_ARRAY_STRIDE_ARB 0x8848
-#define GL_MATRIX_INDEX_ARRAY_POINTER_ARB 0x8849
-#endif
-
-#ifndef GL_ARB_texture_env_combine
-#define GL_COMBINE_ARB 0x8570
-#define GL_COMBINE_RGB_ARB 0x8571
-#define GL_COMBINE_ALPHA_ARB 0x8572
-#define GL_SOURCE0_RGB_ARB 0x8580
-#define GL_SOURCE1_RGB_ARB 0x8581
-#define GL_SOURCE2_RGB_ARB 0x8582
-#define GL_SOURCE0_ALPHA_ARB 0x8588
-#define GL_SOURCE1_ALPHA_ARB 0x8589
-#define GL_SOURCE2_ALPHA_ARB 0x858A
-#define GL_OPERAND0_RGB_ARB 0x8590
-#define GL_OPERAND1_RGB_ARB 0x8591
-#define GL_OPERAND2_RGB_ARB 0x8592
-#define GL_OPERAND0_ALPHA_ARB 0x8598
-#define GL_OPERAND1_ALPHA_ARB 0x8599
-#define GL_OPERAND2_ALPHA_ARB 0x859A
-#define GL_RGB_SCALE_ARB 0x8573
-#define GL_ADD_SIGNED_ARB 0x8574
-#define GL_INTERPOLATE_ARB 0x8575
-#define GL_SUBTRACT_ARB 0x84E7
-#define GL_CONSTANT_ARB 0x8576
-#define GL_PRIMARY_COLOR_ARB 0x8577
-#define GL_PREVIOUS_ARB 0x8578
-#endif
-
-#ifndef GL_ARB_texture_env_crossbar
-#endif
-
-#ifndef GL_ARB_texture_env_dot3
-#define GL_DOT3_RGB_ARB 0x86AE
-#define GL_DOT3_RGBA_ARB 0x86AF
-#endif
-
-#ifndef GL_ARB_texture_mirrored_repeat
-#define GL_MIRRORED_REPEAT_ARB 0x8370
-#endif
-
-#ifndef GL_ARB_depth_texture
-#define GL_DEPTH_COMPONENT16_ARB 0x81A5
-#define GL_DEPTH_COMPONENT24_ARB 0x81A6
-#define GL_DEPTH_COMPONENT32_ARB 0x81A7
-#define GL_TEXTURE_DEPTH_SIZE_ARB 0x884A
-#define GL_DEPTH_TEXTURE_MODE_ARB 0x884B
-#endif
-
-#ifndef GL_ARB_shadow
-#define GL_TEXTURE_COMPARE_MODE_ARB 0x884C
-#define GL_TEXTURE_COMPARE_FUNC_ARB 0x884D
-#define GL_COMPARE_R_TO_TEXTURE_ARB 0x884E
-#endif
-
-#ifndef GL_ARB_shadow_ambient
-#define GL_TEXTURE_COMPARE_FAIL_VALUE_ARB 0x80BF
-#endif
-
-#ifndef GL_ARB_window_pos
-#endif
-
-#ifndef GL_ARB_vertex_program
-#define GL_COLOR_SUM_ARB 0x8458
-#define GL_VERTEX_PROGRAM_ARB 0x8620
-#define GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB 0x8622
-#define GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB 0x8623
-#define GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB 0x8624
-#define GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB 0x8625
-#define GL_CURRENT_VERTEX_ATTRIB_ARB 0x8626
-#define GL_PROGRAM_LENGTH_ARB 0x8627
-#define GL_PROGRAM_STRING_ARB 0x8628
-#define GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB 0x862E
-#define GL_MAX_PROGRAM_MATRICES_ARB 0x862F
-#define GL_CURRENT_MATRIX_STACK_DEPTH_ARB 0x8640
-#define GL_CURRENT_MATRIX_ARB 0x8641
-#define GL_VERTEX_PROGRAM_POINT_SIZE_ARB 0x8642
-#define GL_VERTEX_PROGRAM_TWO_SIDE_ARB 0x8643
-#define GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB 0x8645
-#define GL_PROGRAM_ERROR_POSITION_ARB 0x864B
-#define GL_PROGRAM_BINDING_ARB 0x8677
-#define GL_MAX_VERTEX_ATTRIBS_ARB 0x8869
-#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB 0x886A
-#define GL_PROGRAM_ERROR_STRING_ARB 0x8874
-#define GL_PROGRAM_FORMAT_ASCII_ARB 0x8875
-#define GL_PROGRAM_FORMAT_ARB 0x8876
-#define GL_PROGRAM_INSTRUCTIONS_ARB 0x88A0
-#define GL_MAX_PROGRAM_INSTRUCTIONS_ARB 0x88A1
-#define GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A2
-#define GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A3
-#define GL_PROGRAM_TEMPORARIES_ARB 0x88A4
-#define GL_MAX_PROGRAM_TEMPORARIES_ARB 0x88A5
-#define GL_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A6
-#define GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A7
-#define GL_PROGRAM_PARAMETERS_ARB 0x88A8
-#define GL_MAX_PROGRAM_PARAMETERS_ARB 0x88A9
-#define GL_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AA
-#define GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AB
-#define GL_PROGRAM_ATTRIBS_ARB 0x88AC
-#define GL_MAX_PROGRAM_ATTRIBS_ARB 0x88AD
-#define GL_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AE
-#define GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AF
-#define GL_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B0
-#define GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B1
-#define GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B2
-#define GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B3
-#define GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB 0x88B4
-#define GL_MAX_PROGRAM_ENV_PARAMETERS_ARB 0x88B5
-#define GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB 0x88B6
-#define GL_TRANSPOSE_CURRENT_MATRIX_ARB 0x88B7
-#define GL_MATRIX0_ARB 0x88C0
-#define GL_MATRIX1_ARB 0x88C1
-#define GL_MATRIX2_ARB 0x88C2
-#define GL_MATRIX3_ARB 0x88C3
-#define GL_MATRIX4_ARB 0x88C4
-#define GL_MATRIX5_ARB 0x88C5
-#define GL_MATRIX6_ARB 0x88C6
-#define GL_MATRIX7_ARB 0x88C7
-#define GL_MATRIX8_ARB 0x88C8
-#define GL_MATRIX9_ARB 0x88C9
-#define GL_MATRIX10_ARB 0x88CA
-#define GL_MATRIX11_ARB 0x88CB
-#define GL_MATRIX12_ARB 0x88CC
-#define GL_MATRIX13_ARB 0x88CD
-#define GL_MATRIX14_ARB 0x88CE
-#define GL_MATRIX15_ARB 0x88CF
-#define GL_MATRIX16_ARB 0x88D0
-#define GL_MATRIX17_ARB 0x88D1
-#define GL_MATRIX18_ARB 0x88D2
-#define GL_MATRIX19_ARB 0x88D3
-#define GL_MATRIX20_ARB 0x88D4
-#define GL_MATRIX21_ARB 0x88D5
-#define GL_MATRIX22_ARB 0x88D6
-#define GL_MATRIX23_ARB 0x88D7
-#define GL_MATRIX24_ARB 0x88D8
-#define GL_MATRIX25_ARB 0x88D9
-#define GL_MATRIX26_ARB 0x88DA
-#define GL_MATRIX27_ARB 0x88DB
-#define GL_MATRIX28_ARB 0x88DC
-#define GL_MATRIX29_ARB 0x88DD
-#define GL_MATRIX30_ARB 0x88DE
-#define GL_MATRIX31_ARB 0x88DF
-#endif
-
-#ifndef GL_ARB_fragment_program
-#define GL_FRAGMENT_PROGRAM_ARB 0x8804
-#define GL_PROGRAM_ALU_INSTRUCTIONS_ARB 0x8805
-#define GL_PROGRAM_TEX_INSTRUCTIONS_ARB 0x8806
-#define GL_PROGRAM_TEX_INDIRECTIONS_ARB 0x8807
-#define GL_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x8808
-#define GL_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x8809
-#define GL_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x880A
-#define GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB 0x880B
-#define GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB 0x880C
-#define GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB 0x880D
-#define GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x880E
-#define GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x880F
-#define GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x8810
-#define GL_MAX_TEXTURE_COORDS_ARB 0x8871
-#define GL_MAX_TEXTURE_IMAGE_UNITS_ARB 0x8872
-#endif
-
-#ifndef GL_ARB_vertex_buffer_object
-#define GL_BUFFER_SIZE_ARB 0x8764
-#define GL_BUFFER_USAGE_ARB 0x8765
-#define GL_ARRAY_BUFFER_ARB 0x8892
-#define GL_ELEMENT_ARRAY_BUFFER_ARB 0x8893
-#define GL_ARRAY_BUFFER_BINDING_ARB 0x8894
-#define GL_ELEMENT_ARRAY_BUFFER_BINDING_ARB 0x8895
-#define GL_VERTEX_ARRAY_BUFFER_BINDING_ARB 0x8896
-#define GL_NORMAL_ARRAY_BUFFER_BINDING_ARB 0x8897
-#define GL_COLOR_ARRAY_BUFFER_BINDING_ARB 0x8898
-#define GL_INDEX_ARRAY_BUFFER_BINDING_ARB 0x8899
-#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING_ARB 0x889A
-#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING_ARB 0x889B
-#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING_ARB 0x889C
-#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING_ARB 0x889D
-#define GL_WEIGHT_ARRAY_BUFFER_BINDING_ARB 0x889E
-#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB 0x889F
-#define GL_READ_ONLY_ARB 0x88B8
-#define GL_WRITE_ONLY_ARB 0x88B9
-#define GL_READ_WRITE_ARB 0x88BA
-#define GL_BUFFER_ACCESS_ARB 0x88BB
-#define GL_BUFFER_MAPPED_ARB 0x88BC
-#define GL_BUFFER_MAP_POINTER_ARB 0x88BD
-#define GL_STREAM_DRAW_ARB 0x88E0
-#define GL_STREAM_READ_ARB 0x88E1
-#define GL_STREAM_COPY_ARB 0x88E2
-#define GL_STATIC_DRAW_ARB 0x88E4
-#define GL_STATIC_READ_ARB 0x88E5
-#define GL_STATIC_COPY_ARB 0x88E6
-#define GL_DYNAMIC_DRAW_ARB 0x88E8
-#define GL_DYNAMIC_READ_ARB 0x88E9
-#define GL_DYNAMIC_COPY_ARB 0x88EA
-#endif
-
-#ifndef GL_ARB_occlusion_query
-#define GL_QUERY_COUNTER_BITS_ARB 0x8864
-#define GL_CURRENT_QUERY_ARB 0x8865
-#define GL_QUERY_RESULT_ARB 0x8866
-#define GL_QUERY_RESULT_AVAILABLE_ARB 0x8867
-#define GL_SAMPLES_PASSED_ARB 0x8914
-#endif
-
-#ifndef GL_ARB_shader_objects
-#define GL_PROGRAM_OBJECT_ARB 0x8B40
-#define GL_SHADER_OBJECT_ARB 0x8B48
-#define GL_OBJECT_TYPE_ARB 0x8B4E
-#define GL_OBJECT_SUBTYPE_ARB 0x8B4F
-#define GL_FLOAT_VEC2_ARB 0x8B50
-#define GL_FLOAT_VEC3_ARB 0x8B51
-#define GL_FLOAT_VEC4_ARB 0x8B52
-#define GL_INT_VEC2_ARB 0x8B53
-#define GL_INT_VEC3_ARB 0x8B54
-#define GL_INT_VEC4_ARB 0x8B55
-#define GL_BOOL_ARB 0x8B56
-#define GL_BOOL_VEC2_ARB 0x8B57
-#define GL_BOOL_VEC3_ARB 0x8B58
-#define GL_BOOL_VEC4_ARB 0x8B59
-#define GL_FLOAT_MAT2_ARB 0x8B5A
-#define GL_FLOAT_MAT3_ARB 0x8B5B
-#define GL_FLOAT_MAT4_ARB 0x8B5C
-#define GL_SAMPLER_1D_ARB 0x8B5D
-#define GL_SAMPLER_2D_ARB 0x8B5E
-#define GL_SAMPLER_3D_ARB 0x8B5F
-#define GL_SAMPLER_CUBE_ARB 0x8B60
-#define GL_SAMPLER_1D_SHADOW_ARB 0x8B61
-#define GL_SAMPLER_2D_SHADOW_ARB 0x8B62
-#define GL_SAMPLER_2D_RECT_ARB 0x8B63
-#define GL_SAMPLER_2D_RECT_SHADOW_ARB 0x8B64
-#define GL_OBJECT_DELETE_STATUS_ARB 0x8B80
-#define GL_OBJECT_COMPILE_STATUS_ARB 0x8B81
-#define GL_OBJECT_LINK_STATUS_ARB 0x8B82
-#define GL_OBJECT_VALIDATE_STATUS_ARB 0x8B83
-#define GL_OBJECT_INFO_LOG_LENGTH_ARB 0x8B84
-#define GL_OBJECT_ATTACHED_OBJECTS_ARB 0x8B85
-#define GL_OBJECT_ACTIVE_UNIFORMS_ARB 0x8B86
-#define GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB 0x8B87
-#define GL_OBJECT_SHADER_SOURCE_LENGTH_ARB 0x8B88
-#endif
-
-#ifndef GL_ARB_vertex_shader
-#define GL_VERTEX_SHADER_ARB 0x8B31
-#define GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB 0x8B4A
-#define GL_MAX_VARYING_FLOATS_ARB 0x8B4B
-#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB 0x8B4C
-#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB 0x8B4D
-#define GL_OBJECT_ACTIVE_ATTRIBUTES_ARB 0x8B89
-#define GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB 0x8B8A
-#endif
-
-#ifndef GL_ARB_fragment_shader
-#define GL_FRAGMENT_SHADER_ARB 0x8B30
-#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB 0x8B49
-#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT_ARB 0x8B8B
-#endif
-
-#ifndef GL_ARB_shading_language_100
-#define GL_SHADING_LANGUAGE_VERSION_ARB 0x8B8C
-#endif
-
-#ifndef GL_ARB_texture_non_power_of_two
-#endif
-
-#ifndef GL_ARB_point_sprite
-#define GL_POINT_SPRITE_ARB 0x8861
-#define GL_COORD_REPLACE_ARB 0x8862
-#endif
-
-#ifndef GL_ARB_fragment_program_shadow
-#endif
-
-#ifndef GL_ARB_draw_buffers
-#define GL_MAX_DRAW_BUFFERS_ARB 0x8824
-#define GL_DRAW_BUFFER0_ARB 0x8825
-#define GL_DRAW_BUFFER1_ARB 0x8826
-#define GL_DRAW_BUFFER2_ARB 0x8827
-#define GL_DRAW_BUFFER3_ARB 0x8828
-#define GL_DRAW_BUFFER4_ARB 0x8829
-#define GL_DRAW_BUFFER5_ARB 0x882A
-#define GL_DRAW_BUFFER6_ARB 0x882B
-#define GL_DRAW_BUFFER7_ARB 0x882C
-#define GL_DRAW_BUFFER8_ARB 0x882D
-#define GL_DRAW_BUFFER9_ARB 0x882E
-#define GL_DRAW_BUFFER10_ARB 0x882F
-#define GL_DRAW_BUFFER11_ARB 0x8830
-#define GL_DRAW_BUFFER12_ARB 0x8831
-#define GL_DRAW_BUFFER13_ARB 0x8832
-#define GL_DRAW_BUFFER14_ARB 0x8833
-#define GL_DRAW_BUFFER15_ARB 0x8834
-#endif
-
-#ifndef GL_ARB_texture_rectangle
-#define GL_TEXTURE_RECTANGLE_ARB 0x84F5
-#define GL_TEXTURE_BINDING_RECTANGLE_ARB 0x84F6
-#define GL_PROXY_TEXTURE_RECTANGLE_ARB 0x84F7
-#define GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB 0x84F8
-#endif
-
-#ifndef GL_ARB_color_buffer_float
-#define GL_RGBA_FLOAT_MODE_ARB 0x8820
-#define GL_CLAMP_VERTEX_COLOR_ARB 0x891A
-#define GL_CLAMP_FRAGMENT_COLOR_ARB 0x891B
-#define GL_CLAMP_READ_COLOR_ARB 0x891C
-#define GL_FIXED_ONLY_ARB 0x891D
-#endif
-
-#ifndef GL_ARB_half_float_pixel
-#define GL_HALF_FLOAT_ARB 0x140B
-#endif
-
-#ifndef GL_ARB_texture_float
-#define GL_TEXTURE_RED_TYPE_ARB 0x8C10
-#define GL_TEXTURE_GREEN_TYPE_ARB 0x8C11
-#define GL_TEXTURE_BLUE_TYPE_ARB 0x8C12
-#define GL_TEXTURE_ALPHA_TYPE_ARB 0x8C13
-#define GL_TEXTURE_LUMINANCE_TYPE_ARB 0x8C14
-#define GL_TEXTURE_INTENSITY_TYPE_ARB 0x8C15
-#define GL_TEXTURE_DEPTH_TYPE_ARB 0x8C16
-#define GL_UNSIGNED_NORMALIZED_ARB 0x8C17
-#define GL_RGBA32F_ARB 0x8814
-#define GL_RGB32F_ARB 0x8815
-#define GL_ALPHA32F_ARB 0x8816
-#define GL_INTENSITY32F_ARB 0x8817
-#define GL_LUMINANCE32F_ARB 0x8818
-#define GL_LUMINANCE_ALPHA32F_ARB 0x8819
-#define GL_RGBA16F_ARB 0x881A
-#define GL_RGB16F_ARB 0x881B
-#define GL_ALPHA16F_ARB 0x881C
-#define GL_INTENSITY16F_ARB 0x881D
-#define GL_LUMINANCE16F_ARB 0x881E
-#define GL_LUMINANCE_ALPHA16F_ARB 0x881F
-#endif
-
-#ifndef GL_ARB_pixel_buffer_object
-#define GL_PIXEL_PACK_BUFFER_ARB 0x88EB
-#define GL_PIXEL_UNPACK_BUFFER_ARB 0x88EC
-#define GL_PIXEL_PACK_BUFFER_BINDING_ARB 0x88ED
-#define GL_PIXEL_UNPACK_BUFFER_BINDING_ARB 0x88EF
-#endif
-
-#ifndef GL_EXT_abgr
-#define GL_ABGR_EXT 0x8000
-#endif
-
-#ifndef GL_EXT_blend_color
-#define GL_CONSTANT_COLOR_EXT 0x8001
-#define GL_ONE_MINUS_CONSTANT_COLOR_EXT 0x8002
-#define GL_CONSTANT_ALPHA_EXT 0x8003
-#define GL_ONE_MINUS_CONSTANT_ALPHA_EXT 0x8004
-#define GL_BLEND_COLOR_EXT 0x8005
-#endif
-
-#ifndef GL_EXT_polygon_offset
-#define GL_POLYGON_OFFSET_EXT 0x8037
-#define GL_POLYGON_OFFSET_FACTOR_EXT 0x8038
-#define GL_POLYGON_OFFSET_BIAS_EXT 0x8039
-#endif
-
-#ifndef GL_EXT_texture
-#define GL_ALPHA4_EXT 0x803B
-#define GL_ALPHA8_EXT 0x803C
-#define GL_ALPHA12_EXT 0x803D
-#define GL_ALPHA16_EXT 0x803E
-#define GL_LUMINANCE4_EXT 0x803F
-#define GL_LUMINANCE8_EXT 0x8040
-#define GL_LUMINANCE12_EXT 0x8041
-#define GL_LUMINANCE16_EXT 0x8042
-#define GL_LUMINANCE4_ALPHA4_EXT 0x8043
-#define GL_LUMINANCE6_ALPHA2_EXT 0x8044
-#define GL_LUMINANCE8_ALPHA8_EXT 0x8045
-#define GL_LUMINANCE12_ALPHA4_EXT 0x8046
-#define GL_LUMINANCE12_ALPHA12_EXT 0x8047
-#define GL_LUMINANCE16_ALPHA16_EXT 0x8048
-#define GL_INTENSITY_EXT 0x8049
-#define GL_INTENSITY4_EXT 0x804A
-#define GL_INTENSITY8_EXT 0x804B
-#define GL_INTENSITY12_EXT 0x804C
-#define GL_INTENSITY16_EXT 0x804D
-#define GL_RGB2_EXT 0x804E
-#define GL_RGB4_EXT 0x804F
-#define GL_RGB5_EXT 0x8050
-#define GL_RGB8_EXT 0x8051
-#define GL_RGB10_EXT 0x8052
-#define GL_RGB12_EXT 0x8053
-#define GL_RGB16_EXT 0x8054
-#define GL_RGBA2_EXT 0x8055
-#define GL_RGBA4_EXT 0x8056
-#define GL_RGB5_A1_EXT 0x8057
-#define GL_RGBA8_EXT 0x8058
-#define GL_RGB10_A2_EXT 0x8059
-#define GL_RGBA12_EXT 0x805A
-#define GL_RGBA16_EXT 0x805B
-#define GL_TEXTURE_RED_SIZE_EXT 0x805C
-#define GL_TEXTURE_GREEN_SIZE_EXT 0x805D
-#define GL_TEXTURE_BLUE_SIZE_EXT 0x805E
-#define GL_TEXTURE_ALPHA_SIZE_EXT 0x805F
-#define GL_TEXTURE_LUMINANCE_SIZE_EXT 0x8060
-#define GL_TEXTURE_INTENSITY_SIZE_EXT 0x8061
-#define GL_REPLACE_EXT 0x8062
-#define GL_PROXY_TEXTURE_1D_EXT 0x8063
-#define GL_PROXY_TEXTURE_2D_EXT 0x8064
-#define GL_TEXTURE_TOO_LARGE_EXT 0x8065
-#endif
-
-#ifndef GL_EXT_texture3D
-#define GL_PACK_SKIP_IMAGES_EXT 0x806B
-#define GL_PACK_IMAGE_HEIGHT_EXT 0x806C
-#define GL_UNPACK_SKIP_IMAGES_EXT 0x806D
-#define GL_UNPACK_IMAGE_HEIGHT_EXT 0x806E
-#define GL_TEXTURE_3D_EXT 0x806F
-#define GL_PROXY_TEXTURE_3D_EXT 0x8070
-#define GL_TEXTURE_DEPTH_EXT 0x8071
-#define GL_TEXTURE_WRAP_R_EXT 0x8072
-#define GL_MAX_3D_TEXTURE_SIZE_EXT 0x8073
-#endif
-
-#ifndef GL_SGIS_texture_filter4
-#define GL_FILTER4_SGIS 0x8146
-#define GL_TEXTURE_FILTER4_SIZE_SGIS 0x8147
-#endif
-
-#ifndef GL_EXT_subtexture
-#endif
-
-#ifndef GL_EXT_copy_texture
-#endif
-
-#ifndef GL_EXT_histogram
-#define GL_HISTOGRAM_EXT 0x8024
-#define GL_PROXY_HISTOGRAM_EXT 0x8025
-#define GL_HISTOGRAM_WIDTH_EXT 0x8026
-#define GL_HISTOGRAM_FORMAT_EXT 0x8027
-#define GL_HISTOGRAM_RED_SIZE_EXT 0x8028
-#define GL_HISTOGRAM_GREEN_SIZE_EXT 0x8029
-#define GL_HISTOGRAM_BLUE_SIZE_EXT 0x802A
-#define GL_HISTOGRAM_ALPHA_SIZE_EXT 0x802B
-#define GL_HISTOGRAM_LUMINANCE_SIZE_EXT 0x802C
-#define GL_HISTOGRAM_SINK_EXT 0x802D
-#define GL_MINMAX_EXT 0x802E
-#define GL_MINMAX_FORMAT_EXT 0x802F
-#define GL_MINMAX_SINK_EXT 0x8030
-#define GL_TABLE_TOO_LARGE_EXT 0x8031
-#endif
-
-#ifndef GL_EXT_convolution
-#define GL_CONVOLUTION_1D_EXT 0x8010
-#define GL_CONVOLUTION_2D_EXT 0x8011
-#define GL_SEPARABLE_2D_EXT 0x8012
-#define GL_CONVOLUTION_BORDER_MODE_EXT 0x8013
-#define GL_CONVOLUTION_FILTER_SCALE_EXT 0x8014
-#define GL_CONVOLUTION_FILTER_BIAS_EXT 0x8015
-#define GL_REDUCE_EXT 0x8016
-#define GL_CONVOLUTION_FORMAT_EXT 0x8017
-#define GL_CONVOLUTION_WIDTH_EXT 0x8018
-#define GL_CONVOLUTION_HEIGHT_EXT 0x8019
-#define GL_MAX_CONVOLUTION_WIDTH_EXT 0x801A
-#define GL_MAX_CONVOLUTION_HEIGHT_EXT 0x801B
-#define GL_POST_CONVOLUTION_RED_SCALE_EXT 0x801C
-#define GL_POST_CONVOLUTION_GREEN_SCALE_EXT 0x801D
-#define GL_POST_CONVOLUTION_BLUE_SCALE_EXT 0x801E
-#define GL_POST_CONVOLUTION_ALPHA_SCALE_EXT 0x801F
-#define GL_POST_CONVOLUTION_RED_BIAS_EXT 0x8020
-#define GL_POST_CONVOLUTION_GREEN_BIAS_EXT 0x8021
-#define GL_POST_CONVOLUTION_BLUE_BIAS_EXT 0x8022
-#define GL_POST_CONVOLUTION_ALPHA_BIAS_EXT 0x8023
-#endif
-
-#ifndef GL_SGI_color_matrix
-#define GL_COLOR_MATRIX_SGI 0x80B1
-#define GL_COLOR_MATRIX_STACK_DEPTH_SGI 0x80B2
-#define GL_MAX_COLOR_MATRIX_STACK_DEPTH_SGI 0x80B3
-#define GL_POST_COLOR_MATRIX_RED_SCALE_SGI 0x80B4
-#define GL_POST_COLOR_MATRIX_GREEN_SCALE_SGI 0x80B5
-#define GL_POST_COLOR_MATRIX_BLUE_SCALE_SGI 0x80B6
-#define GL_POST_COLOR_MATRIX_ALPHA_SCALE_SGI 0x80B7
-#define GL_POST_COLOR_MATRIX_RED_BIAS_SGI 0x80B8
-#define GL_POST_COLOR_MATRIX_GREEN_BIAS_SGI 0x80B9
-#define GL_POST_COLOR_MATRIX_BLUE_BIAS_SGI 0x80BA
-#define GL_POST_COLOR_MATRIX_ALPHA_BIAS_SGI 0x80BB
-#endif
-
-#ifndef GL_SGI_color_table
-#define GL_COLOR_TABLE_SGI 0x80D0
-#define GL_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D1
-#define GL_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D2
-#define GL_PROXY_COLOR_TABLE_SGI 0x80D3
-#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D4
-#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D5
-#define GL_COLOR_TABLE_SCALE_SGI 0x80D6
-#define GL_COLOR_TABLE_BIAS_SGI 0x80D7
-#define GL_COLOR_TABLE_FORMAT_SGI 0x80D8
-#define GL_COLOR_TABLE_WIDTH_SGI 0x80D9
-#define GL_COLOR_TABLE_RED_SIZE_SGI 0x80DA
-#define GL_COLOR_TABLE_GREEN_SIZE_SGI 0x80DB
-#define GL_COLOR_TABLE_BLUE_SIZE_SGI 0x80DC
-#define GL_COLOR_TABLE_ALPHA_SIZE_SGI 0x80DD
-#define GL_COLOR_TABLE_LUMINANCE_SIZE_SGI 0x80DE
-#define GL_COLOR_TABLE_INTENSITY_SIZE_SGI 0x80DF
-#endif
-
-#ifndef GL_SGIS_pixel_texture
-#define GL_PIXEL_TEXTURE_SGIS 0x8353
-#define GL_PIXEL_FRAGMENT_RGB_SOURCE_SGIS 0x8354
-#define GL_PIXEL_FRAGMENT_ALPHA_SOURCE_SGIS 0x8355
-#define GL_PIXEL_GROUP_COLOR_SGIS 0x8356
-#endif
-
-#ifndef GL_SGIX_pixel_texture
-#define GL_PIXEL_TEX_GEN_SGIX 0x8139
-#define GL_PIXEL_TEX_GEN_MODE_SGIX 0x832B
-#endif
-
-#ifndef GL_SGIS_texture4D
-#define GL_PACK_SKIP_VOLUMES_SGIS 0x8130
-#define GL_PACK_IMAGE_DEPTH_SGIS 0x8131
-#define GL_UNPACK_SKIP_VOLUMES_SGIS 0x8132
-#define GL_UNPACK_IMAGE_DEPTH_SGIS 0x8133
-#define GL_TEXTURE_4D_SGIS 0x8134
-#define GL_PROXY_TEXTURE_4D_SGIS 0x8135
-#define GL_TEXTURE_4DSIZE_SGIS 0x8136
-#define GL_TEXTURE_WRAP_Q_SGIS 0x8137
-#define GL_MAX_4D_TEXTURE_SIZE_SGIS 0x8138
-#define GL_TEXTURE_4D_BINDING_SGIS 0x814F
-#endif
-
-#ifndef GL_SGI_texture_color_table
-#define GL_TEXTURE_COLOR_TABLE_SGI 0x80BC
-#define GL_PROXY_TEXTURE_COLOR_TABLE_SGI 0x80BD
-#endif
-
-#ifndef GL_EXT_cmyka
-#define GL_CMYK_EXT 0x800C
-#define GL_CMYKA_EXT 0x800D
-#define GL_PACK_CMYK_HINT_EXT 0x800E
-#define GL_UNPACK_CMYK_HINT_EXT 0x800F
-#endif
-
-#ifndef GL_EXT_texture_object
-#define GL_TEXTURE_PRIORITY_EXT 0x8066
-#define GL_TEXTURE_RESIDENT_EXT 0x8067
-#define GL_TEXTURE_1D_BINDING_EXT 0x8068
-#define GL_TEXTURE_2D_BINDING_EXT 0x8069
-#define GL_TEXTURE_3D_BINDING_EXT 0x806A
-#endif
-
-#ifndef GL_SGIS_detail_texture
-#define GL_DETAIL_TEXTURE_2D_SGIS 0x8095
-#define GL_DETAIL_TEXTURE_2D_BINDING_SGIS 0x8096
-#define GL_LINEAR_DETAIL_SGIS 0x8097
-#define GL_LINEAR_DETAIL_ALPHA_SGIS 0x8098
-#define GL_LINEAR_DETAIL_COLOR_SGIS 0x8099
-#define GL_DETAIL_TEXTURE_LEVEL_SGIS 0x809A
-#define GL_DETAIL_TEXTURE_MODE_SGIS 0x809B
-#define GL_DETAIL_TEXTURE_FUNC_POINTS_SGIS 0x809C
-#endif
-
-#ifndef GL_SGIS_sharpen_texture
-#define GL_LINEAR_SHARPEN_SGIS 0x80AD
-#define GL_LINEAR_SHARPEN_ALPHA_SGIS 0x80AE
-#define GL_LINEAR_SHARPEN_COLOR_SGIS 0x80AF
-#define GL_SHARPEN_TEXTURE_FUNC_POINTS_SGIS 0x80B0
-#endif
-
-#ifndef GL_EXT_packed_pixels
-#define GL_UNSIGNED_BYTE_3_3_2_EXT 0x8032
-#define GL_UNSIGNED_SHORT_4_4_4_4_EXT 0x8033
-#define GL_UNSIGNED_SHORT_5_5_5_1_EXT 0x8034
-#define GL_UNSIGNED_INT_8_8_8_8_EXT 0x8035
-#define GL_UNSIGNED_INT_10_10_10_2_EXT 0x8036
-#endif
-
-#ifndef GL_SGIS_texture_lod
-#define GL_TEXTURE_MIN_LOD_SGIS 0x813A
-#define GL_TEXTURE_MAX_LOD_SGIS 0x813B
-#define GL_TEXTURE_BASE_LEVEL_SGIS 0x813C
-#define GL_TEXTURE_MAX_LEVEL_SGIS 0x813D
-#endif
-
-#ifndef GL_SGIS_multisample
-#define GL_MULTISAMPLE_SGIS 0x809D
-#define GL_SAMPLE_ALPHA_TO_MASK_SGIS 0x809E
-#define GL_SAMPLE_ALPHA_TO_ONE_SGIS 0x809F
-#define GL_SAMPLE_MASK_SGIS 0x80A0
-#define GL_1PASS_SGIS 0x80A1
-#define GL_2PASS_0_SGIS 0x80A2
-#define GL_2PASS_1_SGIS 0x80A3
-#define GL_4PASS_0_SGIS 0x80A4
-#define GL_4PASS_1_SGIS 0x80A5
-#define GL_4PASS_2_SGIS 0x80A6
-#define GL_4PASS_3_SGIS 0x80A7
-#define GL_SAMPLE_BUFFERS_SGIS 0x80A8
-#define GL_SAMPLES_SGIS 0x80A9
-#define GL_SAMPLE_MASK_VALUE_SGIS 0x80AA
-#define GL_SAMPLE_MASK_INVERT_SGIS 0x80AB
-#define GL_SAMPLE_PATTERN_SGIS 0x80AC
-#endif
-
-#ifndef GL_EXT_rescale_normal
-#define GL_RESCALE_NORMAL_EXT 0x803A
-#endif
-
-#ifndef GL_EXT_vertex_array
-#define GL_VERTEX_ARRAY_EXT 0x8074
-#define GL_NORMAL_ARRAY_EXT 0x8075
-#define GL_COLOR_ARRAY_EXT 0x8076
-#define GL_INDEX_ARRAY_EXT 0x8077
-#define GL_TEXTURE_COORD_ARRAY_EXT 0x8078
-#define GL_EDGE_FLAG_ARRAY_EXT 0x8079
-#define GL_VERTEX_ARRAY_SIZE_EXT 0x807A
-#define GL_VERTEX_ARRAY_TYPE_EXT 0x807B
-#define GL_VERTEX_ARRAY_STRIDE_EXT 0x807C
-#define GL_VERTEX_ARRAY_COUNT_EXT 0x807D
-#define GL_NORMAL_ARRAY_TYPE_EXT 0x807E
-#define GL_NORMAL_ARRAY_STRIDE_EXT 0x807F
-#define GL_NORMAL_ARRAY_COUNT_EXT 0x8080
-#define GL_COLOR_ARRAY_SIZE_EXT 0x8081
-#define GL_COLOR_ARRAY_TYPE_EXT 0x8082
-#define GL_COLOR_ARRAY_STRIDE_EXT 0x8083
-#define GL_COLOR_ARRAY_COUNT_EXT 0x8084
-#define GL_INDEX_ARRAY_TYPE_EXT 0x8085
-#define GL_INDEX_ARRAY_STRIDE_EXT 0x8086
-#define GL_INDEX_ARRAY_COUNT_EXT 0x8087
-#define GL_TEXTURE_COORD_ARRAY_SIZE_EXT 0x8088
-#define GL_TEXTURE_COORD_ARRAY_TYPE_EXT 0x8089
-#define GL_TEXTURE_COORD_ARRAY_STRIDE_EXT 0x808A
-#define GL_TEXTURE_COORD_ARRAY_COUNT_EXT 0x808B
-#define GL_EDGE_FLAG_ARRAY_STRIDE_EXT 0x808C
-#define GL_EDGE_FLAG_ARRAY_COUNT_EXT 0x808D
-#define GL_VERTEX_ARRAY_POINTER_EXT 0x808E
-#define GL_NORMAL_ARRAY_POINTER_EXT 0x808F
-#define GL_COLOR_ARRAY_POINTER_EXT 0x8090
-#define GL_INDEX_ARRAY_POINTER_EXT 0x8091
-#define GL_TEXTURE_COORD_ARRAY_POINTER_EXT 0x8092
-#define GL_EDGE_FLAG_ARRAY_POINTER_EXT 0x8093
-#endif
-
-#ifndef GL_EXT_misc_attribute
-#endif
-
-#ifndef GL_SGIS_generate_mipmap
-#define GL_GENERATE_MIPMAP_SGIS 0x8191
-#define GL_GENERATE_MIPMAP_HINT_SGIS 0x8192
-#endif
-
-#ifndef GL_SGIX_clipmap
-#define GL_LINEAR_CLIPMAP_LINEAR_SGIX 0x8170
-#define GL_TEXTURE_CLIPMAP_CENTER_SGIX 0x8171
-#define GL_TEXTURE_CLIPMAP_FRAME_SGIX 0x8172
-#define GL_TEXTURE_CLIPMAP_OFFSET_SGIX 0x8173
-#define GL_TEXTURE_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8174
-#define GL_TEXTURE_CLIPMAP_LOD_OFFSET_SGIX 0x8175
-#define GL_TEXTURE_CLIPMAP_DEPTH_SGIX 0x8176
-#define GL_MAX_CLIPMAP_DEPTH_SGIX 0x8177
-#define GL_MAX_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8178
-#define GL_NEAREST_CLIPMAP_NEAREST_SGIX 0x844D
-#define GL_NEAREST_CLIPMAP_LINEAR_SGIX 0x844E
-#define GL_LINEAR_CLIPMAP_NEAREST_SGIX 0x844F
-#endif
-
-#ifndef GL_SGIX_shadow
-#define GL_TEXTURE_COMPARE_SGIX 0x819A
-#define GL_TEXTURE_COMPARE_OPERATOR_SGIX 0x819B
-#define GL_TEXTURE_LEQUAL_R_SGIX 0x819C
-#define GL_TEXTURE_GEQUAL_R_SGIX 0x819D
-#endif
-
-#ifndef GL_SGIS_texture_edge_clamp
-#define GL_CLAMP_TO_EDGE_SGIS 0x812F
-#endif
-
-#ifndef GL_SGIS_texture_border_clamp
-#define GL_CLAMP_TO_BORDER_SGIS 0x812D
-#endif
-
-#ifndef GL_EXT_blend_minmax
-#define GL_FUNC_ADD_EXT 0x8006
-#define GL_MIN_EXT 0x8007
-#define GL_MAX_EXT 0x8008
-#define GL_BLEND_EQUATION_EXT 0x8009
-#endif
-
-#ifndef GL_EXT_blend_subtract
-#define GL_FUNC_SUBTRACT_EXT 0x800A
-#define GL_FUNC_REVERSE_SUBTRACT_EXT 0x800B
-#endif
-
-#ifndef GL_EXT_blend_logic_op
-#endif
-
-#ifndef GL_SGIX_interlace
-#define GL_INTERLACE_SGIX 0x8094
-#endif
-
-#ifndef GL_SGIX_pixel_tiles
-#define GL_PIXEL_TILE_BEST_ALIGNMENT_SGIX 0x813E
-#define GL_PIXEL_TILE_CACHE_INCREMENT_SGIX 0x813F
-#define GL_PIXEL_TILE_WIDTH_SGIX 0x8140
-#define GL_PIXEL_TILE_HEIGHT_SGIX 0x8141
-#define GL_PIXEL_TILE_GRID_WIDTH_SGIX 0x8142
-#define GL_PIXEL_TILE_GRID_HEIGHT_SGIX 0x8143
-#define GL_PIXEL_TILE_GRID_DEPTH_SGIX 0x8144
-#define GL_PIXEL_TILE_CACHE_SIZE_SGIX 0x8145
-#endif
-
-#ifndef GL_SGIS_texture_select
-#define GL_DUAL_ALPHA4_SGIS 0x8110
-#define GL_DUAL_ALPHA8_SGIS 0x8111
-#define GL_DUAL_ALPHA12_SGIS 0x8112
-#define GL_DUAL_ALPHA16_SGIS 0x8113
-#define GL_DUAL_LUMINANCE4_SGIS 0x8114
-#define GL_DUAL_LUMINANCE8_SGIS 0x8115
-#define GL_DUAL_LUMINANCE12_SGIS 0x8116
-#define GL_DUAL_LUMINANCE16_SGIS 0x8117
-#define GL_DUAL_INTENSITY4_SGIS 0x8118
-#define GL_DUAL_INTENSITY8_SGIS 0x8119
-#define GL_DUAL_INTENSITY12_SGIS 0x811A
-#define GL_DUAL_INTENSITY16_SGIS 0x811B
-#define GL_DUAL_LUMINANCE_ALPHA4_SGIS 0x811C
-#define GL_DUAL_LUMINANCE_ALPHA8_SGIS 0x811D
-#define GL_QUAD_ALPHA4_SGIS 0x811E
-#define GL_QUAD_ALPHA8_SGIS 0x811F
-#define GL_QUAD_LUMINANCE4_SGIS 0x8120
-#define GL_QUAD_LUMINANCE8_SGIS 0x8121
-#define GL_QUAD_INTENSITY4_SGIS 0x8122
-#define GL_QUAD_INTENSITY8_SGIS 0x8123
-#define GL_DUAL_TEXTURE_SELECT_SGIS 0x8124
-#define GL_QUAD_TEXTURE_SELECT_SGIS 0x8125
-#endif
-
-#ifndef GL_SGIX_sprite
-#define GL_SPRITE_SGIX 0x8148
-#define GL_SPRITE_MODE_SGIX 0x8149
-#define GL_SPRITE_AXIS_SGIX 0x814A
-#define GL_SPRITE_TRANSLATION_SGIX 0x814B
-#define GL_SPRITE_AXIAL_SGIX 0x814C
-#define GL_SPRITE_OBJECT_ALIGNED_SGIX 0x814D
-#define GL_SPRITE_EYE_ALIGNED_SGIX 0x814E
-#endif
-
-#ifndef GL_SGIX_texture_multi_buffer
-#define GL_TEXTURE_MULTI_BUFFER_HINT_SGIX 0x812E
-#endif
-
-#ifndef GL_EXT_point_parameters
-#define GL_POINT_SIZE_MIN_EXT 0x8126
-#define GL_POINT_SIZE_MAX_EXT 0x8127
-#define GL_POINT_FADE_THRESHOLD_SIZE_EXT 0x8128
-#define GL_DISTANCE_ATTENUATION_EXT 0x8129
-#endif
-
-#ifndef GL_SGIS_point_parameters
-#define GL_POINT_SIZE_MIN_SGIS 0x8126
-#define GL_POINT_SIZE_MAX_SGIS 0x8127
-#define GL_POINT_FADE_THRESHOLD_SIZE_SGIS 0x8128
-#define GL_DISTANCE_ATTENUATION_SGIS 0x8129
-#endif
-
-#ifndef GL_SGIX_instruments
-#define GL_INSTRUMENT_BUFFER_POINTER_SGIX 0x8180
-#define GL_INSTRUMENT_MEASUREMENTS_SGIX 0x8181
-#endif
-
-#ifndef GL_SGIX_texture_scale_bias
-#define GL_POST_TEXTURE_FILTER_BIAS_SGIX 0x8179
-#define GL_POST_TEXTURE_FILTER_SCALE_SGIX 0x817A
-#define GL_POST_TEXTURE_FILTER_BIAS_RANGE_SGIX 0x817B
-#define GL_POST_TEXTURE_FILTER_SCALE_RANGE_SGIX 0x817C
-#endif
-
-#ifndef GL_SGIX_framezoom
-#define GL_FRAMEZOOM_SGIX 0x818B
-#define GL_FRAMEZOOM_FACTOR_SGIX 0x818C
-#define GL_MAX_FRAMEZOOM_FACTOR_SGIX 0x818D
-#endif
-
-#ifndef GL_SGIX_tag_sample_buffer
-#endif
-
-#ifndef GL_FfdMaskSGIX
-#define GL_TEXTURE_DEFORMATION_BIT_SGIX 0x00000001
-#define GL_GEOMETRY_DEFORMATION_BIT_SGIX 0x00000002
-#endif
-
-#ifndef GL_SGIX_polynomial_ffd
-#define GL_GEOMETRY_DEFORMATION_SGIX 0x8194
-#define GL_TEXTURE_DEFORMATION_SGIX 0x8195
-#define GL_DEFORMATIONS_MASK_SGIX 0x8196
-#define GL_MAX_DEFORMATION_ORDER_SGIX 0x8197
-#endif
-
-#ifndef GL_SGIX_reference_plane
-#define GL_REFERENCE_PLANE_SGIX 0x817D
-#define GL_REFERENCE_PLANE_EQUATION_SGIX 0x817E
-#endif
-
-#ifndef GL_SGIX_flush_raster
-#endif
-
-#ifndef GL_SGIX_depth_texture
-#define GL_DEPTH_COMPONENT16_SGIX 0x81A5
-#define GL_DEPTH_COMPONENT24_SGIX 0x81A6
-#define GL_DEPTH_COMPONENT32_SGIX 0x81A7
-#endif
-
-#ifndef GL_SGIS_fog_function
-#define GL_FOG_FUNC_SGIS 0x812A
-#define GL_FOG_FUNC_POINTS_SGIS 0x812B
-#define GL_MAX_FOG_FUNC_POINTS_SGIS 0x812C
-#endif
-
-#ifndef GL_SGIX_fog_offset
-#define GL_FOG_OFFSET_SGIX 0x8198
-#define GL_FOG_OFFSET_VALUE_SGIX 0x8199
-#endif
-
-#ifndef GL_HP_image_transform
-#define GL_IMAGE_SCALE_X_HP 0x8155
-#define GL_IMAGE_SCALE_Y_HP 0x8156
-#define GL_IMAGE_TRANSLATE_X_HP 0x8157
-#define GL_IMAGE_TRANSLATE_Y_HP 0x8158
-#define GL_IMAGE_ROTATE_ANGLE_HP 0x8159
-#define GL_IMAGE_ROTATE_ORIGIN_X_HP 0x815A
-#define GL_IMAGE_ROTATE_ORIGIN_Y_HP 0x815B
-#define GL_IMAGE_MAG_FILTER_HP 0x815C
-#define GL_IMAGE_MIN_FILTER_HP 0x815D
-#define GL_IMAGE_CUBIC_WEIGHT_HP 0x815E
-#define GL_CUBIC_HP 0x815F
-#define GL_AVERAGE_HP 0x8160
-#define GL_IMAGE_TRANSFORM_2D_HP 0x8161
-#define GL_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8162
-#define GL_PROXY_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8163
-#endif
-
-#ifndef GL_HP_convolution_border_modes
-#define GL_IGNORE_BORDER_HP 0x8150
-#define GL_CONSTANT_BORDER_HP 0x8151
-#define GL_REPLICATE_BORDER_HP 0x8153
-#define GL_CONVOLUTION_BORDER_COLOR_HP 0x8154
-#endif
-
-#ifndef GL_INGR_palette_buffer
-#endif
-
-#ifndef GL_SGIX_texture_add_env
-#define GL_TEXTURE_ENV_BIAS_SGIX 0x80BE
-#endif
-
-#ifndef GL_EXT_color_subtable
-#endif
-
-#ifndef GL_PGI_vertex_hints
-#define GL_VERTEX_DATA_HINT_PGI 0x1A22A
-#define GL_VERTEX_CONSISTENT_HINT_PGI 0x1A22B
-#define GL_MATERIAL_SIDE_HINT_PGI 0x1A22C
-#define GL_MAX_VERTEX_HINT_PGI 0x1A22D
-#define GL_COLOR3_BIT_PGI 0x00010000
-#define GL_COLOR4_BIT_PGI 0x00020000
-#define GL_EDGEFLAG_BIT_PGI 0x00040000
-#define GL_INDEX_BIT_PGI 0x00080000
-#define GL_MAT_AMBIENT_BIT_PGI 0x00100000
-#define GL_MAT_AMBIENT_AND_DIFFUSE_BIT_PGI 0x00200000
-#define GL_MAT_DIFFUSE_BIT_PGI 0x00400000
-#define GL_MAT_EMISSION_BIT_PGI 0x00800000
-#define GL_MAT_COLOR_INDEXES_BIT_PGI 0x01000000
-#define GL_MAT_SHININESS_BIT_PGI 0x02000000
-#define GL_MAT_SPECULAR_BIT_PGI 0x04000000
-#define GL_NORMAL_BIT_PGI 0x08000000
-#define GL_TEXCOORD1_BIT_PGI 0x10000000
-#define GL_TEXCOORD2_BIT_PGI 0x20000000
-#define GL_TEXCOORD3_BIT_PGI 0x40000000
-#define GL_TEXCOORD4_BIT_PGI 0x80000000
-#define GL_VERTEX23_BIT_PGI 0x00000004
-#define GL_VERTEX4_BIT_PGI 0x00000008
-#endif
-
-#ifndef GL_PGI_misc_hints
-#define GL_PREFER_DOUBLEBUFFER_HINT_PGI 0x1A1F8
-#define GL_CONSERVE_MEMORY_HINT_PGI 0x1A1FD
-#define GL_RECLAIM_MEMORY_HINT_PGI 0x1A1FE
-#define GL_NATIVE_GRAPHICS_HANDLE_PGI 0x1A202
-#define GL_NATIVE_GRAPHICS_BEGIN_HINT_PGI 0x1A203
-#define GL_NATIVE_GRAPHICS_END_HINT_PGI 0x1A204
-#define GL_ALWAYS_FAST_HINT_PGI 0x1A20C
-#define GL_ALWAYS_SOFT_HINT_PGI 0x1A20D
-#define GL_ALLOW_DRAW_OBJ_HINT_PGI 0x1A20E
-#define GL_ALLOW_DRAW_WIN_HINT_PGI 0x1A20F
-#define GL_ALLOW_DRAW_FRG_HINT_PGI 0x1A210
-#define GL_ALLOW_DRAW_MEM_HINT_PGI 0x1A211
-#define GL_STRICT_DEPTHFUNC_HINT_PGI 0x1A216
-#define GL_STRICT_LIGHTING_HINT_PGI 0x1A217
-#define GL_STRICT_SCISSOR_HINT_PGI 0x1A218
-#define GL_FULL_STIPPLE_HINT_PGI 0x1A219
-#define GL_CLIP_NEAR_HINT_PGI 0x1A220
-#define GL_CLIP_FAR_HINT_PGI 0x1A221
-#define GL_WIDE_LINE_HINT_PGI 0x1A222
-#define GL_BACK_NORMALS_HINT_PGI 0x1A223
-#endif
-
-#ifndef GL_EXT_paletted_texture
-#define GL_COLOR_INDEX1_EXT 0x80E2
-#define GL_COLOR_INDEX2_EXT 0x80E3
-#define GL_COLOR_INDEX4_EXT 0x80E4
-#define GL_COLOR_INDEX8_EXT 0x80E5
-#define GL_COLOR_INDEX12_EXT 0x80E6
-#define GL_COLOR_INDEX16_EXT 0x80E7
-#define GL_TEXTURE_INDEX_SIZE_EXT 0x80ED
-#endif
-
-#ifndef GL_EXT_clip_volume_hint
-#define GL_CLIP_VOLUME_CLIPPING_HINT_EXT 0x80F0
-#endif
-
-#ifndef GL_SGIX_list_priority
-#define GL_LIST_PRIORITY_SGIX 0x8182
-#endif
-
-#ifndef GL_SGIX_ir_instrument1
-#define GL_IR_INSTRUMENT1_SGIX 0x817F
-#endif
-
-#ifndef GL_SGIX_calligraphic_fragment
-#define GL_CALLIGRAPHIC_FRAGMENT_SGIX 0x8183
-#endif
-
-#ifndef GL_SGIX_texture_lod_bias
-#define GL_TEXTURE_LOD_BIAS_S_SGIX 0x818E
-#define GL_TEXTURE_LOD_BIAS_T_SGIX 0x818F
-#define GL_TEXTURE_LOD_BIAS_R_SGIX 0x8190
-#endif
-
-#ifndef GL_SGIX_shadow_ambient
-#define GL_SHADOW_AMBIENT_SGIX 0x80BF
-#endif
-
-#ifndef GL_EXT_index_texture
-#endif
-
-#ifndef GL_EXT_index_material
-#define GL_INDEX_MATERIAL_EXT 0x81B8
-#define GL_INDEX_MATERIAL_PARAMETER_EXT 0x81B9
-#define GL_INDEX_MATERIAL_FACE_EXT 0x81BA
-#endif
-
-#ifndef GL_EXT_index_func
-#define GL_INDEX_TEST_EXT 0x81B5
-#define GL_INDEX_TEST_FUNC_EXT 0x81B6
-#define GL_INDEX_TEST_REF_EXT 0x81B7
-#endif
-
-#ifndef GL_EXT_index_array_formats
-#define GL_IUI_V2F_EXT 0x81AD
-#define GL_IUI_V3F_EXT 0x81AE
-#define GL_IUI_N3F_V2F_EXT 0x81AF
-#define GL_IUI_N3F_V3F_EXT 0x81B0
-#define GL_T2F_IUI_V2F_EXT 0x81B1
-#define GL_T2F_IUI_V3F_EXT 0x81B2
-#define GL_T2F_IUI_N3F_V2F_EXT 0x81B3
-#define GL_T2F_IUI_N3F_V3F_EXT 0x81B4
-#endif
-
-#ifndef GL_EXT_compiled_vertex_array
-#define GL_ARRAY_ELEMENT_LOCK_FIRST_EXT 0x81A8
-#define GL_ARRAY_ELEMENT_LOCK_COUNT_EXT 0x81A9
-#endif
-
-#ifndef GL_EXT_cull_vertex
-#define GL_CULL_VERTEX_EXT 0x81AA
-#define GL_CULL_VERTEX_EYE_POSITION_EXT 0x81AB
-#define GL_CULL_VERTEX_OBJECT_POSITION_EXT 0x81AC
-#endif
-
-#ifndef GL_SGIX_ycrcb
-#define GL_YCRCB_422_SGIX 0x81BB
-#define GL_YCRCB_444_SGIX 0x81BC
-#endif
-
-#ifndef GL_SGIX_fragment_lighting
-#define GL_FRAGMENT_LIGHTING_SGIX 0x8400
-#define GL_FRAGMENT_COLOR_MATERIAL_SGIX 0x8401
-#define GL_FRAGMENT_COLOR_MATERIAL_FACE_SGIX 0x8402
-#define GL_FRAGMENT_COLOR_MATERIAL_PARAMETER_SGIX 0x8403
-#define GL_MAX_FRAGMENT_LIGHTS_SGIX 0x8404
-#define GL_MAX_ACTIVE_LIGHTS_SGIX 0x8405
-#define GL_CURRENT_RASTER_NORMAL_SGIX 0x8406
-#define GL_LIGHT_ENV_MODE_SGIX 0x8407
-#define GL_FRAGMENT_LIGHT_MODEL_LOCAL_VIEWER_SGIX 0x8408
-#define GL_FRAGMENT_LIGHT_MODEL_TWO_SIDE_SGIX 0x8409
-#define GL_FRAGMENT_LIGHT_MODEL_AMBIENT_SGIX 0x840A
-#define GL_FRAGMENT_LIGHT_MODEL_NORMAL_INTERPOLATION_SGIX 0x840B
-#define GL_FRAGMENT_LIGHT0_SGIX 0x840C
-#define GL_FRAGMENT_LIGHT1_SGIX 0x840D
-#define GL_FRAGMENT_LIGHT2_SGIX 0x840E
-#define GL_FRAGMENT_LIGHT3_SGIX 0x840F
-#define GL_FRAGMENT_LIGHT4_SGIX 0x8410
-#define GL_FRAGMENT_LIGHT5_SGIX 0x8411
-#define GL_FRAGMENT_LIGHT6_SGIX 0x8412
-#define GL_FRAGMENT_LIGHT7_SGIX 0x8413
-#endif
-
-#ifndef GL_IBM_rasterpos_clip
-#define GL_RASTER_POSITION_UNCLIPPED_IBM 0x19262
-#endif
-
-#ifndef GL_HP_texture_lighting
-#define GL_TEXTURE_LIGHTING_MODE_HP 0x8167
-#define GL_TEXTURE_POST_SPECULAR_HP 0x8168
-#define GL_TEXTURE_PRE_SPECULAR_HP 0x8169
-#endif
-
-#ifndef GL_EXT_draw_range_elements
-#define GL_MAX_ELEMENTS_VERTICES_EXT 0x80E8
-#define GL_MAX_ELEMENTS_INDICES_EXT 0x80E9
-#endif
-
-#ifndef GL_WIN_phong_shading
-#define GL_PHONG_WIN 0x80EA
-#define GL_PHONG_HINT_WIN 0x80EB
-#endif
-
-#ifndef GL_WIN_specular_fog
-#define GL_FOG_SPECULAR_TEXTURE_WIN 0x80EC
-#endif
-
-#ifndef GL_EXT_light_texture
-#define GL_FRAGMENT_MATERIAL_EXT 0x8349
-#define GL_FRAGMENT_NORMAL_EXT 0x834A
-#define GL_FRAGMENT_COLOR_EXT 0x834C
-#define GL_ATTENUATION_EXT 0x834D
-#define GL_SHADOW_ATTENUATION_EXT 0x834E
-#define GL_TEXTURE_APPLICATION_MODE_EXT 0x834F
-#define GL_TEXTURE_LIGHT_EXT 0x8350
-#define GL_TEXTURE_MATERIAL_FACE_EXT 0x8351
-#define GL_TEXTURE_MATERIAL_PARAMETER_EXT 0x8352
-/* reuse GL_FRAGMENT_DEPTH_EXT */
-#endif
-
-#ifndef GL_SGIX_blend_alpha_minmax
-#define GL_ALPHA_MIN_SGIX 0x8320
-#define GL_ALPHA_MAX_SGIX 0x8321
-#endif
-
-#ifndef GL_SGIX_impact_pixel_texture
-#define GL_PIXEL_TEX_GEN_Q_CEILING_SGIX 0x8184
-#define GL_PIXEL_TEX_GEN_Q_ROUND_SGIX 0x8185
-#define GL_PIXEL_TEX_GEN_Q_FLOOR_SGIX 0x8186
-#define GL_PIXEL_TEX_GEN_ALPHA_REPLACE_SGIX 0x8187
-#define GL_PIXEL_TEX_GEN_ALPHA_NO_REPLACE_SGIX 0x8188
-#define GL_PIXEL_TEX_GEN_ALPHA_LS_SGIX 0x8189
-#define GL_PIXEL_TEX_GEN_ALPHA_MS_SGIX 0x818A
-#endif
-
-#ifndef GL_EXT_bgra
-#define GL_BGR_EXT 0x80E0
-#define GL_BGRA_EXT 0x80E1
-#endif
-
-#ifndef GL_SGIX_async
-#define GL_ASYNC_MARKER_SGIX 0x8329
-#endif
-
-#ifndef GL_SGIX_async_pixel
-#define GL_ASYNC_TEX_IMAGE_SGIX 0x835C
-#define GL_ASYNC_DRAW_PIXELS_SGIX 0x835D
-#define GL_ASYNC_READ_PIXELS_SGIX 0x835E
-#define GL_MAX_ASYNC_TEX_IMAGE_SGIX 0x835F
-#define GL_MAX_ASYNC_DRAW_PIXELS_SGIX 0x8360
-#define GL_MAX_ASYNC_READ_PIXELS_SGIX 0x8361
-#endif
-
-#ifndef GL_SGIX_async_histogram
-#define GL_ASYNC_HISTOGRAM_SGIX 0x832C
-#define GL_MAX_ASYNC_HISTOGRAM_SGIX 0x832D
-#endif
-
-#ifndef GL_INTEL_texture_scissor
-#endif
-
-#ifndef GL_INTEL_parallel_arrays
-#define GL_PARALLEL_ARRAYS_INTEL 0x83F4
-#define GL_VERTEX_ARRAY_PARALLEL_POINTERS_INTEL 0x83F5
-#define GL_NORMAL_ARRAY_PARALLEL_POINTERS_INTEL 0x83F6
-#define GL_COLOR_ARRAY_PARALLEL_POINTERS_INTEL 0x83F7
-#define GL_TEXTURE_COORD_ARRAY_PARALLEL_POINTERS_INTEL 0x83F8
-#endif
-
-#ifndef GL_HP_occlusion_test
-#define GL_OCCLUSION_TEST_HP 0x8165
-#define GL_OCCLUSION_TEST_RESULT_HP 0x8166
-#endif
-
-#ifndef GL_EXT_pixel_transform
-#define GL_PIXEL_TRANSFORM_2D_EXT 0x8330
-#define GL_PIXEL_MAG_FILTER_EXT 0x8331
-#define GL_PIXEL_MIN_FILTER_EXT 0x8332
-#define GL_PIXEL_CUBIC_WEIGHT_EXT 0x8333
-#define GL_CUBIC_EXT 0x8334
-#define GL_AVERAGE_EXT 0x8335
-#define GL_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8336
-#define GL_MAX_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8337
-#define GL_PIXEL_TRANSFORM_2D_MATRIX_EXT 0x8338
-#endif
-
-#ifndef GL_EXT_pixel_transform_color_table
-#endif
-
-#ifndef GL_EXT_shared_texture_palette
-#define GL_SHARED_TEXTURE_PALETTE_EXT 0x81FB
-#endif
-
-#ifndef GL_EXT_separate_specular_color
-#define GL_LIGHT_MODEL_COLOR_CONTROL_EXT 0x81F8
-#define GL_SINGLE_COLOR_EXT 0x81F9
-#define GL_SEPARATE_SPECULAR_COLOR_EXT 0x81FA
-#endif
-
-#ifndef GL_EXT_secondary_color
-#define GL_COLOR_SUM_EXT 0x8458
-#define GL_CURRENT_SECONDARY_COLOR_EXT 0x8459
-#define GL_SECONDARY_COLOR_ARRAY_SIZE_EXT 0x845A
-#define GL_SECONDARY_COLOR_ARRAY_TYPE_EXT 0x845B
-#define GL_SECONDARY_COLOR_ARRAY_STRIDE_EXT 0x845C
-#define GL_SECONDARY_COLOR_ARRAY_POINTER_EXT 0x845D
-#define GL_SECONDARY_COLOR_ARRAY_EXT 0x845E
-#endif
-
-#ifndef GL_EXT_texture_perturb_normal
-#define GL_PERTURB_EXT 0x85AE
-#define GL_TEXTURE_NORMAL_EXT 0x85AF
-#endif
-
-#ifndef GL_EXT_multi_draw_arrays
-#endif
-
-#ifndef GL_EXT_fog_coord
-#define GL_FOG_COORDINATE_SOURCE_EXT 0x8450
-#define GL_FOG_COORDINATE_EXT 0x8451
-#define GL_FRAGMENT_DEPTH_EXT 0x8452
-#define GL_CURRENT_FOG_COORDINATE_EXT 0x8453
-#define GL_FOG_COORDINATE_ARRAY_TYPE_EXT 0x8454
-#define GL_FOG_COORDINATE_ARRAY_STRIDE_EXT 0x8455
-#define GL_FOG_COORDINATE_ARRAY_POINTER_EXT 0x8456
-#define GL_FOG_COORDINATE_ARRAY_EXT 0x8457
-#endif
-
-#ifndef GL_REND_screen_coordinates
-#define GL_SCREEN_COORDINATES_REND 0x8490
-#define GL_INVERTED_SCREEN_W_REND 0x8491
-#endif
-
-#ifndef GL_EXT_coordinate_frame
-#define GL_TANGENT_ARRAY_EXT 0x8439
-#define GL_BINORMAL_ARRAY_EXT 0x843A
-#define GL_CURRENT_TANGENT_EXT 0x843B
-#define GL_CURRENT_BINORMAL_EXT 0x843C
-#define GL_TANGENT_ARRAY_TYPE_EXT 0x843E
-#define GL_TANGENT_ARRAY_STRIDE_EXT 0x843F
-#define GL_BINORMAL_ARRAY_TYPE_EXT 0x8440
-#define GL_BINORMAL_ARRAY_STRIDE_EXT 0x8441
-#define GL_TANGENT_ARRAY_POINTER_EXT 0x8442
-#define GL_BINORMAL_ARRAY_POINTER_EXT 0x8443
-#define GL_MAP1_TANGENT_EXT 0x8444
-#define GL_MAP2_TANGENT_EXT 0x8445
-#define GL_MAP1_BINORMAL_EXT 0x8446
-#define GL_MAP2_BINORMAL_EXT 0x8447
-#endif
-
-#ifndef GL_EXT_texture_env_combine
-#define GL_COMBINE_EXT 0x8570
-#define GL_COMBINE_RGB_EXT 0x8571
-#define GL_COMBINE_ALPHA_EXT 0x8572
-#define GL_RGB_SCALE_EXT 0x8573
-#define GL_ADD_SIGNED_EXT 0x8574
-#define GL_INTERPOLATE_EXT 0x8575
-#define GL_CONSTANT_EXT 0x8576
-#define GL_PRIMARY_COLOR_EXT 0x8577
-#define GL_PREVIOUS_EXT 0x8578
-#define GL_SOURCE0_RGB_EXT 0x8580
-#define GL_SOURCE1_RGB_EXT 0x8581
-#define GL_SOURCE2_RGB_EXT 0x8582
-#define GL_SOURCE0_ALPHA_EXT 0x8588
-#define GL_SOURCE1_ALPHA_EXT 0x8589
-#define GL_SOURCE2_ALPHA_EXT 0x858A
-#define GL_OPERAND0_RGB_EXT 0x8590
-#define GL_OPERAND1_RGB_EXT 0x8591
-#define GL_OPERAND2_RGB_EXT 0x8592
-#define GL_OPERAND0_ALPHA_EXT 0x8598
-#define GL_OPERAND1_ALPHA_EXT 0x8599
-#define GL_OPERAND2_ALPHA_EXT 0x859A
-#endif
-
-#ifndef GL_APPLE_specular_vector
-#define GL_LIGHT_MODEL_SPECULAR_VECTOR_APPLE 0x85B0
-#endif
-
-#ifndef GL_APPLE_transform_hint
-#define GL_TRANSFORM_HINT_APPLE 0x85B1
-#endif
-
-#ifndef GL_SGIX_fog_scale
-#define GL_FOG_SCALE_SGIX 0x81FC
-#define GL_FOG_SCALE_VALUE_SGIX 0x81FD
-#endif
-
-#ifndef GL_SUNX_constant_data
-#define GL_UNPACK_CONSTANT_DATA_SUNX 0x81D5
-#define GL_TEXTURE_CONSTANT_DATA_SUNX 0x81D6
-#endif
-
-#ifndef GL_SUN_global_alpha
-#define GL_GLOBAL_ALPHA_SUN 0x81D9
-#define GL_GLOBAL_ALPHA_FACTOR_SUN 0x81DA
-#endif
-
-#ifndef GL_SUN_triangle_list
-#define GL_RESTART_SUN 0x0001
-#define GL_REPLACE_MIDDLE_SUN 0x0002
-#define GL_REPLACE_OLDEST_SUN 0x0003
-#define GL_TRIANGLE_LIST_SUN 0x81D7
-#define GL_REPLACEMENT_CODE_SUN 0x81D8
-#define GL_REPLACEMENT_CODE_ARRAY_SUN 0x85C0
-#define GL_REPLACEMENT_CODE_ARRAY_TYPE_SUN 0x85C1
-#define GL_REPLACEMENT_CODE_ARRAY_STRIDE_SUN 0x85C2
-#define GL_REPLACEMENT_CODE_ARRAY_POINTER_SUN 0x85C3
-#define GL_R1UI_V3F_SUN 0x85C4
-#define GL_R1UI_C4UB_V3F_SUN 0x85C5
-#define GL_R1UI_C3F_V3F_SUN 0x85C6
-#define GL_R1UI_N3F_V3F_SUN 0x85C7
-#define GL_R1UI_C4F_N3F_V3F_SUN 0x85C8
-#define GL_R1UI_T2F_V3F_SUN 0x85C9
-#define GL_R1UI_T2F_N3F_V3F_SUN 0x85CA
-#define GL_R1UI_T2F_C4F_N3F_V3F_SUN 0x85CB
-#endif
-
-#ifndef GL_SUN_vertex
-#endif
-
-#ifndef GL_EXT_blend_func_separate
-#define GL_BLEND_DST_RGB_EXT 0x80C8
-#define GL_BLEND_SRC_RGB_EXT 0x80C9
-#define GL_BLEND_DST_ALPHA_EXT 0x80CA
-#define GL_BLEND_SRC_ALPHA_EXT 0x80CB
-#endif
-
-#ifndef GL_INGR_color_clamp
-#define GL_RED_MIN_CLAMP_INGR 0x8560
-#define GL_GREEN_MIN_CLAMP_INGR 0x8561
-#define GL_BLUE_MIN_CLAMP_INGR 0x8562
-#define GL_ALPHA_MIN_CLAMP_INGR 0x8563
-#define GL_RED_MAX_CLAMP_INGR 0x8564
-#define GL_GREEN_MAX_CLAMP_INGR 0x8565
-#define GL_BLUE_MAX_CLAMP_INGR 0x8566
-#define GL_ALPHA_MAX_CLAMP_INGR 0x8567
-#endif
-
-#ifndef GL_INGR_interlace_read
-#define GL_INTERLACE_READ_INGR 0x8568
-#endif
-
-#ifndef GL_EXT_stencil_wrap
-#define GL_INCR_WRAP_EXT 0x8507
-#define GL_DECR_WRAP_EXT 0x8508
-#endif
-
-#ifndef GL_EXT_422_pixels
-#define GL_422_EXT 0x80CC
-#define GL_422_REV_EXT 0x80CD
-#define GL_422_AVERAGE_EXT 0x80CE
-#define GL_422_REV_AVERAGE_EXT 0x80CF
-#endif
-
-#ifndef GL_NV_texgen_reflection
-#define GL_NORMAL_MAP_NV 0x8511
-#define GL_REFLECTION_MAP_NV 0x8512
-#endif
-
-#ifndef GL_EXT_texture_cube_map
-#define GL_NORMAL_MAP_EXT 0x8511
-#define GL_REFLECTION_MAP_EXT 0x8512
-#define GL_TEXTURE_CUBE_MAP_EXT 0x8513
-#define GL_TEXTURE_BINDING_CUBE_MAP_EXT 0x8514
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT 0x8515
-#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT 0x8516
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT 0x8517
-#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT 0x8518
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT 0x8519
-#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT 0x851A
-#define GL_PROXY_TEXTURE_CUBE_MAP_EXT 0x851B
-#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_EXT 0x851C
-#endif
-
-#ifndef GL_SUN_convolution_border_modes
-#define GL_WRAP_BORDER_SUN 0x81D4
-#endif
-
-#ifndef GL_EXT_texture_env_add
-#endif
-
-#ifndef GL_EXT_texture_lod_bias
-#define GL_MAX_TEXTURE_LOD_BIAS_EXT 0x84FD
-#define GL_TEXTURE_FILTER_CONTROL_EXT 0x8500
-#define GL_TEXTURE_LOD_BIAS_EXT 0x8501
-#endif
-
-#ifndef GL_EXT_texture_filter_anisotropic
-#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE
-#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
-#endif
-
-#ifndef GL_EXT_vertex_weighting
-#define GL_MODELVIEW0_STACK_DEPTH_EXT GL_MODELVIEW_STACK_DEPTH
-#define GL_MODELVIEW1_STACK_DEPTH_EXT 0x8502
-#define GL_MODELVIEW0_MATRIX_EXT GL_MODELVIEW_MATRIX
-#define GL_MODELVIEW1_MATRIX_EXT 0x8506
-#define GL_VERTEX_WEIGHTING_EXT 0x8509
-#define GL_MODELVIEW0_EXT GL_MODELVIEW
-#define GL_MODELVIEW1_EXT 0x850A
-#define GL_CURRENT_VERTEX_WEIGHT_EXT 0x850B
-#define GL_VERTEX_WEIGHT_ARRAY_EXT 0x850C
-#define GL_VERTEX_WEIGHT_ARRAY_SIZE_EXT 0x850D
-#define GL_VERTEX_WEIGHT_ARRAY_TYPE_EXT 0x850E
-#define GL_VERTEX_WEIGHT_ARRAY_STRIDE_EXT 0x850F
-#define GL_VERTEX_WEIGHT_ARRAY_POINTER_EXT 0x8510
-#endif
-
-#ifndef GL_NV_light_max_exponent
-#define GL_MAX_SHININESS_NV 0x8504
-#define GL_MAX_SPOT_EXPONENT_NV 0x8505
-#endif
-
-#ifndef GL_NV_vertex_array_range
-#define GL_VERTEX_ARRAY_RANGE_NV 0x851D
-#define GL_VERTEX_ARRAY_RANGE_LENGTH_NV 0x851E
-#define GL_VERTEX_ARRAY_RANGE_VALID_NV 0x851F
-#define GL_MAX_VERTEX_ARRAY_RANGE_ELEMENT_NV 0x8520
-#define GL_VERTEX_ARRAY_RANGE_POINTER_NV 0x8521
-#endif
-
-#ifndef GL_NV_register_combiners
-#define GL_REGISTER_COMBINERS_NV 0x8522
-#define GL_VARIABLE_A_NV 0x8523
-#define GL_VARIABLE_B_NV 0x8524
-#define GL_VARIABLE_C_NV 0x8525
-#define GL_VARIABLE_D_NV 0x8526
-#define GL_VARIABLE_E_NV 0x8527
-#define GL_VARIABLE_F_NV 0x8528
-#define GL_VARIABLE_G_NV 0x8529
-#define GL_CONSTANT_COLOR0_NV 0x852A
-#define GL_CONSTANT_COLOR1_NV 0x852B
-#define GL_PRIMARY_COLOR_NV 0x852C
-#define GL_SECONDARY_COLOR_NV 0x852D
-#define GL_SPARE0_NV 0x852E
-#define GL_SPARE1_NV 0x852F
-#define GL_DISCARD_NV 0x8530
-#define GL_E_TIMES_F_NV 0x8531
-#define GL_SPARE0_PLUS_SECONDARY_COLOR_NV 0x8532
-#define GL_UNSIGNED_IDENTITY_NV 0x8536
-#define GL_UNSIGNED_INVERT_NV 0x8537
-#define GL_EXPAND_NORMAL_NV 0x8538
-#define GL_EXPAND_NEGATE_NV 0x8539
-#define GL_HALF_BIAS_NORMAL_NV 0x853A
-#define GL_HALF_BIAS_NEGATE_NV 0x853B
-#define GL_SIGNED_IDENTITY_NV 0x853C
-#define GL_SIGNED_NEGATE_NV 0x853D
-#define GL_SCALE_BY_TWO_NV 0x853E
-#define GL_SCALE_BY_FOUR_NV 0x853F
-#define GL_SCALE_BY_ONE_HALF_NV 0x8540
-#define GL_BIAS_BY_NEGATIVE_ONE_HALF_NV 0x8541
-#define GL_COMBINER_INPUT_NV 0x8542
-#define GL_COMBINER_MAPPING_NV 0x8543
-#define GL_COMBINER_COMPONENT_USAGE_NV 0x8544
-#define GL_COMBINER_AB_DOT_PRODUCT_NV 0x8545
-#define GL_COMBINER_CD_DOT_PRODUCT_NV 0x8546
-#define GL_COMBINER_MUX_SUM_NV 0x8547
-#define GL_COMBINER_SCALE_NV 0x8548
-#define GL_COMBINER_BIAS_NV 0x8549
-#define GL_COMBINER_AB_OUTPUT_NV 0x854A
-#define GL_COMBINER_CD_OUTPUT_NV 0x854B
-#define GL_COMBINER_SUM_OUTPUT_NV 0x854C
-#define GL_MAX_GENERAL_COMBINERS_NV 0x854D
-#define GL_NUM_GENERAL_COMBINERS_NV 0x854E
-#define GL_COLOR_SUM_CLAMP_NV 0x854F
-#define GL_COMBINER0_NV 0x8550
-#define GL_COMBINER1_NV 0x8551
-#define GL_COMBINER2_NV 0x8552
-#define GL_COMBINER3_NV 0x8553
-#define GL_COMBINER4_NV 0x8554
-#define GL_COMBINER5_NV 0x8555
-#define GL_COMBINER6_NV 0x8556
-#define GL_COMBINER7_NV 0x8557
-/* reuse GL_TEXTURE0_ARB */
-/* reuse GL_TEXTURE1_ARB */
-/* reuse GL_ZERO */
-/* reuse GL_NONE */
-/* reuse GL_FOG */
-#endif
-
-#ifndef GL_NV_fog_distance
-#define GL_FOG_DISTANCE_MODE_NV 0x855A
-#define GL_EYE_RADIAL_NV 0x855B
-#define GL_EYE_PLANE_ABSOLUTE_NV 0x855C
-/* reuse GL_EYE_PLANE */
-#endif
-
-#ifndef GL_NV_texgen_emboss
-#define GL_EMBOSS_LIGHT_NV 0x855D
-#define GL_EMBOSS_CONSTANT_NV 0x855E
-#define GL_EMBOSS_MAP_NV 0x855F
-#endif
-
-#ifndef GL_NV_blend_square
-#endif
-
-#ifndef GL_NV_texture_env_combine4
-#define GL_COMBINE4_NV 0x8503
-#define GL_SOURCE3_RGB_NV 0x8583
-#define GL_SOURCE3_ALPHA_NV 0x858B
-#define GL_OPERAND3_RGB_NV 0x8593
-#define GL_OPERAND3_ALPHA_NV 0x859B
-#endif
-
-#ifndef GL_MESA_resize_buffers
-#endif
-
-#ifndef GL_MESA_window_pos
-#endif
-
-#ifndef GL_EXT_texture_compression_s3tc
-#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0
-#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
-#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2
-#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3
-#endif
-
-#ifndef GL_IBM_cull_vertex
-#define GL_CULL_VERTEX_IBM 103050
-#endif
-
-#ifndef GL_IBM_multimode_draw_arrays
-#endif
-
-#ifndef GL_IBM_vertex_array_lists
-#define GL_VERTEX_ARRAY_LIST_IBM 103070
-#define GL_NORMAL_ARRAY_LIST_IBM 103071
-#define GL_COLOR_ARRAY_LIST_IBM 103072
-#define GL_INDEX_ARRAY_LIST_IBM 103073
-#define GL_TEXTURE_COORD_ARRAY_LIST_IBM 103074
-#define GL_EDGE_FLAG_ARRAY_LIST_IBM 103075
-#define GL_FOG_COORDINATE_ARRAY_LIST_IBM 103076
-#define GL_SECONDARY_COLOR_ARRAY_LIST_IBM 103077
-#define GL_VERTEX_ARRAY_LIST_STRIDE_IBM 103080
-#define GL_NORMAL_ARRAY_LIST_STRIDE_IBM 103081
-#define GL_COLOR_ARRAY_LIST_STRIDE_IBM 103082
-#define GL_INDEX_ARRAY_LIST_STRIDE_IBM 103083
-#define GL_TEXTURE_COORD_ARRAY_LIST_STRIDE_IBM 103084
-#define GL_EDGE_FLAG_ARRAY_LIST_STRIDE_IBM 103085
-#define GL_FOG_COORDINATE_ARRAY_LIST_STRIDE_IBM 103086
-#define GL_SECONDARY_COLOR_ARRAY_LIST_STRIDE_IBM 103087
-#endif
-
-#ifndef GL_SGIX_subsample
-#define GL_PACK_SUBSAMPLE_RATE_SGIX 0x85A0
-#define GL_UNPACK_SUBSAMPLE_RATE_SGIX 0x85A1
-#define GL_PIXEL_SUBSAMPLE_4444_SGIX 0x85A2
-#define GL_PIXEL_SUBSAMPLE_2424_SGIX 0x85A3
-#define GL_PIXEL_SUBSAMPLE_4242_SGIX 0x85A4
-#endif
-
-#ifndef GL_SGIX_ycrcb_subsample
-#endif
-
-#ifndef GL_SGIX_ycrcba
-#define GL_YCRCB_SGIX 0x8318
-#define GL_YCRCBA_SGIX 0x8319
-#endif
-
-#ifndef GL_SGI_depth_pass_instrument
-#define GL_DEPTH_PASS_INSTRUMENT_SGIX 0x8310
-#define GL_DEPTH_PASS_INSTRUMENT_COUNTERS_SGIX 0x8311
-#define GL_DEPTH_PASS_INSTRUMENT_MAX_SGIX 0x8312
-#endif
-
-#ifndef GL_3DFX_texture_compression_FXT1
-#define GL_COMPRESSED_RGB_FXT1_3DFX 0x86B0
-#define GL_COMPRESSED_RGBA_FXT1_3DFX 0x86B1
-#endif
-
-#ifndef GL_3DFX_multisample
-#define GL_MULTISAMPLE_3DFX 0x86B2
-#define GL_SAMPLE_BUFFERS_3DFX 0x86B3
-#define GL_SAMPLES_3DFX 0x86B4
-#define GL_MULTISAMPLE_BIT_3DFX 0x20000000
-#endif
-
-#ifndef GL_3DFX_tbuffer
-#endif
-
-#ifndef GL_EXT_multisample
-#define GL_MULTISAMPLE_EXT 0x809D
-#define GL_SAMPLE_ALPHA_TO_MASK_EXT 0x809E
-#define GL_SAMPLE_ALPHA_TO_ONE_EXT 0x809F
-#define GL_SAMPLE_MASK_EXT 0x80A0
-#define GL_1PASS_EXT 0x80A1
-#define GL_2PASS_0_EXT 0x80A2
-#define GL_2PASS_1_EXT 0x80A3
-#define GL_4PASS_0_EXT 0x80A4
-#define GL_4PASS_1_EXT 0x80A5
-#define GL_4PASS_2_EXT 0x80A6
-#define GL_4PASS_3_EXT 0x80A7
-#define GL_SAMPLE_BUFFERS_EXT 0x80A8
-#define GL_SAMPLES_EXT 0x80A9
-#define GL_SAMPLE_MASK_VALUE_EXT 0x80AA
-#define GL_SAMPLE_MASK_INVERT_EXT 0x80AB
-#define GL_SAMPLE_PATTERN_EXT 0x80AC
-#define GL_MULTISAMPLE_BIT_EXT 0x20000000
-#endif
-
-#ifndef GL_SGIX_vertex_preclip
-#define GL_VERTEX_PRECLIP_SGIX 0x83EE
-#define GL_VERTEX_PRECLIP_HINT_SGIX 0x83EF
-#endif
-
-#ifndef GL_SGIX_convolution_accuracy
-#define GL_CONVOLUTION_HINT_SGIX 0x8316
-#endif
-
-#ifndef GL_SGIX_resample
-#define GL_PACK_RESAMPLE_SGIX 0x842C
-#define GL_UNPACK_RESAMPLE_SGIX 0x842D
-#define GL_RESAMPLE_REPLICATE_SGIX 0x842E
-#define GL_RESAMPLE_ZERO_FILL_SGIX 0x842F
-#define GL_RESAMPLE_DECIMATE_SGIX 0x8430
-#endif
-
-#ifndef GL_SGIS_point_line_texgen
-#define GL_EYE_DISTANCE_TO_POINT_SGIS 0x81F0
-#define GL_OBJECT_DISTANCE_TO_POINT_SGIS 0x81F1
-#define GL_EYE_DISTANCE_TO_LINE_SGIS 0x81F2
-#define GL_OBJECT_DISTANCE_TO_LINE_SGIS 0x81F3
-#define GL_EYE_POINT_SGIS 0x81F4
-#define GL_OBJECT_POINT_SGIS 0x81F5
-#define GL_EYE_LINE_SGIS 0x81F6
-#define GL_OBJECT_LINE_SGIS 0x81F7
-#endif
-
-#ifndef GL_SGIS_texture_color_mask
-#define GL_TEXTURE_COLOR_WRITEMASK_SGIS 0x81EF
-#endif
-
-#ifndef GL_EXT_texture_env_dot3
-#define GL_DOT3_RGB_EXT 0x8740
-#define GL_DOT3_RGBA_EXT 0x8741
-#endif
-
-#ifndef GL_ATI_texture_mirror_once
-#define GL_MIRROR_CLAMP_ATI 0x8742
-#define GL_MIRROR_CLAMP_TO_EDGE_ATI 0x8743
-#endif
-
-#ifndef GL_NV_fence
-#define GL_ALL_COMPLETED_NV 0x84F2
-#define GL_FENCE_STATUS_NV 0x84F3
-#define GL_FENCE_CONDITION_NV 0x84F4
-#endif
-
-#ifndef GL_IBM_texture_mirrored_repeat
-#define GL_MIRRORED_REPEAT_IBM 0x8370
-#endif
-
-#ifndef GL_NV_evaluators
-#define GL_EVAL_2D_NV 0x86C0
-#define GL_EVAL_TRIANGULAR_2D_NV 0x86C1
-#define GL_MAP_TESSELLATION_NV 0x86C2
-#define GL_MAP_ATTRIB_U_ORDER_NV 0x86C3
-#define GL_MAP_ATTRIB_V_ORDER_NV 0x86C4
-#define GL_EVAL_FRACTIONAL_TESSELLATION_NV 0x86C5
-#define GL_EVAL_VERTEX_ATTRIB0_NV 0x86C6
-#define GL_EVAL_VERTEX_ATTRIB1_NV 0x86C7
-#define GL_EVAL_VERTEX_ATTRIB2_NV 0x86C8
-#define GL_EVAL_VERTEX_ATTRIB3_NV 0x86C9
-#define GL_EVAL_VERTEX_ATTRIB4_NV 0x86CA
-#define GL_EVAL_VERTEX_ATTRIB5_NV 0x86CB
-#define GL_EVAL_VERTEX_ATTRIB6_NV 0x86CC
-#define GL_EVAL_VERTEX_ATTRIB7_NV 0x86CD
-#define GL_EVAL_VERTEX_ATTRIB8_NV 0x86CE
-#define GL_EVAL_VERTEX_ATTRIB9_NV 0x86CF
-#define GL_EVAL_VERTEX_ATTRIB10_NV 0x86D0
-#define GL_EVAL_VERTEX_ATTRIB11_NV 0x86D1
-#define GL_EVAL_VERTEX_ATTRIB12_NV 0x86D2
-#define GL_EVAL_VERTEX_ATTRIB13_NV 0x86D3
-#define GL_EVAL_VERTEX_ATTRIB14_NV 0x86D4
-#define GL_EVAL_VERTEX_ATTRIB15_NV 0x86D5
-#define GL_MAX_MAP_TESSELLATION_NV 0x86D6
-#define GL_MAX_RATIONAL_EVAL_ORDER_NV 0x86D7
-#endif
-
-#ifndef GL_NV_packed_depth_stencil
-#define GL_DEPTH_STENCIL_NV 0x84F9
-#define GL_UNSIGNED_INT_24_8_NV 0x84FA
-#endif
-
-#ifndef GL_NV_register_combiners2
-#define GL_PER_STAGE_CONSTANTS_NV 0x8535
-#endif
-
-#ifndef GL_NV_texture_compression_vtc
-#endif
-
-#ifndef GL_NV_texture_rectangle
-#define GL_TEXTURE_RECTANGLE_NV 0x84F5
-#define GL_TEXTURE_BINDING_RECTANGLE_NV 0x84F6
-#define GL_PROXY_TEXTURE_RECTANGLE_NV 0x84F7
-#define GL_MAX_RECTANGLE_TEXTURE_SIZE_NV 0x84F8
-#endif
-
-#ifndef GL_NV_texture_shader
-#define GL_OFFSET_TEXTURE_RECTANGLE_NV 0x864C
-#define GL_OFFSET_TEXTURE_RECTANGLE_SCALE_NV 0x864D
-#define GL_DOT_PRODUCT_TEXTURE_RECTANGLE_NV 0x864E
-#define GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV 0x86D9
-#define GL_UNSIGNED_INT_S8_S8_8_8_NV 0x86DA
-#define GL_UNSIGNED_INT_8_8_S8_S8_REV_NV 0x86DB
-#define GL_DSDT_MAG_INTENSITY_NV 0x86DC
-#define GL_SHADER_CONSISTENT_NV 0x86DD
-#define GL_TEXTURE_SHADER_NV 0x86DE
-#define GL_SHADER_OPERATION_NV 0x86DF
-#define GL_CULL_MODES_NV 0x86E0
-#define GL_OFFSET_TEXTURE_MATRIX_NV 0x86E1
-#define GL_OFFSET_TEXTURE_SCALE_NV 0x86E2
-#define GL_OFFSET_TEXTURE_BIAS_NV 0x86E3
-#define GL_OFFSET_TEXTURE_2D_MATRIX_NV GL_OFFSET_TEXTURE_MATRIX_NV
-#define GL_OFFSET_TEXTURE_2D_SCALE_NV GL_OFFSET_TEXTURE_SCALE_NV
-#define GL_OFFSET_TEXTURE_2D_BIAS_NV GL_OFFSET_TEXTURE_BIAS_NV
-#define GL_PREVIOUS_TEXTURE_INPUT_NV 0x86E4
-#define GL_CONST_EYE_NV 0x86E5
-#define GL_PASS_THROUGH_NV 0x86E6
-#define GL_CULL_FRAGMENT_NV 0x86E7
-#define GL_OFFSET_TEXTURE_2D_NV 0x86E8
-#define GL_DEPENDENT_AR_TEXTURE_2D_NV 0x86E9
-#define GL_DEPENDENT_GB_TEXTURE_2D_NV 0x86EA
-#define GL_DOT_PRODUCT_NV 0x86EC
-#define GL_DOT_PRODUCT_DEPTH_REPLACE_NV 0x86ED
-#define GL_DOT_PRODUCT_TEXTURE_2D_NV 0x86EE
-#define GL_DOT_PRODUCT_TEXTURE_CUBE_MAP_NV 0x86F0
-#define GL_DOT_PRODUCT_DIFFUSE_CUBE_MAP_NV 0x86F1
-#define GL_DOT_PRODUCT_REFLECT_CUBE_MAP_NV 0x86F2
-#define GL_DOT_PRODUCT_CONST_EYE_REFLECT_CUBE_MAP_NV 0x86F3
-#define GL_HILO_NV 0x86F4
-#define GL_DSDT_NV 0x86F5
-#define GL_DSDT_MAG_NV 0x86F6
-#define GL_DSDT_MAG_VIB_NV 0x86F7
-#define GL_HILO16_NV 0x86F8
-#define GL_SIGNED_HILO_NV 0x86F9
-#define GL_SIGNED_HILO16_NV 0x86FA
-#define GL_SIGNED_RGBA_NV 0x86FB
-#define GL_SIGNED_RGBA8_NV 0x86FC
-#define GL_SIGNED_RGB_NV 0x86FE
-#define GL_SIGNED_RGB8_NV 0x86FF
-#define GL_SIGNED_LUMINANCE_NV 0x8701
-#define GL_SIGNED_LUMINANCE8_NV 0x8702
-#define GL_SIGNED_LUMINANCE_ALPHA_NV 0x8703
-#define GL_SIGNED_LUMINANCE8_ALPHA8_NV 0x8704
-#define GL_SIGNED_ALPHA_NV 0x8705
-#define GL_SIGNED_ALPHA8_NV 0x8706
-#define GL_SIGNED_INTENSITY_NV 0x8707
-#define GL_SIGNED_INTENSITY8_NV 0x8708
-#define GL_DSDT8_NV 0x8709
-#define GL_DSDT8_MAG8_NV 0x870A
-#define GL_DSDT8_MAG8_INTENSITY8_NV 0x870B
-#define GL_SIGNED_RGB_UNSIGNED_ALPHA_NV 0x870C
-#define GL_SIGNED_RGB8_UNSIGNED_ALPHA8_NV 0x870D
-#define GL_HI_SCALE_NV 0x870E
-#define GL_LO_SCALE_NV 0x870F
-#define GL_DS_SCALE_NV 0x8710
-#define GL_DT_SCALE_NV 0x8711
-#define GL_MAGNITUDE_SCALE_NV 0x8712
-#define GL_VIBRANCE_SCALE_NV 0x8713
-#define GL_HI_BIAS_NV 0x8714
-#define GL_LO_BIAS_NV 0x8715
-#define GL_DS_BIAS_NV 0x8716
-#define GL_DT_BIAS_NV 0x8717
-#define GL_MAGNITUDE_BIAS_NV 0x8718
-#define GL_VIBRANCE_BIAS_NV 0x8719
-#define GL_TEXTURE_BORDER_VALUES_NV 0x871A
-#define GL_TEXTURE_HI_SIZE_NV 0x871B
-#define GL_TEXTURE_LO_SIZE_NV 0x871C
-#define GL_TEXTURE_DS_SIZE_NV 0x871D
-#define GL_TEXTURE_DT_SIZE_NV 0x871E
-#define GL_TEXTURE_MAG_SIZE_NV 0x871F
-#endif
-
-#ifndef GL_NV_texture_shader2
-#define GL_DOT_PRODUCT_TEXTURE_3D_NV 0x86EF
-#endif
-
-#ifndef GL_NV_vertex_array_range2
-#define GL_VERTEX_ARRAY_RANGE_WITHOUT_FLUSH_NV 0x8533
-#endif
-
-#ifndef GL_NV_vertex_program
-#define GL_VERTEX_PROGRAM_NV 0x8620
-#define GL_VERTEX_STATE_PROGRAM_NV 0x8621
-#define GL_ATTRIB_ARRAY_SIZE_NV 0x8623
-#define GL_ATTRIB_ARRAY_STRIDE_NV 0x8624
-#define GL_ATTRIB_ARRAY_TYPE_NV 0x8625
-#define GL_CURRENT_ATTRIB_NV 0x8626
-#define GL_PROGRAM_LENGTH_NV 0x8627
-#define GL_PROGRAM_STRING_NV 0x8628
-#define GL_MODELVIEW_PROJECTION_NV 0x8629
-#define GL_IDENTITY_NV 0x862A
-#define GL_INVERSE_NV 0x862B
-#define GL_TRANSPOSE_NV 0x862C
-#define GL_INVERSE_TRANSPOSE_NV 0x862D
-#define GL_MAX_TRACK_MATRIX_STACK_DEPTH_NV 0x862E
-#define GL_MAX_TRACK_MATRICES_NV 0x862F
-#define GL_MATRIX0_NV 0x8630
-#define GL_MATRIX1_NV 0x8631
-#define GL_MATRIX2_NV 0x8632
-#define GL_MATRIX3_NV 0x8633
-#define GL_MATRIX4_NV 0x8634
-#define GL_MATRIX5_NV 0x8635
-#define GL_MATRIX6_NV 0x8636
-#define GL_MATRIX7_NV 0x8637
-#define GL_CURRENT_MATRIX_STACK_DEPTH_NV 0x8640
-#define GL_CURRENT_MATRIX_NV 0x8641
-#define GL_VERTEX_PROGRAM_POINT_SIZE_NV 0x8642
-#define GL_VERTEX_PROGRAM_TWO_SIDE_NV 0x8643
-#define GL_PROGRAM_PARAMETER_NV 0x8644
-#define GL_ATTRIB_ARRAY_POINTER_NV 0x8645
-#define GL_PROGRAM_TARGET_NV 0x8646
-#define GL_PROGRAM_RESIDENT_NV 0x8647
-#define GL_TRACK_MATRIX_NV 0x8648
-#define GL_TRACK_MATRIX_TRANSFORM_NV 0x8649
-#define GL_VERTEX_PROGRAM_BINDING_NV 0x864A
-#define GL_PROGRAM_ERROR_POSITION_NV 0x864B
-#define GL_VERTEX_ATTRIB_ARRAY0_NV 0x8650
-#define GL_VERTEX_ATTRIB_ARRAY1_NV 0x8651
-#define GL_VERTEX_ATTRIB_ARRAY2_NV 0x8652
-#define GL_VERTEX_ATTRIB_ARRAY3_NV 0x8653
-#define GL_VERTEX_ATTRIB_ARRAY4_NV 0x8654
-#define GL_VERTEX_ATTRIB_ARRAY5_NV 0x8655
-#define GL_VERTEX_ATTRIB_ARRAY6_NV 0x8656
-#define GL_VERTEX_ATTRIB_ARRAY7_NV 0x8657
-#define GL_VERTEX_ATTRIB_ARRAY8_NV 0x8658
-#define GL_VERTEX_ATTRIB_ARRAY9_NV 0x8659
-#define GL_VERTEX_ATTRIB_ARRAY10_NV 0x865A
-#define GL_VERTEX_ATTRIB_ARRAY11_NV 0x865B
-#define GL_VERTEX_ATTRIB_ARRAY12_NV 0x865C
-#define GL_VERTEX_ATTRIB_ARRAY13_NV 0x865D
-#define GL_VERTEX_ATTRIB_ARRAY14_NV 0x865E
-#define GL_VERTEX_ATTRIB_ARRAY15_NV 0x865F
-#define GL_MAP1_VERTEX_ATTRIB0_4_NV 0x8660
-#define GL_MAP1_VERTEX_ATTRIB1_4_NV 0x8661
-#define GL_MAP1_VERTEX_ATTRIB2_4_NV 0x8662
-#define GL_MAP1_VERTEX_ATTRIB3_4_NV 0x8663
-#define GL_MAP1_VERTEX_ATTRIB4_4_NV 0x8664
-#define GL_MAP1_VERTEX_ATTRIB5_4_NV 0x8665
-#define GL_MAP1_VERTEX_ATTRIB6_4_NV 0x8666
-#define GL_MAP1_VERTEX_ATTRIB7_4_NV 0x8667
-#define GL_MAP1_VERTEX_ATTRIB8_4_NV 0x8668
-#define GL_MAP1_VERTEX_ATTRIB9_4_NV 0x8669
-#define GL_MAP1_VERTEX_ATTRIB10_4_NV 0x866A
-#define GL_MAP1_VERTEX_ATTRIB11_4_NV 0x866B
-#define GL_MAP1_VERTEX_ATTRIB12_4_NV 0x866C
-#define GL_MAP1_VERTEX_ATTRIB13_4_NV 0x866D
-#define GL_MAP1_VERTEX_ATTRIB14_4_NV 0x866E
-#define GL_MAP1_VERTEX_ATTRIB15_4_NV 0x866F
-#define GL_MAP2_VERTEX_ATTRIB0_4_NV 0x8670
-#define GL_MAP2_VERTEX_ATTRIB1_4_NV 0x8671
-#define GL_MAP2_VERTEX_ATTRIB2_4_NV 0x8672
-#define GL_MAP2_VERTEX_ATTRIB3_4_NV 0x8673
-#define GL_MAP2_VERTEX_ATTRIB4_4_NV 0x8674
-#define GL_MAP2_VERTEX_ATTRIB5_4_NV 0x8675
-#define GL_MAP2_VERTEX_ATTRIB6_4_NV 0x8676
-#define GL_MAP2_VERTEX_ATTRIB7_4_NV 0x8677
-#define GL_MAP2_VERTEX_ATTRIB8_4_NV 0x8678
-#define GL_MAP2_VERTEX_ATTRIB9_4_NV 0x8679
-#define GL_MAP2_VERTEX_ATTRIB10_4_NV 0x867A
-#define GL_MAP2_VERTEX_ATTRIB11_4_NV 0x867B
-#define GL_MAP2_VERTEX_ATTRIB12_4_NV 0x867C
-#define GL_MAP2_VERTEX_ATTRIB13_4_NV 0x867D
-#define GL_MAP2_VERTEX_ATTRIB14_4_NV 0x867E
-#define GL_MAP2_VERTEX_ATTRIB15_4_NV 0x867F
-#endif
-
-#ifndef GL_SGIX_texture_coordinate_clamp
-#define GL_TEXTURE_MAX_CLAMP_S_SGIX 0x8369
-#define GL_TEXTURE_MAX_CLAMP_T_SGIX 0x836A
-#define GL_TEXTURE_MAX_CLAMP_R_SGIX 0x836B
-#endif
-
-#ifndef GL_SGIX_scalebias_hint
-#define GL_SCALEBIAS_HINT_SGIX 0x8322
-#endif
-
-#ifndef GL_OML_interlace
-#define GL_INTERLACE_OML 0x8980
-#define GL_INTERLACE_READ_OML 0x8981
-#endif
-
-#ifndef GL_OML_subsample
-#define GL_FORMAT_SUBSAMPLE_24_24_OML 0x8982
-#define GL_FORMAT_SUBSAMPLE_244_244_OML 0x8983
-#endif
-
-#ifndef GL_OML_resample
-#define GL_PACK_RESAMPLE_OML 0x8984
-#define GL_UNPACK_RESAMPLE_OML 0x8985
-#define GL_RESAMPLE_REPLICATE_OML 0x8986
-#define GL_RESAMPLE_ZERO_FILL_OML 0x8987
-#define GL_RESAMPLE_AVERAGE_OML 0x8988
-#define GL_RESAMPLE_DECIMATE_OML 0x8989
-#endif
-
-#ifndef GL_NV_copy_depth_to_color
-#define GL_DEPTH_STENCIL_TO_RGBA_NV 0x886E
-#define GL_DEPTH_STENCIL_TO_BGRA_NV 0x886F
-#endif
-
-#ifndef GL_ATI_envmap_bumpmap
-#define GL_BUMP_ROT_MATRIX_ATI 0x8775
-#define GL_BUMP_ROT_MATRIX_SIZE_ATI 0x8776
-#define GL_BUMP_NUM_TEX_UNITS_ATI 0x8777
-#define GL_BUMP_TEX_UNITS_ATI 0x8778
-#define GL_DUDV_ATI 0x8779
-#define GL_DU8DV8_ATI 0x877A
-#define GL_BUMP_ENVMAP_ATI 0x877B
-#define GL_BUMP_TARGET_ATI 0x877C
-#endif
-
-#ifndef GL_ATI_fragment_shader
-#define GL_FRAGMENT_SHADER_ATI 0x8920
-#define GL_REG_0_ATI 0x8921
-#define GL_REG_1_ATI 0x8922
-#define GL_REG_2_ATI 0x8923
-#define GL_REG_3_ATI 0x8924
-#define GL_REG_4_ATI 0x8925
-#define GL_REG_5_ATI 0x8926
-#define GL_REG_6_ATI 0x8927
-#define GL_REG_7_ATI 0x8928
-#define GL_REG_8_ATI 0x8929
-#define GL_REG_9_ATI 0x892A
-#define GL_REG_10_ATI 0x892B
-#define GL_REG_11_ATI 0x892C
-#define GL_REG_12_ATI 0x892D
-#define GL_REG_13_ATI 0x892E
-#define GL_REG_14_ATI 0x892F
-#define GL_REG_15_ATI 0x8930
-#define GL_REG_16_ATI 0x8931
-#define GL_REG_17_ATI 0x8932
-#define GL_REG_18_ATI 0x8933
-#define GL_REG_19_ATI 0x8934
-#define GL_REG_20_ATI 0x8935
-#define GL_REG_21_ATI 0x8936
-#define GL_REG_22_ATI 0x8937
-#define GL_REG_23_ATI 0x8938
-#define GL_REG_24_ATI 0x8939
-#define GL_REG_25_ATI 0x893A
-#define GL_REG_26_ATI 0x893B
-#define GL_REG_27_ATI 0x893C
-#define GL_REG_28_ATI 0x893D
-#define GL_REG_29_ATI 0x893E
-#define GL_REG_30_ATI 0x893F
-#define GL_REG_31_ATI 0x8940
-#define GL_CON_0_ATI 0x8941
-#define GL_CON_1_ATI 0x8942
-#define GL_CON_2_ATI 0x8943
-#define GL_CON_3_ATI 0x8944
-#define GL_CON_4_ATI 0x8945
-#define GL_CON_5_ATI 0x8946
-#define GL_CON_6_ATI 0x8947
-#define GL_CON_7_ATI 0x8948
-#define GL_CON_8_ATI 0x8949
-#define GL_CON_9_ATI 0x894A
-#define GL_CON_10_ATI 0x894B
-#define GL_CON_11_ATI 0x894C
-#define GL_CON_12_ATI 0x894D
-#define GL_CON_13_ATI 0x894E
-#define GL_CON_14_ATI 0x894F
-#define GL_CON_15_ATI 0x8950
-#define GL_CON_16_ATI 0x8951
-#define GL_CON_17_ATI 0x8952
-#define GL_CON_18_ATI 0x8953
-#define GL_CON_19_ATI 0x8954
-#define GL_CON_20_ATI 0x8955
-#define GL_CON_21_ATI 0x8956
-#define GL_CON_22_ATI 0x8957
-#define GL_CON_23_ATI 0x8958
-#define GL_CON_24_ATI 0x8959
-#define GL_CON_25_ATI 0x895A
-#define GL_CON_26_ATI 0x895B
-#define GL_CON_27_ATI 0x895C
-#define GL_CON_28_ATI 0x895D
-#define GL_CON_29_ATI 0x895E
-#define GL_CON_30_ATI 0x895F
-#define GL_CON_31_ATI 0x8960
-#define GL_MOV_ATI 0x8961
-#define GL_ADD_ATI 0x8963
-#define GL_MUL_ATI 0x8964
-#define GL_SUB_ATI 0x8965
-#define GL_DOT3_ATI 0x8966
-#define GL_DOT4_ATI 0x8967
-#define GL_MAD_ATI 0x8968
-#define GL_LERP_ATI 0x8969
-#define GL_CND_ATI 0x896A
-#define GL_CND0_ATI 0x896B
-#define GL_DOT2_ADD_ATI 0x896C
-#define GL_SECONDARY_INTERPOLATOR_ATI 0x896D
-#define GL_NUM_FRAGMENT_REGISTERS_ATI 0x896E
-#define GL_NUM_FRAGMENT_CONSTANTS_ATI 0x896F
-#define GL_NUM_PASSES_ATI 0x8970
-#define GL_NUM_INSTRUCTIONS_PER_PASS_ATI 0x8971
-#define GL_NUM_INSTRUCTIONS_TOTAL_ATI 0x8972
-#define GL_NUM_INPUT_INTERPOLATOR_COMPONENTS_ATI 0x8973
-#define GL_NUM_LOOPBACK_COMPONENTS_ATI 0x8974
-#define GL_COLOR_ALPHA_PAIRING_ATI 0x8975
-#define GL_SWIZZLE_STR_ATI 0x8976
-#define GL_SWIZZLE_STQ_ATI 0x8977
-#define GL_SWIZZLE_STR_DR_ATI 0x8978
-#define GL_SWIZZLE_STQ_DQ_ATI 0x8979
-#define GL_SWIZZLE_STRQ_ATI 0x897A
-#define GL_SWIZZLE_STRQ_DQ_ATI 0x897B
-#define GL_RED_BIT_ATI 0x00000001
-#define GL_GREEN_BIT_ATI 0x00000002
-#define GL_BLUE_BIT_ATI 0x00000004
-#define GL_2X_BIT_ATI 0x00000001
-#define GL_4X_BIT_ATI 0x00000002
-#define GL_8X_BIT_ATI 0x00000004
-#define GL_HALF_BIT_ATI 0x00000008
-#define GL_QUARTER_BIT_ATI 0x00000010
-#define GL_EIGHTH_BIT_ATI 0x00000020
-#define GL_SATURATE_BIT_ATI 0x00000040
-#define GL_COMP_BIT_ATI 0x00000002
-#define GL_NEGATE_BIT_ATI 0x00000004
-#define GL_BIAS_BIT_ATI 0x00000008
-#endif
-
-#ifndef GL_ATI_pn_triangles
-#define GL_PN_TRIANGLES_ATI 0x87F0
-#define GL_MAX_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F1
-#define GL_PN_TRIANGLES_POINT_MODE_ATI 0x87F2
-#define GL_PN_TRIANGLES_NORMAL_MODE_ATI 0x87F3
-#define GL_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F4
-#define GL_PN_TRIANGLES_POINT_MODE_LINEAR_ATI 0x87F5
-#define GL_PN_TRIANGLES_POINT_MODE_CUBIC_ATI 0x87F6
-#define GL_PN_TRIANGLES_NORMAL_MODE_LINEAR_ATI 0x87F7
-#define GL_PN_TRIANGLES_NORMAL_MODE_QUADRATIC_ATI 0x87F8
-#endif
-
-#ifndef GL_ATI_vertex_array_object
-#define GL_STATIC_ATI 0x8760
-#define GL_DYNAMIC_ATI 0x8761
-#define GL_PRESERVE_ATI 0x8762
-#define GL_DISCARD_ATI 0x8763
-#define GL_OBJECT_BUFFER_SIZE_ATI 0x8764
-#define GL_OBJECT_BUFFER_USAGE_ATI 0x8765
-#define GL_ARRAY_OBJECT_BUFFER_ATI 0x8766
-#define GL_ARRAY_OBJECT_OFFSET_ATI 0x8767
-#endif
-
-#ifndef GL_EXT_vertex_shader
-#define GL_VERTEX_SHADER_EXT 0x8780
-#define GL_VERTEX_SHADER_BINDING_EXT 0x8781
-#define GL_OP_INDEX_EXT 0x8782
-#define GL_OP_NEGATE_EXT 0x8783
-#define GL_OP_DOT3_EXT 0x8784
-#define GL_OP_DOT4_EXT 0x8785
-#define GL_OP_MUL_EXT 0x8786
-#define GL_OP_ADD_EXT 0x8787
-#define GL_OP_MADD_EXT 0x8788
-#define GL_OP_FRAC_EXT 0x8789
-#define GL_OP_MAX_EXT 0x878A
-#define GL_OP_MIN_EXT 0x878B
-#define GL_OP_SET_GE_EXT 0x878C
-#define GL_OP_SET_LT_EXT 0x878D
-#define GL_OP_CLAMP_EXT 0x878E
-#define GL_OP_FLOOR_EXT 0x878F
-#define GL_OP_ROUND_EXT 0x8790
-#define GL_OP_EXP_BASE_2_EXT 0x8791
-#define GL_OP_LOG_BASE_2_EXT 0x8792
-#define GL_OP_POWER_EXT 0x8793
-#define GL_OP_RECIP_EXT 0x8794
-#define GL_OP_RECIP_SQRT_EXT 0x8795
-#define GL_OP_SUB_EXT 0x8796
-#define GL_OP_CROSS_PRODUCT_EXT 0x8797
-#define GL_OP_MULTIPLY_MATRIX_EXT 0x8798
-#define GL_OP_MOV_EXT 0x8799
-#define GL_OUTPUT_VERTEX_EXT 0x879A
-#define GL_OUTPUT_COLOR0_EXT 0x879B
-#define GL_OUTPUT_COLOR1_EXT 0x879C
-#define GL_OUTPUT_TEXTURE_COORD0_EXT 0x879D
-#define GL_OUTPUT_TEXTURE_COORD1_EXT 0x879E
-#define GL_OUTPUT_TEXTURE_COORD2_EXT 0x879F
-#define GL_OUTPUT_TEXTURE_COORD3_EXT 0x87A0
-#define GL_OUTPUT_TEXTURE_COORD4_EXT 0x87A1
-#define GL_OUTPUT_TEXTURE_COORD5_EXT 0x87A2
-#define GL_OUTPUT_TEXTURE_COORD6_EXT 0x87A3
-#define GL_OUTPUT_TEXTURE_COORD7_EXT 0x87A4
-#define GL_OUTPUT_TEXTURE_COORD8_EXT 0x87A5
-#define GL_OUTPUT_TEXTURE_COORD9_EXT 0x87A6
-#define GL_OUTPUT_TEXTURE_COORD10_EXT 0x87A7
-#define GL_OUTPUT_TEXTURE_COORD11_EXT 0x87A8
-#define GL_OUTPUT_TEXTURE_COORD12_EXT 0x87A9
-#define GL_OUTPUT_TEXTURE_COORD13_EXT 0x87AA
-#define GL_OUTPUT_TEXTURE_COORD14_EXT 0x87AB
-#define GL_OUTPUT_TEXTURE_COORD15_EXT 0x87AC
-#define GL_OUTPUT_TEXTURE_COORD16_EXT 0x87AD
-#define GL_OUTPUT_TEXTURE_COORD17_EXT 0x87AE
-#define GL_OUTPUT_TEXTURE_COORD18_EXT 0x87AF
-#define GL_OUTPUT_TEXTURE_COORD19_EXT 0x87B0
-#define GL_OUTPUT_TEXTURE_COORD20_EXT 0x87B1
-#define GL_OUTPUT_TEXTURE_COORD21_EXT 0x87B2
-#define GL_OUTPUT_TEXTURE_COORD22_EXT 0x87B3
-#define GL_OUTPUT_TEXTURE_COORD23_EXT 0x87B4
-#define GL_OUTPUT_TEXTURE_COORD24_EXT 0x87B5
-#define GL_OUTPUT_TEXTURE_COORD25_EXT 0x87B6
-#define GL_OUTPUT_TEXTURE_COORD26_EXT 0x87B7
-#define GL_OUTPUT_TEXTURE_COORD27_EXT 0x87B8
-#define GL_OUTPUT_TEXTURE_COORD28_EXT 0x87B9
-#define GL_OUTPUT_TEXTURE_COORD29_EXT 0x87BA
-#define GL_OUTPUT_TEXTURE_COORD30_EXT 0x87BB
-#define GL_OUTPUT_TEXTURE_COORD31_EXT 0x87BC
-#define GL_OUTPUT_FOG_EXT 0x87BD
-#define GL_SCALAR_EXT 0x87BE
-#define GL_VECTOR_EXT 0x87BF
-#define GL_MATRIX_EXT 0x87C0
-#define GL_VARIANT_EXT 0x87C1
-#define GL_INVARIANT_EXT 0x87C2
-#define GL_LOCAL_CONSTANT_EXT 0x87C3
-#define GL_LOCAL_EXT 0x87C4
-#define GL_MAX_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87C5
-#define GL_MAX_VERTEX_SHADER_VARIANTS_EXT 0x87C6
-#define GL_MAX_VERTEX_SHADER_INVARIANTS_EXT 0x87C7
-#define GL_MAX_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87C8
-#define GL_MAX_VERTEX_SHADER_LOCALS_EXT 0x87C9
-#define GL_MAX_OPTIMIZED_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CA
-#define GL_MAX_OPTIMIZED_VERTEX_SHADER_VARIANTS_EXT 0x87CB
-#define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87CC
-#define GL_MAX_OPTIMIZED_VERTEX_SHADER_INVARIANTS_EXT 0x87CD
-#define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCALS_EXT 0x87CE
-#define GL_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CF
-#define GL_VERTEX_SHADER_VARIANTS_EXT 0x87D0
-#define GL_VERTEX_SHADER_INVARIANTS_EXT 0x87D1
-#define GL_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87D2
-#define GL_VERTEX_SHADER_LOCALS_EXT 0x87D3
-#define GL_VERTEX_SHADER_OPTIMIZED_EXT 0x87D4
-#define GL_X_EXT 0x87D5
-#define GL_Y_EXT 0x87D6
-#define GL_Z_EXT 0x87D7
-#define GL_W_EXT 0x87D8
-#define GL_NEGATIVE_X_EXT 0x87D9
-#define GL_NEGATIVE_Y_EXT 0x87DA
-#define GL_NEGATIVE_Z_EXT 0x87DB
-#define GL_NEGATIVE_W_EXT 0x87DC
-#define GL_ZERO_EXT 0x87DD
-#define GL_ONE_EXT 0x87DE
-#define GL_NEGATIVE_ONE_EXT 0x87DF
-#define GL_NORMALIZED_RANGE_EXT 0x87E0
-#define GL_FULL_RANGE_EXT 0x87E1
-#define GL_CURRENT_VERTEX_EXT 0x87E2
-#define GL_MVP_MATRIX_EXT 0x87E3
-#define GL_VARIANT_VALUE_EXT 0x87E4
-#define GL_VARIANT_DATATYPE_EXT 0x87E5
-#define GL_VARIANT_ARRAY_STRIDE_EXT 0x87E6
-#define GL_VARIANT_ARRAY_TYPE_EXT 0x87E7
-#define GL_VARIANT_ARRAY_EXT 0x87E8
-#define GL_VARIANT_ARRAY_POINTER_EXT 0x87E9
-#define GL_INVARIANT_VALUE_EXT 0x87EA
-#define GL_INVARIANT_DATATYPE_EXT 0x87EB
-#define GL_LOCAL_CONSTANT_VALUE_EXT 0x87EC
-#define GL_LOCAL_CONSTANT_DATATYPE_EXT 0x87ED
-#endif
-
-#ifndef GL_ATI_vertex_streams
-#define GL_MAX_VERTEX_STREAMS_ATI 0x876B
-#define GL_VERTEX_STREAM0_ATI 0x876C
-#define GL_VERTEX_STREAM1_ATI 0x876D
-#define GL_VERTEX_STREAM2_ATI 0x876E
-#define GL_VERTEX_STREAM3_ATI 0x876F
-#define GL_VERTEX_STREAM4_ATI 0x8770
-#define GL_VERTEX_STREAM5_ATI 0x8771
-#define GL_VERTEX_STREAM6_ATI 0x8772
-#define GL_VERTEX_STREAM7_ATI 0x8773
-#define GL_VERTEX_SOURCE_ATI 0x8774
-#endif
-
-#ifndef GL_ATI_element_array
-#define GL_ELEMENT_ARRAY_ATI 0x8768
-#define GL_ELEMENT_ARRAY_TYPE_ATI 0x8769
-#define GL_ELEMENT_ARRAY_POINTER_ATI 0x876A
-#endif
-
-#ifndef GL_SUN_mesh_array
-#define GL_QUAD_MESH_SUN 0x8614
-#define GL_TRIANGLE_MESH_SUN 0x8615
-#endif
-
-#ifndef GL_SUN_slice_accum
-#define GL_SLICE_ACCUM_SUN 0x85CC
-#endif
-
-#ifndef GL_NV_multisample_filter_hint
-#define GL_MULTISAMPLE_FILTER_HINT_NV 0x8534
-#endif
-
-#ifndef GL_NV_depth_clamp
-#define GL_DEPTH_CLAMP_NV 0x864F
-#endif
-
-#ifndef GL_NV_occlusion_query
-#define GL_PIXEL_COUNTER_BITS_NV 0x8864
-#define GL_CURRENT_OCCLUSION_QUERY_ID_NV 0x8865
-#define GL_PIXEL_COUNT_NV 0x8866
-#define GL_PIXEL_COUNT_AVAILABLE_NV 0x8867
-#endif
-
-#ifndef GL_NV_point_sprite
-#define GL_POINT_SPRITE_NV 0x8861
-#define GL_COORD_REPLACE_NV 0x8862
-#define GL_POINT_SPRITE_R_MODE_NV 0x8863
-#endif
-
-#ifndef GL_NV_texture_shader3
-#define GL_OFFSET_PROJECTIVE_TEXTURE_2D_NV 0x8850
-#define GL_OFFSET_PROJECTIVE_TEXTURE_2D_SCALE_NV 0x8851
-#define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8852
-#define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_SCALE_NV 0x8853
-#define GL_OFFSET_HILO_TEXTURE_2D_NV 0x8854
-#define GL_OFFSET_HILO_TEXTURE_RECTANGLE_NV 0x8855
-#define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_2D_NV 0x8856
-#define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8857
-#define GL_DEPENDENT_HILO_TEXTURE_2D_NV 0x8858
-#define GL_DEPENDENT_RGB_TEXTURE_3D_NV 0x8859
-#define GL_DEPENDENT_RGB_TEXTURE_CUBE_MAP_NV 0x885A
-#define GL_DOT_PRODUCT_PASS_THROUGH_NV 0x885B
-#define GL_DOT_PRODUCT_TEXTURE_1D_NV 0x885C
-#define GL_DOT_PRODUCT_AFFINE_DEPTH_REPLACE_NV 0x885D
-#define GL_HILO8_NV 0x885E
-#define GL_SIGNED_HILO8_NV 0x885F
-#define GL_FORCE_BLUE_TO_ONE_NV 0x8860
-#endif
-
-#ifndef GL_NV_vertex_program1_1
-#endif
-
-#ifndef GL_EXT_shadow_funcs
-#endif
-
-#ifndef GL_EXT_stencil_two_side
-#define GL_STENCIL_TEST_TWO_SIDE_EXT 0x8910
-#define GL_ACTIVE_STENCIL_FACE_EXT 0x8911
-#endif
-
-#ifndef GL_ATI_text_fragment_shader
-#define GL_TEXT_FRAGMENT_SHADER_ATI 0x8200
-#endif
-
-#ifndef GL_APPLE_client_storage
-#define GL_UNPACK_CLIENT_STORAGE_APPLE 0x85B2
-#endif
-
-#ifndef GL_APPLE_element_array
-#define GL_ELEMENT_ARRAY_APPLE 0x8768
-#define GL_ELEMENT_ARRAY_TYPE_APPLE 0x8769
-#define GL_ELEMENT_ARRAY_POINTER_APPLE 0x876A
-#endif
-
-#ifndef GL_APPLE_fence
-#define GL_DRAW_PIXELS_APPLE 0x8A0A
-#define GL_FENCE_APPLE 0x8A0B
-#endif
-
-#ifndef GL_APPLE_vertex_array_object
-#define GL_VERTEX_ARRAY_BINDING_APPLE 0x85B5
-#endif
-
-#ifndef GL_APPLE_vertex_array_range
-#define GL_VERTEX_ARRAY_RANGE_APPLE 0x851D
-#define GL_VERTEX_ARRAY_RANGE_LENGTH_APPLE 0x851E
-#define GL_VERTEX_ARRAY_STORAGE_HINT_APPLE 0x851F
-#define GL_VERTEX_ARRAY_RANGE_POINTER_APPLE 0x8521
-#define GL_STORAGE_CACHED_APPLE 0x85BE
-#define GL_STORAGE_SHARED_APPLE 0x85BF
-#endif
-
-#ifndef GL_APPLE_ycbcr_422
-#define GL_YCBCR_422_APPLE 0x85B9
-#define GL_UNSIGNED_SHORT_8_8_APPLE 0x85BA
-#define GL_UNSIGNED_SHORT_8_8_REV_APPLE 0x85BB
-#endif
-
-#ifndef GL_S3_s3tc
-#define GL_RGB_S3TC 0x83A0
-#define GL_RGB4_S3TC 0x83A1
-#define GL_RGBA_S3TC 0x83A2
-#define GL_RGBA4_S3TC 0x83A3
-#endif
-
-#ifndef GL_ATI_draw_buffers
-#define GL_MAX_DRAW_BUFFERS_ATI 0x8824
-#define GL_DRAW_BUFFER0_ATI 0x8825
-#define GL_DRAW_BUFFER1_ATI 0x8826
-#define GL_DRAW_BUFFER2_ATI 0x8827
-#define GL_DRAW_BUFFER3_ATI 0x8828
-#define GL_DRAW_BUFFER4_ATI 0x8829
-#define GL_DRAW_BUFFER5_ATI 0x882A
-#define GL_DRAW_BUFFER6_ATI 0x882B
-#define GL_DRAW_BUFFER7_ATI 0x882C
-#define GL_DRAW_BUFFER8_ATI 0x882D
-#define GL_DRAW_BUFFER9_ATI 0x882E
-#define GL_DRAW_BUFFER10_ATI 0x882F
-#define GL_DRAW_BUFFER11_ATI 0x8830
-#define GL_DRAW_BUFFER12_ATI 0x8831
-#define GL_DRAW_BUFFER13_ATI 0x8832
-#define GL_DRAW_BUFFER14_ATI 0x8833
-#define GL_DRAW_BUFFER15_ATI 0x8834
-#endif
-
-#ifndef GL_ATI_pixel_format_float
-#define GL_TYPE_RGBA_FLOAT_ATI 0x8820
-#define GL_COLOR_CLEAR_UNCLAMPED_VALUE_ATI 0x8835
-#endif
-
-#ifndef GL_ATI_texture_env_combine3
-#define GL_MODULATE_ADD_ATI 0x8744
-#define GL_MODULATE_SIGNED_ADD_ATI 0x8745
-#define GL_MODULATE_SUBTRACT_ATI 0x8746
-#endif
-
-#ifndef GL_ATI_texture_float
-#define GL_RGBA_FLOAT32_ATI 0x8814
-#define GL_RGB_FLOAT32_ATI 0x8815
-#define GL_ALPHA_FLOAT32_ATI 0x8816
-#define GL_INTENSITY_FLOAT32_ATI 0x8817
-#define GL_LUMINANCE_FLOAT32_ATI 0x8818
-#define GL_LUMINANCE_ALPHA_FLOAT32_ATI 0x8819
-#define GL_RGBA_FLOAT16_ATI 0x881A
-#define GL_RGB_FLOAT16_ATI 0x881B
-#define GL_ALPHA_FLOAT16_ATI 0x881C
-#define GL_INTENSITY_FLOAT16_ATI 0x881D
-#define GL_LUMINANCE_FLOAT16_ATI 0x881E
-#define GL_LUMINANCE_ALPHA_FLOAT16_ATI 0x881F
-#endif
-
-#ifndef GL_NV_float_buffer
-#define GL_FLOAT_R_NV 0x8880
-#define GL_FLOAT_RG_NV 0x8881
-#define GL_FLOAT_RGB_NV 0x8882
-#define GL_FLOAT_RGBA_NV 0x8883
-#define GL_FLOAT_R16_NV 0x8884
-#define GL_FLOAT_R32_NV 0x8885
-#define GL_FLOAT_RG16_NV 0x8886
-#define GL_FLOAT_RG32_NV 0x8887
-#define GL_FLOAT_RGB16_NV 0x8888
-#define GL_FLOAT_RGB32_NV 0x8889
-#define GL_FLOAT_RGBA16_NV 0x888A
-#define GL_FLOAT_RGBA32_NV 0x888B
-#define GL_TEXTURE_FLOAT_COMPONENTS_NV 0x888C
-#define GL_FLOAT_CLEAR_COLOR_VALUE_NV 0x888D
-#define GL_FLOAT_RGBA_MODE_NV 0x888E
-#endif
-
-#ifndef GL_NV_fragment_program
-#define GL_MAX_FRAGMENT_PROGRAM_LOCAL_PARAMETERS_NV 0x8868
-#define GL_FRAGMENT_PROGRAM_NV 0x8870
-#define GL_MAX_TEXTURE_COORDS_NV 0x8871
-#define GL_MAX_TEXTURE_IMAGE_UNITS_NV 0x8872
-#define GL_FRAGMENT_PROGRAM_BINDING_NV 0x8873
-#define GL_PROGRAM_ERROR_STRING_NV 0x8874
-#endif
-
-#ifndef GL_NV_half_float
-#define GL_HALF_FLOAT_NV 0x140B
-#endif
-
-#ifndef GL_NV_pixel_data_range
-#define GL_WRITE_PIXEL_DATA_RANGE_NV 0x8878
-#define GL_READ_PIXEL_DATA_RANGE_NV 0x8879
-#define GL_WRITE_PIXEL_DATA_RANGE_LENGTH_NV 0x887A
-#define GL_READ_PIXEL_DATA_RANGE_LENGTH_NV 0x887B
-#define GL_WRITE_PIXEL_DATA_RANGE_POINTER_NV 0x887C
-#define GL_READ_PIXEL_DATA_RANGE_POINTER_NV 0x887D
-#endif
-
-#ifndef GL_NV_primitive_restart
-#define GL_PRIMITIVE_RESTART_NV 0x8558
-#define GL_PRIMITIVE_RESTART_INDEX_NV 0x8559
-#endif
-
-#ifndef GL_NV_texture_expand_normal
-#define GL_TEXTURE_UNSIGNED_REMAP_MODE_NV 0x888F
-#endif
-
-#ifndef GL_NV_vertex_program2
-#endif
-
-#ifndef GL_ATI_map_object_buffer
-#endif
-
-#ifndef GL_ATI_separate_stencil
-#define GL_STENCIL_BACK_FUNC_ATI 0x8800
-#define GL_STENCIL_BACK_FAIL_ATI 0x8801
-#define GL_STENCIL_BACK_PASS_DEPTH_FAIL_ATI 0x8802
-#define GL_STENCIL_BACK_PASS_DEPTH_PASS_ATI 0x8803
-#endif
-
-#ifndef GL_ATI_vertex_attrib_array_object
-#endif
-
-#ifndef GL_OES_read_format
-#define GL_IMPLEMENTATION_COLOR_READ_TYPE_OES 0x8B9A
-#define GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES 0x8B9B
-#endif
-
-#ifndef GL_EXT_depth_bounds_test
-#define GL_DEPTH_BOUNDS_TEST_EXT 0x8890
-#define GL_DEPTH_BOUNDS_EXT 0x8891
-#endif
-
-#ifndef GL_EXT_texture_mirror_clamp
-#define GL_MIRROR_CLAMP_EXT 0x8742
-#define GL_MIRROR_CLAMP_TO_EDGE_EXT 0x8743
-#define GL_MIRROR_CLAMP_TO_BORDER_EXT 0x8912
-#endif
-
-#ifndef GL_EXT_blend_equation_separate
-#define GL_BLEND_EQUATION_RGB_EXT GL_BLEND_EQUATION
-#define GL_BLEND_EQUATION_ALPHA_EXT 0x883D
-#endif
-
-#ifndef GL_MESA_pack_invert
-#define GL_PACK_INVERT_MESA 0x8758
-#endif
-
-#ifndef GL_MESA_ycbcr_texture
-#define GL_UNSIGNED_SHORT_8_8_MESA 0x85BA
-#define GL_UNSIGNED_SHORT_8_8_REV_MESA 0x85BB
-#define GL_YCBCR_MESA 0x8757
-#endif
-
-#ifndef GL_EXT_pixel_buffer_object
-#define GL_PIXEL_PACK_BUFFER_EXT 0x88EB
-#define GL_PIXEL_UNPACK_BUFFER_EXT 0x88EC
-#define GL_PIXEL_PACK_BUFFER_BINDING_EXT 0x88ED
-#define GL_PIXEL_UNPACK_BUFFER_BINDING_EXT 0x88EF
-#endif
-
-#ifndef GL_NV_fragment_program_option
-#endif
-
-#ifndef GL_NV_fragment_program2
-#define GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV 0x88F4
-#define GL_MAX_PROGRAM_CALL_DEPTH_NV 0x88F5
-#define GL_MAX_PROGRAM_IF_DEPTH_NV 0x88F6
-#define GL_MAX_PROGRAM_LOOP_DEPTH_NV 0x88F7
-#define GL_MAX_PROGRAM_LOOP_COUNT_NV 0x88F8
-#endif
-
-#ifndef GL_NV_vertex_program2_option
-/* reuse GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV */
-/* reuse GL_MAX_PROGRAM_CALL_DEPTH_NV */
-#endif
-
-#ifndef GL_NV_vertex_program3
-/* reuse GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB */
-#endif
-
-#ifndef GL_EXT_framebuffer_object
-#define GL_INVALID_FRAMEBUFFER_OPERATION_EXT 0x0506
-#define GL_MAX_RENDERBUFFER_SIZE_EXT 0x84E8
-#define GL_FRAMEBUFFER_BINDING_EXT 0x8CA6
-#define GL_RENDERBUFFER_BINDING_EXT 0x8CA7
-#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT 0x8CD0
-#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT 0x8CD1
-#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT 0x8CD2
-#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT 0x8CD3
-#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT 0x8CD4
-#define GL_FRAMEBUFFER_COMPLETE_EXT 0x8CD5
-#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT 0x8CD6
-#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT 0x8CD7
-#define GL_FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT_EXT 0x8CD8
-#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT 0x8CD9
-#define GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT 0x8CDA
-#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT 0x8CDB
-#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT 0x8CDC
-#define GL_FRAMEBUFFER_UNSUPPORTED_EXT 0x8CDD
-#define GL_MAX_COLOR_ATTACHMENTS_EXT 0x8CDF
-#define GL_COLOR_ATTACHMENT0_EXT 0x8CE0
-#define GL_COLOR_ATTACHMENT1_EXT 0x8CE1
-#define GL_COLOR_ATTACHMENT2_EXT 0x8CE2
-#define GL_COLOR_ATTACHMENT3_EXT 0x8CE3
-#define GL_COLOR_ATTACHMENT4_EXT 0x8CE4
-#define GL_COLOR_ATTACHMENT5_EXT 0x8CE5
-#define GL_COLOR_ATTACHMENT6_EXT 0x8CE6
-#define GL_COLOR_ATTACHMENT7_EXT 0x8CE7
-#define GL_COLOR_ATTACHMENT8_EXT 0x8CE8
-#define GL_COLOR_ATTACHMENT9_EXT 0x8CE9
-#define GL_COLOR_ATTACHMENT10_EXT 0x8CEA
-#define GL_COLOR_ATTACHMENT11_EXT 0x8CEB
-#define GL_COLOR_ATTACHMENT12_EXT 0x8CEC
-#define GL_COLOR_ATTACHMENT13_EXT 0x8CED
-#define GL_COLOR_ATTACHMENT14_EXT 0x8CEE
-#define GL_COLOR_ATTACHMENT15_EXT 0x8CEF
-#define GL_DEPTH_ATTACHMENT_EXT 0x8D00
-#define GL_STENCIL_ATTACHMENT_EXT 0x8D20
-#define GL_FRAMEBUFFER_EXT 0x8D40
-#define GL_RENDERBUFFER_EXT 0x8D41
-#define GL_RENDERBUFFER_WIDTH_EXT 0x8D42
-#define GL_RENDERBUFFER_HEIGHT_EXT 0x8D43
-#define GL_RENDERBUFFER_INTERNAL_FORMAT_EXT 0x8D44
-#define GL_STENCIL_INDEX1_EXT 0x8D46
-#define GL_STENCIL_INDEX4_EXT 0x8D47
-#define GL_STENCIL_INDEX8_EXT 0x8D48
-#define GL_STENCIL_INDEX16_EXT 0x8D49
-#define GL_RENDERBUFFER_RED_SIZE_EXT 0x8D50
-#define GL_RENDERBUFFER_GREEN_SIZE_EXT 0x8D51
-#define GL_RENDERBUFFER_BLUE_SIZE_EXT 0x8D52
-#define GL_RENDERBUFFER_ALPHA_SIZE_EXT 0x8D53
-#define GL_RENDERBUFFER_DEPTH_SIZE_EXT 0x8D54
-#define GL_RENDERBUFFER_STENCIL_SIZE_EXT 0x8D55
-#endif
-
-#ifndef GL_GREMEDY_string_marker
-#endif
-
-
-/*************************************************************/
-
-#include <stddef.h>
-#ifndef GL_VERSION_2_0
-/* GL type for program/shader text */
-typedef char GLchar; /* native character */
-#endif
-
-#ifndef GL_VERSION_1_5
-/* GL types for handling large vertex buffer objects */
-typedef ptrdiff_t GLintptr;
-typedef ptrdiff_t GLsizeiptr;
-#endif
-
-#ifndef GL_ARB_vertex_buffer_object
-/* GL types for handling large vertex buffer objects */
-typedef ptrdiff_t GLintptrARB;
-typedef ptrdiff_t GLsizeiptrARB;
-#endif
-
-#ifndef GL_ARB_shader_objects
-/* GL types for handling shader object handles and program/shader text */
-typedef char GLcharARB; /* native character */
-typedef unsigned int GLhandleARB; /* shader object handle */
-#endif
-
-/* GL types for "half" precision (s10e5) float data in host memory */
-#ifndef GL_ARB_half_float_pixel
-typedef unsigned short GLhalfARB;
-#endif
-
-#ifndef GL_NV_half_float
-typedef unsigned short GLhalfNV;
-#endif
-
-#ifndef GL_VERSION_1_2
-#define GL_VERSION_1_2 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBlendColor (GLclampf, GLclampf, GLclampf, GLclampf);
-GLAPI void APIENTRY glBlendEquation (GLenum);
-GLAPI void APIENTRY glDrawRangeElements (GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *);
-GLAPI void APIENTRY glColorTable (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glColorTableParameterfv (GLenum, GLenum, const GLfloat *);
-GLAPI void APIENTRY glColorTableParameteriv (GLenum, GLenum, const GLint *);
-GLAPI void APIENTRY glCopyColorTable (GLenum, GLenum, GLint, GLint, GLsizei);
-GLAPI void APIENTRY glGetColorTable (GLenum, GLenum, GLenum, GLvoid *);
-GLAPI void APIENTRY glGetColorTableParameterfv (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetColorTableParameteriv (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glColorSubTable (GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glCopyColorSubTable (GLenum, GLsizei, GLint, GLint, GLsizei);
-GLAPI void APIENTRY glConvolutionFilter1D (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glConvolutionFilter2D (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glConvolutionParameterf (GLenum, GLenum, GLfloat);
-GLAPI void APIENTRY glConvolutionParameterfv (GLenum, GLenum, const GLfloat *);
-GLAPI void APIENTRY glConvolutionParameteri (GLenum, GLenum, GLint);
-GLAPI void APIENTRY glConvolutionParameteriv (GLenum, GLenum, const GLint *);
-GLAPI void APIENTRY glCopyConvolutionFilter1D (GLenum, GLenum, GLint, GLint, GLsizei);
-GLAPI void APIENTRY glCopyConvolutionFilter2D (GLenum, GLenum, GLint, GLint, GLsizei, GLsizei);
-GLAPI void APIENTRY glGetConvolutionFilter (GLenum, GLenum, GLenum, GLvoid *);
-GLAPI void APIENTRY glGetConvolutionParameterfv (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetConvolutionParameteriv (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetSeparableFilter (GLenum, GLenum, GLenum, GLvoid *, GLvoid *, GLvoid *);
-GLAPI void APIENTRY glSeparableFilter2D (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *, const GLvoid *);
-GLAPI void APIENTRY glGetHistogram (GLenum, GLboolean, GLenum, GLenum, GLvoid *);
-GLAPI void APIENTRY glGetHistogramParameterfv (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetHistogramParameteriv (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetMinmax (GLenum, GLboolean, GLenum, GLenum, GLvoid *);
-GLAPI void APIENTRY glGetMinmaxParameterfv (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetMinmaxParameteriv (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glHistogram (GLenum, GLsizei, GLenum, GLboolean);
-GLAPI void APIENTRY glMinmax (GLenum, GLenum, GLboolean);
-GLAPI void APIENTRY glResetHistogram (GLenum);
-GLAPI void APIENTRY glResetMinmax (GLenum);
-GLAPI void APIENTRY glTexImage3D (GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glCopyTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBLENDCOLORPROC) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
-typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode);
-typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices);
-typedef void (APIENTRYP PFNGLCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
-typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLCOPYCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
-typedef void (APIENTRYP PFNGLGETCOLORTABLEPROC) (GLenum target, GLenum format, GLenum type, GLvoid *table);
-typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width);
-typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image);
-typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image);
-typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFPROC) (GLenum target, GLenum pname, GLfloat params);
-typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIPROC) (GLenum target, GLenum pname, GLint params);
-typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
-typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height);
-typedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTERPROC) (GLenum target, GLenum format, GLenum type, GLvoid *image);
-typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETSEPARABLEFILTERPROC) (GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span);
-typedef void (APIENTRYP PFNGLSEPARABLEFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column);
-typedef void (APIENTRYP PFNGLGETHISTOGRAMPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
-typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETMINMAXPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
-typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLHISTOGRAMPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink);
-typedef void (APIENTRYP PFNGLMINMAXPROC) (GLenum target, GLenum internalformat, GLboolean sink);
-typedef void (APIENTRYP PFNGLRESETHISTOGRAMPROC) (GLenum target);
-typedef void (APIENTRYP PFNGLRESETMINMAXPROC) (GLenum target);
-typedef void (APIENTRYP PFNGLTEXIMAGE3DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
-typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
-typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
-#endif
-
-#ifndef GL_VERSION_1_3
-#define GL_VERSION_1_3 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glActiveTexture (GLenum);
-GLAPI void APIENTRY glClientActiveTexture (GLenum);
-GLAPI void APIENTRY glMultiTexCoord1d (GLenum, GLdouble);
-GLAPI void APIENTRY glMultiTexCoord1dv (GLenum, const GLdouble *);
-GLAPI void APIENTRY glMultiTexCoord1f (GLenum, GLfloat);
-GLAPI void APIENTRY glMultiTexCoord1fv (GLenum, const GLfloat *);
-GLAPI void APIENTRY glMultiTexCoord1i (GLenum, GLint);
-GLAPI void APIENTRY glMultiTexCoord1iv (GLenum, const GLint *);
-GLAPI void APIENTRY glMultiTexCoord1s (GLenum, GLshort);
-GLAPI void APIENTRY glMultiTexCoord1sv (GLenum, const GLshort *);
-GLAPI void APIENTRY glMultiTexCoord2d (GLenum, GLdouble, GLdouble);
-GLAPI void APIENTRY glMultiTexCoord2dv (GLenum, const GLdouble *);
-GLAPI void APIENTRY glMultiTexCoord2f (GLenum, GLfloat, GLfloat);
-GLAPI void APIENTRY glMultiTexCoord2fv (GLenum, const GLfloat *);
-GLAPI void APIENTRY glMultiTexCoord2i (GLenum, GLint, GLint);
-GLAPI void APIENTRY glMultiTexCoord2iv (GLenum, const GLint *);
-GLAPI void APIENTRY glMultiTexCoord2s (GLenum, GLshort, GLshort);
-GLAPI void APIENTRY glMultiTexCoord2sv (GLenum, const GLshort *);
-GLAPI void APIENTRY glMultiTexCoord3d (GLenum, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glMultiTexCoord3dv (GLenum, const GLdouble *);
-GLAPI void APIENTRY glMultiTexCoord3f (GLenum, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glMultiTexCoord3fv (GLenum, const GLfloat *);
-GLAPI void APIENTRY glMultiTexCoord3i (GLenum, GLint, GLint, GLint);
-GLAPI void APIENTRY glMultiTexCoord3iv (GLenum, const GLint *);
-GLAPI void APIENTRY glMultiTexCoord3s (GLenum, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glMultiTexCoord3sv (GLenum, const GLshort *);
-GLAPI void APIENTRY glMultiTexCoord4d (GLenum, GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glMultiTexCoord4dv (GLenum, const GLdouble *);
-GLAPI void APIENTRY glMultiTexCoord4f (GLenum, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glMultiTexCoord4fv (GLenum, const GLfloat *);
-GLAPI void APIENTRY glMultiTexCoord4i (GLenum, GLint, GLint, GLint, GLint);
-GLAPI void APIENTRY glMultiTexCoord4iv (GLenum, const GLint *);
-GLAPI void APIENTRY glMultiTexCoord4s (GLenum, GLshort, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glMultiTexCoord4sv (GLenum, const GLshort *);
-GLAPI void APIENTRY glLoadTransposeMatrixf (const GLfloat *);
-GLAPI void APIENTRY glLoadTransposeMatrixd (const GLdouble *);
-GLAPI void APIENTRY glMultTransposeMatrixf (const GLfloat *);
-GLAPI void APIENTRY glMultTransposeMatrixd (const GLdouble *);
-GLAPI void APIENTRY glSampleCoverage (GLclampf, GLboolean);
-GLAPI void APIENTRY glCompressedTexImage3D (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glCompressedTexImage2D (GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glCompressedTexImage1D (GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glCompressedTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glCompressedTexSubImage2D (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glCompressedTexSubImage1D (GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glGetCompressedTexImage (GLenum, GLint, GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture);
-typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREPROC) (GLenum texture);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1DPROC) (GLenum target, GLdouble s);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVPROC) (GLenum target, const GLdouble *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1FPROC) (GLenum target, GLfloat s);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVPROC) (GLenum target, const GLfloat *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1IPROC) (GLenum target, GLint s);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVPROC) (GLenum target, const GLint *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1SPROC) (GLenum target, GLshort s);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVPROC) (GLenum target, const GLshort *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2DPROC) (GLenum target, GLdouble s, GLdouble t);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVPROC) (GLenum target, const GLdouble *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2FPROC) (GLenum target, GLfloat s, GLfloat t);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVPROC) (GLenum target, const GLfloat *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2IPROC) (GLenum target, GLint s, GLint t);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVPROC) (GLenum target, const GLint *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2SPROC) (GLenum target, GLshort s, GLshort t);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVPROC) (GLenum target, const GLshort *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVPROC) (GLenum target, const GLdouble *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVPROC) (GLenum target, const GLfloat *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3IPROC) (GLenum target, GLint s, GLint t, GLint r);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVPROC) (GLenum target, const GLint *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3SPROC) (GLenum target, GLshort s, GLshort t, GLshort r);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVPROC) (GLenum target, const GLshort *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVPROC) (GLenum target, const GLdouble *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVPROC) (GLenum target, const GLfloat *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4IPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVPROC) (GLenum target, const GLint *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4SPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVPROC) (GLenum target, const GLshort *v);
-typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFPROC) (const GLfloat *m);
-typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDPROC) (const GLdouble *m);
-typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFPROC) (const GLfloat *m);
-typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDPROC) (const GLdouble *m);
-typedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC) (GLclampf value, GLboolean invert);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC) (GLenum target, GLint level, GLvoid *img);
-#endif
-
-#ifndef GL_VERSION_1_4
-#define GL_VERSION_1_4 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBlendFuncSeparate (GLenum, GLenum, GLenum, GLenum);
-GLAPI void APIENTRY glFogCoordf (GLfloat);
-GLAPI void APIENTRY glFogCoordfv (const GLfloat *);
-GLAPI void APIENTRY glFogCoordd (GLdouble);
-GLAPI void APIENTRY glFogCoorddv (const GLdouble *);
-GLAPI void APIENTRY glFogCoordPointer (GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glMultiDrawArrays (GLenum, GLint *, GLsizei *, GLsizei);
-GLAPI void APIENTRY glMultiDrawElements (GLenum, const GLsizei *, GLenum, const GLvoid* *, GLsizei);
-GLAPI void APIENTRY glPointParameterf (GLenum, GLfloat);
-GLAPI void APIENTRY glPointParameterfv (GLenum, const GLfloat *);
-GLAPI void APIENTRY glPointParameteri (GLenum, GLint);
-GLAPI void APIENTRY glPointParameteriv (GLenum, const GLint *);
-GLAPI void APIENTRY glSecondaryColor3b (GLbyte, GLbyte, GLbyte);
-GLAPI void APIENTRY glSecondaryColor3bv (const GLbyte *);
-GLAPI void APIENTRY glSecondaryColor3d (GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glSecondaryColor3dv (const GLdouble *);
-GLAPI void APIENTRY glSecondaryColor3f (GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glSecondaryColor3fv (const GLfloat *);
-GLAPI void APIENTRY glSecondaryColor3i (GLint, GLint, GLint);
-GLAPI void APIENTRY glSecondaryColor3iv (const GLint *);
-GLAPI void APIENTRY glSecondaryColor3s (GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glSecondaryColor3sv (const GLshort *);
-GLAPI void APIENTRY glSecondaryColor3ub (GLubyte, GLubyte, GLubyte);
-GLAPI void APIENTRY glSecondaryColor3ubv (const GLubyte *);
-GLAPI void APIENTRY glSecondaryColor3ui (GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glSecondaryColor3uiv (const GLuint *);
-GLAPI void APIENTRY glSecondaryColor3us (GLushort, GLushort, GLushort);
-GLAPI void APIENTRY glSecondaryColor3usv (const GLushort *);
-GLAPI void APIENTRY glSecondaryColorPointer (GLint, GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glWindowPos2d (GLdouble, GLdouble);
-GLAPI void APIENTRY glWindowPos2dv (const GLdouble *);
-GLAPI void APIENTRY glWindowPos2f (GLfloat, GLfloat);
-GLAPI void APIENTRY glWindowPos2fv (const GLfloat *);
-GLAPI void APIENTRY glWindowPos2i (GLint, GLint);
-GLAPI void APIENTRY glWindowPos2iv (const GLint *);
-GLAPI void APIENTRY glWindowPos2s (GLshort, GLshort);
-GLAPI void APIENTRY glWindowPos2sv (const GLshort *);
-GLAPI void APIENTRY glWindowPos3d (GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glWindowPos3dv (const GLdouble *);
-GLAPI void APIENTRY glWindowPos3f (GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glWindowPos3fv (const GLfloat *);
-GLAPI void APIENTRY glWindowPos3i (GLint, GLint, GLint);
-GLAPI void APIENTRY glWindowPos3iv (const GLint *);
-GLAPI void APIENTRY glWindowPos3s (GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glWindowPos3sv (const GLshort *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
-typedef void (APIENTRYP PFNGLFOGCOORDFPROC) (GLfloat coord);
-typedef void (APIENTRYP PFNGLFOGCOORDFVPROC) (const GLfloat *coord);
-typedef void (APIENTRYP PFNGLFOGCOORDDPROC) (GLdouble coord);
-typedef void (APIENTRYP PFNGLFOGCOORDDVPROC) (const GLdouble *coord);
-typedef void (APIENTRYP PFNGLFOGCOORDPOINTERPROC) (GLenum type, GLsizei stride, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount);
-typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount);
-typedef void (APIENTRYP PFNGLPOINTPARAMETERFPROC) (GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLPOINTPARAMETERFVPROC) (GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLPOINTPARAMETERIPROC) (GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLPOINTPARAMETERIVPROC) (GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BPROC) (GLbyte red, GLbyte green, GLbyte blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVPROC) (const GLbyte *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DPROC) (GLdouble red, GLdouble green, GLdouble blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FPROC) (GLfloat red, GLfloat green, GLfloat blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IPROC) (GLint red, GLint green, GLint blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SPROC) (GLshort red, GLshort green, GLshort blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVPROC) (const GLshort *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBPROC) (GLubyte red, GLubyte green, GLubyte blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVPROC) (const GLubyte *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIPROC) (GLuint red, GLuint green, GLuint blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVPROC) (const GLuint *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USPROC) (GLushort red, GLushort green, GLushort blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVPROC) (const GLushort *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLWINDOWPOS2DPROC) (GLdouble x, GLdouble y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2DVPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS2FPROC) (GLfloat x, GLfloat y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2FVPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS2IPROC) (GLint x, GLint y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2IVPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS2SPROC) (GLshort x, GLshort y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2SVPROC) (const GLshort *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3DPROC) (GLdouble x, GLdouble y, GLdouble z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3DVPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3FPROC) (GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3FVPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3IPROC) (GLint x, GLint y, GLint z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3IVPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3SPROC) (GLshort x, GLshort y, GLshort z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3SVPROC) (const GLshort *v);
-#endif
-
-#ifndef GL_VERSION_1_5
-#define GL_VERSION_1_5 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glGenQueries (GLsizei, GLuint *);
-GLAPI void APIENTRY glDeleteQueries (GLsizei, const GLuint *);
-GLAPI GLboolean APIENTRY glIsQuery (GLuint);
-GLAPI void APIENTRY glBeginQuery (GLenum, GLuint);
-GLAPI void APIENTRY glEndQuery (GLenum);
-GLAPI void APIENTRY glGetQueryiv (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetQueryObjectiv (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetQueryObjectuiv (GLuint, GLenum, GLuint *);
-GLAPI void APIENTRY glBindBuffer (GLenum, GLuint);
-GLAPI void APIENTRY glDeleteBuffers (GLsizei, const GLuint *);
-GLAPI void APIENTRY glGenBuffers (GLsizei, GLuint *);
-GLAPI GLboolean APIENTRY glIsBuffer (GLuint);
-GLAPI void APIENTRY glBufferData (GLenum, GLsizeiptr, const GLvoid *, GLenum);
-GLAPI void APIENTRY glBufferSubData (GLenum, GLintptr, GLsizeiptr, const GLvoid *);
-GLAPI void APIENTRY glGetBufferSubData (GLenum, GLintptr, GLsizeiptr, GLvoid *);
-GLAPI GLvoid* APIENTRY glMapBuffer (GLenum, GLenum);
-GLAPI GLboolean APIENTRY glUnmapBuffer (GLenum);
-GLAPI void APIENTRY glGetBufferParameteriv (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetBufferPointerv (GLenum, GLenum, GLvoid* *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLGENQUERIESPROC) (GLsizei n, GLuint *ids);
-typedef void (APIENTRYP PFNGLDELETEQUERIESPROC) (GLsizei n, const GLuint *ids);
-typedef GLboolean (APIENTRYP PFNGLISQUERYPROC) (GLuint id);
-typedef void (APIENTRYP PFNGLBEGINQUERYPROC) (GLenum target, GLuint id);
-typedef void (APIENTRYP PFNGLENDQUERYPROC) (GLenum target);
-typedef void (APIENTRYP PFNGLGETQUERYIVPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVPROC) (GLuint id, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVPROC) (GLuint id, GLenum pname, GLuint *params);
-typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer);
-typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers);
-typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers);
-typedef GLboolean (APIENTRYP PFNGLISBUFFERPROC) (GLuint buffer);
-typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage);
-typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data);
-typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, GLvoid *data);
-typedef GLvoid* (APIENTRYP PFNGLMAPBUFFERPROC) (GLenum target, GLenum access);
-typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERPROC) (GLenum target);
-typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVPROC) (GLenum target, GLenum pname, GLvoid* *params);
-#endif
-
-#ifndef GL_VERSION_2_0
-#define GL_VERSION_2_0 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBlendEquationSeparate (GLenum, GLenum);
-GLAPI void APIENTRY glDrawBuffers (GLsizei, const GLenum *);
-GLAPI void APIENTRY glStencilOpSeparate (GLenum, GLenum, GLenum, GLenum);
-GLAPI void APIENTRY glStencilFuncSeparate (GLenum, GLenum, GLint, GLuint);
-GLAPI void APIENTRY glStencilMaskSeparate (GLenum, GLuint);
-GLAPI void APIENTRY glAttachShader (GLuint, GLuint);
-GLAPI void APIENTRY glBindAttribLocation (GLuint, GLuint, const GLchar *);
-GLAPI void APIENTRY glCompileShader (GLuint);
-GLAPI GLuint APIENTRY glCreateProgram (void);
-GLAPI GLuint APIENTRY glCreateShader (GLenum);
-GLAPI void APIENTRY glDeleteProgram (GLuint);
-GLAPI void APIENTRY glDeleteShader (GLuint);
-GLAPI void APIENTRY glDetachShader (GLuint, GLuint);
-GLAPI void APIENTRY glDisableVertexAttribArray (GLuint);
-GLAPI void APIENTRY glEnableVertexAttribArray (GLuint);
-GLAPI void APIENTRY glGetActiveAttrib (GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *);
-GLAPI void APIENTRY glGetActiveUniform (GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *);
-GLAPI void APIENTRY glGetAttachedShaders (GLuint, GLsizei, GLsizei *, GLuint *);
-GLAPI GLint APIENTRY glGetAttribLocation (GLuint, const GLchar *);
-GLAPI void APIENTRY glGetProgramiv (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetProgramInfoLog (GLuint, GLsizei, GLsizei *, GLchar *);
-GLAPI void APIENTRY glGetShaderiv (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetShaderInfoLog (GLuint, GLsizei, GLsizei *, GLchar *);
-GLAPI void APIENTRY glGetShaderSource (GLuint, GLsizei, GLsizei *, GLchar *);
-GLAPI GLint APIENTRY glGetUniformLocation (GLuint, const GLchar *);
-GLAPI void APIENTRY glGetUniformfv (GLuint, GLint, GLfloat *);
-GLAPI void APIENTRY glGetUniformiv (GLuint, GLint, GLint *);
-GLAPI void APIENTRY glGetVertexAttribdv (GLuint, GLenum, GLdouble *);
-GLAPI void APIENTRY glGetVertexAttribfv (GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetVertexAttribiv (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetVertexAttribPointerv (GLuint, GLenum, GLvoid* *);
-GLAPI GLboolean APIENTRY glIsProgram (GLuint);
-GLAPI GLboolean APIENTRY glIsShader (GLuint);
-GLAPI void APIENTRY glLinkProgram (GLuint);
-GLAPI void APIENTRY glShaderSource (GLuint, GLsizei, const GLchar* *, const GLint *);
-GLAPI void APIENTRY glUseProgram (GLuint);
-GLAPI void APIENTRY glUniform1f (GLint, GLfloat);
-GLAPI void APIENTRY glUniform2f (GLint, GLfloat, GLfloat);
-GLAPI void APIENTRY glUniform3f (GLint, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glUniform4f (GLint, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glUniform1i (GLint, GLint);
-GLAPI void APIENTRY glUniform2i (GLint, GLint, GLint);
-GLAPI void APIENTRY glUniform3i (GLint, GLint, GLint, GLint);
-GLAPI void APIENTRY glUniform4i (GLint, GLint, GLint, GLint, GLint);
-GLAPI void APIENTRY glUniform1fv (GLint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glUniform2fv (GLint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glUniform3fv (GLint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glUniform4fv (GLint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glUniform1iv (GLint, GLsizei, const GLint *);
-GLAPI void APIENTRY glUniform2iv (GLint, GLsizei, const GLint *);
-GLAPI void APIENTRY glUniform3iv (GLint, GLsizei, const GLint *);
-GLAPI void APIENTRY glUniform4iv (GLint, GLsizei, const GLint *);
-GLAPI void APIENTRY glUniformMatrix2fv (GLint, GLsizei, GLboolean, const GLfloat *);
-GLAPI void APIENTRY glUniformMatrix3fv (GLint, GLsizei, GLboolean, const GLfloat *);
-GLAPI void APIENTRY glUniformMatrix4fv (GLint, GLsizei, GLboolean, const GLfloat *);
-GLAPI void APIENTRY glValidateProgram (GLuint);
-GLAPI void APIENTRY glVertexAttrib1d (GLuint, GLdouble);
-GLAPI void APIENTRY glVertexAttrib1dv (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib1f (GLuint, GLfloat);
-GLAPI void APIENTRY glVertexAttrib1fv (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib1s (GLuint, GLshort);
-GLAPI void APIENTRY glVertexAttrib1sv (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib2d (GLuint, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexAttrib2dv (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib2f (GLuint, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexAttrib2fv (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib2s (GLuint, GLshort, GLshort);
-GLAPI void APIENTRY glVertexAttrib2sv (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib3d (GLuint, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexAttrib3dv (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib3f (GLuint, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexAttrib3fv (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib3s (GLuint, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glVertexAttrib3sv (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib4Nbv (GLuint, const GLbyte *);
-GLAPI void APIENTRY glVertexAttrib4Niv (GLuint, const GLint *);
-GLAPI void APIENTRY glVertexAttrib4Nsv (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib4Nub (GLuint, GLubyte, GLubyte, GLubyte, GLubyte);
-GLAPI void APIENTRY glVertexAttrib4Nubv (GLuint, const GLubyte *);
-GLAPI void APIENTRY glVertexAttrib4Nuiv (GLuint, const GLuint *);
-GLAPI void APIENTRY glVertexAttrib4Nusv (GLuint, const GLushort *);
-GLAPI void APIENTRY glVertexAttrib4bv (GLuint, const GLbyte *);
-GLAPI void APIENTRY glVertexAttrib4d (GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexAttrib4dv (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib4f (GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexAttrib4fv (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib4iv (GLuint, const GLint *);
-GLAPI void APIENTRY glVertexAttrib4s (GLuint, GLshort, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glVertexAttrib4sv (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib4ubv (GLuint, const GLubyte *);
-GLAPI void APIENTRY glVertexAttrib4uiv (GLuint, const GLuint *);
-GLAPI void APIENTRY glVertexAttrib4usv (GLuint, const GLushort *);
-GLAPI void APIENTRY glVertexAttribPointer (GLuint, GLint, GLenum, GLboolean, GLsizei, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha);
-typedef void (APIENTRYP PFNGLDRAWBUFFERSPROC) (GLsizei n, const GLenum *bufs);
-typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);
-typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC) (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask);
-typedef void (APIENTRYP PFNGLSTENCILMASKSEPARATEPROC) (GLenum face, GLuint mask);
-typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader);
-typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONPROC) (GLuint program, GLuint index, const GLchar *name);
-typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader);
-typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void);
-typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type);
-typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program);
-typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader);
-typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader);
-typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index);
-typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index);
-typedef void (APIENTRYP PFNGLGETACTIVEATTRIBPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
-typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
-typedef void (APIENTRYP PFNGLGETATTACHEDSHADERSPROC) (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *obj);
-typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name);
-typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
-typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
-typedef void (APIENTRYP PFNGLGETSHADERSOURCEPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source);
-typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name);
-typedef void (APIENTRYP PFNGLGETUNIFORMFVPROC) (GLuint program, GLint location, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETUNIFORMIVPROC) (GLuint program, GLint location, GLint *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVPROC) (GLuint index, GLenum pname, GLdouble *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVPROC) (GLuint index, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, GLvoid* *pointer);
-typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC) (GLuint program);
-typedef GLboolean (APIENTRYP PFNGLISSHADERPROC) (GLuint shader);
-typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program);
-typedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar* *string, const GLint *length);
-typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program);
-typedef void (APIENTRYP PFNGLUNIFORM1FPROC) (GLint location, GLfloat v0);
-typedef void (APIENTRYP PFNGLUNIFORM2FPROC) (GLint location, GLfloat v0, GLfloat v1);
-typedef void (APIENTRYP PFNGLUNIFORM3FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
-typedef void (APIENTRYP PFNGLUNIFORM4FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
-typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0);
-typedef void (APIENTRYP PFNGLUNIFORM2IPROC) (GLint location, GLint v0, GLint v1);
-typedef void (APIENTRYP PFNGLUNIFORM3IPROC) (GLint location, GLint v0, GLint v1, GLint v2);
-typedef void (APIENTRYP PFNGLUNIFORM4IPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
-typedef void (APIENTRYP PFNGLUNIFORM1FVPROC) (GLint location, GLsizei count, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORM2FVPROC) (GLint location, GLsizei count, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORM3FVPROC) (GLint location, GLsizei count, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORM4FVPROC) (GLint location, GLsizei count, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORM1IVPROC) (GLint location, GLsizei count, const GLint *value);
-typedef void (APIENTRYP PFNGLUNIFORM2IVPROC) (GLint location, GLsizei count, const GLint *value);
-typedef void (APIENTRYP PFNGLUNIFORM3IVPROC) (GLint location, GLsizei count, const GLint *value);
-typedef void (APIENTRYP PFNGLUNIFORM4IVPROC) (GLint location, GLsizei count, const GLint *value);
-typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
-typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPROC) (GLuint program);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1DPROC) (GLuint index, GLdouble x);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1FPROC) (GLuint index, GLfloat x);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1SPROC) (GLuint index, GLshort x);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2DPROC) (GLuint index, GLdouble x, GLdouble y);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2FPROC) (GLuint index, GLfloat x, GLfloat y);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2SPROC) (GLuint index, GLshort x, GLshort y);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3SPROC) (GLuint index, GLshort x, GLshort y, GLshort z);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVPROC) (GLuint index, const GLbyte *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVPROC) (GLuint index, const GLint *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVPROC) (GLuint index, const GLubyte *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVPROC) (GLuint index, const GLuint *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVPROC) (GLuint index, const GLushort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVPROC) (GLuint index, const GLbyte *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVPROC) (GLuint index, const GLint *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4SPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVPROC) (GLuint index, const GLubyte *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVPROC) (GLuint index, const GLuint *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVPROC) (GLuint index, const GLushort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer);
-#endif
-
-#ifndef GL_ARB_multitexture
-#define GL_ARB_multitexture 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glActiveTextureARB (GLenum);
-GLAPI void APIENTRY glClientActiveTextureARB (GLenum);
-GLAPI void APIENTRY glMultiTexCoord1dARB (GLenum, GLdouble);
-GLAPI void APIENTRY glMultiTexCoord1dvARB (GLenum, const GLdouble *);
-GLAPI void APIENTRY glMultiTexCoord1fARB (GLenum, GLfloat);
-GLAPI void APIENTRY glMultiTexCoord1fvARB (GLenum, const GLfloat *);
-GLAPI void APIENTRY glMultiTexCoord1iARB (GLenum, GLint);
-GLAPI void APIENTRY glMultiTexCoord1ivARB (GLenum, const GLint *);
-GLAPI void APIENTRY glMultiTexCoord1sARB (GLenum, GLshort);
-GLAPI void APIENTRY glMultiTexCoord1svARB (GLenum, const GLshort *);
-GLAPI void APIENTRY glMultiTexCoord2dARB (GLenum, GLdouble, GLdouble);
-GLAPI void APIENTRY glMultiTexCoord2dvARB (GLenum, const GLdouble *);
-GLAPI void APIENTRY glMultiTexCoord2fARB (GLenum, GLfloat, GLfloat);
-GLAPI void APIENTRY glMultiTexCoord2fvARB (GLenum, const GLfloat *);
-GLAPI void APIENTRY glMultiTexCoord2iARB (GLenum, GLint, GLint);
-GLAPI void APIENTRY glMultiTexCoord2ivARB (GLenum, const GLint *);
-GLAPI void APIENTRY glMultiTexCoord2sARB (GLenum, GLshort, GLshort);
-GLAPI void APIENTRY glMultiTexCoord2svARB (GLenum, const GLshort *);
-GLAPI void APIENTRY glMultiTexCoord3dARB (GLenum, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glMultiTexCoord3dvARB (GLenum, const GLdouble *);
-GLAPI void APIENTRY glMultiTexCoord3fARB (GLenum, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glMultiTexCoord3fvARB (GLenum, const GLfloat *);
-GLAPI void APIENTRY glMultiTexCoord3iARB (GLenum, GLint, GLint, GLint);
-GLAPI void APIENTRY glMultiTexCoord3ivARB (GLenum, const GLint *);
-GLAPI void APIENTRY glMultiTexCoord3sARB (GLenum, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glMultiTexCoord3svARB (GLenum, const GLshort *);
-GLAPI void APIENTRY glMultiTexCoord4dARB (GLenum, GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glMultiTexCoord4dvARB (GLenum, const GLdouble *);
-GLAPI void APIENTRY glMultiTexCoord4fARB (GLenum, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glMultiTexCoord4fvARB (GLenum, const GLfloat *);
-GLAPI void APIENTRY glMultiTexCoord4iARB (GLenum, GLint, GLint, GLint, GLint);
-GLAPI void APIENTRY glMultiTexCoord4ivARB (GLenum, const GLint *);
-GLAPI void APIENTRY glMultiTexCoord4sARB (GLenum, GLshort, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glMultiTexCoord4svARB (GLenum, const GLshort *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLACTIVETEXTUREARBPROC) (GLenum texture);
-typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREARBPROC) (GLenum texture);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1DARBPROC) (GLenum target, GLdouble s);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVARBPROC) (GLenum target, const GLdouble *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1FARBPROC) (GLenum target, GLfloat s);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVARBPROC) (GLenum target, const GLfloat *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1IARBPROC) (GLenum target, GLint s);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVARBPROC) (GLenum target, const GLint *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1SARBPROC) (GLenum target, GLshort s);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVARBPROC) (GLenum target, const GLshort *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2DARBPROC) (GLenum target, GLdouble s, GLdouble t);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVARBPROC) (GLenum target, const GLdouble *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2FARBPROC) (GLenum target, GLfloat s, GLfloat t);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVARBPROC) (GLenum target, const GLfloat *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2IARBPROC) (GLenum target, GLint s, GLint t);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVARBPROC) (GLenum target, const GLint *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2SARBPROC) (GLenum target, GLshort s, GLshort t);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVARBPROC) (GLenum target, const GLshort *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVARBPROC) (GLenum target, const GLdouble *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVARBPROC) (GLenum target, const GLfloat *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3IARBPROC) (GLenum target, GLint s, GLint t, GLint r);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVARBPROC) (GLenum target, const GLint *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVARBPROC) (GLenum target, const GLshort *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVARBPROC) (GLenum target, const GLdouble *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVARBPROC) (GLenum target, const GLfloat *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4IARBPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVARBPROC) (GLenum target, const GLint *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVARBPROC) (GLenum target, const GLshort *v);
-#endif
-
-#ifndef GL_ARB_transpose_matrix
-#define GL_ARB_transpose_matrix 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glLoadTransposeMatrixfARB (const GLfloat *);
-GLAPI void APIENTRY glLoadTransposeMatrixdARB (const GLdouble *);
-GLAPI void APIENTRY glMultTransposeMatrixfARB (const GLfloat *);
-GLAPI void APIENTRY glMultTransposeMatrixdARB (const GLdouble *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFARBPROC) (const GLfloat *m);
-typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDARBPROC) (const GLdouble *m);
-typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFARBPROC) (const GLfloat *m);
-typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDARBPROC) (const GLdouble *m);
-#endif
-
-#ifndef GL_ARB_multisample
-#define GL_ARB_multisample 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glSampleCoverageARB (GLclampf, GLboolean);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLSAMPLECOVERAGEARBPROC) (GLclampf value, GLboolean invert);
-#endif
-
-#ifndef GL_ARB_texture_env_add
-#define GL_ARB_texture_env_add 1
-#endif
-
-#ifndef GL_ARB_texture_cube_map
-#define GL_ARB_texture_cube_map 1
-#endif
-
-#ifndef GL_ARB_texture_compression
-#define GL_ARB_texture_compression 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glCompressedTexImage3DARB (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glCompressedTexImage2DARB (GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glCompressedTexImage1DARB (GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glCompressedTexSubImage3DARB (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glCompressedTexSubImage2DARB (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glCompressedTexSubImage1DARB (GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glGetCompressedTexImageARB (GLenum, GLint, GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GLint level, GLvoid *img);
-#endif
-
-#ifndef GL_ARB_texture_border_clamp
-#define GL_ARB_texture_border_clamp 1
-#endif
-
-#ifndef GL_ARB_point_parameters
-#define GL_ARB_point_parameters 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPointParameterfARB (GLenum, GLfloat);
-GLAPI void APIENTRY glPointParameterfvARB (GLenum, const GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPOINTPARAMETERFARBPROC) (GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLPOINTPARAMETERFVARBPROC) (GLenum pname, const GLfloat *params);
-#endif
-
-#ifndef GL_ARB_vertex_blend
-#define GL_ARB_vertex_blend 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glWeightbvARB (GLint, const GLbyte *);
-GLAPI void APIENTRY glWeightsvARB (GLint, const GLshort *);
-GLAPI void APIENTRY glWeightivARB (GLint, const GLint *);
-GLAPI void APIENTRY glWeightfvARB (GLint, const GLfloat *);
-GLAPI void APIENTRY glWeightdvARB (GLint, const GLdouble *);
-GLAPI void APIENTRY glWeightubvARB (GLint, const GLubyte *);
-GLAPI void APIENTRY glWeightusvARB (GLint, const GLushort *);
-GLAPI void APIENTRY glWeightuivARB (GLint, const GLuint *);
-GLAPI void APIENTRY glWeightPointerARB (GLint, GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glVertexBlendARB (GLint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLWEIGHTBVARBPROC) (GLint size, const GLbyte *weights);
-typedef void (APIENTRYP PFNGLWEIGHTSVARBPROC) (GLint size, const GLshort *weights);
-typedef void (APIENTRYP PFNGLWEIGHTIVARBPROC) (GLint size, const GLint *weights);
-typedef void (APIENTRYP PFNGLWEIGHTFVARBPROC) (GLint size, const GLfloat *weights);
-typedef void (APIENTRYP PFNGLWEIGHTDVARBPROC) (GLint size, const GLdouble *weights);
-typedef void (APIENTRYP PFNGLWEIGHTUBVARBPROC) (GLint size, const GLubyte *weights);
-typedef void (APIENTRYP PFNGLWEIGHTUSVARBPROC) (GLint size, const GLushort *weights);
-typedef void (APIENTRYP PFNGLWEIGHTUIVARBPROC) (GLint size, const GLuint *weights);
-typedef void (APIENTRYP PFNGLWEIGHTPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLVERTEXBLENDARBPROC) (GLint count);
-#endif
-
-#ifndef GL_ARB_matrix_palette
-#define GL_ARB_matrix_palette 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glCurrentPaletteMatrixARB (GLint);
-GLAPI void APIENTRY glMatrixIndexubvARB (GLint, const GLubyte *);
-GLAPI void APIENTRY glMatrixIndexusvARB (GLint, const GLushort *);
-GLAPI void APIENTRY glMatrixIndexuivARB (GLint, const GLuint *);
-GLAPI void APIENTRY glMatrixIndexPointerARB (GLint, GLenum, GLsizei, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCURRENTPALETTEMATRIXARBPROC) (GLint index);
-typedef void (APIENTRYP PFNGLMATRIXINDEXUBVARBPROC) (GLint size, const GLubyte *indices);
-typedef void (APIENTRYP PFNGLMATRIXINDEXUSVARBPROC) (GLint size, const GLushort *indices);
-typedef void (APIENTRYP PFNGLMATRIXINDEXUIVARBPROC) (GLint size, const GLuint *indices);
-typedef void (APIENTRYP PFNGLMATRIXINDEXPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
-#endif
-
-#ifndef GL_ARB_texture_env_combine
-#define GL_ARB_texture_env_combine 1
-#endif
-
-#ifndef GL_ARB_texture_env_crossbar
-#define GL_ARB_texture_env_crossbar 1
-#endif
-
-#ifndef GL_ARB_texture_env_dot3
-#define GL_ARB_texture_env_dot3 1
-#endif
-
-#ifndef GL_ARB_texture_mirrored_repeat
-#define GL_ARB_texture_mirrored_repeat 1
-#endif
-
-#ifndef GL_ARB_depth_texture
-#define GL_ARB_depth_texture 1
-#endif
-
-#ifndef GL_ARB_shadow
-#define GL_ARB_shadow 1
-#endif
-
-#ifndef GL_ARB_shadow_ambient
-#define GL_ARB_shadow_ambient 1
-#endif
-
-#ifndef GL_ARB_window_pos
-#define GL_ARB_window_pos 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glWindowPos2dARB (GLdouble, GLdouble);
-GLAPI void APIENTRY glWindowPos2dvARB (const GLdouble *);
-GLAPI void APIENTRY glWindowPos2fARB (GLfloat, GLfloat);
-GLAPI void APIENTRY glWindowPos2fvARB (const GLfloat *);
-GLAPI void APIENTRY glWindowPos2iARB (GLint, GLint);
-GLAPI void APIENTRY glWindowPos2ivARB (const GLint *);
-GLAPI void APIENTRY glWindowPos2sARB (GLshort, GLshort);
-GLAPI void APIENTRY glWindowPos2svARB (const GLshort *);
-GLAPI void APIENTRY glWindowPos3dARB (GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glWindowPos3dvARB (const GLdouble *);
-GLAPI void APIENTRY glWindowPos3fARB (GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glWindowPos3fvARB (const GLfloat *);
-GLAPI void APIENTRY glWindowPos3iARB (GLint, GLint, GLint);
-GLAPI void APIENTRY glWindowPos3ivARB (const GLint *);
-GLAPI void APIENTRY glWindowPos3sARB (GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glWindowPos3svARB (const GLshort *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLWINDOWPOS2DARBPROC) (GLdouble x, GLdouble y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2DVARBPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS2FARBPROC) (GLfloat x, GLfloat y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2FVARBPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS2IARBPROC) (GLint x, GLint y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2IVARBPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS2SARBPROC) (GLshort x, GLshort y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2SVARBPROC) (const GLshort *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3DARBPROC) (GLdouble x, GLdouble y, GLdouble z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3DVARBPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3FARBPROC) (GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3FVARBPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3IARBPROC) (GLint x, GLint y, GLint z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3IVARBPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3SARBPROC) (GLshort x, GLshort y, GLshort z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3SVARBPROC) (const GLshort *v);
-#endif
-
-#ifndef GL_ARB_vertex_program
-#define GL_ARB_vertex_program 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glVertexAttrib1dARB (GLuint, GLdouble);
-GLAPI void APIENTRY glVertexAttrib1dvARB (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib1fARB (GLuint, GLfloat);
-GLAPI void APIENTRY glVertexAttrib1fvARB (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib1sARB (GLuint, GLshort);
-GLAPI void APIENTRY glVertexAttrib1svARB (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib2dARB (GLuint, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexAttrib2dvARB (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib2fARB (GLuint, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexAttrib2fvARB (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib2sARB (GLuint, GLshort, GLshort);
-GLAPI void APIENTRY glVertexAttrib2svARB (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib3dARB (GLuint, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexAttrib3dvARB (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib3fARB (GLuint, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexAttrib3fvARB (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib3sARB (GLuint, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glVertexAttrib3svARB (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib4NbvARB (GLuint, const GLbyte *);
-GLAPI void APIENTRY glVertexAttrib4NivARB (GLuint, const GLint *);
-GLAPI void APIENTRY glVertexAttrib4NsvARB (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib4NubARB (GLuint, GLubyte, GLubyte, GLubyte, GLubyte);
-GLAPI void APIENTRY glVertexAttrib4NubvARB (GLuint, const GLubyte *);
-GLAPI void APIENTRY glVertexAttrib4NuivARB (GLuint, const GLuint *);
-GLAPI void APIENTRY glVertexAttrib4NusvARB (GLuint, const GLushort *);
-GLAPI void APIENTRY glVertexAttrib4bvARB (GLuint, const GLbyte *);
-GLAPI void APIENTRY glVertexAttrib4dARB (GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexAttrib4dvARB (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib4fARB (GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexAttrib4fvARB (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib4ivARB (GLuint, const GLint *);
-GLAPI void APIENTRY glVertexAttrib4sARB (GLuint, GLshort, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glVertexAttrib4svARB (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib4ubvARB (GLuint, const GLubyte *);
-GLAPI void APIENTRY glVertexAttrib4uivARB (GLuint, const GLuint *);
-GLAPI void APIENTRY glVertexAttrib4usvARB (GLuint, const GLushort *);
-GLAPI void APIENTRY glVertexAttribPointerARB (GLuint, GLint, GLenum, GLboolean, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glEnableVertexAttribArrayARB (GLuint);
-GLAPI void APIENTRY glDisableVertexAttribArrayARB (GLuint);
-GLAPI void APIENTRY glProgramStringARB (GLenum, GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glBindProgramARB (GLenum, GLuint);
-GLAPI void APIENTRY glDeleteProgramsARB (GLsizei, const GLuint *);
-GLAPI void APIENTRY glGenProgramsARB (GLsizei, GLuint *);
-GLAPI void APIENTRY glProgramEnvParameter4dARB (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glProgramEnvParameter4dvARB (GLenum, GLuint, const GLdouble *);
-GLAPI void APIENTRY glProgramEnvParameter4fARB (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glProgramEnvParameter4fvARB (GLenum, GLuint, const GLfloat *);
-GLAPI void APIENTRY glProgramLocalParameter4dARB (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glProgramLocalParameter4dvARB (GLenum, GLuint, const GLdouble *);
-GLAPI void APIENTRY glProgramLocalParameter4fARB (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glProgramLocalParameter4fvARB (GLenum, GLuint, const GLfloat *);
-GLAPI void APIENTRY glGetProgramEnvParameterdvARB (GLenum, GLuint, GLdouble *);
-GLAPI void APIENTRY glGetProgramEnvParameterfvARB (GLenum, GLuint, GLfloat *);
-GLAPI void APIENTRY glGetProgramLocalParameterdvARB (GLenum, GLuint, GLdouble *);
-GLAPI void APIENTRY glGetProgramLocalParameterfvARB (GLenum, GLuint, GLfloat *);
-GLAPI void APIENTRY glGetProgramivARB (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetProgramStringARB (GLenum, GLenum, GLvoid *);
-GLAPI void APIENTRY glGetVertexAttribdvARB (GLuint, GLenum, GLdouble *);
-GLAPI void APIENTRY glGetVertexAttribfvARB (GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetVertexAttribivARB (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetVertexAttribPointervARB (GLuint, GLenum, GLvoid* *);
-GLAPI GLboolean APIENTRY glIsProgramARB (GLuint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1DARBPROC) (GLuint index, GLdouble x);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVARBPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1FARBPROC) (GLuint index, GLfloat x);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVARBPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1SARBPROC) (GLuint index, GLshort x);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVARBPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2DARBPROC) (GLuint index, GLdouble x, GLdouble y);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVARBPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2FARBPROC) (GLuint index, GLfloat x, GLfloat y);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVARBPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2SARBPROC) (GLuint index, GLshort x, GLshort y);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVARBPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVARBPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVARBPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVARBPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVARBPROC) (GLuint index, const GLbyte *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVARBPROC) (GLuint index, const GLint *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVARBPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBARBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVARBPROC) (GLuint index, const GLubyte *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVARBPROC) (GLuint index, const GLuint *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVARBPROC) (GLuint index, const GLushort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVARBPROC) (GLuint index, const GLbyte *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVARBPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVARBPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVARBPROC) (GLuint index, const GLint *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVARBPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVARBPROC) (GLuint index, const GLubyte *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVARBPROC) (GLuint index, const GLuint *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVARBPROC) (GLuint index, const GLushort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERARBPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYARBPROC) (GLuint index);
-typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYARBPROC) (GLuint index);
-typedef void (APIENTRYP PFNGLPROGRAMSTRINGARBPROC) (GLenum target, GLenum format, GLsizei len, const GLvoid *string);
-typedef void (APIENTRYP PFNGLBINDPROGRAMARBPROC) (GLenum target, GLuint program);
-typedef void (APIENTRYP PFNGLDELETEPROGRAMSARBPROC) (GLsizei n, const GLuint *programs);
-typedef void (APIENTRYP PFNGLGENPROGRAMSARBPROC) (GLsizei n, GLuint *programs);
-typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
-typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params);
-typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params);
-typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
-typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params);
-typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMIVARBPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGARBPROC) (GLenum target, GLenum pname, GLvoid *string);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVARBPROC) (GLuint index, GLenum pname, GLdouble *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVARBPROC) (GLuint index, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVARBPROC) (GLuint index, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVARBPROC) (GLuint index, GLenum pname, GLvoid* *pointer);
-typedef GLboolean (APIENTRYP PFNGLISPROGRAMARBPROC) (GLuint program);
-#endif
-
-#ifndef GL_ARB_fragment_program
-#define GL_ARB_fragment_program 1
-/* All ARB_fragment_program entry points are shared with ARB_vertex_program. */
-#endif
-
-#ifndef GL_ARB_vertex_buffer_object
-#define GL_ARB_vertex_buffer_object 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBindBufferARB (GLenum, GLuint);
-GLAPI void APIENTRY glDeleteBuffersARB (GLsizei, const GLuint *);
-GLAPI void APIENTRY glGenBuffersARB (GLsizei, GLuint *);
-GLAPI GLboolean APIENTRY glIsBufferARB (GLuint);
-GLAPI void APIENTRY glBufferDataARB (GLenum, GLsizeiptrARB, const GLvoid *, GLenum);
-GLAPI void APIENTRY glBufferSubDataARB (GLenum, GLintptrARB, GLsizeiptrARB, const GLvoid *);
-GLAPI void APIENTRY glGetBufferSubDataARB (GLenum, GLintptrARB, GLsizeiptrARB, GLvoid *);
-GLAPI GLvoid* APIENTRY glMapBufferARB (GLenum, GLenum);
-GLAPI GLboolean APIENTRY glUnmapBufferARB (GLenum);
-GLAPI void APIENTRY glGetBufferParameterivARB (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetBufferPointervARB (GLenum, GLenum, GLvoid* *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer);
-typedef void (APIENTRYP PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers);
-typedef void (APIENTRYP PFNGLGENBUFFERSARBPROC) (GLsizei n, GLuint *buffers);
-typedef GLboolean (APIENTRYP PFNGLISBUFFERARBPROC) (GLuint buffer);
-typedef void (APIENTRYP PFNGLBUFFERDATAARBPROC) (GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage);
-typedef void (APIENTRYP PFNGLBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data);
-typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data);
-typedef GLvoid* (APIENTRYP PFNGLMAPBUFFERARBPROC) (GLenum target, GLenum access);
-typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERARBPROC) (GLenum target);
-typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVARBPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVARBPROC) (GLenum target, GLenum pname, GLvoid* *params);
-#endif
-
-#ifndef GL_ARB_occlusion_query
-#define GL_ARB_occlusion_query 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glGenQueriesARB (GLsizei, GLuint *);
-GLAPI void APIENTRY glDeleteQueriesARB (GLsizei, const GLuint *);
-GLAPI GLboolean APIENTRY glIsQueryARB (GLuint);
-GLAPI void APIENTRY glBeginQueryARB (GLenum, GLuint);
-GLAPI void APIENTRY glEndQueryARB (GLenum);
-GLAPI void APIENTRY glGetQueryivARB (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetQueryObjectivARB (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetQueryObjectuivARB (GLuint, GLenum, GLuint *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLGENQUERIESARBPROC) (GLsizei n, GLuint *ids);
-typedef void (APIENTRYP PFNGLDELETEQUERIESARBPROC) (GLsizei n, const GLuint *ids);
-typedef GLboolean (APIENTRYP PFNGLISQUERYARBPROC) (GLuint id);
-typedef void (APIENTRYP PFNGLBEGINQUERYARBPROC) (GLenum target, GLuint id);
-typedef void (APIENTRYP PFNGLENDQUERYARBPROC) (GLenum target);
-typedef void (APIENTRYP PFNGLGETQUERYIVARBPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVARBPROC) (GLuint id, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVARBPROC) (GLuint id, GLenum pname, GLuint *params);
-#endif
-
-#ifndef GL_ARB_shader_objects
-#define GL_ARB_shader_objects 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glDeleteObjectARB (GLhandleARB);
-GLAPI GLhandleARB APIENTRY glGetHandleARB (GLenum);
-GLAPI void APIENTRY glDetachObjectARB (GLhandleARB, GLhandleARB);
-GLAPI GLhandleARB APIENTRY glCreateShaderObjectARB (GLenum);
-GLAPI void APIENTRY glShaderSourceARB (GLhandleARB, GLsizei, const GLcharARB* *, const GLint *);
-GLAPI void APIENTRY glCompileShaderARB (GLhandleARB);
-GLAPI GLhandleARB APIENTRY glCreateProgramObjectARB (void);
-GLAPI void APIENTRY glAttachObjectARB (GLhandleARB, GLhandleARB);
-GLAPI void APIENTRY glLinkProgramARB (GLhandleARB);
-GLAPI void APIENTRY glUseProgramObjectARB (GLhandleARB);
-GLAPI void APIENTRY glValidateProgramARB (GLhandleARB);
-GLAPI void APIENTRY glUniform1fARB (GLint, GLfloat);
-GLAPI void APIENTRY glUniform2fARB (GLint, GLfloat, GLfloat);
-GLAPI void APIENTRY glUniform3fARB (GLint, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glUniform4fARB (GLint, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glUniform1iARB (GLint, GLint);
-GLAPI void APIENTRY glUniform2iARB (GLint, GLint, GLint);
-GLAPI void APIENTRY glUniform3iARB (GLint, GLint, GLint, GLint);
-GLAPI void APIENTRY glUniform4iARB (GLint, GLint, GLint, GLint, GLint);
-GLAPI void APIENTRY glUniform1fvARB (GLint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glUniform2fvARB (GLint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glUniform3fvARB (GLint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glUniform4fvARB (GLint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glUniform1ivARB (GLint, GLsizei, const GLint *);
-GLAPI void APIENTRY glUniform2ivARB (GLint, GLsizei, const GLint *);
-GLAPI void APIENTRY glUniform3ivARB (GLint, GLsizei, const GLint *);
-GLAPI void APIENTRY glUniform4ivARB (GLint, GLsizei, const GLint *);
-GLAPI void APIENTRY glUniformMatrix2fvARB (GLint, GLsizei, GLboolean, const GLfloat *);
-GLAPI void APIENTRY glUniformMatrix3fvARB (GLint, GLsizei, GLboolean, const GLfloat *);
-GLAPI void APIENTRY glUniformMatrix4fvARB (GLint, GLsizei, GLboolean, const GLfloat *);
-GLAPI void APIENTRY glGetObjectParameterfvARB (GLhandleARB, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetObjectParameterivARB (GLhandleARB, GLenum, GLint *);
-GLAPI void APIENTRY glGetInfoLogARB (GLhandleARB, GLsizei, GLsizei *, GLcharARB *);
-GLAPI void APIENTRY glGetAttachedObjectsARB (GLhandleARB, GLsizei, GLsizei *, GLhandleARB *);
-GLAPI GLint APIENTRY glGetUniformLocationARB (GLhandleARB, const GLcharARB *);
-GLAPI void APIENTRY glGetActiveUniformARB (GLhandleARB, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLcharARB *);
-GLAPI void APIENTRY glGetUniformfvARB (GLhandleARB, GLint, GLfloat *);
-GLAPI void APIENTRY glGetUniformivARB (GLhandleARB, GLint, GLint *);
-GLAPI void APIENTRY glGetShaderSourceARB (GLhandleARB, GLsizei, GLsizei *, GLcharARB *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLDELETEOBJECTARBPROC) (GLhandleARB obj);
-typedef GLhandleARB (APIENTRYP PFNGLGETHANDLEARBPROC) (GLenum pname);
-typedef void (APIENTRYP PFNGLDETACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB attachedObj);
-typedef GLhandleARB (APIENTRYP PFNGLCREATESHADEROBJECTARBPROC) (GLenum shaderType);
-typedef void (APIENTRYP PFNGLSHADERSOURCEARBPROC) (GLhandleARB shaderObj, GLsizei count, const GLcharARB* *string, const GLint *length);
-typedef void (APIENTRYP PFNGLCOMPILESHADERARBPROC) (GLhandleARB shaderObj);
-typedef GLhandleARB (APIENTRYP PFNGLCREATEPROGRAMOBJECTARBPROC) (void);
-typedef void (APIENTRYP PFNGLATTACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB obj);
-typedef void (APIENTRYP PFNGLLINKPROGRAMARBPROC) (GLhandleARB programObj);
-typedef void (APIENTRYP PFNGLUSEPROGRAMOBJECTARBPROC) (GLhandleARB programObj);
-typedef void (APIENTRYP PFNGLVALIDATEPROGRAMARBPROC) (GLhandleARB programObj);
-typedef void (APIENTRYP PFNGLUNIFORM1FARBPROC) (GLint location, GLfloat v0);
-typedef void (APIENTRYP PFNGLUNIFORM2FARBPROC) (GLint location, GLfloat v0, GLfloat v1);
-typedef void (APIENTRYP PFNGLUNIFORM3FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
-typedef void (APIENTRYP PFNGLUNIFORM4FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
-typedef void (APIENTRYP PFNGLUNIFORM1IARBPROC) (GLint location, GLint v0);
-typedef void (APIENTRYP PFNGLUNIFORM2IARBPROC) (GLint location, GLint v0, GLint v1);
-typedef void (APIENTRYP PFNGLUNIFORM3IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2);
-typedef void (APIENTRYP PFNGLUNIFORM4IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
-typedef void (APIENTRYP PFNGLUNIFORM1FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORM2FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORM3FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORM4FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORM1IVARBPROC) (GLint location, GLsizei count, const GLint *value);
-typedef void (APIENTRYP PFNGLUNIFORM2IVARBPROC) (GLint location, GLsizei count, const GLint *value);
-typedef void (APIENTRYP PFNGLUNIFORM3IVARBPROC) (GLint location, GLsizei count, const GLint *value);
-typedef void (APIENTRYP PFNGLUNIFORM4IVARBPROC) (GLint location, GLsizei count, const GLint *value);
-typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
-typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERFVARBPROC) (GLhandleARB obj, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERIVARBPROC) (GLhandleARB obj, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETINFOLOGARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog);
-typedef void (APIENTRYP PFNGLGETATTACHEDOBJECTSARBPROC) (GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj);
-typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name);
-typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);
-typedef void (APIENTRYP PFNGLGETUNIFORMFVARBPROC) (GLhandleARB programObj, GLint location, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETUNIFORMIVARBPROC) (GLhandleARB programObj, GLint location, GLint *params);
-typedef void (APIENTRYP PFNGLGETSHADERSOURCEARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source);
-#endif
-
-#ifndef GL_ARB_vertex_shader
-#define GL_ARB_vertex_shader 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBindAttribLocationARB (GLhandleARB, GLuint, const GLcharARB *);
-GLAPI void APIENTRY glGetActiveAttribARB (GLhandleARB, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLcharARB *);
-GLAPI GLint APIENTRY glGetAttribLocationARB (GLhandleARB, const GLcharARB *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONARBPROC) (GLhandleARB programObj, GLuint index, const GLcharARB *name);
-typedef void (APIENTRYP PFNGLGETACTIVEATTRIBARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);
-typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name);
-#endif
-
-#ifndef GL_ARB_fragment_shader
-#define GL_ARB_fragment_shader 1
-#endif
-
-#ifndef GL_ARB_shading_language_100
-#define GL_ARB_shading_language_100 1
-#endif
-
-#ifndef GL_ARB_texture_non_power_of_two
-#define GL_ARB_texture_non_power_of_two 1
-#endif
-
-#ifndef GL_ARB_point_sprite
-#define GL_ARB_point_sprite 1
-#endif
-
-#ifndef GL_ARB_fragment_program_shadow
-#define GL_ARB_fragment_program_shadow 1
-#endif
-
-#ifndef GL_ARB_draw_buffers
-#define GL_ARB_draw_buffers 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glDrawBuffersARB (GLsizei, const GLenum *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLDRAWBUFFERSARBPROC) (GLsizei n, const GLenum *bufs);
-#endif
-
-#ifndef GL_ARB_texture_rectangle
-#define GL_ARB_texture_rectangle 1
-#endif
-
-#ifndef GL_ARB_color_buffer_float
-#define GL_ARB_color_buffer_float 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glClampColorARB (GLenum, GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCLAMPCOLORARBPROC) (GLenum target, GLenum clamp);
-#endif
-
-#ifndef GL_ARB_half_float_pixel
-#define GL_ARB_half_float_pixel 1
-#endif
-
-#ifndef GL_ARB_texture_float
-#define GL_ARB_texture_float 1
-#endif
-
-#ifndef GL_ARB_pixel_buffer_object
-#define GL_ARB_pixel_buffer_object 1
-#endif
-
-#ifndef GL_EXT_abgr
-#define GL_EXT_abgr 1
-#endif
-
-#ifndef GL_EXT_blend_color
-#define GL_EXT_blend_color 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBlendColorEXT (GLclampf, GLclampf, GLclampf, GLclampf);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBLENDCOLOREXTPROC) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
-#endif
-
-#ifndef GL_EXT_polygon_offset
-#define GL_EXT_polygon_offset 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPolygonOffsetEXT (GLfloat, GLfloat);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPOLYGONOFFSETEXTPROC) (GLfloat factor, GLfloat bias);
-#endif
-
-#ifndef GL_EXT_texture
-#define GL_EXT_texture 1
-#endif
-
-#ifndef GL_EXT_texture3D
-#define GL_EXT_texture3D 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glTexImage3DEXT (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glTexSubImage3DEXT (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLTEXIMAGE3DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
-typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
-#endif
-
-#ifndef GL_SGIS_texture_filter4
-#define GL_SGIS_texture_filter4 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glGetTexFilterFuncSGIS (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glTexFilterFuncSGIS (GLenum, GLenum, GLsizei, const GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLGETTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLfloat *weights);
-typedef void (APIENTRYP PFNGLTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLsizei n, const GLfloat *weights);
-#endif
-
-#ifndef GL_EXT_subtexture
-#define GL_EXT_subtexture 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glTexSubImage1DEXT (GLenum, GLint, GLint, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glTexSubImage2DEXT (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
-typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
-#endif
-
-#ifndef GL_EXT_copy_texture
-#define GL_EXT_copy_texture 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glCopyTexImage1DEXT (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLint);
-GLAPI void APIENTRY glCopyTexImage2DEXT (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint);
-GLAPI void APIENTRY glCopyTexSubImage1DEXT (GLenum, GLint, GLint, GLint, GLint, GLsizei);
-GLAPI void APIENTRY glCopyTexSubImage2DEXT (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei);
-GLAPI void APIENTRY glCopyTexSubImage3DEXT (GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCOPYTEXIMAGE1DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);
-typedef void (APIENTRYP PFNGLCOPYTEXIMAGE2DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
-typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
-typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
-typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
-#endif
-
-#ifndef GL_EXT_histogram
-#define GL_EXT_histogram 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glGetHistogramEXT (GLenum, GLboolean, GLenum, GLenum, GLvoid *);
-GLAPI void APIENTRY glGetHistogramParameterfvEXT (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetHistogramParameterivEXT (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetMinmaxEXT (GLenum, GLboolean, GLenum, GLenum, GLvoid *);
-GLAPI void APIENTRY glGetMinmaxParameterfvEXT (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetMinmaxParameterivEXT (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glHistogramEXT (GLenum, GLsizei, GLenum, GLboolean);
-GLAPI void APIENTRY glMinmaxEXT (GLenum, GLenum, GLboolean);
-GLAPI void APIENTRY glResetHistogramEXT (GLenum);
-GLAPI void APIENTRY glResetMinmaxEXT (GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLGETHISTOGRAMEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
-typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETMINMAXEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
-typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLHISTOGRAMEXTPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink);
-typedef void (APIENTRYP PFNGLMINMAXEXTPROC) (GLenum target, GLenum internalformat, GLboolean sink);
-typedef void (APIENTRYP PFNGLRESETHISTOGRAMEXTPROC) (GLenum target);
-typedef void (APIENTRYP PFNGLRESETMINMAXEXTPROC) (GLenum target);
-#endif
-
-#ifndef GL_EXT_convolution
-#define GL_EXT_convolution 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glConvolutionFilter1DEXT (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glConvolutionFilter2DEXT (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glConvolutionParameterfEXT (GLenum, GLenum, GLfloat);
-GLAPI void APIENTRY glConvolutionParameterfvEXT (GLenum, GLenum, const GLfloat *);
-GLAPI void APIENTRY glConvolutionParameteriEXT (GLenum, GLenum, GLint);
-GLAPI void APIENTRY glConvolutionParameterivEXT (GLenum, GLenum, const GLint *);
-GLAPI void APIENTRY glCopyConvolutionFilter1DEXT (GLenum, GLenum, GLint, GLint, GLsizei);
-GLAPI void APIENTRY glCopyConvolutionFilter2DEXT (GLenum, GLenum, GLint, GLint, GLsizei, GLsizei);
-GLAPI void APIENTRY glGetConvolutionFilterEXT (GLenum, GLenum, GLenum, GLvoid *);
-GLAPI void APIENTRY glGetConvolutionParameterfvEXT (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetConvolutionParameterivEXT (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetSeparableFilterEXT (GLenum, GLenum, GLenum, GLvoid *, GLvoid *, GLvoid *);
-GLAPI void APIENTRY glSeparableFilter2DEXT (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image);
-typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image);
-typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat params);
-typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint params);
-typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
-typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height);
-typedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *image);
-typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETSEPARABLEFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span);
-typedef void (APIENTRYP PFNGLSEPARABLEFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column);
-#endif
-
-#ifndef GL_EXT_color_matrix
-#define GL_EXT_color_matrix 1
-#endif
-
-#ifndef GL_SGI_color_table
-#define GL_SGI_color_table 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glColorTableSGI (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glColorTableParameterfvSGI (GLenum, GLenum, const GLfloat *);
-GLAPI void APIENTRY glColorTableParameterivSGI (GLenum, GLenum, const GLint *);
-GLAPI void APIENTRY glCopyColorTableSGI (GLenum, GLenum, GLint, GLint, GLsizei);
-GLAPI void APIENTRY glGetColorTableSGI (GLenum, GLenum, GLenum, GLvoid *);
-GLAPI void APIENTRY glGetColorTableParameterfvSGI (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetColorTableParameterivSGI (GLenum, GLenum, GLint *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
-typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLCOPYCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
-typedef void (APIENTRYP PFNGLGETCOLORTABLESGIPROC) (GLenum target, GLenum format, GLenum type, GLvoid *table);
-typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, GLint *params);
-#endif
-
-#ifndef GL_SGIX_pixel_texture
-#define GL_SGIX_pixel_texture 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPixelTexGenSGIX (GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPIXELTEXGENSGIXPROC) (GLenum mode);
-#endif
-
-#ifndef GL_SGIS_pixel_texture
-#define GL_SGIS_pixel_texture 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPixelTexGenParameteriSGIS (GLenum, GLint);
-GLAPI void APIENTRY glPixelTexGenParameterivSGIS (GLenum, const GLint *);
-GLAPI void APIENTRY glPixelTexGenParameterfSGIS (GLenum, GLfloat);
-GLAPI void APIENTRY glPixelTexGenParameterfvSGIS (GLenum, const GLfloat *);
-GLAPI void APIENTRY glGetPixelTexGenParameterivSGIS (GLenum, GLint *);
-GLAPI void APIENTRY glGetPixelTexGenParameterfvSGIS (GLenum, GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERISGISPROC) (GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFSGISPROC) (GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, GLfloat *params);
-#endif
-
-#ifndef GL_SGIS_texture4D
-#define GL_SGIS_texture4D 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glTexImage4DSGIS (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glTexSubImage4DSGIS (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLTEXIMAGE4DSGISPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
-typedef void (APIENTRYP PFNGLTEXSUBIMAGE4DSGISPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint woffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLenum format, GLenum type, const GLvoid *pixels);
-#endif
-
-#ifndef GL_SGI_texture_color_table
-#define GL_SGI_texture_color_table 1
-#endif
-
-#ifndef GL_EXT_cmyka
-#define GL_EXT_cmyka 1
-#endif
-
-#ifndef GL_EXT_texture_object
-#define GL_EXT_texture_object 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI GLboolean APIENTRY glAreTexturesResidentEXT (GLsizei, const GLuint *, GLboolean *);
-GLAPI void APIENTRY glBindTextureEXT (GLenum, GLuint);
-GLAPI void APIENTRY glDeleteTexturesEXT (GLsizei, const GLuint *);
-GLAPI void APIENTRY glGenTexturesEXT (GLsizei, GLuint *);
-GLAPI GLboolean APIENTRY glIsTextureEXT (GLuint);
-GLAPI void APIENTRY glPrioritizeTexturesEXT (GLsizei, const GLuint *, const GLclampf *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef GLboolean (APIENTRYP PFNGLARETEXTURESRESIDENTEXTPROC) (GLsizei n, const GLuint *textures, GLboolean *residences);
-typedef void (APIENTRYP PFNGLBINDTEXTUREEXTPROC) (GLenum target, GLuint texture);
-typedef void (APIENTRYP PFNGLDELETETEXTURESEXTPROC) (GLsizei n, const GLuint *textures);
-typedef void (APIENTRYP PFNGLGENTEXTURESEXTPROC) (GLsizei n, GLuint *textures);
-typedef GLboolean (APIENTRYP PFNGLISTEXTUREEXTPROC) (GLuint texture);
-typedef void (APIENTRYP PFNGLPRIORITIZETEXTURESEXTPROC) (GLsizei n, const GLuint *textures, const GLclampf *priorities);
-#endif
-
-#ifndef GL_SGIS_detail_texture
-#define GL_SGIS_detail_texture 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glDetailTexFuncSGIS (GLenum, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glGetDetailTexFuncSGIS (GLenum, GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLDETAILTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points);
-typedef void (APIENTRYP PFNGLGETDETAILTEXFUNCSGISPROC) (GLenum target, GLfloat *points);
-#endif
-
-#ifndef GL_SGIS_sharpen_texture
-#define GL_SGIS_sharpen_texture 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glSharpenTexFuncSGIS (GLenum, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glGetSharpenTexFuncSGIS (GLenum, GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLSHARPENTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points);
-typedef void (APIENTRYP PFNGLGETSHARPENTEXFUNCSGISPROC) (GLenum target, GLfloat *points);
-#endif
-
-#ifndef GL_EXT_packed_pixels
-#define GL_EXT_packed_pixels 1
-#endif
-
-#ifndef GL_SGIS_texture_lod
-#define GL_SGIS_texture_lod 1
-#endif
-
-#ifndef GL_SGIS_multisample
-#define GL_SGIS_multisample 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glSampleMaskSGIS (GLclampf, GLboolean);
-GLAPI void APIENTRY glSamplePatternSGIS (GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLSAMPLEMASKSGISPROC) (GLclampf value, GLboolean invert);
-typedef void (APIENTRYP PFNGLSAMPLEPATTERNSGISPROC) (GLenum pattern);
-#endif
-
-#ifndef GL_EXT_rescale_normal
-#define GL_EXT_rescale_normal 1
-#endif
-
-#ifndef GL_EXT_vertex_array
-#define GL_EXT_vertex_array 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glArrayElementEXT (GLint);
-GLAPI void APIENTRY glColorPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glDrawArraysEXT (GLenum, GLint, GLsizei);
-GLAPI void APIENTRY glEdgeFlagPointerEXT (GLsizei, GLsizei, const GLboolean *);
-GLAPI void APIENTRY glGetPointervEXT (GLenum, GLvoid* *);
-GLAPI void APIENTRY glIndexPointerEXT (GLenum, GLsizei, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glNormalPointerEXT (GLenum, GLsizei, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glTexCoordPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glVertexPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLARRAYELEMENTEXTPROC) (GLint i);
-typedef void (APIENTRYP PFNGLCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLDRAWARRAYSEXTPROC) (GLenum mode, GLint first, GLsizei count);
-typedef void (APIENTRYP PFNGLEDGEFLAGPOINTEREXTPROC) (GLsizei stride, GLsizei count, const GLboolean *pointer);
-typedef void (APIENTRYP PFNGLGETPOINTERVEXTPROC) (GLenum pname, GLvoid* *params);
-typedef void (APIENTRYP PFNGLINDEXPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLNORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLTEXCOORDPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLVERTEXPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
-#endif
-
-#ifndef GL_EXT_misc_attribute
-#define GL_EXT_misc_attribute 1
-#endif
-
-#ifndef GL_SGIS_generate_mipmap
-#define GL_SGIS_generate_mipmap 1
-#endif
-
-#ifndef GL_SGIX_clipmap
-#define GL_SGIX_clipmap 1
-#endif
-
-#ifndef GL_SGIX_shadow
-#define GL_SGIX_shadow 1
-#endif
-
-#ifndef GL_SGIS_texture_edge_clamp
-#define GL_SGIS_texture_edge_clamp 1
-#endif
-
-#ifndef GL_SGIS_texture_border_clamp
-#define GL_SGIS_texture_border_clamp 1
-#endif
-
-#ifndef GL_EXT_blend_minmax
-#define GL_EXT_blend_minmax 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBlendEquationEXT (GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBLENDEQUATIONEXTPROC) (GLenum mode);
-#endif
-
-#ifndef GL_EXT_blend_subtract
-#define GL_EXT_blend_subtract 1
-#endif
-
-#ifndef GL_EXT_blend_logic_op
-#define GL_EXT_blend_logic_op 1
-#endif
-
-#ifndef GL_SGIX_interlace
-#define GL_SGIX_interlace 1
-#endif
-
-#ifndef GL_SGIX_pixel_tiles
-#define GL_SGIX_pixel_tiles 1
-#endif
-
-#ifndef GL_SGIX_texture_select
-#define GL_SGIX_texture_select 1
-#endif
-
-#ifndef GL_SGIX_sprite
-#define GL_SGIX_sprite 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glSpriteParameterfSGIX (GLenum, GLfloat);
-GLAPI void APIENTRY glSpriteParameterfvSGIX (GLenum, const GLfloat *);
-GLAPI void APIENTRY glSpriteParameteriSGIX (GLenum, GLint);
-GLAPI void APIENTRY glSpriteParameterivSGIX (GLenum, const GLint *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLSPRITEPARAMETERFSGIXPROC) (GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLSPRITEPARAMETERFVSGIXPROC) (GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLSPRITEPARAMETERISGIXPROC) (GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLSPRITEPARAMETERIVSGIXPROC) (GLenum pname, const GLint *params);
-#endif
-
-#ifndef GL_SGIX_texture_multi_buffer
-#define GL_SGIX_texture_multi_buffer 1
-#endif
-
-#ifndef GL_EXT_point_parameters
-#define GL_EXT_point_parameters 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPointParameterfEXT (GLenum, GLfloat);
-GLAPI void APIENTRY glPointParameterfvEXT (GLenum, const GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPOINTPARAMETERFEXTPROC) (GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLPOINTPARAMETERFVEXTPROC) (GLenum pname, const GLfloat *params);
-#endif
-
-#ifndef GL_SGIS_point_parameters
-#define GL_SGIS_point_parameters 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPointParameterfSGIS (GLenum, GLfloat);
-GLAPI void APIENTRY glPointParameterfvSGIS (GLenum, const GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPOINTPARAMETERFSGISPROC) (GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLPOINTPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params);
-#endif
-
-#ifndef GL_SGIX_instruments
-#define GL_SGIX_instruments 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI GLint APIENTRY glGetInstrumentsSGIX (void);
-GLAPI void APIENTRY glInstrumentsBufferSGIX (GLsizei, GLint *);
-GLAPI GLint APIENTRY glPollInstrumentsSGIX (GLint *);
-GLAPI void APIENTRY glReadInstrumentsSGIX (GLint);
-GLAPI void APIENTRY glStartInstrumentsSGIX (void);
-GLAPI void APIENTRY glStopInstrumentsSGIX (GLint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef GLint (APIENTRYP PFNGLGETINSTRUMENTSSGIXPROC) (void);
-typedef void (APIENTRYP PFNGLINSTRUMENTSBUFFERSGIXPROC) (GLsizei size, GLint *buffer);
-typedef GLint (APIENTRYP PFNGLPOLLINSTRUMENTSSGIXPROC) (GLint *marker_p);
-typedef void (APIENTRYP PFNGLREADINSTRUMENTSSGIXPROC) (GLint marker);
-typedef void (APIENTRYP PFNGLSTARTINSTRUMENTSSGIXPROC) (void);
-typedef void (APIENTRYP PFNGLSTOPINSTRUMENTSSGIXPROC) (GLint marker);
-#endif
-
-#ifndef GL_SGIX_texture_scale_bias
-#define GL_SGIX_texture_scale_bias 1
-#endif
-
-#ifndef GL_SGIX_framezoom
-#define GL_SGIX_framezoom 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glFrameZoomSGIX (GLint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLFRAMEZOOMSGIXPROC) (GLint factor);
-#endif
-
-#ifndef GL_SGIX_tag_sample_buffer
-#define GL_SGIX_tag_sample_buffer 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glTagSampleBufferSGIX (void);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLTAGSAMPLEBUFFERSGIXPROC) (void);
-#endif
-
-#ifndef GL_SGIX_polynomial_ffd
-#define GL_SGIX_polynomial_ffd 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glDeformationMap3dSGIX (GLenum, GLdouble, GLdouble, GLint, GLint, GLdouble, GLdouble, GLint, GLint, GLdouble, GLdouble, GLint, GLint, const GLdouble *);
-GLAPI void APIENTRY glDeformationMap3fSGIX (GLenum, GLfloat, GLfloat, GLint, GLint, GLfloat, GLfloat, GLint, GLint, GLfloat, GLfloat, GLint, GLint, const GLfloat *);
-GLAPI void APIENTRY glDeformSGIX (GLbitfield);
-GLAPI void APIENTRY glLoadIdentityDeformationMapSGIX (GLbitfield);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLDEFORMATIONMAP3DSGIXPROC) (GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, GLdouble w1, GLdouble w2, GLint wstride, GLint worder, const GLdouble *points);
-typedef void (APIENTRYP PFNGLDEFORMATIONMAP3FSGIXPROC) (GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, GLfloat w1, GLfloat w2, GLint wstride, GLint worder, const GLfloat *points);
-typedef void (APIENTRYP PFNGLDEFORMSGIXPROC) (GLbitfield mask);
-typedef void (APIENTRYP PFNGLLOADIDENTITYDEFORMATIONMAPSGIXPROC) (GLbitfield mask);
-#endif
-
-#ifndef GL_SGIX_reference_plane
-#define GL_SGIX_reference_plane 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glReferencePlaneSGIX (const GLdouble *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLREFERENCEPLANESGIXPROC) (const GLdouble *equation);
-#endif
-
-#ifndef GL_SGIX_flush_raster
-#define GL_SGIX_flush_raster 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glFlushRasterSGIX (void);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLFLUSHRASTERSGIXPROC) (void);
-#endif
-
-#ifndef GL_SGIX_depth_texture
-#define GL_SGIX_depth_texture 1
-#endif
-
-#ifndef GL_SGIS_fog_function
-#define GL_SGIS_fog_function 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glFogFuncSGIS (GLsizei, const GLfloat *);
-GLAPI void APIENTRY glGetFogFuncSGIS (GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLFOGFUNCSGISPROC) (GLsizei n, const GLfloat *points);
-typedef void (APIENTRYP PFNGLGETFOGFUNCSGISPROC) (GLfloat *points);
-#endif
-
-#ifndef GL_SGIX_fog_offset
-#define GL_SGIX_fog_offset 1
-#endif
-
-#ifndef GL_HP_image_transform
-#define GL_HP_image_transform 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glImageTransformParameteriHP (GLenum, GLenum, GLint);
-GLAPI void APIENTRY glImageTransformParameterfHP (GLenum, GLenum, GLfloat);
-GLAPI void APIENTRY glImageTransformParameterivHP (GLenum, GLenum, const GLint *);
-GLAPI void APIENTRY glImageTransformParameterfvHP (GLenum, GLenum, const GLfloat *);
-GLAPI void APIENTRY glGetImageTransformParameterivHP (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetImageTransformParameterfvHP (GLenum, GLenum, GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIHPPROC) (GLenum target, GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFHPPROC) (GLenum target, GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, GLfloat *params);
-#endif
-
-#ifndef GL_HP_convolution_border_modes
-#define GL_HP_convolution_border_modes 1
-#endif
-
-#ifndef GL_SGIX_texture_add_env
-#define GL_SGIX_texture_add_env 1
-#endif
-
-#ifndef GL_EXT_color_subtable
-#define GL_EXT_color_subtable 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glColorSubTableEXT (GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glCopyColorSubTableEXT (GLenum, GLsizei, GLint, GLint, GLsizei);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width);
-#endif
-
-#ifndef GL_PGI_vertex_hints
-#define GL_PGI_vertex_hints 1
-#endif
-
-#ifndef GL_PGI_misc_hints
-#define GL_PGI_misc_hints 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glHintPGI (GLenum, GLint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLHINTPGIPROC) (GLenum target, GLint mode);
-#endif
-
-#ifndef GL_EXT_paletted_texture
-#define GL_EXT_paletted_texture 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glColorTableEXT (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glGetColorTableEXT (GLenum, GLenum, GLenum, GLvoid *);
-GLAPI void APIENTRY glGetColorTableParameterivEXT (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetColorTableParameterfvEXT (GLenum, GLenum, GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCOLORTABLEEXTPROC) (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
-typedef void (APIENTRYP PFNGLGETCOLORTABLEEXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *data);
-typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);
-#endif
-
-#ifndef GL_EXT_clip_volume_hint
-#define GL_EXT_clip_volume_hint 1
-#endif
-
-#ifndef GL_SGIX_list_priority
-#define GL_SGIX_list_priority 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glGetListParameterfvSGIX (GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetListParameterivSGIX (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glListParameterfSGIX (GLuint, GLenum, GLfloat);
-GLAPI void APIENTRY glListParameterfvSGIX (GLuint, GLenum, const GLfloat *);
-GLAPI void APIENTRY glListParameteriSGIX (GLuint, GLenum, GLint);
-GLAPI void APIENTRY glListParameterivSGIX (GLuint, GLenum, const GLint *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLGETLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLLISTPARAMETERFSGIXPROC) (GLuint list, GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLLISTPARAMETERISGIXPROC) (GLuint list, GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, const GLint *params);
-#endif
-
-#ifndef GL_SGIX_ir_instrument1
-#define GL_SGIX_ir_instrument1 1
-#endif
-
-#ifndef GL_SGIX_calligraphic_fragment
-#define GL_SGIX_calligraphic_fragment 1
-#endif
-
-#ifndef GL_SGIX_texture_lod_bias
-#define GL_SGIX_texture_lod_bias 1
-#endif
-
-#ifndef GL_SGIX_shadow_ambient
-#define GL_SGIX_shadow_ambient 1
-#endif
-
-#ifndef GL_EXT_index_texture
-#define GL_EXT_index_texture 1
-#endif
-
-#ifndef GL_EXT_index_material
-#define GL_EXT_index_material 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glIndexMaterialEXT (GLenum, GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLINDEXMATERIALEXTPROC) (GLenum face, GLenum mode);
-#endif
-
-#ifndef GL_EXT_index_func
-#define GL_EXT_index_func 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glIndexFuncEXT (GLenum, GLclampf);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLINDEXFUNCEXTPROC) (GLenum func, GLclampf ref);
-#endif
-
-#ifndef GL_EXT_index_array_formats
-#define GL_EXT_index_array_formats 1
-#endif
-
-#ifndef GL_EXT_compiled_vertex_array
-#define GL_EXT_compiled_vertex_array 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glLockArraysEXT (GLint, GLsizei);
-GLAPI void APIENTRY glUnlockArraysEXT (void);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLLOCKARRAYSEXTPROC) (GLint first, GLsizei count);
-typedef void (APIENTRYP PFNGLUNLOCKARRAYSEXTPROC) (void);
-#endif
-
-#ifndef GL_EXT_cull_vertex
-#define GL_EXT_cull_vertex 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glCullParameterdvEXT (GLenum, GLdouble *);
-GLAPI void APIENTRY glCullParameterfvEXT (GLenum, GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCULLPARAMETERDVEXTPROC) (GLenum pname, GLdouble *params);
-typedef void (APIENTRYP PFNGLCULLPARAMETERFVEXTPROC) (GLenum pname, GLfloat *params);
-#endif
-
-#ifndef GL_SGIX_ycrcb
-#define GL_SGIX_ycrcb 1
-#endif
-
-#ifndef GL_SGIX_fragment_lighting
-#define GL_SGIX_fragment_lighting 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glFragmentColorMaterialSGIX (GLenum, GLenum);
-GLAPI void APIENTRY glFragmentLightfSGIX (GLenum, GLenum, GLfloat);
-GLAPI void APIENTRY glFragmentLightfvSGIX (GLenum, GLenum, const GLfloat *);
-GLAPI void APIENTRY glFragmentLightiSGIX (GLenum, GLenum, GLint);
-GLAPI void APIENTRY glFragmentLightivSGIX (GLenum, GLenum, const GLint *);
-GLAPI void APIENTRY glFragmentLightModelfSGIX (GLenum, GLfloat);
-GLAPI void APIENTRY glFragmentLightModelfvSGIX (GLenum, const GLfloat *);
-GLAPI void APIENTRY glFragmentLightModeliSGIX (GLenum, GLint);
-GLAPI void APIENTRY glFragmentLightModelivSGIX (GLenum, const GLint *);
-GLAPI void APIENTRY glFragmentMaterialfSGIX (GLenum, GLenum, GLfloat);
-GLAPI void APIENTRY glFragmentMaterialfvSGIX (GLenum, GLenum, const GLfloat *);
-GLAPI void APIENTRY glFragmentMaterialiSGIX (GLenum, GLenum, GLint);
-GLAPI void APIENTRY glFragmentMaterialivSGIX (GLenum, GLenum, const GLint *);
-GLAPI void APIENTRY glGetFragmentLightfvSGIX (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetFragmentLightivSGIX (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetFragmentMaterialfvSGIX (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetFragmentMaterialivSGIX (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glLightEnviSGIX (GLenum, GLint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLFRAGMENTCOLORMATERIALSGIXPROC) (GLenum face, GLenum mode);
-typedef void (APIENTRYP PFNGLFRAGMENTLIGHTFSGIXPROC) (GLenum light, GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLFRAGMENTLIGHTISGIXPROC) (GLenum light, GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFSGIXPROC) (GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFVSGIXPROC) (GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELISGIXPROC) (GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELIVSGIXPROC) (GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLFRAGMENTMATERIALFSGIXPROC) (GLenum face, GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLFRAGMENTMATERIALISGIXPROC) (GLenum face, GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLLIGHTENVISGIXPROC) (GLenum pname, GLint param);
-#endif
-
-#ifndef GL_IBM_rasterpos_clip
-#define GL_IBM_rasterpos_clip 1
-#endif
-
-#ifndef GL_HP_texture_lighting
-#define GL_HP_texture_lighting 1
-#endif
-
-#ifndef GL_EXT_draw_range_elements
-#define GL_EXT_draw_range_elements 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glDrawRangeElementsEXT (GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSEXTPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices);
-#endif
-
-#ifndef GL_WIN_phong_shading
-#define GL_WIN_phong_shading 1
-#endif
-
-#ifndef GL_WIN_specular_fog
-#define GL_WIN_specular_fog 1
-#endif
-
-#ifndef GL_EXT_light_texture
-#define GL_EXT_light_texture 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glApplyTextureEXT (GLenum);
-GLAPI void APIENTRY glTextureLightEXT (GLenum);
-GLAPI void APIENTRY glTextureMaterialEXT (GLenum, GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLAPPLYTEXTUREEXTPROC) (GLenum mode);
-typedef void (APIENTRYP PFNGLTEXTURELIGHTEXTPROC) (GLenum pname);
-typedef void (APIENTRYP PFNGLTEXTUREMATERIALEXTPROC) (GLenum face, GLenum mode);
-#endif
-
-#ifndef GL_SGIX_blend_alpha_minmax
-#define GL_SGIX_blend_alpha_minmax 1
-#endif
-
-#ifndef GL_EXT_bgra
-#define GL_EXT_bgra 1
-#endif
-
-#ifndef GL_SGIX_async
-#define GL_SGIX_async 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glAsyncMarkerSGIX (GLuint);
-GLAPI GLint APIENTRY glFinishAsyncSGIX (GLuint *);
-GLAPI GLint APIENTRY glPollAsyncSGIX (GLuint *);
-GLAPI GLuint APIENTRY glGenAsyncMarkersSGIX (GLsizei);
-GLAPI void APIENTRY glDeleteAsyncMarkersSGIX (GLuint, GLsizei);
-GLAPI GLboolean APIENTRY glIsAsyncMarkerSGIX (GLuint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLASYNCMARKERSGIXPROC) (GLuint marker);
-typedef GLint (APIENTRYP PFNGLFINISHASYNCSGIXPROC) (GLuint *markerp);
-typedef GLint (APIENTRYP PFNGLPOLLASYNCSGIXPROC) (GLuint *markerp);
-typedef GLuint (APIENTRYP PFNGLGENASYNCMARKERSSGIXPROC) (GLsizei range);
-typedef void (APIENTRYP PFNGLDELETEASYNCMARKERSSGIXPROC) (GLuint marker, GLsizei range);
-typedef GLboolean (APIENTRYP PFNGLISASYNCMARKERSGIXPROC) (GLuint marker);
-#endif
-
-#ifndef GL_SGIX_async_pixel
-#define GL_SGIX_async_pixel 1
-#endif
-
-#ifndef GL_SGIX_async_histogram
-#define GL_SGIX_async_histogram 1
-#endif
-
-#ifndef GL_INTEL_parallel_arrays
-#define GL_INTEL_parallel_arrays 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glVertexPointervINTEL (GLint, GLenum, const GLvoid* *);
-GLAPI void APIENTRY glNormalPointervINTEL (GLenum, const GLvoid* *);
-GLAPI void APIENTRY glColorPointervINTEL (GLint, GLenum, const GLvoid* *);
-GLAPI void APIENTRY glTexCoordPointervINTEL (GLint, GLenum, const GLvoid* *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLVERTEXPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer);
-typedef void (APIENTRYP PFNGLNORMALPOINTERVINTELPROC) (GLenum type, const GLvoid* *pointer);
-typedef void (APIENTRYP PFNGLCOLORPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer);
-typedef void (APIENTRYP PFNGLTEXCOORDPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer);
-#endif
-
-#ifndef GL_HP_occlusion_test
-#define GL_HP_occlusion_test 1
-#endif
-
-#ifndef GL_EXT_pixel_transform
-#define GL_EXT_pixel_transform 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPixelTransformParameteriEXT (GLenum, GLenum, GLint);
-GLAPI void APIENTRY glPixelTransformParameterfEXT (GLenum, GLenum, GLfloat);
-GLAPI void APIENTRY glPixelTransformParameterivEXT (GLenum, GLenum, const GLint *);
-GLAPI void APIENTRY glPixelTransformParameterfvEXT (GLenum, GLenum, const GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params);
-#endif
-
-#ifndef GL_EXT_pixel_transform_color_table
-#define GL_EXT_pixel_transform_color_table 1
-#endif
-
-#ifndef GL_EXT_shared_texture_palette
-#define GL_EXT_shared_texture_palette 1
-#endif
-
-#ifndef GL_EXT_separate_specular_color
-#define GL_EXT_separate_specular_color 1
-#endif
-
-#ifndef GL_EXT_secondary_color
-#define GL_EXT_secondary_color 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glSecondaryColor3bEXT (GLbyte, GLbyte, GLbyte);
-GLAPI void APIENTRY glSecondaryColor3bvEXT (const GLbyte *);
-GLAPI void APIENTRY glSecondaryColor3dEXT (GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glSecondaryColor3dvEXT (const GLdouble *);
-GLAPI void APIENTRY glSecondaryColor3fEXT (GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glSecondaryColor3fvEXT (const GLfloat *);
-GLAPI void APIENTRY glSecondaryColor3iEXT (GLint, GLint, GLint);
-GLAPI void APIENTRY glSecondaryColor3ivEXT (const GLint *);
-GLAPI void APIENTRY glSecondaryColor3sEXT (GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glSecondaryColor3svEXT (const GLshort *);
-GLAPI void APIENTRY glSecondaryColor3ubEXT (GLubyte, GLubyte, GLubyte);
-GLAPI void APIENTRY glSecondaryColor3ubvEXT (const GLubyte *);
-GLAPI void APIENTRY glSecondaryColor3uiEXT (GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glSecondaryColor3uivEXT (const GLuint *);
-GLAPI void APIENTRY glSecondaryColor3usEXT (GLushort, GLushort, GLushort);
-GLAPI void APIENTRY glSecondaryColor3usvEXT (const GLushort *);
-GLAPI void APIENTRY glSecondaryColorPointerEXT (GLint, GLenum, GLsizei, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BEXTPROC) (GLbyte red, GLbyte green, GLbyte blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVEXTPROC) (const GLbyte *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DEXTPROC) (GLdouble red, GLdouble green, GLdouble blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVEXTPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FEXTPROC) (GLfloat red, GLfloat green, GLfloat blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVEXTPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IEXTPROC) (GLint red, GLint green, GLint blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVEXTPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SEXTPROC) (GLshort red, GLshort green, GLshort blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVEXTPROC) (const GLshort *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBEXTPROC) (GLubyte red, GLubyte green, GLubyte blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVEXTPROC) (const GLubyte *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIEXTPROC) (GLuint red, GLuint green, GLuint blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVEXTPROC) (const GLuint *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USEXTPROC) (GLushort red, GLushort green, GLushort blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVEXTPROC) (const GLushort *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
-#endif
-
-#ifndef GL_EXT_texture_perturb_normal
-#define GL_EXT_texture_perturb_normal 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glTextureNormalEXT (GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLTEXTURENORMALEXTPROC) (GLenum mode);
-#endif
-
-#ifndef GL_EXT_multi_draw_arrays
-#define GL_EXT_multi_draw_arrays 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glMultiDrawArraysEXT (GLenum, GLint *, GLsizei *, GLsizei);
-GLAPI void APIENTRY glMultiDrawElementsEXT (GLenum, const GLsizei *, GLenum, const GLvoid* *, GLsizei);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSEXTPROC) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount);
-typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount);
-#endif
-
-#ifndef GL_EXT_fog_coord
-#define GL_EXT_fog_coord 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glFogCoordfEXT (GLfloat);
-GLAPI void APIENTRY glFogCoordfvEXT (const GLfloat *);
-GLAPI void APIENTRY glFogCoorddEXT (GLdouble);
-GLAPI void APIENTRY glFogCoorddvEXT (const GLdouble *);
-GLAPI void APIENTRY glFogCoordPointerEXT (GLenum, GLsizei, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLFOGCOORDFEXTPROC) (GLfloat coord);
-typedef void (APIENTRYP PFNGLFOGCOORDFVEXTPROC) (const GLfloat *coord);
-typedef void (APIENTRYP PFNGLFOGCOORDDEXTPROC) (GLdouble coord);
-typedef void (APIENTRYP PFNGLFOGCOORDDVEXTPROC) (const GLdouble *coord);
-typedef void (APIENTRYP PFNGLFOGCOORDPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer);
-#endif
-
-#ifndef GL_REND_screen_coordinates
-#define GL_REND_screen_coordinates 1
-#endif
-
-#ifndef GL_EXT_coordinate_frame
-#define GL_EXT_coordinate_frame 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glTangent3bEXT (GLbyte, GLbyte, GLbyte);
-GLAPI void APIENTRY glTangent3bvEXT (const GLbyte *);
-GLAPI void APIENTRY glTangent3dEXT (GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glTangent3dvEXT (const GLdouble *);
-GLAPI void APIENTRY glTangent3fEXT (GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glTangent3fvEXT (const GLfloat *);
-GLAPI void APIENTRY glTangent3iEXT (GLint, GLint, GLint);
-GLAPI void APIENTRY glTangent3ivEXT (const GLint *);
-GLAPI void APIENTRY glTangent3sEXT (GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glTangent3svEXT (const GLshort *);
-GLAPI void APIENTRY glBinormal3bEXT (GLbyte, GLbyte, GLbyte);
-GLAPI void APIENTRY glBinormal3bvEXT (const GLbyte *);
-GLAPI void APIENTRY glBinormal3dEXT (GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glBinormal3dvEXT (const GLdouble *);
-GLAPI void APIENTRY glBinormal3fEXT (GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glBinormal3fvEXT (const GLfloat *);
-GLAPI void APIENTRY glBinormal3iEXT (GLint, GLint, GLint);
-GLAPI void APIENTRY glBinormal3ivEXT (const GLint *);
-GLAPI void APIENTRY glBinormal3sEXT (GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glBinormal3svEXT (const GLshort *);
-GLAPI void APIENTRY glTangentPointerEXT (GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glBinormalPointerEXT (GLenum, GLsizei, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLTANGENT3BEXTPROC) (GLbyte tx, GLbyte ty, GLbyte tz);
-typedef void (APIENTRYP PFNGLTANGENT3BVEXTPROC) (const GLbyte *v);
-typedef void (APIENTRYP PFNGLTANGENT3DEXTPROC) (GLdouble tx, GLdouble ty, GLdouble tz);
-typedef void (APIENTRYP PFNGLTANGENT3DVEXTPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLTANGENT3FEXTPROC) (GLfloat tx, GLfloat ty, GLfloat tz);
-typedef void (APIENTRYP PFNGLTANGENT3FVEXTPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLTANGENT3IEXTPROC) (GLint tx, GLint ty, GLint tz);
-typedef void (APIENTRYP PFNGLTANGENT3IVEXTPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLTANGENT3SEXTPROC) (GLshort tx, GLshort ty, GLshort tz);
-typedef void (APIENTRYP PFNGLTANGENT3SVEXTPROC) (const GLshort *v);
-typedef void (APIENTRYP PFNGLBINORMAL3BEXTPROC) (GLbyte bx, GLbyte by, GLbyte bz);
-typedef void (APIENTRYP PFNGLBINORMAL3BVEXTPROC) (const GLbyte *v);
-typedef void (APIENTRYP PFNGLBINORMAL3DEXTPROC) (GLdouble bx, GLdouble by, GLdouble bz);
-typedef void (APIENTRYP PFNGLBINORMAL3DVEXTPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLBINORMAL3FEXTPROC) (GLfloat bx, GLfloat by, GLfloat bz);
-typedef void (APIENTRYP PFNGLBINORMAL3FVEXTPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLBINORMAL3IEXTPROC) (GLint bx, GLint by, GLint bz);
-typedef void (APIENTRYP PFNGLBINORMAL3IVEXTPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLBINORMAL3SEXTPROC) (GLshort bx, GLshort by, GLshort bz);
-typedef void (APIENTRYP PFNGLBINORMAL3SVEXTPROC) (const GLshort *v);
-typedef void (APIENTRYP PFNGLTANGENTPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLBINORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer);
-#endif
-
-#ifndef GL_EXT_texture_env_combine
-#define GL_EXT_texture_env_combine 1
-#endif
-
-#ifndef GL_APPLE_specular_vector
-#define GL_APPLE_specular_vector 1
-#endif
-
-#ifndef GL_APPLE_transform_hint
-#define GL_APPLE_transform_hint 1
-#endif
-
-#ifndef GL_SGIX_fog_scale
-#define GL_SGIX_fog_scale 1
-#endif
-
-#ifndef GL_SUNX_constant_data
-#define GL_SUNX_constant_data 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glFinishTextureSUNX (void);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLFINISHTEXTURESUNXPROC) (void);
-#endif
-
-#ifndef GL_SUN_global_alpha
-#define GL_SUN_global_alpha 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glGlobalAlphaFactorbSUN (GLbyte);
-GLAPI void APIENTRY glGlobalAlphaFactorsSUN (GLshort);
-GLAPI void APIENTRY glGlobalAlphaFactoriSUN (GLint);
-GLAPI void APIENTRY glGlobalAlphaFactorfSUN (GLfloat);
-GLAPI void APIENTRY glGlobalAlphaFactordSUN (GLdouble);
-GLAPI void APIENTRY glGlobalAlphaFactorubSUN (GLubyte);
-GLAPI void APIENTRY glGlobalAlphaFactorusSUN (GLushort);
-GLAPI void APIENTRY glGlobalAlphaFactoruiSUN (GLuint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORBSUNPROC) (GLbyte factor);
-typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORSSUNPROC) (GLshort factor);
-typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORISUNPROC) (GLint factor);
-typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORFSUNPROC) (GLfloat factor);
-typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORDSUNPROC) (GLdouble factor);
-typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUBSUNPROC) (GLubyte factor);
-typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUSSUNPROC) (GLushort factor);
-typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUISUNPROC) (GLuint factor);
-#endif
-
-#ifndef GL_SUN_triangle_list
-#define GL_SUN_triangle_list 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glReplacementCodeuiSUN (GLuint);
-GLAPI void APIENTRY glReplacementCodeusSUN (GLushort);
-GLAPI void APIENTRY glReplacementCodeubSUN (GLubyte);
-GLAPI void APIENTRY glReplacementCodeuivSUN (const GLuint *);
-GLAPI void APIENTRY glReplacementCodeusvSUN (const GLushort *);
-GLAPI void APIENTRY glReplacementCodeubvSUN (const GLubyte *);
-GLAPI void APIENTRY glReplacementCodePointerSUN (GLenum, GLsizei, const GLvoid* *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUISUNPROC) (GLuint code);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUSSUNPROC) (GLushort code);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUBSUNPROC) (GLubyte code);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVSUNPROC) (const GLuint *code);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUSVSUNPROC) (const GLushort *code);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUBVSUNPROC) (const GLubyte *code);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEPOINTERSUNPROC) (GLenum type, GLsizei stride, const GLvoid* *pointer);
-#endif
-
-#ifndef GL_SUN_vertex
-#define GL_SUN_vertex 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glColor4ubVertex2fSUN (GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat);
-GLAPI void APIENTRY glColor4ubVertex2fvSUN (const GLubyte *, const GLfloat *);
-GLAPI void APIENTRY glColor4ubVertex3fSUN (GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glColor4ubVertex3fvSUN (const GLubyte *, const GLfloat *);
-GLAPI void APIENTRY glColor3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glColor3fVertex3fvSUN (const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glColor4fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glColor4fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glTexCoord2fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glTexCoord2fVertex3fvSUN (const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glTexCoord4fVertex4fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glTexCoord4fVertex4fvSUN (const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glTexCoord2fColor4ubVertex3fSUN (GLfloat, GLfloat, GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glTexCoord2fColor4ubVertex3fvSUN (const GLfloat *, const GLubyte *, const GLfloat *);
-GLAPI void APIENTRY glTexCoord2fColor3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glTexCoord2fColor3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glTexCoord2fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glTexCoord2fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fvSUN (const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glReplacementCodeuiVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glReplacementCodeuiVertex3fvSUN (const GLuint *, const GLfloat *);
-GLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fSUN (GLuint, GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fvSUN (const GLuint *, const GLubyte *, const GLfloat *);
-GLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y);
-typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FVSUNPROC) (const GLubyte *c, const GLfloat *v);
-typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FVSUNPROC) (const GLubyte *c, const GLfloat *v);
-typedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *v);
-typedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FSUNPROC) (GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *n, const GLfloat *v);
-typedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *n, const GLfloat *v);
-typedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *v);
-typedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *v);
-typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FVSUNPROC) (const GLfloat *tc, const GLubyte *c, const GLfloat *v);
-typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *v);
-typedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *n, const GLfloat *v);
-typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
-typedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FSUNPROC) (GLuint rc, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *v);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FSUNPROC) (GLuint rc, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FVSUNPROC) (const GLuint *rc, const GLubyte *c, const GLfloat *v);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *v);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *n, const GLfloat *v);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *v);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *n, const GLfloat *v);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
-#endif
-
-#ifndef GL_EXT_blend_func_separate
-#define GL_EXT_blend_func_separate 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBlendFuncSeparateEXT (GLenum, GLenum, GLenum, GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEEXTPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
-#endif
-
-#ifndef GL_INGR_blend_func_separate
-#define GL_INGR_blend_func_separate 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBlendFuncSeparateINGR (GLenum, GLenum, GLenum, GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEINGRPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
-#endif
-
-#ifndef GL_INGR_color_clamp
-#define GL_INGR_color_clamp 1
-#endif
-
-#ifndef GL_INGR_interlace_read
-#define GL_INGR_interlace_read 1
-#endif
-
-#ifndef GL_EXT_stencil_wrap
-#define GL_EXT_stencil_wrap 1
-#endif
-
-#ifndef GL_EXT_422_pixels
-#define GL_EXT_422_pixels 1
-#endif
-
-#ifndef GL_NV_texgen_reflection
-#define GL_NV_texgen_reflection 1
-#endif
-
-#ifndef GL_SUN_convolution_border_modes
-#define GL_SUN_convolution_border_modes 1
-#endif
-
-#ifndef GL_EXT_texture_env_add
-#define GL_EXT_texture_env_add 1
-#endif
-
-#ifndef GL_EXT_texture_lod_bias
-#define GL_EXT_texture_lod_bias 1
-#endif
-
-#ifndef GL_EXT_texture_filter_anisotropic
-#define GL_EXT_texture_filter_anisotropic 1
-#endif
-
-#ifndef GL_EXT_vertex_weighting
-#define GL_EXT_vertex_weighting 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glVertexWeightfEXT (GLfloat);
-GLAPI void APIENTRY glVertexWeightfvEXT (const GLfloat *);
-GLAPI void APIENTRY glVertexWeightPointerEXT (GLsizei, GLenum, GLsizei, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLVERTEXWEIGHTFEXTPROC) (GLfloat weight);
-typedef void (APIENTRYP PFNGLVERTEXWEIGHTFVEXTPROC) (const GLfloat *weight);
-typedef void (APIENTRYP PFNGLVERTEXWEIGHTPOINTEREXTPROC) (GLsizei size, GLenum type, GLsizei stride, const GLvoid *pointer);
-#endif
-
-#ifndef GL_NV_light_max_exponent
-#define GL_NV_light_max_exponent 1
-#endif
-
-#ifndef GL_NV_vertex_array_range
-#define GL_NV_vertex_array_range 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glFlushVertexArrayRangeNV (void);
-GLAPI void APIENTRY glVertexArrayRangeNV (GLsizei, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGENVPROC) (void);
-typedef void (APIENTRYP PFNGLVERTEXARRAYRANGENVPROC) (GLsizei length, const GLvoid *pointer);
-#endif
-
-#ifndef GL_NV_register_combiners
-#define GL_NV_register_combiners 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glCombinerParameterfvNV (GLenum, const GLfloat *);
-GLAPI void APIENTRY glCombinerParameterfNV (GLenum, GLfloat);
-GLAPI void APIENTRY glCombinerParameterivNV (GLenum, const GLint *);
-GLAPI void APIENTRY glCombinerParameteriNV (GLenum, GLint);
-GLAPI void APIENTRY glCombinerInputNV (GLenum, GLenum, GLenum, GLenum, GLenum, GLenum);
-GLAPI void APIENTRY glCombinerOutputNV (GLenum, GLenum, GLenum, GLenum, GLenum, GLenum, GLenum, GLboolean, GLboolean, GLboolean);
-GLAPI void APIENTRY glFinalCombinerInputNV (GLenum, GLenum, GLenum, GLenum);
-GLAPI void APIENTRY glGetCombinerInputParameterfvNV (GLenum, GLenum, GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetCombinerInputParameterivNV (GLenum, GLenum, GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetCombinerOutputParameterfvNV (GLenum, GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetCombinerOutputParameterivNV (GLenum, GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetFinalCombinerInputParameterfvNV (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetFinalCombinerInputParameterivNV (GLenum, GLenum, GLint *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFVNVPROC) (GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFNVPROC) (GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLCOMBINERPARAMETERIVNVPROC) (GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLCOMBINERPARAMETERINVPROC) (GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLCOMBINERINPUTNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage);
-typedef void (APIENTRYP PFNGLCOMBINEROUTPUTNVPROC) (GLenum stage, GLenum portion, GLenum abOutput, GLenum cdOutput, GLenum sumOutput, GLenum scale, GLenum bias, GLboolean abDotProduct, GLboolean cdDotProduct, GLboolean muxSum);
-typedef void (APIENTRYP PFNGLFINALCOMBINERINPUTNVPROC) (GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage);
-typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERFVNVPROC) (GLenum variable, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC) (GLenum variable, GLenum pname, GLint *params);
-#endif
-
-#ifndef GL_NV_fog_distance
-#define GL_NV_fog_distance 1
-#endif
-
-#ifndef GL_NV_texgen_emboss
-#define GL_NV_texgen_emboss 1
-#endif
-
-#ifndef GL_NV_blend_square
-#define GL_NV_blend_square 1
-#endif
-
-#ifndef GL_NV_texture_env_combine4
-#define GL_NV_texture_env_combine4 1
-#endif
-
-#ifndef GL_MESA_resize_buffers
-#define GL_MESA_resize_buffers 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glResizeBuffersMESA (void);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLRESIZEBUFFERSMESAPROC) (void);
-#endif
-
-#ifndef GL_MESA_window_pos
-#define GL_MESA_window_pos 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glWindowPos2dMESA (GLdouble, GLdouble);
-GLAPI void APIENTRY glWindowPos2dvMESA (const GLdouble *);
-GLAPI void APIENTRY glWindowPos2fMESA (GLfloat, GLfloat);
-GLAPI void APIENTRY glWindowPos2fvMESA (const GLfloat *);
-GLAPI void APIENTRY glWindowPos2iMESA (GLint, GLint);
-GLAPI void APIENTRY glWindowPos2ivMESA (const GLint *);
-GLAPI void APIENTRY glWindowPos2sMESA (GLshort, GLshort);
-GLAPI void APIENTRY glWindowPos2svMESA (const GLshort *);
-GLAPI void APIENTRY glWindowPos3dMESA (GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glWindowPos3dvMESA (const GLdouble *);
-GLAPI void APIENTRY glWindowPos3fMESA (GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glWindowPos3fvMESA (const GLfloat *);
-GLAPI void APIENTRY glWindowPos3iMESA (GLint, GLint, GLint);
-GLAPI void APIENTRY glWindowPos3ivMESA (const GLint *);
-GLAPI void APIENTRY glWindowPos3sMESA (GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glWindowPos3svMESA (const GLshort *);
-GLAPI void APIENTRY glWindowPos4dMESA (GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glWindowPos4dvMESA (const GLdouble *);
-GLAPI void APIENTRY glWindowPos4fMESA (GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glWindowPos4fvMESA (const GLfloat *);
-GLAPI void APIENTRY glWindowPos4iMESA (GLint, GLint, GLint, GLint);
-GLAPI void APIENTRY glWindowPos4ivMESA (const GLint *);
-GLAPI void APIENTRY glWindowPos4sMESA (GLshort, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glWindowPos4svMESA (const GLshort *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLWINDOWPOS2DMESAPROC) (GLdouble x, GLdouble y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2DVMESAPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS2FMESAPROC) (GLfloat x, GLfloat y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2FVMESAPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS2IMESAPROC) (GLint x, GLint y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2IVMESAPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS2SMESAPROC) (GLshort x, GLshort y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2SVMESAPROC) (const GLshort *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3DMESAPROC) (GLdouble x, GLdouble y, GLdouble z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3DVMESAPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3FMESAPROC) (GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3FVMESAPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3IMESAPROC) (GLint x, GLint y, GLint z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3IVMESAPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3SMESAPROC) (GLshort x, GLshort y, GLshort z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3SVMESAPROC) (const GLshort *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS4DMESAPROC) (GLdouble x, GLdouble y, GLdouble z, GLdouble w);
-typedef void (APIENTRYP PFNGLWINDOWPOS4DVMESAPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS4FMESAPROC) (GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLWINDOWPOS4FVMESAPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS4IMESAPROC) (GLint x, GLint y, GLint z, GLint w);
-typedef void (APIENTRYP PFNGLWINDOWPOS4IVMESAPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS4SMESAPROC) (GLshort x, GLshort y, GLshort z, GLshort w);
-typedef void (APIENTRYP PFNGLWINDOWPOS4SVMESAPROC) (const GLshort *v);
-#endif
-
-#ifndef GL_IBM_cull_vertex
-#define GL_IBM_cull_vertex 1
-#endif
-
-#ifndef GL_IBM_multimode_draw_arrays
-#define GL_IBM_multimode_draw_arrays 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glMultiModeDrawArraysIBM (const GLenum *, const GLint *, const GLsizei *, GLsizei, GLint);
-GLAPI void APIENTRY glMultiModeDrawElementsIBM (const GLenum *, const GLsizei *, GLenum, const GLvoid* const *, GLsizei, GLint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLMULTIMODEDRAWARRAYSIBMPROC) (const GLenum *mode, const GLint *first, const GLsizei *count, GLsizei primcount, GLint modestride);
-typedef void (APIENTRYP PFNGLMULTIMODEDRAWELEMENTSIBMPROC) (const GLenum *mode, const GLsizei *count, GLenum type, const GLvoid* const *indices, GLsizei primcount, GLint modestride);
-#endif
-
-#ifndef GL_IBM_vertex_array_lists
-#define GL_IBM_vertex_array_lists 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glColorPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint);
-GLAPI void APIENTRY glSecondaryColorPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint);
-GLAPI void APIENTRY glEdgeFlagPointerListIBM (GLint, const GLboolean* *, GLint);
-GLAPI void APIENTRY glFogCoordPointerListIBM (GLenum, GLint, const GLvoid* *, GLint);
-GLAPI void APIENTRY glIndexPointerListIBM (GLenum, GLint, const GLvoid* *, GLint);
-GLAPI void APIENTRY glNormalPointerListIBM (GLenum, GLint, const GLvoid* *, GLint);
-GLAPI void APIENTRY glTexCoordPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint);
-GLAPI void APIENTRY glVertexPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
-typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
-typedef void (APIENTRYP PFNGLEDGEFLAGPOINTERLISTIBMPROC) (GLint stride, const GLboolean* *pointer, GLint ptrstride);
-typedef void (APIENTRYP PFNGLFOGCOORDPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
-typedef void (APIENTRYP PFNGLINDEXPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
-typedef void (APIENTRYP PFNGLNORMALPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
-typedef void (APIENTRYP PFNGLTEXCOORDPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
-typedef void (APIENTRYP PFNGLVERTEXPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
-#endif
-
-#ifndef GL_SGIX_subsample
-#define GL_SGIX_subsample 1
-#endif
-
-#ifndef GL_SGIX_ycrcba
-#define GL_SGIX_ycrcba 1
-#endif
-
-#ifndef GL_SGIX_ycrcb_subsample
-#define GL_SGIX_ycrcb_subsample 1
-#endif
-
-#ifndef GL_SGIX_depth_pass_instrument
-#define GL_SGIX_depth_pass_instrument 1
-#endif
-
-#ifndef GL_3DFX_texture_compression_FXT1
-#define GL_3DFX_texture_compression_FXT1 1
-#endif
-
-#ifndef GL_3DFX_multisample
-#define GL_3DFX_multisample 1
-#endif
-
-#ifndef GL_3DFX_tbuffer
-#define GL_3DFX_tbuffer 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glTbufferMask3DFX (GLuint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLTBUFFERMASK3DFXPROC) (GLuint mask);
-#endif
-
-#ifndef GL_EXT_multisample
-#define GL_EXT_multisample 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glSampleMaskEXT (GLclampf, GLboolean);
-GLAPI void APIENTRY glSamplePatternEXT (GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLSAMPLEMASKEXTPROC) (GLclampf value, GLboolean invert);
-typedef void (APIENTRYP PFNGLSAMPLEPATTERNEXTPROC) (GLenum pattern);
-#endif
-
-#ifndef GL_SGIX_vertex_preclip
-#define GL_SGIX_vertex_preclip 1
-#endif
-
-#ifndef GL_SGIX_convolution_accuracy
-#define GL_SGIX_convolution_accuracy 1
-#endif
-
-#ifndef GL_SGIX_resample
-#define GL_SGIX_resample 1
-#endif
-
-#ifndef GL_SGIS_point_line_texgen
-#define GL_SGIS_point_line_texgen 1
-#endif
-
-#ifndef GL_SGIS_texture_color_mask
-#define GL_SGIS_texture_color_mask 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glTextureColorMaskSGIS (GLboolean, GLboolean, GLboolean, GLboolean);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLTEXTURECOLORMASKSGISPROC) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
-#endif
-
-#ifndef GL_SGIX_igloo_interface
-#define GL_SGIX_igloo_interface 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glIglooInterfaceSGIX (GLenum, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLIGLOOINTERFACESGIXPROC) (GLenum pname, const GLvoid *params);
-#endif
-
-#ifndef GL_EXT_texture_env_dot3
-#define GL_EXT_texture_env_dot3 1
-#endif
-
-#ifndef GL_ATI_texture_mirror_once
-#define GL_ATI_texture_mirror_once 1
-#endif
-
-#ifndef GL_NV_fence
-#define GL_NV_fence 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glDeleteFencesNV (GLsizei, const GLuint *);
-GLAPI void APIENTRY glGenFencesNV (GLsizei, GLuint *);
-GLAPI GLboolean APIENTRY glIsFenceNV (GLuint);
-GLAPI GLboolean APIENTRY glTestFenceNV (GLuint);
-GLAPI void APIENTRY glGetFenceivNV (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glFinishFenceNV (GLuint);
-GLAPI void APIENTRY glSetFenceNV (GLuint, GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLDELETEFENCESNVPROC) (GLsizei n, const GLuint *fences);
-typedef void (APIENTRYP PFNGLGENFENCESNVPROC) (GLsizei n, GLuint *fences);
-typedef GLboolean (APIENTRYP PFNGLISFENCENVPROC) (GLuint fence);
-typedef GLboolean (APIENTRYP PFNGLTESTFENCENVPROC) (GLuint fence);
-typedef void (APIENTRYP PFNGLGETFENCEIVNVPROC) (GLuint fence, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLFINISHFENCENVPROC) (GLuint fence);
-typedef void (APIENTRYP PFNGLSETFENCENVPROC) (GLuint fence, GLenum condition);
-#endif
-
-#ifndef GL_NV_evaluators
-#define GL_NV_evaluators 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glMapControlPointsNV (GLenum, GLuint, GLenum, GLsizei, GLsizei, GLint, GLint, GLboolean, const GLvoid *);
-GLAPI void APIENTRY glMapParameterivNV (GLenum, GLenum, const GLint *);
-GLAPI void APIENTRY glMapParameterfvNV (GLenum, GLenum, const GLfloat *);
-GLAPI void APIENTRY glGetMapControlPointsNV (GLenum, GLuint, GLenum, GLsizei, GLsizei, GLboolean, GLvoid *);
-GLAPI void APIENTRY glGetMapParameterivNV (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetMapParameterfvNV (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetMapAttribParameterivNV (GLenum, GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetMapAttribParameterfvNV (GLenum, GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glEvalMapsNV (GLenum, GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLint uorder, GLint vorder, GLboolean packed, const GLvoid *points);
-typedef void (APIENTRYP PFNGLMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLGETMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLboolean packed, GLvoid *points);
-typedef void (APIENTRYP PFNGLGETMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERIVNVPROC) (GLenum target, GLuint index, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLEVALMAPSNVPROC) (GLenum target, GLenum mode);
-#endif
-
-#ifndef GL_NV_packed_depth_stencil
-#define GL_NV_packed_depth_stencil 1
-#endif
-
-#ifndef GL_NV_register_combiners2
-#define GL_NV_register_combiners2 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glCombinerStageParameterfvNV (GLenum, GLenum, const GLfloat *);
-GLAPI void APIENTRY glGetCombinerStageParameterfvNV (GLenum, GLenum, GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, GLfloat *params);
-#endif
-
-#ifndef GL_NV_texture_compression_vtc
-#define GL_NV_texture_compression_vtc 1
-#endif
-
-#ifndef GL_NV_texture_rectangle
-#define GL_NV_texture_rectangle 1
-#endif
-
-#ifndef GL_NV_texture_shader
-#define GL_NV_texture_shader 1
-#endif
-
-#ifndef GL_NV_texture_shader2
-#define GL_NV_texture_shader2 1
-#endif
-
-#ifndef GL_NV_vertex_array_range2
-#define GL_NV_vertex_array_range2 1
-#endif
-
-#ifndef GL_NV_vertex_program
-#define GL_NV_vertex_program 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI GLboolean APIENTRY glAreProgramsResidentNV (GLsizei, const GLuint *, GLboolean *);
-GLAPI void APIENTRY glBindProgramNV (GLenum, GLuint);
-GLAPI void APIENTRY glDeleteProgramsNV (GLsizei, const GLuint *);
-GLAPI void APIENTRY glExecuteProgramNV (GLenum, GLuint, const GLfloat *);
-GLAPI void APIENTRY glGenProgramsNV (GLsizei, GLuint *);
-GLAPI void APIENTRY glGetProgramParameterdvNV (GLenum, GLuint, GLenum, GLdouble *);
-GLAPI void APIENTRY glGetProgramParameterfvNV (GLenum, GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetProgramivNV (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetProgramStringNV (GLuint, GLenum, GLubyte *);
-GLAPI void APIENTRY glGetTrackMatrixivNV (GLenum, GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetVertexAttribdvNV (GLuint, GLenum, GLdouble *);
-GLAPI void APIENTRY glGetVertexAttribfvNV (GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetVertexAttribivNV (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetVertexAttribPointervNV (GLuint, GLenum, GLvoid* *);
-GLAPI GLboolean APIENTRY glIsProgramNV (GLuint);
-GLAPI void APIENTRY glLoadProgramNV (GLenum, GLuint, GLsizei, const GLubyte *);
-GLAPI void APIENTRY glProgramParameter4dNV (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glProgramParameter4dvNV (GLenum, GLuint, const GLdouble *);
-GLAPI void APIENTRY glProgramParameter4fNV (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glProgramParameter4fvNV (GLenum, GLuint, const GLfloat *);
-GLAPI void APIENTRY glProgramParameters4dvNV (GLenum, GLuint, GLuint, const GLdouble *);
-GLAPI void APIENTRY glProgramParameters4fvNV (GLenum, GLuint, GLuint, const GLfloat *);
-GLAPI void APIENTRY glRequestResidentProgramsNV (GLsizei, const GLuint *);
-GLAPI void APIENTRY glTrackMatrixNV (GLenum, GLuint, GLenum, GLenum);
-GLAPI void APIENTRY glVertexAttribPointerNV (GLuint, GLint, GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glVertexAttrib1dNV (GLuint, GLdouble);
-GLAPI void APIENTRY glVertexAttrib1dvNV (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib1fNV (GLuint, GLfloat);
-GLAPI void APIENTRY glVertexAttrib1fvNV (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib1sNV (GLuint, GLshort);
-GLAPI void APIENTRY glVertexAttrib1svNV (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib2dNV (GLuint, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexAttrib2dvNV (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib2fNV (GLuint, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexAttrib2fvNV (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib2sNV (GLuint, GLshort, GLshort);
-GLAPI void APIENTRY glVertexAttrib2svNV (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib3dNV (GLuint, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexAttrib3dvNV (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib3fNV (GLuint, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexAttrib3fvNV (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib3sNV (GLuint, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glVertexAttrib3svNV (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib4dNV (GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexAttrib4dvNV (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib4fNV (GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexAttrib4fvNV (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib4sNV (GLuint, GLshort, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glVertexAttrib4svNV (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib4ubNV (GLuint, GLubyte, GLubyte, GLubyte, GLubyte);
-GLAPI void APIENTRY glVertexAttrib4ubvNV (GLuint, const GLubyte *);
-GLAPI void APIENTRY glVertexAttribs1dvNV (GLuint, GLsizei, const GLdouble *);
-GLAPI void APIENTRY glVertexAttribs1fvNV (GLuint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glVertexAttribs1svNV (GLuint, GLsizei, const GLshort *);
-GLAPI void APIENTRY glVertexAttribs2dvNV (GLuint, GLsizei, const GLdouble *);
-GLAPI void APIENTRY glVertexAttribs2fvNV (GLuint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glVertexAttribs2svNV (GLuint, GLsizei, const GLshort *);
-GLAPI void APIENTRY glVertexAttribs3dvNV (GLuint, GLsizei, const GLdouble *);
-GLAPI void APIENTRY glVertexAttribs3fvNV (GLuint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glVertexAttribs3svNV (GLuint, GLsizei, const GLshort *);
-GLAPI void APIENTRY glVertexAttribs4dvNV (GLuint, GLsizei, const GLdouble *);
-GLAPI void APIENTRY glVertexAttribs4fvNV (GLuint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glVertexAttribs4svNV (GLuint, GLsizei, const GLshort *);
-GLAPI void APIENTRY glVertexAttribs4ubvNV (GLuint, GLsizei, const GLubyte *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef GLboolean (APIENTRYP PFNGLAREPROGRAMSRESIDENTNVPROC) (GLsizei n, const GLuint *programs, GLboolean *residences);
-typedef void (APIENTRYP PFNGLBINDPROGRAMNVPROC) (GLenum target, GLuint id);
-typedef void (APIENTRYP PFNGLDELETEPROGRAMSNVPROC) (GLsizei n, const GLuint *programs);
-typedef void (APIENTRYP PFNGLEXECUTEPROGRAMNVPROC) (GLenum target, GLuint id, const GLfloat *params);
-typedef void (APIENTRYP PFNGLGENPROGRAMSNVPROC) (GLsizei n, GLuint *programs);
-typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERDVNVPROC) (GLenum target, GLuint index, GLenum pname, GLdouble *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMIVNVPROC) (GLuint id, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGNVPROC) (GLuint id, GLenum pname, GLubyte *program);
-typedef void (APIENTRYP PFNGLGETTRACKMATRIXIVNVPROC) (GLenum target, GLuint address, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVNVPROC) (GLuint index, GLenum pname, GLdouble *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVNVPROC) (GLuint index, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVNVPROC) (GLuint index, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVNVPROC) (GLuint index, GLenum pname, GLvoid* *pointer);
-typedef GLboolean (APIENTRYP PFNGLISPROGRAMNVPROC) (GLuint id);
-typedef void (APIENTRYP PFNGLLOADPROGRAMNVPROC) (GLenum target, GLuint id, GLsizei len, const GLubyte *program);
-typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DNVPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
-typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DVNVPROC) (GLenum target, GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FNVPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FVNVPROC) (GLenum target, GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4DVNVPROC) (GLenum target, GLuint index, GLuint count, const GLdouble *v);
-typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4FVNVPROC) (GLenum target, GLuint index, GLuint count, const GLfloat *v);
-typedef void (APIENTRYP PFNGLREQUESTRESIDENTPROGRAMSNVPROC) (GLsizei n, const GLuint *programs);
-typedef void (APIENTRYP PFNGLTRACKMATRIXNVPROC) (GLenum target, GLuint address, GLenum matrix, GLenum transform);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERNVPROC) (GLuint index, GLint fsize, GLenum type, GLsizei stride, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1DNVPROC) (GLuint index, GLdouble x);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVNVPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1FNVPROC) (GLuint index, GLfloat x);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVNVPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1SNVPROC) (GLuint index, GLshort x);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVNVPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2DNVPROC) (GLuint index, GLdouble x, GLdouble y);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVNVPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2FNVPROC) (GLuint index, GLfloat x, GLfloat y);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVNVPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2SNVPROC) (GLuint index, GLshort x, GLshort y);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVNVPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVNVPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVNVPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVNVPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVNVPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVNVPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVNVPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBNVPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVNVPROC) (GLuint index, const GLubyte *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS1DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS1FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS1SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS2DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS2FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS2SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS3DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS3FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS3SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS4DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS4FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS4SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS4UBVNVPROC) (GLuint index, GLsizei count, const GLubyte *v);
-#endif
-
-#ifndef GL_SGIX_texture_coordinate_clamp
-#define GL_SGIX_texture_coordinate_clamp 1
-#endif
-
-#ifndef GL_SGIX_scalebias_hint
-#define GL_SGIX_scalebias_hint 1
-#endif
-
-#ifndef GL_OML_interlace
-#define GL_OML_interlace 1
-#endif
-
-#ifndef GL_OML_subsample
-#define GL_OML_subsample 1
-#endif
-
-#ifndef GL_OML_resample
-#define GL_OML_resample 1
-#endif
-
-#ifndef GL_NV_copy_depth_to_color
-#define GL_NV_copy_depth_to_color 1
-#endif
-
-#ifndef GL_ATI_envmap_bumpmap
-#define GL_ATI_envmap_bumpmap 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glTexBumpParameterivATI (GLenum, const GLint *);
-GLAPI void APIENTRY glTexBumpParameterfvATI (GLenum, const GLfloat *);
-GLAPI void APIENTRY glGetTexBumpParameterivATI (GLenum, GLint *);
-GLAPI void APIENTRY glGetTexBumpParameterfvATI (GLenum, GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERIVATIPROC) (GLenum pname, const GLint *param);
-typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERFVATIPROC) (GLenum pname, const GLfloat *param);
-typedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERIVATIPROC) (GLenum pname, GLint *param);
-typedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERFVATIPROC) (GLenum pname, GLfloat *param);
-#endif
-
-#ifndef GL_ATI_fragment_shader
-#define GL_ATI_fragment_shader 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI GLuint APIENTRY glGenFragmentShadersATI (GLuint);
-GLAPI void APIENTRY glBindFragmentShaderATI (GLuint);
-GLAPI void APIENTRY glDeleteFragmentShaderATI (GLuint);
-GLAPI void APIENTRY glBeginFragmentShaderATI (void);
-GLAPI void APIENTRY glEndFragmentShaderATI (void);
-GLAPI void APIENTRY glPassTexCoordATI (GLuint, GLuint, GLenum);
-GLAPI void APIENTRY glSampleMapATI (GLuint, GLuint, GLenum);
-GLAPI void APIENTRY glColorFragmentOp1ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glColorFragmentOp2ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glColorFragmentOp3ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glAlphaFragmentOp1ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glAlphaFragmentOp2ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glAlphaFragmentOp3ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glSetFragmentShaderConstantATI (GLuint, const GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef GLuint (APIENTRYP PFNGLGENFRAGMENTSHADERSATIPROC) (GLuint range);
-typedef void (APIENTRYP PFNGLBINDFRAGMENTSHADERATIPROC) (GLuint id);
-typedef void (APIENTRYP PFNGLDELETEFRAGMENTSHADERATIPROC) (GLuint id);
-typedef void (APIENTRYP PFNGLBEGINFRAGMENTSHADERATIPROC) (void);
-typedef void (APIENTRYP PFNGLENDFRAGMENTSHADERATIPROC) (void);
-typedef void (APIENTRYP PFNGLPASSTEXCOORDATIPROC) (GLuint dst, GLuint coord, GLenum swizzle);
-typedef void (APIENTRYP PFNGLSAMPLEMAPATIPROC) (GLuint dst, GLuint interp, GLenum swizzle);
-typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod);
-typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod);
-typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod);
-typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod);
-typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod);
-typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod);
-typedef void (APIENTRYP PFNGLSETFRAGMENTSHADERCONSTANTATIPROC) (GLuint dst, const GLfloat *value);
-#endif
-
-#ifndef GL_ATI_pn_triangles
-#define GL_ATI_pn_triangles 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPNTrianglesiATI (GLenum, GLint);
-GLAPI void APIENTRY glPNTrianglesfATI (GLenum, GLfloat);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPNTRIANGLESIATIPROC) (GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLPNTRIANGLESFATIPROC) (GLenum pname, GLfloat param);
-#endif
-
-#ifndef GL_ATI_vertex_array_object
-#define GL_ATI_vertex_array_object 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI GLuint APIENTRY glNewObjectBufferATI (GLsizei, const GLvoid *, GLenum);
-GLAPI GLboolean APIENTRY glIsObjectBufferATI (GLuint);
-GLAPI void APIENTRY glUpdateObjectBufferATI (GLuint, GLuint, GLsizei, const GLvoid *, GLenum);
-GLAPI void APIENTRY glGetObjectBufferfvATI (GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetObjectBufferivATI (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glFreeObjectBufferATI (GLuint);
-GLAPI void APIENTRY glArrayObjectATI (GLenum, GLint, GLenum, GLsizei, GLuint, GLuint);
-GLAPI void APIENTRY glGetArrayObjectfvATI (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetArrayObjectivATI (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glVariantArrayObjectATI (GLuint, GLenum, GLsizei, GLuint, GLuint);
-GLAPI void APIENTRY glGetVariantArrayObjectfvATI (GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetVariantArrayObjectivATI (GLuint, GLenum, GLint *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef GLuint (APIENTRYP PFNGLNEWOBJECTBUFFERATIPROC) (GLsizei size, const GLvoid *pointer, GLenum usage);
-typedef GLboolean (APIENTRYP PFNGLISOBJECTBUFFERATIPROC) (GLuint buffer);
-typedef void (APIENTRYP PFNGLUPDATEOBJECTBUFFERATIPROC) (GLuint buffer, GLuint offset, GLsizei size, const GLvoid *pointer, GLenum preserve);
-typedef void (APIENTRYP PFNGLGETOBJECTBUFFERFVATIPROC) (GLuint buffer, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETOBJECTBUFFERIVATIPROC) (GLuint buffer, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLFREEOBJECTBUFFERATIPROC) (GLuint buffer);
-typedef void (APIENTRYP PFNGLARRAYOBJECTATIPROC) (GLenum array, GLint size, GLenum type, GLsizei stride, GLuint buffer, GLuint offset);
-typedef void (APIENTRYP PFNGLGETARRAYOBJECTFVATIPROC) (GLenum array, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETARRAYOBJECTIVATIPROC) (GLenum array, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLVARIANTARRAYOBJECTATIPROC) (GLuint id, GLenum type, GLsizei stride, GLuint buffer, GLuint offset);
-typedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTFVATIPROC) (GLuint id, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTIVATIPROC) (GLuint id, GLenum pname, GLint *params);
-#endif
-
-#ifndef GL_EXT_vertex_shader
-#define GL_EXT_vertex_shader 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBeginVertexShaderEXT (void);
-GLAPI void APIENTRY glEndVertexShaderEXT (void);
-GLAPI void APIENTRY glBindVertexShaderEXT (GLuint);
-GLAPI GLuint APIENTRY glGenVertexShadersEXT (GLuint);
-GLAPI void APIENTRY glDeleteVertexShaderEXT (GLuint);
-GLAPI void APIENTRY glShaderOp1EXT (GLenum, GLuint, GLuint);
-GLAPI void APIENTRY glShaderOp2EXT (GLenum, GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glShaderOp3EXT (GLenum, GLuint, GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glSwizzleEXT (GLuint, GLuint, GLenum, GLenum, GLenum, GLenum);
-GLAPI void APIENTRY glWriteMaskEXT (GLuint, GLuint, GLenum, GLenum, GLenum, GLenum);
-GLAPI void APIENTRY glInsertComponentEXT (GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glExtractComponentEXT (GLuint, GLuint, GLuint);
-GLAPI GLuint APIENTRY glGenSymbolsEXT (GLenum, GLenum, GLenum, GLuint);
-GLAPI void APIENTRY glSetInvariantEXT (GLuint, GLenum, const GLvoid *);
-GLAPI void APIENTRY glSetLocalConstantEXT (GLuint, GLenum, const GLvoid *);
-GLAPI void APIENTRY glVariantbvEXT (GLuint, const GLbyte *);
-GLAPI void APIENTRY glVariantsvEXT (GLuint, const GLshort *);
-GLAPI void APIENTRY glVariantivEXT (GLuint, const GLint *);
-GLAPI void APIENTRY glVariantfvEXT (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVariantdvEXT (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVariantubvEXT (GLuint, const GLubyte *);
-GLAPI void APIENTRY glVariantusvEXT (GLuint, const GLushort *);
-GLAPI void APIENTRY glVariantuivEXT (GLuint, const GLuint *);
-GLAPI void APIENTRY glVariantPointerEXT (GLuint, GLenum, GLuint, const GLvoid *);
-GLAPI void APIENTRY glEnableVariantClientStateEXT (GLuint);
-GLAPI void APIENTRY glDisableVariantClientStateEXT (GLuint);
-GLAPI GLuint APIENTRY glBindLightParameterEXT (GLenum, GLenum);
-GLAPI GLuint APIENTRY glBindMaterialParameterEXT (GLenum, GLenum);
-GLAPI GLuint APIENTRY glBindTexGenParameterEXT (GLenum, GLenum, GLenum);
-GLAPI GLuint APIENTRY glBindTextureUnitParameterEXT (GLenum, GLenum);
-GLAPI GLuint APIENTRY glBindParameterEXT (GLenum);
-GLAPI GLboolean APIENTRY glIsVariantEnabledEXT (GLuint, GLenum);
-GLAPI void APIENTRY glGetVariantBooleanvEXT (GLuint, GLenum, GLboolean *);
-GLAPI void APIENTRY glGetVariantIntegervEXT (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetVariantFloatvEXT (GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetVariantPointervEXT (GLuint, GLenum, GLvoid* *);
-GLAPI void APIENTRY glGetInvariantBooleanvEXT (GLuint, GLenum, GLboolean *);
-GLAPI void APIENTRY glGetInvariantIntegervEXT (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetInvariantFloatvEXT (GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetLocalConstantBooleanvEXT (GLuint, GLenum, GLboolean *);
-GLAPI void APIENTRY glGetLocalConstantIntegervEXT (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetLocalConstantFloatvEXT (GLuint, GLenum, GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBEGINVERTEXSHADEREXTPROC) (void);
-typedef void (APIENTRYP PFNGLENDVERTEXSHADEREXTPROC) (void);
-typedef void (APIENTRYP PFNGLBINDVERTEXSHADEREXTPROC) (GLuint id);
-typedef GLuint (APIENTRYP PFNGLGENVERTEXSHADERSEXTPROC) (GLuint range);
-typedef void (APIENTRYP PFNGLDELETEVERTEXSHADEREXTPROC) (GLuint id);
-typedef void (APIENTRYP PFNGLSHADEROP1EXTPROC) (GLenum op, GLuint res, GLuint arg1);
-typedef void (APIENTRYP PFNGLSHADEROP2EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2);
-typedef void (APIENTRYP PFNGLSHADEROP3EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2, GLuint arg3);
-typedef void (APIENTRYP PFNGLSWIZZLEEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW);
-typedef void (APIENTRYP PFNGLWRITEMASKEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW);
-typedef void (APIENTRYP PFNGLINSERTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num);
-typedef void (APIENTRYP PFNGLEXTRACTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num);
-typedef GLuint (APIENTRYP PFNGLGENSYMBOLSEXTPROC) (GLenum datatype, GLenum storagetype, GLenum range, GLuint components);
-typedef void (APIENTRYP PFNGLSETINVARIANTEXTPROC) (GLuint id, GLenum type, const GLvoid *addr);
-typedef void (APIENTRYP PFNGLSETLOCALCONSTANTEXTPROC) (GLuint id, GLenum type, const GLvoid *addr);
-typedef void (APIENTRYP PFNGLVARIANTBVEXTPROC) (GLuint id, const GLbyte *addr);
-typedef void (APIENTRYP PFNGLVARIANTSVEXTPROC) (GLuint id, const GLshort *addr);
-typedef void (APIENTRYP PFNGLVARIANTIVEXTPROC) (GLuint id, const GLint *addr);
-typedef void (APIENTRYP PFNGLVARIANTFVEXTPROC) (GLuint id, const GLfloat *addr);
-typedef void (APIENTRYP PFNGLVARIANTDVEXTPROC) (GLuint id, const GLdouble *addr);
-typedef void (APIENTRYP PFNGLVARIANTUBVEXTPROC) (GLuint id, const GLubyte *addr);
-typedef void (APIENTRYP PFNGLVARIANTUSVEXTPROC) (GLuint id, const GLushort *addr);
-typedef void (APIENTRYP PFNGLVARIANTUIVEXTPROC) (GLuint id, const GLuint *addr);
-typedef void (APIENTRYP PFNGLVARIANTPOINTEREXTPROC) (GLuint id, GLenum type, GLuint stride, const GLvoid *addr);
-typedef void (APIENTRYP PFNGLENABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id);
-typedef void (APIENTRYP PFNGLDISABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id);
-typedef GLuint (APIENTRYP PFNGLBINDLIGHTPARAMETEREXTPROC) (GLenum light, GLenum value);
-typedef GLuint (APIENTRYP PFNGLBINDMATERIALPARAMETEREXTPROC) (GLenum face, GLenum value);
-typedef GLuint (APIENTRYP PFNGLBINDTEXGENPARAMETEREXTPROC) (GLenum unit, GLenum coord, GLenum value);
-typedef GLuint (APIENTRYP PFNGLBINDTEXTUREUNITPARAMETEREXTPROC) (GLenum unit, GLenum value);
-typedef GLuint (APIENTRYP PFNGLBINDPARAMETEREXTPROC) (GLenum value);
-typedef GLboolean (APIENTRYP PFNGLISVARIANTENABLEDEXTPROC) (GLuint id, GLenum cap);
-typedef void (APIENTRYP PFNGLGETVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data);
-typedef void (APIENTRYP PFNGLGETVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data);
-typedef void (APIENTRYP PFNGLGETVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data);
-typedef void (APIENTRYP PFNGLGETVARIANTPOINTERVEXTPROC) (GLuint id, GLenum value, GLvoid* *data);
-typedef void (APIENTRYP PFNGLGETINVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data);
-typedef void (APIENTRYP PFNGLGETINVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data);
-typedef void (APIENTRYP PFNGLGETINVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data);
-typedef void (APIENTRYP PFNGLGETLOCALCONSTANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data);
-typedef void (APIENTRYP PFNGLGETLOCALCONSTANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data);
-typedef void (APIENTRYP PFNGLGETLOCALCONSTANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data);
-#endif
-
-#ifndef GL_ATI_vertex_streams
-#define GL_ATI_vertex_streams 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glVertexStream1sATI (GLenum, GLshort);
-GLAPI void APIENTRY glVertexStream1svATI (GLenum, const GLshort *);
-GLAPI void APIENTRY glVertexStream1iATI (GLenum, GLint);
-GLAPI void APIENTRY glVertexStream1ivATI (GLenum, const GLint *);
-GLAPI void APIENTRY glVertexStream1fATI (GLenum, GLfloat);
-GLAPI void APIENTRY glVertexStream1fvATI (GLenum, const GLfloat *);
-GLAPI void APIENTRY glVertexStream1dATI (GLenum, GLdouble);
-GLAPI void APIENTRY glVertexStream1dvATI (GLenum, const GLdouble *);
-GLAPI void APIENTRY glVertexStream2sATI (GLenum, GLshort, GLshort);
-GLAPI void APIENTRY glVertexStream2svATI (GLenum, const GLshort *);
-GLAPI void APIENTRY glVertexStream2iATI (GLenum, GLint, GLint);
-GLAPI void APIENTRY glVertexStream2ivATI (GLenum, const GLint *);
-GLAPI void APIENTRY glVertexStream2fATI (GLenum, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexStream2fvATI (GLenum, const GLfloat *);
-GLAPI void APIENTRY glVertexStream2dATI (GLenum, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexStream2dvATI (GLenum, const GLdouble *);
-GLAPI void APIENTRY glVertexStream3sATI (GLenum, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glVertexStream3svATI (GLenum, const GLshort *);
-GLAPI void APIENTRY glVertexStream3iATI (GLenum, GLint, GLint, GLint);
-GLAPI void APIENTRY glVertexStream3ivATI (GLenum, const GLint *);
-GLAPI void APIENTRY glVertexStream3fATI (GLenum, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexStream3fvATI (GLenum, const GLfloat *);
-GLAPI void APIENTRY glVertexStream3dATI (GLenum, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexStream3dvATI (GLenum, const GLdouble *);
-GLAPI void APIENTRY glVertexStream4sATI (GLenum, GLshort, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glVertexStream4svATI (GLenum, const GLshort *);
-GLAPI void APIENTRY glVertexStream4iATI (GLenum, GLint, GLint, GLint, GLint);
-GLAPI void APIENTRY glVertexStream4ivATI (GLenum, const GLint *);
-GLAPI void APIENTRY glVertexStream4fATI (GLenum, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexStream4fvATI (GLenum, const GLfloat *);
-GLAPI void APIENTRY glVertexStream4dATI (GLenum, GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexStream4dvATI (GLenum, const GLdouble *);
-GLAPI void APIENTRY glNormalStream3bATI (GLenum, GLbyte, GLbyte, GLbyte);
-GLAPI void APIENTRY glNormalStream3bvATI (GLenum, const GLbyte *);
-GLAPI void APIENTRY glNormalStream3sATI (GLenum, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glNormalStream3svATI (GLenum, const GLshort *);
-GLAPI void APIENTRY glNormalStream3iATI (GLenum, GLint, GLint, GLint);
-GLAPI void APIENTRY glNormalStream3ivATI (GLenum, const GLint *);
-GLAPI void APIENTRY glNormalStream3fATI (GLenum, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glNormalStream3fvATI (GLenum, const GLfloat *);
-GLAPI void APIENTRY glNormalStream3dATI (GLenum, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glNormalStream3dvATI (GLenum, const GLdouble *);
-GLAPI void APIENTRY glClientActiveVertexStreamATI (GLenum);
-GLAPI void APIENTRY glVertexBlendEnviATI (GLenum, GLint);
-GLAPI void APIENTRY glVertexBlendEnvfATI (GLenum, GLfloat);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLVERTEXSTREAM1SATIPROC) (GLenum stream, GLshort x);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM1SVATIPROC) (GLenum stream, const GLshort *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM1IATIPROC) (GLenum stream, GLint x);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM1IVATIPROC) (GLenum stream, const GLint *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM1FATIPROC) (GLenum stream, GLfloat x);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM1FVATIPROC) (GLenum stream, const GLfloat *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM1DATIPROC) (GLenum stream, GLdouble x);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM1DVATIPROC) (GLenum stream, const GLdouble *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM2SATIPROC) (GLenum stream, GLshort x, GLshort y);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM2SVATIPROC) (GLenum stream, const GLshort *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM2IATIPROC) (GLenum stream, GLint x, GLint y);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM2IVATIPROC) (GLenum stream, const GLint *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM2FATIPROC) (GLenum stream, GLfloat x, GLfloat y);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM2FVATIPROC) (GLenum stream, const GLfloat *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM2DATIPROC) (GLenum stream, GLdouble x, GLdouble y);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM2DVATIPROC) (GLenum stream, const GLdouble *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM3SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM3IATIPROC) (GLenum stream, GLint x, GLint y, GLint z);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM3IVATIPROC) (GLenum stream, const GLint *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM3FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM3DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM4SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z, GLshort w);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM4SVATIPROC) (GLenum stream, const GLshort *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM4IATIPROC) (GLenum stream, GLint x, GLint y, GLint z, GLint w);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM4IVATIPROC) (GLenum stream, const GLint *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM4FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM4FVATIPROC) (GLenum stream, const GLfloat *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM4DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM4DVATIPROC) (GLenum stream, const GLdouble *coords);
-typedef void (APIENTRYP PFNGLNORMALSTREAM3BATIPROC) (GLenum stream, GLbyte nx, GLbyte ny, GLbyte nz);
-typedef void (APIENTRYP PFNGLNORMALSTREAM3BVATIPROC) (GLenum stream, const GLbyte *coords);
-typedef void (APIENTRYP PFNGLNORMALSTREAM3SATIPROC) (GLenum stream, GLshort nx, GLshort ny, GLshort nz);
-typedef void (APIENTRYP PFNGLNORMALSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords);
-typedef void (APIENTRYP PFNGLNORMALSTREAM3IATIPROC) (GLenum stream, GLint nx, GLint ny, GLint nz);
-typedef void (APIENTRYP PFNGLNORMALSTREAM3IVATIPROC) (GLenum stream, const GLint *coords);
-typedef void (APIENTRYP PFNGLNORMALSTREAM3FATIPROC) (GLenum stream, GLfloat nx, GLfloat ny, GLfloat nz);
-typedef void (APIENTRYP PFNGLNORMALSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords);
-typedef void (APIENTRYP PFNGLNORMALSTREAM3DATIPROC) (GLenum stream, GLdouble nx, GLdouble ny, GLdouble nz);
-typedef void (APIENTRYP PFNGLNORMALSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords);
-typedef void (APIENTRYP PFNGLCLIENTACTIVEVERTEXSTREAMATIPROC) (GLenum stream);
-typedef void (APIENTRYP PFNGLVERTEXBLENDENVIATIPROC) (GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLVERTEXBLENDENVFATIPROC) (GLenum pname, GLfloat param);
-#endif
-
-#ifndef GL_ATI_element_array
-#define GL_ATI_element_array 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glElementPointerATI (GLenum, const GLvoid *);
-GLAPI void APIENTRY glDrawElementArrayATI (GLenum, GLsizei);
-GLAPI void APIENTRY glDrawRangeElementArrayATI (GLenum, GLuint, GLuint, GLsizei);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLELEMENTPOINTERATIPROC) (GLenum type, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYATIPROC) (GLenum mode, GLsizei count);
-typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYATIPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count);
-#endif
-
-#ifndef GL_SUN_mesh_array
-#define GL_SUN_mesh_array 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glDrawMeshArraysSUN (GLenum, GLint, GLsizei, GLsizei);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLDRAWMESHARRAYSSUNPROC) (GLenum mode, GLint first, GLsizei count, GLsizei width);
-#endif
-
-#ifndef GL_SUN_slice_accum
-#define GL_SUN_slice_accum 1
-#endif
-
-#ifndef GL_NV_multisample_filter_hint
-#define GL_NV_multisample_filter_hint 1
-#endif
-
-#ifndef GL_NV_depth_clamp
-#define GL_NV_depth_clamp 1
-#endif
-
-#ifndef GL_NV_occlusion_query
-#define GL_NV_occlusion_query 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glGenOcclusionQueriesNV (GLsizei, GLuint *);
-GLAPI void APIENTRY glDeleteOcclusionQueriesNV (GLsizei, const GLuint *);
-GLAPI GLboolean APIENTRY glIsOcclusionQueryNV (GLuint);
-GLAPI void APIENTRY glBeginOcclusionQueryNV (GLuint);
-GLAPI void APIENTRY glEndOcclusionQueryNV (void);
-GLAPI void APIENTRY glGetOcclusionQueryivNV (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetOcclusionQueryuivNV (GLuint, GLenum, GLuint *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLGENOCCLUSIONQUERIESNVPROC) (GLsizei n, GLuint *ids);
-typedef void (APIENTRYP PFNGLDELETEOCCLUSIONQUERIESNVPROC) (GLsizei n, const GLuint *ids);
-typedef GLboolean (APIENTRYP PFNGLISOCCLUSIONQUERYNVPROC) (GLuint id);
-typedef void (APIENTRYP PFNGLBEGINOCCLUSIONQUERYNVPROC) (GLuint id);
-typedef void (APIENTRYP PFNGLENDOCCLUSIONQUERYNVPROC) (void);
-typedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYIVNVPROC) (GLuint id, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYUIVNVPROC) (GLuint id, GLenum pname, GLuint *params);
-#endif
-
-#ifndef GL_NV_point_sprite
-#define GL_NV_point_sprite 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPointParameteriNV (GLenum, GLint);
-GLAPI void APIENTRY glPointParameterivNV (GLenum, const GLint *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPOINTPARAMETERINVPROC) (GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLPOINTPARAMETERIVNVPROC) (GLenum pname, const GLint *params);
-#endif
-
-#ifndef GL_NV_texture_shader3
-#define GL_NV_texture_shader3 1
-#endif
-
-#ifndef GL_NV_vertex_program1_1
-#define GL_NV_vertex_program1_1 1
-#endif
-
-#ifndef GL_EXT_shadow_funcs
-#define GL_EXT_shadow_funcs 1
-#endif
-
-#ifndef GL_EXT_stencil_two_side
-#define GL_EXT_stencil_two_side 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glActiveStencilFaceEXT (GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLACTIVESTENCILFACEEXTPROC) (GLenum face);
-#endif
-
-#ifndef GL_ATI_text_fragment_shader
-#define GL_ATI_text_fragment_shader 1
-#endif
-
-#ifndef GL_APPLE_client_storage
-#define GL_APPLE_client_storage 1
-#endif
-
-#ifndef GL_APPLE_element_array
-#define GL_APPLE_element_array 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glElementPointerAPPLE (GLenum, const GLvoid *);
-GLAPI void APIENTRY glDrawElementArrayAPPLE (GLenum, GLint, GLsizei);
-GLAPI void APIENTRY glDrawRangeElementArrayAPPLE (GLenum, GLuint, GLuint, GLint, GLsizei);
-GLAPI void APIENTRY glMultiDrawElementArrayAPPLE (GLenum, const GLint *, const GLsizei *, GLsizei);
-GLAPI void APIENTRY glMultiDrawRangeElementArrayAPPLE (GLenum, GLuint, GLuint, const GLint *, const GLsizei *, GLsizei);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLELEMENTPOINTERAPPLEPROC) (GLenum type, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, GLint first, GLsizei count);
-typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count);
-typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount);
-typedef void (APIENTRYP PFNGLMULTIDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount);
-#endif
-
-#ifndef GL_APPLE_fence
-#define GL_APPLE_fence 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glGenFencesAPPLE (GLsizei, GLuint *);
-GLAPI void APIENTRY glDeleteFencesAPPLE (GLsizei, const GLuint *);
-GLAPI void APIENTRY glSetFenceAPPLE (GLuint);
-GLAPI GLboolean APIENTRY glIsFenceAPPLE (GLuint);
-GLAPI GLboolean APIENTRY glTestFenceAPPLE (GLuint);
-GLAPI void APIENTRY glFinishFenceAPPLE (GLuint);
-GLAPI GLboolean APIENTRY glTestObjectAPPLE (GLenum, GLuint);
-GLAPI void APIENTRY glFinishObjectAPPLE (GLenum, GLint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLGENFENCESAPPLEPROC) (GLsizei n, GLuint *fences);
-typedef void (APIENTRYP PFNGLDELETEFENCESAPPLEPROC) (GLsizei n, const GLuint *fences);
-typedef void (APIENTRYP PFNGLSETFENCEAPPLEPROC) (GLuint fence);
-typedef GLboolean (APIENTRYP PFNGLISFENCEAPPLEPROC) (GLuint fence);
-typedef GLboolean (APIENTRYP PFNGLTESTFENCEAPPLEPROC) (GLuint fence);
-typedef void (APIENTRYP PFNGLFINISHFENCEAPPLEPROC) (GLuint fence);
-typedef GLboolean (APIENTRYP PFNGLTESTOBJECTAPPLEPROC) (GLenum object, GLuint name);
-typedef void (APIENTRYP PFNGLFINISHOBJECTAPPLEPROC) (GLenum object, GLint name);
-#endif
-
-#ifndef GL_APPLE_vertex_array_object
-#define GL_APPLE_vertex_array_object 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBindVertexArrayAPPLE (GLuint);
-GLAPI void APIENTRY glDeleteVertexArraysAPPLE (GLsizei, const GLuint *);
-GLAPI void APIENTRY glGenVertexArraysAPPLE (GLsizei, const GLuint *);
-GLAPI GLboolean APIENTRY glIsVertexArrayAPPLE (GLuint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBINDVERTEXARRAYAPPLEPROC) (GLuint array);
-typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSAPPLEPROC) (GLsizei n, const GLuint *arrays);
-typedef void (APIENTRYP PFNGLGENVERTEXARRAYSAPPLEPROC) (GLsizei n, const GLuint *arrays);
-typedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYAPPLEPROC) (GLuint array);
-#endif
-
-#ifndef GL_APPLE_vertex_array_range
-#define GL_APPLE_vertex_array_range 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glVertexArrayRangeAPPLE (GLsizei, GLvoid *);
-GLAPI void APIENTRY glFlushVertexArrayRangeAPPLE (GLsizei, GLvoid *);
-GLAPI void APIENTRY glVertexArrayParameteriAPPLE (GLenum, GLint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, GLvoid *pointer);
-typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, GLvoid *pointer);
-typedef void (APIENTRYP PFNGLVERTEXARRAYPARAMETERIAPPLEPROC) (GLenum pname, GLint param);
-#endif
-
-#ifndef GL_APPLE_ycbcr_422
-#define GL_APPLE_ycbcr_422 1
-#endif
-
-#ifndef GL_S3_s3tc
-#define GL_S3_s3tc 1
-#endif
-
-#ifndef GL_ATI_draw_buffers
-#define GL_ATI_draw_buffers 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glDrawBuffersATI (GLsizei, const GLenum *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLDRAWBUFFERSATIPROC) (GLsizei n, const GLenum *bufs);
-#endif
-
-#ifndef GL_ATI_pixel_format_float
-#define GL_ATI_pixel_format_float 1
-/* This is really a WGL extension, but defines some associated GL enums.
- * ATI does not export "GL_ATI_pixel_format_float" in the GL_EXTENSIONS string.
- */
-#endif
-
-#ifndef GL_ATI_texture_env_combine3
-#define GL_ATI_texture_env_combine3 1
-#endif
-
-#ifndef GL_ATI_texture_float
-#define GL_ATI_texture_float 1
-#endif
-
-#ifndef GL_NV_float_buffer
-#define GL_NV_float_buffer 1
-#endif
-
-#ifndef GL_NV_fragment_program
-#define GL_NV_fragment_program 1
-/* Some NV_fragment_program entry points are shared with ARB_vertex_program. */
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glProgramNamedParameter4fNV (GLuint, GLsizei, const GLubyte *, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glProgramNamedParameter4dNV (GLuint, GLsizei, const GLubyte *, GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glProgramNamedParameter4fvNV (GLuint, GLsizei, const GLubyte *, const GLfloat *);
-GLAPI void APIENTRY glProgramNamedParameter4dvNV (GLuint, GLsizei, const GLubyte *, const GLdouble *);
-GLAPI void APIENTRY glGetProgramNamedParameterfvNV (GLuint, GLsizei, const GLubyte *, GLfloat *);
-GLAPI void APIENTRY glGetProgramNamedParameterdvNV (GLuint, GLsizei, const GLubyte *, GLdouble *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
-typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLfloat *v);
-typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLdouble *v);
-typedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERFVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERDVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble *params);
-#endif
-
-#ifndef GL_NV_half_float
-#define GL_NV_half_float 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glVertex2hNV (GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glVertex2hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glVertex3hNV (GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glVertex3hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glVertex4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glVertex4hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glNormal3hNV (GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glNormal3hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glColor3hNV (GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glColor3hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glColor4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glColor4hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glTexCoord1hNV (GLhalfNV);
-GLAPI void APIENTRY glTexCoord1hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glTexCoord2hNV (GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glTexCoord2hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glTexCoord3hNV (GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glTexCoord3hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glTexCoord4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glTexCoord4hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glMultiTexCoord1hNV (GLenum, GLhalfNV);
-GLAPI void APIENTRY glMultiTexCoord1hvNV (GLenum, const GLhalfNV *);
-GLAPI void APIENTRY glMultiTexCoord2hNV (GLenum, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glMultiTexCoord2hvNV (GLenum, const GLhalfNV *);
-GLAPI void APIENTRY glMultiTexCoord3hNV (GLenum, GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glMultiTexCoord3hvNV (GLenum, const GLhalfNV *);
-GLAPI void APIENTRY glMultiTexCoord4hNV (GLenum, GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glMultiTexCoord4hvNV (GLenum, const GLhalfNV *);
-GLAPI void APIENTRY glFogCoordhNV (GLhalfNV);
-GLAPI void APIENTRY glFogCoordhvNV (const GLhalfNV *);
-GLAPI void APIENTRY glSecondaryColor3hNV (GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glSecondaryColor3hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glVertexWeighthNV (GLhalfNV);
-GLAPI void APIENTRY glVertexWeighthvNV (const GLhalfNV *);
-GLAPI void APIENTRY glVertexAttrib1hNV (GLuint, GLhalfNV);
-GLAPI void APIENTRY glVertexAttrib1hvNV (GLuint, const GLhalfNV *);
-GLAPI void APIENTRY glVertexAttrib2hNV (GLuint, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glVertexAttrib2hvNV (GLuint, const GLhalfNV *);
-GLAPI void APIENTRY glVertexAttrib3hNV (GLuint, GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glVertexAttrib3hvNV (GLuint, const GLhalfNV *);
-GLAPI void APIENTRY glVertexAttrib4hNV (GLuint, GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glVertexAttrib4hvNV (GLuint, const GLhalfNV *);
-GLAPI void APIENTRY glVertexAttribs1hvNV (GLuint, GLsizei, const GLhalfNV *);
-GLAPI void APIENTRY glVertexAttribs2hvNV (GLuint, GLsizei, const GLhalfNV *);
-GLAPI void APIENTRY glVertexAttribs3hvNV (GLuint, GLsizei, const GLhalfNV *);
-GLAPI void APIENTRY glVertexAttribs4hvNV (GLuint, GLsizei, const GLhalfNV *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLVERTEX2HNVPROC) (GLhalfNV x, GLhalfNV y);
-typedef void (APIENTRYP PFNGLVERTEX2HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLVERTEX3HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z);
-typedef void (APIENTRYP PFNGLVERTEX3HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLVERTEX4HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w);
-typedef void (APIENTRYP PFNGLVERTEX4HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLNORMAL3HNVPROC) (GLhalfNV nx, GLhalfNV ny, GLhalfNV nz);
-typedef void (APIENTRYP PFNGLNORMAL3HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue);
-typedef void (APIENTRYP PFNGLCOLOR3HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLCOLOR4HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue, GLhalfNV alpha);
-typedef void (APIENTRYP PFNGLCOLOR4HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLTEXCOORD1HNVPROC) (GLhalfNV s);
-typedef void (APIENTRYP PFNGLTEXCOORD1HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLTEXCOORD2HNVPROC) (GLhalfNV s, GLhalfNV t);
-typedef void (APIENTRYP PFNGLTEXCOORD2HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLTEXCOORD3HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r);
-typedef void (APIENTRYP PFNGLTEXCOORD3HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLTEXCOORD4HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q);
-typedef void (APIENTRYP PFNGLTEXCOORD4HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1HNVPROC) (GLenum target, GLhalfNV s);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1HVNVPROC) (GLenum target, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2HVNVPROC) (GLenum target, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3HVNVPROC) (GLenum target, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4HVNVPROC) (GLenum target, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLFOGCOORDHNVPROC) (GLhalfNV fog);
-typedef void (APIENTRYP PFNGLFOGCOORDHVNVPROC) (const GLhalfNV *fog);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLVERTEXWEIGHTHNVPROC) (GLhalfNV weight);
-typedef void (APIENTRYP PFNGLVERTEXWEIGHTHVNVPROC) (const GLhalfNV *weight);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1HNVPROC) (GLuint index, GLhalfNV x);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1HVNVPROC) (GLuint index, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2HVNVPROC) (GLuint index, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3HVNVPROC) (GLuint index, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4HVNVPROC) (GLuint index, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS1HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS2HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS3HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS4HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);
-#endif
-
-#ifndef GL_NV_pixel_data_range
-#define GL_NV_pixel_data_range 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPixelDataRangeNV (GLenum, GLsizei, GLvoid *);
-GLAPI void APIENTRY glFlushPixelDataRangeNV (GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPIXELDATARANGENVPROC) (GLenum target, GLsizei length, GLvoid *pointer);
-typedef void (APIENTRYP PFNGLFLUSHPIXELDATARANGENVPROC) (GLenum target);
-#endif
-
-#ifndef GL_NV_primitive_restart
-#define GL_NV_primitive_restart 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPrimitiveRestartNV (void);
-GLAPI void APIENTRY glPrimitiveRestartIndexNV (GLuint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPRIMITIVERESTARTNVPROC) (void);
-typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXNVPROC) (GLuint index);
-#endif
-
-#ifndef GL_NV_texture_expand_normal
-#define GL_NV_texture_expand_normal 1
-#endif
-
-#ifndef GL_NV_vertex_program2
-#define GL_NV_vertex_program2 1
-#endif
-
-#ifndef GL_ATI_map_object_buffer
-#define GL_ATI_map_object_buffer 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI GLvoid* APIENTRY glMapObjectBufferATI (GLuint);
-GLAPI void APIENTRY glUnmapObjectBufferATI (GLuint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef GLvoid* (APIENTRYP PFNGLMAPOBJECTBUFFERATIPROC) (GLuint buffer);
-typedef void (APIENTRYP PFNGLUNMAPOBJECTBUFFERATIPROC) (GLuint buffer);
-#endif
-
-#ifndef GL_ATI_separate_stencil
-#define GL_ATI_separate_stencil 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glStencilOpSeparateATI (GLenum, GLenum, GLenum, GLenum);
-GLAPI void APIENTRY glStencilFuncSeparateATI (GLenum, GLenum, GLint, GLuint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEATIPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);
-typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEATIPROC) (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask);
-#endif
-
-#ifndef GL_ATI_vertex_attrib_array_object
-#define GL_ATI_vertex_attrib_array_object 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glVertexAttribArrayObjectATI (GLuint, GLint, GLenum, GLboolean, GLsizei, GLuint, GLuint);
-GLAPI void APIENTRY glGetVertexAttribArrayObjectfvATI (GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetVertexAttribArrayObjectivATI (GLuint, GLenum, GLint *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLVERTEXATTRIBARRAYOBJECTATIPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLuint buffer, GLuint offset);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTFVATIPROC) (GLuint index, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTIVATIPROC) (GLuint index, GLenum pname, GLint *params);
-#endif
-
-#ifndef GL_OES_read_format
-#define GL_OES_read_format 1
-#endif
-
-#ifndef GL_EXT_depth_bounds_test
-#define GL_EXT_depth_bounds_test 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glDepthBoundsEXT (GLclampd, GLclampd);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLDEPTHBOUNDSEXTPROC) (GLclampd zmin, GLclampd zmax);
-#endif
-
-#ifndef GL_EXT_texture_mirror_clamp
-#define GL_EXT_texture_mirror_clamp 1
-#endif
-
-#ifndef GL_EXT_blend_equation_separate
-#define GL_EXT_blend_equation_separate 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBlendEquationSeparateEXT (GLenum, GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEEXTPROC) (GLenum modeRGB, GLenum modeAlpha);
-#endif
-
-#ifndef GL_MESA_pack_invert
-#define GL_MESA_pack_invert 1
-#endif
-
-#ifndef GL_MESA_ycbcr_texture
-#define GL_MESA_ycbcr_texture 1
-#endif
-
-#ifndef GL_EXT_pixel_buffer_object
-#define GL_EXT_pixel_buffer_object 1
-#endif
-
-#ifndef GL_NV_fragment_program_option
-#define GL_NV_fragment_program_option 1
-#endif
-
-#ifndef GL_NV_fragment_program2
-#define GL_NV_fragment_program2 1
-#endif
-
-#ifndef GL_NV_vertex_program2_option
-#define GL_NV_vertex_program2_option 1
-#endif
-
-#ifndef GL_NV_vertex_program3
-#define GL_NV_vertex_program3 1
-#endif
-
-#ifndef GL_EXT_framebuffer_object
-#define GL_EXT_framebuffer_object 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI GLboolean APIENTRY glIsRenderbufferEXT (GLuint);
-GLAPI void APIENTRY glBindRenderbufferEXT (GLenum, GLuint);
-GLAPI void APIENTRY glDeleteRenderbuffersEXT (GLsizei, const GLuint *);
-GLAPI void APIENTRY glGenRenderbuffersEXT (GLsizei, GLuint *);
-GLAPI void APIENTRY glRenderbufferStorageEXT (GLenum, GLenum, GLsizei, GLsizei);
-GLAPI void APIENTRY glGetRenderbufferParameterivEXT (GLenum, GLenum, GLint *);
-GLAPI GLboolean APIENTRY glIsFramebufferEXT (GLuint);
-GLAPI void APIENTRY glBindFramebufferEXT (GLenum, GLuint);
-GLAPI void APIENTRY glDeleteFramebuffersEXT (GLsizei, const GLuint *);
-GLAPI void APIENTRY glGenFramebuffersEXT (GLsizei, GLuint *);
-GLAPI GLenum APIENTRY glCheckFramebufferStatusEXT (GLenum);
-GLAPI void APIENTRY glFramebufferTexture1DEXT (GLenum, GLenum, GLenum, GLuint, GLint);
-GLAPI void APIENTRY glFramebufferTexture2DEXT (GLenum, GLenum, GLenum, GLuint, GLint);
-GLAPI void APIENTRY glFramebufferTexture3DEXT (GLenum, GLenum, GLenum, GLuint, GLint, GLint);
-GLAPI void APIENTRY glFramebufferRenderbufferEXT (GLenum, GLenum, GLenum, GLuint);
-GLAPI void APIENTRY glGetFramebufferAttachmentParameterivEXT (GLenum, GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGenerateMipmapEXT (GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFEREXTPROC) (GLuint renderbuffer);
-typedef void (APIENTRYP PFNGLBINDRENDERBUFFEREXTPROC) (GLenum target, GLuint renderbuffer);
-typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSEXTPROC) (GLsizei n, const GLuint *renderbuffers);
-typedef void (APIENTRYP PFNGLGENRENDERBUFFERSEXTPROC) (GLsizei n, GLuint *renderbuffers);
-typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
-typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
-typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFEREXTPROC) (GLuint framebuffer);
-typedef void (APIENTRYP PFNGLBINDFRAMEBUFFEREXTPROC) (GLenum target, GLuint framebuffer);
-typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSEXTPROC) (GLsizei n, const GLuint *framebuffers);
-typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSEXTPROC) (GLsizei n, GLuint *framebuffers);
-typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) (GLenum target);
-typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
-typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
-typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);
-typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
-typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC) (GLenum target, GLenum attachment, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGENERATEMIPMAPEXTPROC) (GLenum target);
-#endif
-
-#ifndef GL_GREMEDY_string_marker
-#define GL_GREMEDY_string_marker 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glStringMarkerGREMEDY (GLsizei, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLSTRINGMARKERGREMEDYPROC) (GLsizei len, const GLvoid *string);
-#endif
-
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/mkglext.py b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/mkglext.py
deleted file mode 100644
index 8f4065b3d6a..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/mkglext.py
+++ /dev/null
@@ -1,627 +0,0 @@
-#!/usr/bin/python
-#
-# $Id$
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-# The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
-# All rights reserved.
-#
-# The Original Code is: all of this file.
-#
-# Contributor(s): none yet.
-#
-# ***** END GPL LICENSE BLOCK *****
-
-#
-# mkglext.py generates code for linking extensions.
-#
-# It reads the glext.h header from stdin and writes code to stdout.
-#
-# Usage: mkglext.py < glext.h > tmp
-# Code can be copied & pasted from tmp to GL_ExtensionManager.cpp.
-#
-# glext.h is available here: http://oss.sgi.com/projects/ogl-sample/ABI/glext.h
-#
-
-from sys import stdin
-import string, re
-
-glext_h = string.split(stdin.read(), '\n')
-
-# These extensions have been incorporated into the core GL or been superceded.
-# Code will not be generated for these extensions
-blacklist = [
- "GL_EXT_multisample",
- "GL_INGR_blend_func_separate",
- "GL_SGIX_fragment_lighting",
- "GL_SGIX_polynomial_ffd",
- "GL_SGIS_point_parameters",
- "GL_EXT_texture_object",
- "GL_EXT_subtexture",
- "GL_EXT_copy_texture",
- "GL_EXT_vertex_array",
- "GL_EXT_point_parameters",
- "GL_EXT_blend_color",
- "GL_EXT_polygon_offset",
- "GL_EXT_texture"]
-
-# Only code for these extensions will be generated. Extensions on both the
-# blacklist & whitelist will not have code generated.
-# This list is from http://oss.sgi.com/projects/ogl-sample/registry/ at 14-Mar-04
-whitelist = [
- # ARB Extensions
- "GL_ARB_multitexture",
- "GLX_ARB_get_proc_address",
- "GL_ARB_transpose_matrix",
- "WGL_ARB_buffer_region",
- "GL_ARB_multisample",
- "GL_ARB_texture_env_add",
- "GL_ARB_texture_cube_map",
- "WGL_ARB_extensions_string",
- "WGL_ARB_pixel_format",
- "WGL_ARB_make_current_read",
- "WGL_ARB_pbuffer",
- "GL_ARB_texture_compression",
- "GL_ARB_texture_border_clamp",
- "GL_ARB_point_parameters",
- "GL_ARB_vertex_blend",
- "GL_ARB_matrix_palette",
- "GL_ARB_texture_env_combine",
- "GL_ARB_texture_env_crossbar",
- "GL_ARB_texture_env_dot3",
- "WGL_ARB_render_texture",
- "GL_ARB_texture_mirrored_repeat",
- "GL_ARB_depth_texture",
- "GL_ARB_shadow",
- "GL_ARB_shadow_ambient",
- "GL_ARB_window_pos",
- "GL_ARB_vertex_program",
- "GL_ARB_fragment_program",
- "GL_ARB_vertex_buffer_object",
- "GL_ARB_occlusion_query",
- "GL_ARB_shader_objects",
- "GL_ARB_vertex_shader",
- "GL_ARB_fragment_shader",
- "GL_ARB_shading_language_100",
- "GL_ARB_texture_non_power_of_two",
- "GL_ARB_point_sprite",
- "GL_ARB_fragment_program_shadow",
-
- # Non ARB Extensions
- "GL_EXT_abgr",
- "GL_EXT_blend_color",
- "GL_EXT_polygon_offset",
- "GL_EXT_texture",
- "GL_EXT_texture3D",
- "GL_SGIS_texture_filter4",
- "GL_EXT_subtexture",
- "GL_EXT_copy_texture",
- "GL_EXT_histogram",
- "GL_EXT_convolution",
- "GL_SGI_color_matrix",
- "GL_SGI_color_table",
- "GL_SGIS_pixel_texture",
- "GL_SGIS_texture4D",
- "GL_SGI_texture_color_table",
- "GL_EXT_cmyka",
- "GL_EXT_texture_object",
- "GL_SGIS_detail_texture",
- "GL_SGIS_sharpen_texture",
- "GL_EXT_packed_pixels",
- "GL_SGIS_texture_lod",
- "GL_SGIS_multisample",
- "GL_EXT_rescale_normal",
- "GLX_EXT_visual_info",
- "GL_EXT_vertex_array",
- "GL_EXT_misc_attribute",
- "GL_SGIS_generate_mipmap",
- "GL_SGIX_clipmap",
- "GL_SGIX_shadow",
- "GL_SGIS_texture_edge_clamp",
- "GL_SGIS_texture_border_clamp",
- "GL_EXT_blend_minmax",
- "GL_EXT_blend_subtract",
- "GL_EXT_blend_logic_op",
- "GLX_SGI_swap_control",
- "GLX_SGI_video_sync",
- "GLX_SGI_make_current_read",
- "GLX_SGIX_video_source",
- "GLX_EXT_visual_rating",
- "GL_SGIX_interlace",
- "GLX_EXT_import_context",
- "GLX_SGIX_fbconfig",
- "GLX_SGIX_pbuffer",
- "GL_SGIS_texture_select",
- "GL_SGIX_sprite",
- "GL_SGIX_texture_multi_buffer",
- "GL_EXT_point_parameters",
- "GL_SGIX_instruments",
- "GL_SGIX_texture_scale_bias",
- "GL_SGIX_framezoom",
- "GL_SGIX_tag_sample_buffer",
- "GL_SGIX_reference_plane",
- "GL_SGIX_flush_raster",
- "GLX_SGI_cushion",
- "GL_SGIX_depth_texture",
- "GL_SGIS_fog_function",
- "GL_SGIX_fog_offset",
- "GL_HP_image_transform",
- "GL_HP_convolution_border_modes",
- "GL_SGIX_texture_add_env",
- "GL_EXT_color_subtable",
- "GLU_EXT_object_space_tess",
- "GL_PGI_vertex_hints",
- "GL_PGI_misc_hints",
- "GL_EXT_paletted_texture",
- "GL_EXT_clip_volume_hint",
- "GL_SGIX_list_priority",
- "GL_SGIX_ir_instrument1",
- "GLX_SGIX_video_resize",
- "GL_SGIX_texture_lod_bias",
- "GLU_SGI_filter4_parameters",
- "GLX_SGIX_dm_buffer",
- "GL_SGIX_shadow_ambient",
- "GLX_SGIX_swap_group",
- "GLX_SGIX_swap_barrier",
- "GL_EXT_index_texture",
- "GL_EXT_index_material",
- "GL_EXT_index_func",
- "GL_EXT_index_array_formats",
- "GL_EXT_compiled_vertex_array",
- "GL_EXT_cull_vertex",
- "GLU_EXT_nurbs_tessellator",
- "GL_SGIX_ycrcb",
- "GL_EXT_fragment_lighting",
- "GL_IBM_rasterpos_clip",
- "GL_HP_texture_lighting",
- "GL_EXT_draw_range_elements",
- "GL_WIN_phong_shading",
- "GL_WIN_specular_fog",
- "GLX_SGIS_color_range",
- "GL_EXT_light_texture",
- "GL_SGIX_blend_alpha_minmax",
- "GL_EXT_scene_marker",
- "GL_SGIX_pixel_texture_bits",
- "GL_EXT_bgra",
- "GL_SGIX_async",
- "GL_SGIX_async_pixel",
- "GL_SGIX_async_histogram",
- "GL_INTEL_texture_scissor",
- "GL_INTEL_parallel_arrays",
- "GL_HP_occlusion_test",
- "GL_EXT_pixel_transform",
- "GL_EXT_pixel_transform_color_table",
- "GL_EXT_shared_texture_palette",
- "GLX_SGIS_blended_overlay",
- "GL_EXT_separate_specular_color",
- "GL_EXT_secondary_color",
- "GL_EXT_texture_env",
- "GL_EXT_texture_perturb_normal",
- "GL_EXT_multi_draw_arrays",
- "GL_EXT_fog_coord",
- "GL_REND_screen_coordinates",
- "GL_EXT_coordinate_frame",
- "GL_EXT_texture_env_combine",
- "GL_APPLE_specular_vector",
- "GL_SGIX_pixel_texture",
- "GL_APPLE_transform_hint",
- "GL_SUNX_constant_data",
- "GL_SUN_global_alpha",
- "GL_SUN_triangle_list",
- "GL_SUN_vertex",
- "WGL_EXT_display_color_table",
- "WGL_EXT_extensions_string",
- "WGL_EXT_make_current_read",
- "WGL_EXT_pixel_format",
- "WGL_EXT_pbuffer",
- "WGL_EXT_swap_control",
- "GL_EXT_blend_func_separate",
- "GL_INGR_color_clamp",
- "GL_INGR_interlace_read",
- "GL_EXT_stencil_wrap",
- "WGL_EXT_depth_float",
- "GL_EXT_422_pixels",
- "GL_NV_texgen_reflection",
- "GL_SGIX_texture_range",
- "GL_SUN_convolution_border_modes",
- "GLX_SUN_get_transparent_index",
- "GL_EXT_texture_env_add",
- "GL_EXT_texture_lod_bias",
- "GL_EXT_texture_filter_anisotropic",
- "GL_EXT_vertex_weighting",
- "GL_NV_light_max_exponent",
- "GL_NV_vertex_array_range",
- "GL_NV_register_combiners",
- "GL_NV_fog_distance",
- "GL_NV_texgen_emboss",
- "GL_NV_blend_square",
- "GL_NV_texture_env_combine4",
- "GL_MESA_resize_buffers",
- "GL_MESA_window_pos",
- "GL_EXT_texture_compression_s3tc",
- "GL_IBM_cull_vertex",
- "GL_IBM_multimode_draw_arrays",
- "GL_IBM_vertex_array_lists",
- "GL_3DFX_texture_compression_FXT1",
- "GL_3DFX_multisample",
- "GL_3DFX_tbuffer",
- "WGL_EXT_multisample",
- "GL_SGIX_vertex_preclip",
- "GL_SGIX_resample",
- "GL_SGIS_texture_color_mask",
- "GLX_MESA_copy_sub_buffer",
- "GLX_MESA_pixmap_colormap",
- "GLX_MESA_release_buffers",
- "GLX_MESA_set_3dfx_mode",
- "GL_EXT_texture_env_dot3",
- "GL_ATI_texture_mirror_once",
- "GL_NV_fence",
- "GL_IBM_static_data",
- "GL_IBM_texture_mirrored_repeat",
- "GL_NV_evaluators",
- "GL_NV_packed_depth_stencil",
- "GL_NV_register_combiners2",
- "GL_NV_texture_compression_vtc",
- "GL_NV_texture_rectangle",
- "GL_NV_texture_shader",
- "GL_NV_texture_shader2",
- "GL_NV_vertex_array_range2",
- "GL_NV_vertex_program",
- "GLX_SGIX_visual_select_group",
- "GL_SGIX_texture_coordinate_clamp",
- "GLX_OML_swap_method",
- "GLX_OML_sync_control",
- "GL_OML_interlace",
- "GL_OML_subsample",
- "GL_OML_resample",
- "WGL_OML_sync_control",
- "GL_NV_copy_depth_to_color",
- "GL_ATI_envmap_bumpmap",
- "GL_ATI_fragment_shader",
- "GL_ATI_pn_triangles",
- "GL_ATI_vertex_array_object",
- "GL_EXT_vertex_shader",
- "GL_ATI_vertex_streams",
- "WGL_I3D_digital_video_control",
- "WGL_I3D_gamma",
- "WGL_I3D_genlock",
- "WGL_I3D_image_buffer",
- "WGL_I3D_swap_frame_lock",
- "WGL_I3D_swap_frame_usage",
- "GL_ATI_element_array",
- "GL_SUN_mesh_array",
- "GL_SUN_slice_accum",
- "GL_NV_multisample_filter_hint",
- "GL_NV_depth_clamp",
- "GL_NV_occlusion_query",
- "GL_NV_point_sprite",
- "WGL_NV_render_depth_texture",
- "WGL_NV_render_texture_rectangle",
- "GL_NV_texture_shader3",
- "GL_NV_vertex_program1_1",
- "GL_EXT_shadow_funcs",
- "GL_EXT_stencil_two_side",
- "GL_ATI_text_fragment_shader",
- "GL_APPLE_client_storage",
- "GL_APPLE_element_array",
- "GL_APPLE_fence",
- "GL_APPLE_vertex_array_object",
- "GL_APPLE_vertex_array_range",
- "GL_APPLE_ycbcr_422",
- "GL_S3_s3tc",
- "GL_ATI_draw_buffers",
- "WGL_ATI_pixel_format_float",
- "GL_ATI_texture_env_combine3",
- "GL_ATI_texture_float",
- "GL_NV_float_buffer",
- "GL_NV_fragment_program",
- "GL_NV_half_float",
- "GL_NV_pixel_data_range",
- "GL_NV_primitive_restart",
- "GL_NV_texture_expand_normal",
- "GL_NV_vertex_program2",
- "GL_ATI_map_object_buffer",
- "GL_ATI_separate_stencil",
- "GL_ATI_vertex_attrib_array_object",
- "GL_OES_byte_coordinates",
- "GL_OES_fixed_point",
- "GL_OES_single_precision",
- "GL_OES_compressed_paletted_texture",
- "GL_OES_read_format",
- "GL_OES_query_matrix",
- "GL_EXT_depth_bounds_test",
- "GL_EXT_texture_mirror_clamp",
- "GL_EXT_blend_equation_separate",
- "GL_MESA_pack_invert",
- "GL_MESA_ycbcr_texture"]
-
-"""
-Example code output:
-#ifdef GL_EXT_compiled_vertex_array
- if (QueryExtension("GL_EXT_compiled_vertex_array"))
- {
- glUnlockArraysEXT = reinterpret_cast<PFNGLUNLOCKARRAYSEXTPROC>(bglGetProcAddress((const GLubyte *) "glUnlockArraysEXT"));
- glLockArraysEXT = reinterpret_cast<PFNGLLOCKARRAYSEXTPROC>(bglGetProcAddress((const GLubyte *) "glLockArraysEXT"));
- if (glUnlockArraysEXT && glLockArraysEXT)
- {
- EnableExtension(_GL_EXT_compiled_vertex_array);
- if (doDebugMessages)
- std::cout << "Detected GL_EXT_compiled_vertex_array" << std::endl;
- } else {
- std::cout << "ERROR: GL_EXT_compiled_vertex_array implementation is broken!" << std::endl;
- }
- }
-#endif
-"""
-def writeext(ext, fnlist):
- if (find(blacklist, ext)):
- return
- if (len(fnlist) == 0):
- # This extension has no functions to detect - don't need to wrap in
- # #ifdef GL_extension names
- print "\tif (QueryExtension(\"" + ext + "\"))"
- print "\t{"
- print "\t\tEnableExtension(_" + ext + ");"
- print "\t\tif (doDebugMessages)"
- print "\t\t\tstd::cout << \"Detected " + ext + "\" << std::endl;"
- print "\t}"
- print
- return
- print "#if defined(" + ext + ")"
- print "\tif (QueryExtension(\"" + ext + "\"))"
- print "\t{"
- for fn in fnlist:
- print "\t\t" + fn[0] + " = reinterpret_cast<" + fn[1] + ">(bglGetProcAddress((const GLubyte *) \"" + fn[0] + "\"));"
- errcheck = ""
- for fn in fnlist:
- if (errcheck == ""):
- errcheck = fn[0]
- else:
- errcheck = errcheck + " && " + fn[0]
- print "\t\tif (" + errcheck + ") {"
- print "\t\t\tEnableExtension(_" + ext + ");"
- print "\t\t\tif (doDebugMessages)"
- print "\t\t\t\tstd::cout << \"Enabled " + ext + "\" << std::endl;"
- print "\t\t} else {"
- print "\t\t\tstd::cout << \"ERROR: " + ext + " implementation is broken!\" << std::endl;"
- print "\t\t}"
- print "\t}"
- print "#endif"
- print
-
-"""
-Example Output:
-#if defined(GL_EXT_compiled_vertex_array)
-PFNGLLOCKARRAYSEXTPROC glLockArraysEXT;
-PFNGLUNLOCKARRAYSEXTPROC glUnlockArraysEXT;
-#endif
-"""
-def writeproto(ext, fnlist):
- if (find(blacklist, ext) or not find(whitelist, ext)):
- return
- print "#if defined(" + ext + ")"
- for fn in fnlist:
- print fn[1] + " " + fn[0] + ";"
- print "#endif"
- print
-
-"""
-#ifdef GL_EXT_compiled_vertex_array
-extern PFNGLLOCKARRAYSEXTPROC glLockArraysEXT;
-extern PFNGLUNLOCKARRAYSEXTPROC glUnlockArraysEXT;
-#endif
-"""
-def writeheader(ext, fnlisti):
- if (find(blacklist, ext) or not find(whitelist, ext)):
- return
- print "#if defined(" + ext + ")"
- for fn in fnlist:
- print "extern " + fn[1] + " " + fn[0] + ";"
- print "#endif"
- print
-
-def find(l, x):
- for i in l:
- if (i == x):
- return 1
- return 0
-
-
-# Write Prototypes
-ext = ""
-fns = []
-fnlist = []
-ifdef = 0
-for i in glext_h:
- line = re.search('^#ifn?def', i)
- if (line):
- ifdef = ifdef + 1
-
- line = re.search('^#ifndef (GL_.*)', i)
- if (line):
- if (not re.search('GL_VERSION.*', line.group(1)) and find(whitelist, line.group(1))):
- ext = line.group(1)
-
- line = re.search('^#endif', i)
- if (line):
- ifdef = ifdef - 1
- if (ifdef == 0 and ext != ""):
- writeproto(ext, fnlist)
- ext = ""
- fns = []
- fnlist = []
- if (ext != ""):
- line = re.search('.* (gl.*) \(.*\);', i)
- if (line):
- fns += [line.group(1)]
- line = re.search('.*PFN(.*)PROC.*', i)
- if (line):
- for j in fns:
- if (string.lower(line.group(1)) == string.lower(j)):
- fnlist += [(j, "PFN" + line.group(1) + "PROC")]
-
-# Write link code
-ext = ""
-fns = []
-fnlist = []
-ifdef = 0
-for i in glext_h:
- line = re.search('^#ifn?def', i)
- if (line):
- ifdef = ifdef + 1
-
- line = re.search('^#ifndef (GL_.*)', i)
- if (line):
- if (not re.search('GL_VERSION.*', line.group(1)) and find(whitelist, line.group(1))):
- ext = line.group(1)
-
- line = re.search('^#endif', i)
- if (line):
- ifdef = ifdef - 1
- if (ifdef == 0 and ext != ""):
- writeext(ext, fnlist)
- ext = ""
- fns = []
- fnlist = []
- if (ext != ""):
- line = re.search('.* (gl.*) \(.*\);', i)
- if (line):
- fns += [line.group(1)]
- line = re.search('.*PFN(.*)PROC.*', i)
- if (line):
- for j in fns:
- if (string.lower(line.group(1)) == string.lower(j)):
- fnlist += [(j, "PFN" + line.group(1) + "PROC")]
-
-# Write header code
-ext = ""
-fns = []
-fnlist = []
-ifdef = 0
-for i in glext_h:
- line = re.search('^#ifn?def', i)
- if (line):
- ifdef = ifdef + 1
-
- line = re.search('^#ifndef (GL_.*)', i)
- if (line):
- if (not re.search('GL_VERSION.*', line.group(1)) and find(whitelist, line.group(1))):
- ext = line.group(1)
-
- line = re.search('^#endif', i)
- if (line):
- ifdef = ifdef - 1
- if (ifdef == 0 and ext != ""):
- writeheader(ext, fnlist)
- ext = ""
- fns = []
- fnlist = []
- if (ext != ""):
- line = re.search('.* (gl.*) \(.*\);', i)
- if (line):
- fns += [line.group(1)]
- line = re.search('.*PFN(.*)PROC.*', i)
- if (line):
- for j in fns:
- if (string.lower(line.group(1)) == string.lower(j)):
- fnlist += [(j, "PFN" + line.group(1) + "PROC")]
-
-# Write Python link code
-ext = ""
-extensions = []
-fns = []
-defines = []
-ifdef = 0
-for i in glext_h:
- line = re.search('^#ifn?def', i)
- if (line):
- ifdef = ifdef + 1
-
- line = re.search('^#ifndef (GL_.*)', i)
- if (line):
- if (not re.search('GL_VERSION.*', line.group(1)) and find(whitelist, line.group(1))):
- ext = line.group(1)
-
- line = re.search('^#endif', i)
- if (line):
- ifdef = ifdef - 1
- if (ifdef == 0 and ext != ""):
- done = 0
- for e in range(len(extensions)):
- if extensions[e][0] == ext:
- extensions[e] = (ext, defines + extensions[e][1], fns + extensions[e][2])
- done = 1
- if not done:
- extensions = extensions + [(ext, defines, fns)]
- ext = ""
- fns = []
- defines = []
- if (ext != ""):
- line = re.search('#define +(GL.*) +(0x.*)', i) # #define GL_ONE_MINUS_CONSTANT_COLOR 0x8002
- if (line):
- defines += [(line.group(1), line.group(2))]
-
- line = re.search('(.* )(gl.*)(\(.*\));', i) # GLAPI void APIENTRY glMultiTexCoord2f (GLenum, GLfloat, GLfloat);
- if (line):
- fns += [(line.group(1), line.group(2), line.group(3))]
-
-for ext in extensions:
- if (find(blacklist, ext[0]) or not find(whitelist, ext[0])):
- continue
- print "#if defined(" + ext[0] + ")"
- for fn in ext[2]:
- line = re.search('gl(.*)', fn[1])
- # BGL_Wrap(2, RasterPos2f, void, (GLfloat, GLfloat))
- rtype = ""
- for r in string.split(fn[0]):
- if r != "GLAPI" and r != "APIENTRY":
- rtype = rtype + " " + r
- params = ""
- for p in string.split(fn[2], ','):
- pline = re.search('(.*) \*', p)
- if (pline):
- p = pline.group(1) + "P"
- if params == "":
- params = p
- else:
- params = params + "," + p
- if not params[-1] == ")":
- params = params + ")"
- print "BGL_Wrap(" + str(len(string.split(fn[2], ','))) + ", " + line.group(1) + ",\t" + rtype + ",\t" + params + ")"
- print "#endif"
- print
-
-for ext in extensions:
- if (find(blacklist, ext[0]) or not find(whitelist, ext[0])):
- continue
- print 'PyDict_SetItemString(dict, "' + ext[0] + '", PyInt_FromLong(_' + ext[0] + '))'
- print "#if defined(" + ext[0] + ")"
- print "if (bglQueryExtension(_" + ext[0] + ")) {"
- if len(ext[2]) > 0:
- for fn in ext[2]:
- line = re.search('gl(.*)', fn[1])
- # MethodDef(Vertex3iv),
- print " BGL_AddMethod(" + line.group(1) + ");"
- print
-
- for define in ext[1]:
- print " BGL_AddConst(" + define[0] + ");"
- print
-
- print "}"
- print "#endif"
- print
diff --git a/source/gameengine/Rasterizer/RAS_Polygon.cpp b/source/gameengine/Rasterizer/RAS_Polygon.cpp
index 852c94def3f..50331d7a664 100644
--- a/source/gameengine/Rasterizer/RAS_Polygon.cpp
+++ b/source/gameengine/Rasterizer/RAS_Polygon.cpp
@@ -26,117 +26,82 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
#ifdef WIN32
-
#pragma warning (disable:4786)
#endif
#include "RAS_Polygon.h"
-/*
-RAS_TexVert* RAS_Polygon::GetVertex(int index)
-{
- if (m_bucket)
- return m_bucket->GetVertex(m_vertexindexbase.m_vtxarray, m_vertexindexbase.m_indexarray[index]);
- else
- return NULL;
-}
-*/
-
-/*void RAS_Polygon::Bucketize(double* oglmatrix)
+RAS_Polygon::RAS_Polygon(RAS_MaterialBucket* bucket, RAS_DisplayArray *darray, int numvert)
{
- //Transform(trans);
- if (m_bucket)
- m_bucket->AddPolygon(this,oglmatrix);
-}
-*/
-
-RAS_Polygon::RAS_Polygon(RAS_MaterialBucket* bucket,
- bool visible,
- int numverts,
- int vtxarrayindex)
- :m_bucket(bucket),
- m_vertexindexbase(numverts),
- m_numverts(numverts),
- m_edgecode(65535)
-{
- m_vertexindexbase.m_vtxarray = vtxarrayindex ;//m_bucket->FindVertexArray(numverts);
- m_polyFlags.Visible = visible;
-}
-
+ m_bucket = bucket;
+ m_darray = darray;
+ m_offset[0]= m_offset[1]= m_offset[2]= m_offset[3]= 0;
+ m_numvert = numvert;
+ m_edgecode = 255;
+ m_polyflags = 0;
+}
int RAS_Polygon::VertexCount()
{
- return m_numverts;
+ return m_numvert;
}
-
-
-void RAS_Polygon::SetVertex(int i,
- unsigned int vertexindex ) //const MT_Point3& xyz,const MT_Point2& uv,const unsigned int rgbacolor,const MT_Vector3& normal)
+void RAS_Polygon::SetVertexOffset(int i, unsigned short offset)
{
- m_vertexindexbase.SetIndex(i,vertexindex); //m_bucket->FindOrAddVertex(m_vertexindexbase.m_vtxarray,
- //xyz,uv,rgbacolor,normal));
+ m_offset[i] = offset;
}
-
-
-const KX_VertexIndex& RAS_Polygon::GetIndexBase()
+RAS_TexVert *RAS_Polygon::GetVertex(int i)
{
- return m_vertexindexbase;
+ return &m_darray->m_vertex[m_offset[i]];
}
-
-
-void RAS_Polygon::SetVisibleWireframeEdges(int edgecode)
+int RAS_Polygon::GetVertexOffset(int i)
{
- m_edgecode = edgecode;
+ return m_offset[i];
}
-
-
-// each bit is for a visible edge, starting with bit 1 for the first edge, bit 2 for second etc.
int RAS_Polygon::GetEdgeCode()
{
return m_edgecode;
}
+void RAS_Polygon::SetEdgeCode(int edgecode)
+{
+ m_edgecode = edgecode;
+}
bool RAS_Polygon::IsVisible()
{
- return m_polyFlags.Visible;
+ return (m_polyflags & VISIBLE) != 0;
}
-
+void RAS_Polygon::SetVisible(bool visible)
+{
+ if(visible) m_polyflags |= VISIBLE;
+ else m_polyflags &= ~VISIBLE;
+}
bool RAS_Polygon::IsCollider()
{
- return m_polyFlags.Collider;
+ return (m_polyflags & COLLIDER) != 0;
}
-
-
-void RAS_Polygon::SetCollider(bool col)
+void RAS_Polygon::SetCollider(bool visible)
{
- m_polyFlags.Collider = col;
+ if(visible) m_polyflags |= COLLIDER;
+ else m_polyflags &= ~COLLIDER;
}
-
-
-KX_VertexIndex& RAS_Polygon::GetVertexIndexBase()
+RAS_MaterialBucket* RAS_Polygon::GetMaterial()
{
- return m_vertexindexbase;
+ return m_bucket;
}
-
-
-RAS_MaterialBucket* RAS_Polygon::GetMaterial()
+RAS_DisplayArray* RAS_Polygon::GetDisplayArray()
{
- return m_bucket;
+ return m_darray;
}
diff --git a/source/gameengine/Rasterizer/RAS_Polygon.h b/source/gameengine/Rasterizer/RAS_Polygon.h
index 7ce7926a816..18526ba45f7 100644
--- a/source/gameengine/Rasterizer/RAS_Polygon.h
+++ b/source/gameengine/Rasterizer/RAS_Polygon.h
@@ -35,55 +35,47 @@
#include <vector>
using namespace std;
-
-//
-// Bitfield that stores the flags for each CValue derived class
-//
-struct PolygonFlags {
- PolygonFlags() :
- Visible(true),
- Collider(true)
- {
- }
- unsigned char Visible : 1;
- unsigned char Collider : 1;
- //int Visible : 1;
- //int Collider : 1;
-};
+/* polygon flags */
class RAS_Polygon
{
+ /* location */
RAS_MaterialBucket* m_bucket;
- KX_VertexIndex m_vertexindexbase;
- int m_numverts;
- int m_edgecode;
- PolygonFlags m_polyFlags;
-
+ RAS_DisplayArray* m_darray;
+ unsigned short m_offset[4];
+ unsigned short m_numvert;
+
+ /* flags */
+ unsigned char m_edgecode;
+ unsigned char m_polyflags;
public:
- RAS_Polygon(RAS_MaterialBucket* bucket,
- bool visible,
- int numverts,
- int vtxarrayindex) ;
+ enum {
+ VISIBLE = 1,
+ COLLIDER = 2
+ };
+
+ RAS_Polygon(RAS_MaterialBucket* bucket, RAS_DisplayArray* darray, int numvert);
virtual ~RAS_Polygon() {};
-// RAS_TexVert* GetVertex(int index);
int VertexCount();
- void SetVertex(int i, unsigned int vertexindex); //const MT_Point3& xyz,const MT_Point2& uv,const unsigned int rgbacolor,const MT_Vector3& normal)
-
- const KX_VertexIndex& GetIndexBase();
+ RAS_TexVert* GetVertex(int i);
- void SetVisibleWireframeEdges(int edgecode);
+ void SetVertexOffset(int i, unsigned short offset);
+ int GetVertexOffset(int i);
+
// each bit is for a visible edge, starting with bit 1 for the first edge, bit 2 for second etc.
int GetEdgeCode();
+ void SetEdgeCode(int edgecode);
bool IsVisible();
+ void SetVisible(bool visible);
+
bool IsCollider();
- void SetCollider(bool col);
+ void SetCollider(bool collider);
- KX_VertexIndex& GetVertexIndexBase();
RAS_MaterialBucket* GetMaterial();
-
+ RAS_DisplayArray* GetDisplayArray();
};
#endif
diff --git a/source/gameengine/Rasterizer/RAS_TexVert.cpp b/source/gameengine/Rasterizer/RAS_TexVert.cpp
index 61ac456b2bc..b92965ed1cc 100644
--- a/source/gameengine/Rasterizer/RAS_TexVert.cpp
+++ b/source/gameengine/Rasterizer/RAS_TexVert.cpp
@@ -27,12 +27,7 @@
*/
#include "RAS_TexVert.h"
-
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-#define SHORT(x) short(x*32767.0)
+#include "MT_Matrix4x4.h"
RAS_TexVert::RAS_TexVert(const MT_Point3& xyz,
const MT_Point2& uv,
@@ -40,7 +35,8 @@ RAS_TexVert::RAS_TexVert(const MT_Point3& xyz,
const MT_Vector4& tangent,
const unsigned int rgba,
const MT_Vector3& normal,
- const short flag)
+ const bool flat,
+ const unsigned int origindex)
{
xyz.getValue(m_localxyz);
uv.getValue(m_uv1);
@@ -48,8 +44,10 @@ RAS_TexVert::RAS_TexVert(const MT_Point3& xyz,
SetRGBA(rgba);
SetNormal(normal);
tangent.getValue(m_tangent);
- m_flag = flag;
+ m_flag = (flat)? FLAT: 0;
+ m_origindex = origindex;
m_unit = 2;
+ m_softBodyIndex = -1;
}
const MT_Point3& RAS_TexVert::xyz()
@@ -99,7 +97,7 @@ void RAS_TexVert::SetFlag(const short flag)
void RAS_TexVert::SetUnit(const unsigned int u)
{
- m_unit = u<=TV_MAX?u:TV_MAX;
+ m_unit = u<=MAX_UNIT?u:MAX_UNIT;
}
void RAS_TexVert::SetNormal(const MT_Vector3& normal)
@@ -107,50 +105,18 @@ void RAS_TexVert::SetNormal(const MT_Vector3& normal)
normal.getValue(m_normal);
}
-#ifndef RAS_TexVert_INLINE
-
-// leave multiline for debugging
-const float* RAS_TexVert::getUV1 () const
-{
- return m_uv1;
-}
-
-const float* RAS_TexVert::getUV2 () const
-{
- return m_uv2;
-}
-
-
-
-const float* RAS_TexVert::getNormal() const
-{
- return m_normal;
-}
-
-const float* RAS_TexVert::getTangent() const
+void RAS_TexVert::SetTangent(const MT_Vector3& tangent)
{
- return m_tangent;
-}
-
-
-const float* RAS_TexVert::getLocalXYZ() const
-{
- return m_localxyz;
-}
-
-const unsigned char* RAS_TexVert::getRGBA() const
-{
- return (unsigned char*) &m_rgba;
+ tangent.getValue(m_tangent);
}
-#endif
-
// compare two vertices, and return TRUE if both are almost identical (they can be shared)
bool RAS_TexVert::closeTo(const RAS_TexVert* other)
{
return (m_flag == other->m_flag &&
m_rgba == other->m_rgba &&
MT_fuzzyEqual(MT_Vector3(m_normal), MT_Vector3(other->m_normal)) &&
+ MT_fuzzyEqual(MT_Vector3(m_tangent), MT_Vector3(other->m_tangent)) &&
MT_fuzzyEqual(MT_Vector2(m_uv1), MT_Vector2(other->m_uv1)) &&
MT_fuzzyEqual(MT_Vector2(m_uv2), MT_Vector2(other->m_uv2)) && // p --
MT_fuzzyEqual(MT_Vector3(m_localxyz), MT_Vector3(other->m_localxyz))) ;
@@ -167,11 +133,10 @@ unsigned int RAS_TexVert::getUnit() const
return m_unit;
}
-
-void RAS_TexVert::getOffsets(void* &xyz, void* &uv1, void* &rgba, void* &normal) const
+void RAS_TexVert::Transform(const MT_Matrix4x4& mat, const MT_Matrix4x4& nmat)
{
- xyz = (void *) m_localxyz;
- uv1 = (void *) m_uv1;
- rgba = (void *) &m_rgba;
- normal = (void *) m_normal;
+ SetXYZ((mat*MT_Vector4(m_localxyz[0], m_localxyz[1], m_localxyz[2], 1.0)).getValue());
+ SetNormal((nmat*MT_Vector4(m_normal[0], m_normal[1], m_normal[2], 1.0)).getValue());
+ SetTangent((nmat*MT_Vector4(m_tangent[0], m_tangent[1], m_tangent[2], 1.0)).getValue());
}
+
diff --git a/source/gameengine/Rasterizer/RAS_TexVert.h b/source/gameengine/Rasterizer/RAS_TexVert.h
index 84135db918f..54da109cbf1 100644
--- a/source/gameengine/Rasterizer/RAS_TexVert.h
+++ b/source/gameengine/Rasterizer/RAS_TexVert.h
@@ -37,13 +37,6 @@
static MT_Point3 g_pt3;
static MT_Point2 g_pt2;
-#define TV_CALCFACENORMAL 0x0001
-#define TV_2NDUV 0x0002
-
-#define TV_MAX 3//match Def in BL_Material.h
-
-#define RAS_TexVert_INLINE 1
-
class RAS_TexVert
{
@@ -51,15 +44,23 @@ class RAS_TexVert
float m_uv1[2]; // 2*4 = 8
float m_uv2[2]; // 2*4 = 8
unsigned int m_rgba; // 4
- float m_tangent[4]; // 4*2 = 8
- float m_normal[3]; // 3*2 = 6
+ float m_tangent[4]; // 4*4 = 16
+ float m_normal[3]; // 3*4 = 12
short m_flag; // 2
+ short m_softBodyIndex; //2
unsigned int m_unit; // 4
+ unsigned int m_origindex; // 4
//---------
- // 52
- //32 bytes total size, fits nice = 52 = not fit nice.
- // We'll go for 64 bytes total size - 24 bytes left.
+ // 56+6+8+2=72
+ // 32 bytes total size, fits nice = 56 = not fit nice.
+
public:
+ enum {
+ FLAT = 1,
+ SECOND_UV = 2,
+ MAX_UNIT = 8
+ };
+
short getFlag() const;
unsigned int getUnit() const;
@@ -71,11 +72,10 @@ public:
const MT_Vector4& tangent,
const unsigned int rgba,
const MT_Vector3& normal,
- const short flag);
+ const bool flat,
+ const unsigned int origindex);
~RAS_TexVert() {};
- // leave multiline for debugging
-#ifdef RAS_TexVert_INLINE
const float* getUV1 () const {
return m_uv1;
};
@@ -84,7 +84,7 @@ public:
return m_uv2;
};
- const float* getLocalXYZ() const {
+ const float* getXYZ() const {
return m_localxyz;
};
@@ -92,6 +92,16 @@ public:
return m_normal;
}
+ short int getSoftBodyIndex() const
+ {
+ return m_softBodyIndex;
+ }
+
+ void setSoftBodyIndex(short int sbIndex)
+ {
+ m_softBodyIndex = sbIndex;
+ }
+
const float* getTangent() const {
return m_tangent;
}
@@ -99,33 +109,30 @@ public:
const unsigned char* getRGBA() const {
return (unsigned char *) &m_rgba;
}
-#else
- const float* getUV1 () const;
- const float* getUV2 () const;
- const float* getNormal() const;
- const float* getLocalXYZ() const;
- const unsigned char* getRGBA() const;
-#endif
+
+ const unsigned int getOrigIndex() const {
+ return m_origindex;
+ }
+
void SetXYZ(const MT_Point3& xyz);
void SetUV(const MT_Point2& uv);
void SetUV2(const MT_Point2& uv);
void SetRGBA(const unsigned int rgba);
void SetNormal(const MT_Vector3& normal);
+ void SetTangent(const MT_Vector3& tangent);
void SetFlag(const short flag);
void SetUnit(const unsigned u);
void SetRGBA(const MT_Vector4& rgba);
const MT_Point3& xyz();
- // compare two vertices, and return TRUE if both are almost identical (they can be shared)
- bool closeTo(const RAS_TexVert* other);
+ void Transform(const class MT_Matrix4x4& mat,
+ const class MT_Matrix4x4& nmat);
- bool closeTo(const MT_Point3& otherxyz,
- const MT_Point2& otheruv,
- const unsigned int otherrgba,
- short othernormal[3]) const;
- void getOffsets(void*&xyz, void *&uv1, void *&rgba, void *&normal) const;
+ // compare two vertices, to test if they can be shared, used for
+ // splitting up based on uv's, colors, etc
+ bool closeTo(const RAS_TexVert* other);
};
#endif //__RAS_TEXVERT
diff --git a/source/gameengine/Rasterizer/SConscript b/source/gameengine/Rasterizer/SConscript
index 62325bc80a9..a024f7e0ee6 100644
--- a/source/gameengine/Rasterizer/SConscript
+++ b/source/gameengine/Rasterizer/SConscript
@@ -3,11 +3,13 @@ Import ('env')
sources = env.Glob('*.cpp')
-incs = '. #source/kernel/gen_system #intern/string #intern/moto/include'
+
+incs = '. #source/kernel/gen_system #intern/string #intern/moto/include #source/gameengine/BlenderRoutines #extern/glew/include #source/gameengine/Expressions #source/blender/blenkernel #source/blender/makesdna'
+incs += ' ' + env['BF_PYTHON_INC']
if env['OURPLATFORM']=='win32-vc':
cflags = []
cflags.append('/Ox')
- env.BlenderLib ( 'bf_rasterizer', sources, Split(incs), [], libtype=['game','player'], priority=[35,110], compileflags = cflags )
+ env.BlenderLib ( 'bf_rasterizer', sources, Split(incs), [], libtype=['game','player'], priority=[35,115], compileflags = cflags )
else:
- env.BlenderLib ( 'bf_rasterizer', sources, Split(incs), [], libtype=['game','player'], priority=[35,110] )
+ env.BlenderLib ( 'bf_rasterizer', sources, Split(incs), [], libtype=['game','player'], priority=[35,115] )
diff --git a/source/gameengine/SConscript b/source/gameengine/SConscript
index 3578e74ea55..e841f206eee 100644
--- a/source/gameengine/SConscript
+++ b/source/gameengine/SConscript
@@ -2,26 +2,27 @@
Import ('env')
SConscript(['BlenderRoutines/SConscript',
- 'Converter/SConscript',
- 'Expressions/SConscript',
- 'GameLogic/SConscript',
- 'Ketsji/SConscript',
- 'Ketsji/KXNetwork/SConscript',
- 'Network/SConscript',
- 'Network/LoopBackNetwork/SConscript',
- 'Physics/common/SConscript',
- 'Physics/Dummy/SConscript',
- 'Rasterizer/SConscript',
- 'Rasterizer/RAS_OpenGLRasterizer/SConscript',
- 'SceneGraph/SConscript',
- 'Physics/Bullet/SConscript',
- 'Physics/Sumo/SConscript'
- ])
+ 'Converter/SConscript',
+ 'Expressions/SConscript',
+ 'GameLogic/SConscript',
+ 'Ketsji/SConscript',
+ 'Ketsji/KXNetwork/SConscript',
+ 'Network/SConscript',
+ 'Network/LoopBackNetwork/SConscript',
+ 'Physics/common/SConscript',
+ 'Physics/Dummy/SConscript',
+ 'Rasterizer/SConscript',
+ 'Rasterizer/RAS_OpenGLRasterizer/SConscript',
+ 'SceneGraph/SConscript',
+ 'Physics/Bullet/SConscript',
+ 'Physics/Sumo/SConscript',
+ 'VideoTexture/SConscript'
+ ])
if env['WITH_BF_PLAYER']:
- SConscript(['GamePlayer/SConscript'])
+ SConscript(['GamePlayer/SConscript'])
#if user_options_dict['USE_PHYSICS'] == 'solid':
-# SConscript(['Physics/Sumo/SConscript'])
+# SConscript(['Physics/Sumo/SConscript'])
#elif user_options_dict['USE_PHYSICS'] == 'ode':
-# SConscript(['Physics/BlOde/SConscript'])
+# SConscript(['Physics/BlOde/SConscript'])
diff --git a/source/gameengine/SceneGraph/SG_Controller.h b/source/gameengine/SceneGraph/SG_Controller.h
index d65a2f0c256..c32885b915f 100644
--- a/source/gameengine/SceneGraph/SG_Controller.h
+++ b/source/gameengine/SceneGraph/SG_Controller.h
@@ -101,7 +101,9 @@ public:
enum SG_Controller_option {
SG_CONTR_NODEF = 0,
SG_CONTR_IPO_IPO_AS_FORCE,
- SG_CONTR_IPO_FORCES_ACT_LOCAL,
+ SG_CONTR_IPO_IPO_ADD,
+ SG_CONTR_IPO_LOCAL,
+ SG_CONTR_IPO_RESET,
SG_CONTR_CAMIPO_LENS,
SG_CONTR_CAMIPO_CLIPEND,
SG_CONTR_CAMIPO_CLIPSTART,
diff --git a/source/gameengine/SceneGraph/SG_IObject.cpp b/source/gameengine/SceneGraph/SG_IObject.cpp
index 1a8dc894ce9..d0bdac5c8f0 100644
--- a/source/gameengine/SceneGraph/SG_IObject.cpp
+++ b/source/gameengine/SceneGraph/SG_IObject.cpp
@@ -104,7 +104,7 @@ SetSGClientObject(
}
- void
+ bool
SG_IObject::
ActivateReplicationCallback(
SG_IObject *replica
@@ -112,8 +112,10 @@ ActivateReplicationCallback(
if (m_callbacks.m_replicafunc)
{
// Call client provided replication func
- m_callbacks.m_replicafunc(replica,m_SGclientObject,m_SGclientInfo);
+ if (m_callbacks.m_replicafunc(replica,m_SGclientObject,m_SGclientInfo) == NULL)
+ return false;
}
+ return true;
};
void
@@ -125,6 +127,11 @@ ActivateDestructionCallback(
// Call client provided destruction function on this!
m_callbacks.m_destructionfunc(this,m_SGclientObject,m_SGclientInfo);
}
+ else
+ {
+ // no callback but must still destroy the node to avoid memory leak
+ delete this;
+ }
}
void
diff --git a/source/gameengine/SceneGraph/SG_IObject.h b/source/gameengine/SceneGraph/SG_IObject.h
index 438ab48c556..7f6bdfbbb1c 100644
--- a/source/gameengine/SceneGraph/SG_IObject.h
+++ b/source/gameengine/SceneGraph/SG_IObject.h
@@ -202,7 +202,7 @@ public:
protected :
- void
+ bool
ActivateReplicationCallback(
SG_IObject *replica
);
diff --git a/source/gameengine/SceneGraph/SG_Node.cpp b/source/gameengine/SceneGraph/SG_Node.cpp
index 73e16863173..8de7ac83477 100644
--- a/source/gameengine/SceneGraph/SG_Node.cpp
+++ b/source/gameengine/SceneGraph/SG_Node.cpp
@@ -68,7 +68,7 @@ SG_Node* SG_Node::GetSGReplica()
SG_Node* replica = new SG_Node(*this);
if (replica == NULL) return NULL;
- ProcessSGReplica(replica);
+ ProcessSGReplica(&replica);
return replica;
}
@@ -76,25 +76,42 @@ SG_Node* SG_Node::GetSGReplica()
void
SG_Node::
ProcessSGReplica(
- SG_Node* replica
+ SG_Node** replica
){
// Apply the replication call back function.
- ActivateReplicationCallback(replica);
+ if (!ActivateReplicationCallback(*replica))
+ {
+ delete (*replica);
+ *replica = NULL;
+ return;
+ }
// clear the replica node of it's parent.
- static_cast<SG_Node*>(replica)->m_SGparent = NULL;
+ static_cast<SG_Node*>(*replica)->m_SGparent = NULL;
if (m_children.begin() != m_children.end())
{
// if this node has children, the replica has too, so clear and clone children
- replica->ClearSGChildren();
+ (*replica)->ClearSGChildren();
NodeList::iterator childit;
for (childit = m_children.begin();childit!=m_children.end();++childit)
{
- replica->AddChild((*childit)->GetSGReplica());
+ SG_Node* childnode = (*childit)->GetSGReplica();
+ if (childnode)
+ (*replica)->AddChild(childnode);
}
}
+ // Nodes without children and without client object are
+ // not worth to keep, they will just take up CPU
+ // This can happen in partial replication of hierarchy
+ // during group duplication.
+ if ((*replica)->m_children.empty() &&
+ (*replica)->GetSGClientObject() == NULL)
+ {
+ delete (*replica);
+ *replica = NULL;
+ }
}
@@ -148,6 +165,27 @@ GetRootSGParent(
return (m_SGparent ? (const SG_Node*) m_SGparent->GetRootSGParent() : (const SG_Node*) this);
}
+ bool
+SG_Node::
+IsVertexParent()
+{
+ if (m_parent_relation)
+ {
+ return m_parent_relation->IsVertexRelation();
+ }
+ return false;
+}
+
+ bool
+SG_Node::
+IsSlowParent()
+{
+ if (m_parent_relation)
+ {
+ return m_parent_relation->IsSlowRelation();
+ }
+ return false;
+}
void
SG_Node::
diff --git a/source/gameengine/SceneGraph/SG_Node.h b/source/gameengine/SceneGraph/SG_Node.h
index 4808f6f7d94..ffaaad861e2 100644
--- a/source/gameengine/SceneGraph/SG_Node.h
+++ b/source/gameengine/SceneGraph/SG_Node.h
@@ -152,6 +152,22 @@ public:
) ;
+ /**
+ * Return vertex parent status.
+ */
+
+ bool
+ IsVertexParent(
+ ) ;
+
+ /**
+ * Return slow parent status.
+ */
+
+ bool
+ IsSlowParent(
+ ) ;
+
/**
* Update the spatial data of this node. Iterate through
* the children of this node and update their world data.
@@ -189,7 +205,7 @@ private:
void
ProcessSGReplica(
- SG_Node* replica
+ SG_Node** replica
);
/**
diff --git a/source/gameengine/SceneGraph/SG_ParentRelation.h b/source/gameengine/SceneGraph/SG_ParentRelation.h
index 1d211a9f39f..6507cb98519 100644
--- a/source/gameengine/SceneGraph/SG_ParentRelation.h
+++ b/source/gameengine/SceneGraph/SG_ParentRelation.h
@@ -90,6 +90,25 @@ public :
NewCopy(
) = 0;
+ /**
+ * Vertex Parent Relation are special: they don't propagate rotation
+ */
+ virtual
+ bool
+ IsVertexRelation(
+ ) {
+ return false;
+ }
+
+ /**
+ * Need this to see if we are able to adjust time-offset from the python api
+ */
+ virtual
+ bool
+ IsSlowRelation(
+ ) {
+ return false;
+ }
protected :
/**
diff --git a/source/gameengine/SceneGraph/SG_Spatial.cpp b/source/gameengine/SceneGraph/SG_Spatial.cpp
index 18049592977..5ba116e59db 100644
--- a/source/gameengine/SceneGraph/SG_Spatial.cpp
+++ b/source/gameengine/SceneGraph/SG_Spatial.cpp
@@ -87,6 +87,13 @@ SG_Spatial::
delete (m_parent_relation);
}
+ SG_ParentRelation *
+SG_Spatial::
+GetParentRelation(
+){
+ return m_parent_relation;
+}
+
void
SG_Spatial::
SetParentRelation(
diff --git a/source/gameengine/SceneGraph/SG_Spatial.h b/source/gameengine/SceneGraph/SG_Spatial.h
index a70784472a7..28848b0f933 100644
--- a/source/gameengine/SceneGraph/SG_Spatial.h
+++ b/source/gameengine/SceneGraph/SG_Spatial.h
@@ -83,6 +83,10 @@ public:
SetParentRelation(
SG_ParentRelation *relation
);
+
+ SG_ParentRelation *
+ GetParentRelation(
+ );
/**
diff --git a/source/gameengine/VideoTexture/BlendType.h b/source/gameengine/VideoTexture/BlendType.h
new file mode 100644
index 00000000000..ac3ed8812a6
--- /dev/null
+++ b/source/gameengine/VideoTexture/BlendType.h
@@ -0,0 +1,75 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2006 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+#if !defined BLENDTYPE_H
+#define BLENDTYPE_H
+
+
+/// class allows check type of blender python object and access its contained object
+template <class PyObj> class BlendType
+{
+public:
+ /// constructor
+ BlendType (char * name) : m_name(name) {}
+
+ /// check blender type and return pointer to contained object or NULL (if type is not valid)
+ PyObj * checkType (PyObject * obj)
+ {
+ // if pointer to type isn't set
+ if (m_objType == NULL)
+ {
+ // compare names of type
+ if (strcmp(obj->ob_type->tp_name, m_name) == 0)
+ // if name of type match, save pointer to type
+ m_objType = obj->ob_type;
+ else
+ // if names of type don't match, return NULL
+ return NULL;
+ }
+ // if pointer to type is set and don't match to type of provided object, return NULL
+ else if (obj->ob_type != m_objType)
+ return NULL;
+ // return pointer to object
+ return (PyObj*)obj;
+ }
+
+ /// parse arguments to get object
+ PyObj * parseArg (PyObject * args)
+ {
+ // parse arguments
+ PyObject * obj;
+ if (PyArg_ParseTuple(args, "O", &obj))
+ // if successfully parsed, return pointer to object
+ return checkType(obj);
+ // otherwise return NULL
+ return NULL;
+ }
+
+protected:
+ /// name of Python type
+ char * m_name;
+ /// pointer to Python type
+ PyTypeObject * m_objType;
+};
+
+
+#endif
diff --git a/source/gameengine/VideoTexture/CMakeLists.txt b/source/gameengine/VideoTexture/CMakeLists.txt
new file mode 100644
index 00000000000..1674602edd7
--- /dev/null
+++ b/source/gameengine/VideoTexture/CMakeLists.txt
@@ -0,0 +1,61 @@
+# $Id$
+# ***** BEGIN GPL LICENSE BLOCK *****
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software Foundation,
+# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+# The Original Code is Copyright (C) 2006, Blender Foundation
+# All rights reserved.
+#
+# The Original Code is: all of this file.
+#
+# Contributor(s): Jacques Beaurain.
+#
+# ***** END GPL LICENSE BLOCK *****
+
+FILE(GLOB SRC *.cpp)
+
+SET(INC
+ .
+ ../../../source/gameengine/Ketsji
+ ../../../source/gameengine/Expressions
+ ../../../source/gameengine/GameLogic
+ ../../../source/gameengine/SceneGraph
+ ../../../source/gameengine/Rasterizer
+ ../../../source/gameengine/Rasterizer/RAS_OpenGLRasterizer
+ ../../../source/gameengine/BlenderRoutines
+ ../../../source/blender/include
+ ../../../source/blender/blenlib
+ ../../../source/blender/blenkernel
+ ../../../source/blender/makesdna
+ ../../../source/blender/imbuf
+ ../../../source/blender/python
+ ../../../source/blender/gpu
+ ../../../source/kernel/gen_system
+ ../../../intern/string
+ ../../../intern/moto/include
+ ../../../intern/guardedalloc
+ ../../../intern/SoundSystem
+ ../../../extern/glew/include
+ ${PYTHON_INC}
+)
+
+IF(WITH_FFMPEG)
+ SET(INC ${INC} ${FFMPEG_INC})
+ ADD_DEFINITIONS(-DWITH_FFMPEG)
+ ADD_DEFINITIONS(-D__STDC_CONSTANT_MACROS)
+ENDIF(WITH_FFMPEG)
+
+BLENDERLIB(bf_videotex "${SRC}" "${INC}")
+#env.BlenderLib ( 'bf_videotex', sources, Split(incs), [], libtype=['game','player'], priority=[25, 72], compileflags = cflags )
diff --git a/source/gameengine/VideoTexture/Common.h b/source/gameengine/VideoTexture/Common.h
new file mode 100644
index 00000000000..f771077bbba
--- /dev/null
+++ b/source/gameengine/VideoTexture/Common.h
@@ -0,0 +1,55 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2006 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+#if defined WIN32
+#define WINDOWS_LEAN_AND_MEAN
+#endif
+
+#if !defined NULL
+#define NULL 0
+#endif
+
+#if !defined HRESULT
+#define HRESULT long
+#endif
+
+#if !defined DWORD
+#define DWORD unsigned long
+#endif
+
+#if !defined S_OK
+#define S_OK ((HRESULT)0L)
+#endif
+
+#if !defined BYTE
+#define BYTE unsigned char
+#endif
+
+#if !defined WIN32
+#define Sleep(time) sleep(time)
+#endif
+
+#if !defined FAILED
+#define FAILED(Status) ((HRESULT)(Status)<0)
+#endif
+
+#include <iostream>
diff --git a/source/gameengine/VideoTexture/Exception.cpp b/source/gameengine/VideoTexture/Exception.cpp
new file mode 100644
index 00000000000..3f939de6bc2
--- /dev/null
+++ b/source/gameengine/VideoTexture/Exception.cpp
@@ -0,0 +1,209 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2006 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+
+#include <strstream>
+#include <fstream>
+
+#include <PyObjectPlus.h>
+
+#include "Exception.h"
+
+
+// exception identificators
+ExceptionID ErrGeneral, ErrNotFound;
+
+// exception descriptions
+ExpDesc errGenerDesc (ErrGeneral, "General Error");
+ExpDesc errNFoundDesc (ErrNotFound, "Error description not found");
+
+
+
+// implementation of ExpDesc
+
+// constructor
+ExpDesc::ExpDesc (ExceptionID & exp, char * desc, RESULT hres)
+: m_expID(exp), m_hRslt(hres), m_description(desc)
+{
+}
+
+// destructor
+ExpDesc::~ExpDesc (void) {}
+
+// list of descriptions
+std::vector<ExpDesc*> ExpDesc::m_expDescs;
+
+
+// class Exception
+
+
+// last exception description
+std::string Exception::m_lastError;
+
+// log file name
+char * Exception::m_logFile = NULL;
+
+
+// basic constructor
+Exception::Exception ()
+{
+ // default values
+ m_expID = &ErrNotFound;
+ m_hRslt = S_OK;
+ m_line = 0;
+}
+
+
+// destructor
+Exception::~Exception () throw() { }
+
+
+// copy constructor
+Exception::Exception (const Exception & xpt)
+{ copy (xpt); }
+
+
+// assignment operator
+Exception & Exception::operator= (const Exception & xpt)
+{ copy (xpt); return *this; }
+
+
+// get exception description
+const char * Exception::what()
+{
+ // set exception description
+ setXptDesc();
+ // return c string
+ return m_desc.c_str();
+}
+
+
+// debug version - with file and line of exception
+Exception::Exception (ExceptionID & expID, RESULT rslt, char * fil, int lin)
+: m_expID (&expID), m_hRslt (rslt)
+{
+ // set file and line
+ if (strlen(fil) > 0 || lin > 0)
+ setFileLine (fil, lin);
+}
+
+
+// set file and line
+void Exception::setFileLine (char * fil, int lin)
+{
+ if (fil != NULL) m_fileName = fil;
+ m_line = lin;
+}
+
+
+// report exception
+void Exception::report(void)
+{
+ // set exception description
+ setXptDesc();
+ // set python error
+ PyErr_SetString(PyExc_RuntimeError, what());
+ // if log file is set
+ if (m_logFile != NULL)
+ {
+ // write description to log
+ std::ofstream logf (m_logFile, std::ios_base::app);
+ logf << m_fileName << ':' << m_line << ':' << m_desc << std::endl;
+ logf.flush();
+ logf.close();
+ }
+}
+
+
+// set exception description
+void Exception::setXptDesc (void)
+{
+ // if description is not set
+ if (m_desc.size() == 0)
+ {
+ // start of search -1
+ // found description "NotFound" 0
+ // found description without matching result 1
+ // found description with matching result 2
+ int best = -1;
+ // find exception description
+ for (std::vector<ExpDesc*>::iterator it = ExpDesc::m_expDescs.begin(); it != ExpDesc::m_expDescs.end(); ++it)
+ {
+ // use "NotFound", if there is not better
+ if (best < 0 && (*it)->isExp(&ErrNotFound) > 0)
+ {
+ (*it)->loadDesc(m_desc);
+ best = 0;
+ }
+ // match exception
+ int nBest = (*it)->isExp(m_expID, m_hRslt);
+ // if exception is matching better
+ if (nBest > 0 && best < nBest)
+ {
+ // set description
+ (*it)->loadDesc(m_desc);
+ best = nBest;
+ // if matching exactly, finish search
+ if (best == 2) break;
+ }
+ }
+ // add result code
+ // length of result code
+ const size_t rsltSize = 11;
+ // delimit description
+ const char delimRslt[] = ": ";
+ // set text of description
+ char rsltTxt[rsltSize];
+ std::ostrstream os(rsltTxt, rsltSize);
+ os << std::hex << m_hRslt << delimRslt << '\0';
+ // copy result to description
+ m_desc.insert(0, rsltTxt);
+ // copy exception description to last exception string
+ m_lastError = m_desc;
+ }
+}
+
+
+// copy exception data
+void Exception::copy (const Exception & xpt)
+{
+ // standard data
+ m_expID = xpt.m_expID;
+ m_hRslt = xpt.m_hRslt;
+ m_desc = xpt.m_desc;
+
+ // debug data
+ m_fileName = xpt.m_fileName;
+ m_line = xpt.m_line;
+}
+
+void registerAllExceptions(void)
+{
+ errGenerDesc.registerDesc();
+ errNFoundDesc.registerDesc();
+ MaterialNotAvailDesc.registerDesc();
+ ImageSizesNotMatchDesc.registerDesc();
+ SceneInvalidDesc.registerDesc();
+ CameraInvalidDesc.registerDesc();
+ SourceVideoEmptyDesc.registerDesc();
+ SourceVideoCreationDesc.registerDesc();
+}
diff --git a/source/gameengine/VideoTexture/Exception.h b/source/gameengine/VideoTexture/Exception.h
new file mode 100644
index 00000000000..5345e87f199
--- /dev/null
+++ b/source/gameengine/VideoTexture/Exception.h
@@ -0,0 +1,210 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2006 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+
+#if !defined EXCEPTION_H
+#define EXCEPTION_H
+
+#include <exception>
+#include <vector>
+#include <string>
+#include <algorithm>
+
+#include "Common.h"
+
+
+#define CHCKHRSLTV(fnc,val,err) \
+{ \
+ HRESULT macroHRslt = (fnc); \
+ if (macroHRslt != val) \
+ throw Exception (err, macroHRslt, __FILE__, __LINE__); \
+}
+
+#define THRWEXCP(err,hRslt) throw Exception (err, hRslt, __FILE__, __LINE__);
+
+
+#if defined WIN32
+
+#define CHCKHRSLT(fnc,err) \
+{ \
+ HRESULT macroHRslt = (fnc); \
+ if (FAILED(macroHRslt)) \
+ throw Exception (err, macroHRslt, __FILE__, __LINE__); \
+}
+
+#else
+
+#define CHCKHRSLT(fnc,err) CHCKHRSLTV(fnc,S_OK,err)
+
+#endif
+
+
+// forward declarations
+class ExceptionID;
+class Exception;
+
+
+// exception identificators
+extern ExceptionID ErrGeneral, ErrNotFound;
+
+
+// result type
+typedef long RESULT;
+
+
+// class ExceptionID for exception identification
+class ExceptionID
+{
+public:
+ // constructor a destructor
+ ExceptionID (void) {}
+ ~ExceptionID (void) {}
+
+private:
+ // not allowed
+ ExceptionID (const ExceptionID & obj) throw() {}
+ ExceptionID & operator= (const ExceptionID & obj) throw() { return *this; }
+};
+
+
+// class ExpDesc for exception description
+class ExpDesc
+{
+public:
+ // constructor a destructor
+ ExpDesc (ExceptionID & exp, char * desc, RESULT hres = S_OK);
+ ~ExpDesc (void);
+
+ // comparision function
+ // returns 0, if exception identification don't match at all
+ // returns 1, if only exception identification is matching
+ // returns 2, if both exception identification and result are matching
+ int isExp (ExceptionID * exp, RESULT hres = S_OK) throw()
+ {
+ // check exception identification
+ if (&m_expID == exp)
+ {
+ // check result value
+ if (m_hRslt == hres) return 2;
+ // only identification match
+ if (m_hRslt == S_OK) return 1;
+ }
+ // no match
+ return 0;
+ }
+
+ // get exception description
+ void loadDesc (std::string & desc) throw()
+ {
+ desc = m_description;
+ }
+
+ void registerDesc(void)
+ {
+ if (std::find(m_expDescs.begin(), m_expDescs.end(), this) == m_expDescs.end())
+ m_expDescs.push_back(this);
+ }
+ // list of exception descriptions
+ static std::vector<ExpDesc*> m_expDescs;
+
+private:
+ // exception ID
+ ExceptionID & m_expID;
+ // result
+ RESULT m_hRslt;
+ // description
+ char * m_description;
+
+ // not allowed
+ ExpDesc (const ExpDesc & obj) : m_expID (ErrNotFound) {}
+ ExpDesc & operator= (const ExpDesc & obj) { return *this; }
+};
+
+
+
+// class Exception
+class Exception : public std::exception
+{
+public:
+ // constructor
+ Exception ();
+ // destructor
+ virtual ~Exception () throw();
+ // copy constructor
+ Exception (const Exception & xpt);
+ // assignment operator
+ Exception & operator= (const Exception & xpt);
+ // get exception description
+ virtual const char * what(void);
+
+ // debug version of constructor
+ Exception (ExceptionID & expID, RESULT rslt, char * fil, int lin);
+ // set source file and line of exception
+ void setFileLine (char * fil, int lin);
+
+ // get description in string
+ std::string & getDesc (void) throw() { return m_desc; }
+
+ // report exception
+ virtual void report (void);
+
+ // get exception id
+ ExceptionID * getID (void) throw() { return m_expID; }
+
+ /// last exception description
+ static std::string m_lastError;
+
+ /// log file name
+ static char * m_logFile;
+
+protected:
+ // exception identification
+ ExceptionID * m_expID;
+ // RESULT code
+ RESULT m_hRslt;
+
+ // exception description
+ std::string m_desc;
+
+ // set exception description
+ virtual void setXptDesc (void);
+
+ // copy exception
+ void copy (const Exception & xpt);
+
+ // file name where exception was thrown
+ std::string m_fileName;
+ // line number in file
+ int m_line;
+
+};
+
+extern ExpDesc MaterialNotAvailDesc;
+extern ExpDesc ImageSizesNotMatchDesc;
+extern ExpDesc SceneInvalidDesc;
+extern ExpDesc CameraInvalidDesc;
+extern ExpDesc SourceVideoEmptyDesc;
+extern ExpDesc SourceVideoCreationDesc;
+
+
+void registerAllExceptions(void);
+#endif
diff --git a/source/gameengine/VideoTexture/FilterBase.cpp b/source/gameengine/VideoTexture/FilterBase.cpp
new file mode 100644
index 00000000000..b0112cd355b
--- /dev/null
+++ b/source/gameengine/VideoTexture/FilterBase.cpp
@@ -0,0 +1,150 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+#include "FilterBase.h"
+
+#include <PyObjectPlus.h>
+#include <structmember.h>
+
+
+// FilterBase class implementation
+
+// constructor
+FilterBase::FilterBase (void) : m_previous(NULL) {}
+
+
+// destructor
+FilterBase::~FilterBase (void)
+{
+ // release Python objects, if not released yet
+ release();
+}
+
+
+// release python objects
+void FilterBase::release (void)
+{
+ // release previous filter object
+ setPrevious(NULL);
+}
+
+
+// set new previous filter
+void FilterBase::setPrevious (PyFilter * filt, bool useRefCnt)
+{
+ // if reference counting has to be used
+ if (useRefCnt)
+ {
+ // reference new filter
+ if (filt != NULL) Py_INCREF(filt);
+ // release old filter
+ Py_XDECREF(m_previous);
+ }
+ // set new previous filter
+ m_previous = filt;
+}
+
+
+// find first filter
+FilterBase * FilterBase::findFirst (void)
+{
+ // find first filter in chain
+ FilterBase * frst;
+ for (frst = this; frst->m_previous != NULL; frst = frst->m_previous->m_filter);
+ // set first filter
+ return frst;
+}
+
+
+
+// list offilter types
+PyTypeList pyFilterTypes;
+
+
+
+// functions for python interface
+
+
+// object allocation
+PyObject * Filter_allocNew (PyTypeObject * type, PyObject * args, PyObject * kwds)
+{
+ // allocate object
+ PyFilter * self = reinterpret_cast<PyFilter*>(type->tp_alloc(type, 0));
+ // initialize object structure
+ self->m_filter = NULL;
+ // return allocated object
+ return reinterpret_cast<PyObject*>(self);
+}
+
+// object deallocation
+void Filter_dealloc (PyFilter * self)
+{
+ // release object attributes
+ if (self->m_filter != NULL)
+ {
+ self->m_filter->release();
+ delete self->m_filter;
+ self->m_filter = NULL;
+ }
+}
+
+
+// get previous pixel filter object
+PyObject * Filter_getPrevious (PyFilter * self, void * closure)
+{
+ // if filter object is available
+ if (self->m_filter != NULL)
+ {
+ // pixel filter object
+ PyObject * filt = reinterpret_cast<PyObject*>(self->m_filter->getPrevious());
+ // if filter is present
+ if (filt != NULL)
+ {
+ // return it
+ Py_INCREF(filt);
+ return filt;
+ }
+ }
+ // otherwise return none
+ Py_RETURN_NONE;
+}
+
+
+// set previous pixel filter object
+int Filter_setPrevious (PyFilter * self, PyObject * value, void * closure)
+{
+ // if filter object is available
+ if (self->m_filter != NULL)
+ {
+ // check new value
+ if (value == NULL || !pyFilterTypes.in(value->ob_type))
+ {
+ // report value error
+ PyErr_SetString(PyExc_TypeError, "Invalid type of value");
+ return -1;
+ }
+ // set new value
+ self->m_filter->setPrevious(reinterpret_cast<PyFilter*>(value));
+ }
+ // return success
+ return 0;
+}
diff --git a/source/gameengine/VideoTexture/FilterBase.h b/source/gameengine/VideoTexture/FilterBase.h
new file mode 100644
index 00000000000..b6080f018d5
--- /dev/null
+++ b/source/gameengine/VideoTexture/FilterBase.h
@@ -0,0 +1,138 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+#if !defined FILTERBASE_H
+#define FILTERBASE_H
+
+#include "Common.h"
+
+#include <PyObjectPlus.h>
+
+#include "PyTypeList.h"
+
+#define VT_C(v,idx) ((unsigned char*)&v)[idx]
+#define VT_R(v) ((unsigned char*)&v)[0]
+#define VT_G(v) ((unsigned char*)&v)[1]
+#define VT_B(v) ((unsigned char*)&v)[2]
+#define VT_A(v) ((unsigned char*)&v)[3]
+#define VT_RGBA(v,r,g,b,a) VT_R(v)=(unsigned char)r, VT_G(v)=(unsigned char)g, VT_B(v)=(unsigned char)b, VT_A(v)=(unsigned char)a
+
+// forward declaration
+class FilterBase;
+
+
+// python structure for filter
+struct PyFilter
+{
+ PyObject_HEAD
+ // source object
+ FilterBase * m_filter;
+};
+
+
+/// base class for pixel filters
+class FilterBase
+{
+public:
+ /// constructor
+ FilterBase (void);
+ /// destructor
+ virtual ~FilterBase (void);
+ // release python objects
+ virtual void release (void);
+
+ /// convert pixel
+ template <class SRC> unsigned int convert (SRC src, short x, short y,
+ short * size, unsigned int pixSize)
+ {
+ return filter(src, x, y, size, pixSize,
+ convertPrevious(src, x, y, size, pixSize));
+ }
+
+ /// get previous filter
+ PyFilter * getPrevious (void) { return m_previous; }
+ /// set previous filter
+ void setPrevious (PyFilter * filt, bool useRefCnt = true);
+
+ /// find first filter in chain
+ FilterBase * findFirst (void);
+
+ /// get first filter's source pixel size
+ unsigned int firstPixelSize (void) { return findFirst()->getPixelSize(); }
+
+protected:
+ /// previous pixel filter
+ PyFilter * m_previous;
+
+ /// filter pixel, source byte buffer
+ virtual unsigned int filter (unsigned char * src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val = 0)
+ { return val; }
+ /// filter pixel, source int buffer
+ virtual unsigned int filter (unsigned int * src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val = 0)
+ { return val; }
+
+ /// get source pixel size
+ virtual unsigned int getPixelSize (void) { return 1; }
+
+ /// get converted pixel from previous filters
+ template <class SRC> unsigned int convertPrevious (SRC src, short x, short y,
+ short * size, unsigned int pixSize)
+ {
+ // if previous filter doesn't exists, return source pixel
+ if (m_previous == NULL) return *src;
+ // otherwise return converted pixel
+ return m_previous->m_filter->convert(src, x, y, size, pixSize);
+ }
+};
+
+
+// list of python filter types
+extern PyTypeList pyFilterTypes;
+
+
+// functions for python interface
+
+// object initialization
+template <class T> static int Filter_init (PyObject * pySelf, PyObject * args, PyObject * kwds)
+{
+ PyFilter * self = reinterpret_cast<PyFilter*>(pySelf);
+ // create filter object
+ if (self->m_filter != NULL) delete self->m_filter;
+ self->m_filter = new T();
+ // initialization succeded
+ return 0;
+}
+
+// object allocation
+PyObject * Filter_allocNew (PyTypeObject * type, PyObject * args, PyObject * kwds);
+// object deallocation
+void Filter_dealloc (PyFilter * self);
+
+// get previous pixel filter object
+PyObject * Filter_getPrevious (PyFilter * self, void * closure);
+// set previous pixel filter object
+int Filter_setPrevious (PyFilter * self, PyObject * value, void * closure);
+
+
+#endif
diff --git a/source/gameengine/VideoTexture/FilterBlueScreen.cpp b/source/gameengine/VideoTexture/FilterBlueScreen.cpp
new file mode 100644
index 00000000000..43d7566102a
--- /dev/null
+++ b/source/gameengine/VideoTexture/FilterBlueScreen.cpp
@@ -0,0 +1,178 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+
+#include <PyObjectPlus.h>
+#include <structmember.h>
+
+#include "FilterBlueScreen.h"
+
+#include "FilterBase.h"
+#include "PyTypeList.h"
+
+// implementation FilterBlueScreen
+
+// constructor
+FilterBlueScreen::FilterBlueScreen (void)
+{
+ // set color to blue
+ setColor(0, 0, 255);
+ // set limits
+ setLimits(64, 64);
+}
+
+// set color
+void FilterBlueScreen::setColor (unsigned char red, unsigned char green, unsigned char blue)
+{
+ m_color[0] = red;
+ m_color[1] = green;
+ m_color[2] = blue;
+}
+
+// set limits for color variation
+void FilterBlueScreen::setLimits (unsigned short minLimit, unsigned short maxLimit)
+{
+ m_limits[0] = minLimit;
+ m_limits[1] = maxLimit > minLimit ? maxLimit : minLimit;
+ // calculate square values
+ for (short idx = 0; idx < 2; ++idx)
+ m_squareLimits[idx] = m_limits[idx] * m_limits[idx];
+ // limits distance
+ m_limitDist = m_squareLimits[1] - m_squareLimits[0];
+}
+
+
+
+// cast Filter pointer to FilterBlueScreen
+inline FilterBlueScreen * getFilter (PyFilter * self)
+{ return static_cast<FilterBlueScreen*>(self->m_filter); }
+
+
+// python methods and get/sets
+
+// get color
+static PyObject * getColor (PyFilter * self, void * closure)
+{
+ return Py_BuildValue("[BBB]", getFilter(self)->getColor()[0],
+ getFilter(self)->getColor()[1], getFilter(self)->getColor()[2]);
+}
+
+// set color
+static int setColor (PyFilter * self, PyObject * value, void * closure)
+{
+ // check validity of parameter
+ if (value == NULL || !PySequence_Check(value) || PySequence_Length(value) != 3
+ || !PyInt_Check(PySequence_Fast_GET_ITEM(value, 0))
+ || !PyInt_Check(PySequence_Fast_GET_ITEM(value, 1))
+ || !PyInt_Check(PySequence_Fast_GET_ITEM(value, 2)))
+ {
+ PyErr_SetString(PyExc_TypeError, "The value must be a sequence of 3 ints");
+ return -1;
+ }
+ // set color
+ getFilter(self)->setColor((unsigned char)(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 0))),
+ (unsigned char)(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 1))),
+ (unsigned char)(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 2))));
+ // success
+ return 0;
+}
+
+// get limits
+static PyObject * getLimits (PyFilter * self, void * closure)
+{
+ return Py_BuildValue("[II]", getFilter(self)->getLimits()[0],
+ getFilter(self)->getLimits()[1]);
+}
+
+// set limit
+static int setLimits (PyFilter * self, PyObject * value, void * closure)
+{
+ // check validity of parameter
+ if (value == NULL || !PySequence_Check(value) || PySequence_Length(value) != 2
+ || !PyInt_Check(PySequence_Fast_GET_ITEM(value, 0))
+ || !PyInt_Check(PySequence_Fast_GET_ITEM(value, 1)))
+ {
+ PyErr_SetString(PyExc_TypeError, "The value must be a sequence of 2 ints");
+ return -1;
+ }
+ // set limits
+ getFilter(self)->setLimits((unsigned short)(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 0))),
+ (unsigned short)(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 1))));
+ // success
+ return 0;
+}
+
+
+// attributes structure
+static PyGetSetDef filterBSGetSets[] =
+{
+ {(char*)"color", (getter)getColor, (setter)setColor, (char*)"blue screen color", NULL},
+ {(char*)"limits", (getter)getLimits, (setter)setLimits, (char*)"blue screen color limits", NULL},
+ // attributes from FilterBase class
+ {(char*)"previous", (getter)Filter_getPrevious, (setter)Filter_setPrevious, (char*)"previous pixel filter", NULL},
+ {NULL}
+};
+
+// define python type
+PyTypeObject FilterBlueScreenType =
+{
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "VideoTexture.FilterBlueScreen", /*tp_name*/
+ sizeof(PyFilter), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)Filter_dealloc,/*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash */
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ "Filter for Blue Screen objects", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ NULL, /* tp_methods */
+ 0, /* tp_members */
+ filterBSGetSets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)Filter_init<FilterBlueScreen>, /* tp_init */
+ 0, /* tp_alloc */
+ Filter_allocNew, /* tp_new */
+};
+
diff --git a/source/gameengine/VideoTexture/FilterBlueScreen.h b/source/gameengine/VideoTexture/FilterBlueScreen.h
new file mode 100644
index 00000000000..820e4a44501
--- /dev/null
+++ b/source/gameengine/VideoTexture/FilterBlueScreen.h
@@ -0,0 +1,97 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of blendTex library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+#if !defined FILTERBLUESCREEN_H
+#define FILTERBLUESCREEN_H
+
+#include "Common.h"
+
+#include "FilterBase.h"
+
+
+/// pixel filter for blue screen
+class FilterBlueScreen : public FilterBase
+{
+public:
+ /// constructor
+ FilterBlueScreen (void);
+ /// destructor
+ virtual ~FilterBlueScreen (void) {}
+
+ /// get color
+ unsigned char * getColor (void) { return m_color; }
+ /// set color
+ void setColor (unsigned char red, unsigned char green, unsigned char blue);
+
+ /// get limits for color variation
+ unsigned short * getLimits (void) { return m_limits; }
+ /// set limits for color variation
+ void setLimits (unsigned short minLimit, unsigned short maxLimit);
+
+protected:
+ /// blue screen color (red component first)
+ unsigned char m_color[3];
+ /// limits for color variation - first defines, where ends fully transparent
+ /// color, second defines, where begins fully opaque color
+ unsigned short m_limits[2];
+ /// squared limits for color variation
+ unsigned int m_squareLimits[2];
+ /// distance between squared limits
+ unsigned int m_limitDist;
+
+ /// filter pixel template, source int buffer
+ template <class SRC> unsigned int tFilter (SRC src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val)
+ {
+ // calculate differences
+ int difRed = int(VT_R(val)) - int(m_color[0]);
+ int difGreen = int(VT_G(val)) - int(m_color[1]);
+ int difBlue = int(VT_B(val)) - int(m_color[2]);
+ // calc distance from "blue screen" color
+ unsigned int dist = (unsigned int)(difRed * difRed + difGreen * difGreen
+ + difBlue * difBlue);
+ // condition for fully transparent color
+ if (m_squareLimits[0] >= dist)
+ // return color with zero alpha
+ VT_A(val) = 0;
+ // condition for fully opaque color
+ else if (m_squareLimits[1] <= dist)
+ // return normal colour
+ VT_A(val) = 0xFF;
+ // otherwise calc alpha
+ else
+ VT_A(val) = (((dist - m_squareLimits[0]) << 8) / m_limitDist);
+ return val;
+ }
+
+ /// virtual filtering function for byte source
+ virtual unsigned int filter (unsigned char * src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val = 0)
+ { return tFilter(src, x, y, size, pixSize, val); }
+ /// virtual filtering function for unsigned int source
+ virtual unsigned int filter (unsigned int * src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val = 0)
+ { return tFilter(src, x, y, size, pixSize, val); }
+};
+
+
+#endif
diff --git a/source/gameengine/VideoTexture/FilterColor.cpp b/source/gameengine/VideoTexture/FilterColor.cpp
new file mode 100644
index 00000000000..22ee729b200
--- /dev/null
+++ b/source/gameengine/VideoTexture/FilterColor.cpp
@@ -0,0 +1,350 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+
+#include <PyObjectPlus.h>
+#include <structmember.h>
+
+#include "FilterColor.h"
+
+#include "FilterBase.h"
+#include "PyTypeList.h"
+
+// implementation FilterGray
+
+// attributes structure
+static PyGetSetDef filterGrayGetSets[] =
+{ // attributes from FilterBase class
+ {(char*)"previous", (getter)Filter_getPrevious, (setter)Filter_setPrevious, (char*)"previous pixel filter", NULL},
+ {NULL}
+};
+
+// define python type
+PyTypeObject FilterGrayType =
+{
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "VideoTexture.FilterGray", /*tp_name*/
+ sizeof(PyFilter), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)Filter_dealloc,/*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash */
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ "Filter for gray scale effect", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ NULL, /* tp_methods */
+ 0, /* tp_members */
+ filterGrayGetSets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)Filter_init<FilterGray>, /* tp_init */
+ 0, /* tp_alloc */
+ Filter_allocNew, /* tp_new */
+};
+
+
+// implementation FilterColor
+
+// constructor
+FilterColor::FilterColor (void)
+{
+ // reset color matrix to identity
+ for (int r = 0; r < 4; ++r)
+ for (int c = 0; c < 5; ++c)
+ m_matrix[r][c] = (r == c) ? 256 : 0;
+}
+
+// set color matrix
+void FilterColor::setMatrix (ColorMatrix & mat)
+{
+ // copy matrix
+ for (int r = 0; r < 4; ++r)
+ for (int c = 0; c < 5; ++c)
+ m_matrix[r][c] = mat[r][c];
+}
+
+
+
+// cast Filter pointer to FilterColor
+inline FilterColor * getFilterColor (PyFilter * self)
+{ return static_cast<FilterColor*>(self->m_filter); }
+
+
+// python methods and get/sets
+
+// get color matrix
+static PyObject * getMatrix (PyFilter * self, void * closure)
+{
+ ColorMatrix & mat = getFilterColor(self)->getMatrix();
+ return Py_BuildValue("((hhhhh)(hhhhh)(hhhhh)(hhhhh))",
+ mat[0][0], mat[0][1], mat[0][2], mat[0][3], mat[0][4],
+ mat[1][0], mat[1][1], mat[1][2], mat[1][3], mat[1][4],
+ mat[2][0], mat[2][1], mat[2][2], mat[2][3], mat[2][4],
+ mat[3][0], mat[3][1], mat[3][2], mat[3][3], mat[3][4]);
+}
+
+// set color matrix
+static int setMatrix (PyFilter * self, PyObject * value, void * closure)
+{
+ // matrix to store items
+ ColorMatrix mat;
+ // check validity of parameter
+ bool valid = value != NULL && PySequence_Check(value)
+ && PySequence_Length(value) == 4;
+ // check rows
+ for (int r = 0; valid && r < 4; ++r)
+ {
+ // get row object
+ PyObject * row = PySequence_Fast_GET_ITEM(value, r);
+ // check sequence
+ valid = PySequence_Check(row) && PySequence_Length(row) == 5;
+ // check items
+ for (int c = 0; valid && c < 5; ++c)
+ {
+ // item must be int
+ valid = PyInt_Check(PySequence_Fast_GET_ITEM(row, c));
+ // if it is valid, save it in matrix
+ if (valid)
+ mat[r][c] = short(PyInt_AsLong(PySequence_Fast_GET_ITEM(row, c)));
+ }
+ }
+ // if parameter is not valid, report error
+ if (!valid)
+ {
+ PyErr_SetString(PyExc_TypeError, "The value must be a matrix [4][5] of ints");
+ return -1;
+ }
+ // set color matrix
+ getFilterColor(self)->setMatrix(mat);
+ // success
+ return 0;
+}
+
+
+// attributes structure
+static PyGetSetDef filterColorGetSets[] =
+{
+ {(char*)"matrix", (getter)getMatrix, (setter)setMatrix, (char*)"matrix [4][5] for color calculation", NULL},
+ // attributes from FilterBase class
+ {(char*)"previous", (getter)Filter_getPrevious, (setter)Filter_setPrevious, (char*)"previous pixel filter", NULL},
+ {NULL}
+};
+
+// define python type
+PyTypeObject FilterColorType =
+{
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "VideoTexture.FilterColor", /*tp_name*/
+ sizeof(PyFilter), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)Filter_dealloc,/*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash */
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ "Filter for color calculations", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ NULL, /* tp_methods */
+ 0, /* tp_members */
+ filterColorGetSets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)Filter_init<FilterColor>, /* tp_init */
+ 0, /* tp_alloc */
+ Filter_allocNew, /* tp_new */
+};
+
+// implementation FilterLevel
+
+// constructor
+FilterLevel::FilterLevel (void)
+{
+ // reset color levels
+ for (int r = 0; r < 4; ++r)
+ {
+ levels[r][0] = 0;
+ levels[r][1] = 0xFF;
+ levels[r][2] = 0xFF;
+ }
+}
+
+// set color levels
+void FilterLevel::setLevels (ColorLevel & lev)
+{
+ // copy levels
+ for (int r = 0; r < 4; ++r)
+ {
+ for (int c = 0; c < 2; ++c)
+ levels[r][c] = lev[r][c];
+ levels[r][2] = lev[r][0] < lev[r][1] ? lev[r][1] - lev[r][0] : 1;
+ }
+}
+
+
+// cast Filter pointer to FilterLevel
+inline FilterLevel * getFilterLevel (PyFilter * self)
+{ return static_cast<FilterLevel*>(self->m_filter); }
+
+
+// python methods and get/sets
+
+// get color levels
+static PyObject * getLevels (PyFilter * self, void * closure)
+{
+ ColorLevel & lev = getFilterLevel(self)->getLevels();
+ return Py_BuildValue("((HH)(HH)(HH)(HH))",
+ lev[0][0], lev[0][1], lev[1][0], lev[1][1],
+ lev[2][0], lev[2][1], lev[3][0], lev[3][1]);
+}
+
+// set color levels
+static int setLevels (PyFilter * self, PyObject * value, void * closure)
+{
+ // matrix to store items
+ ColorLevel lev;
+ // check validity of parameter
+ bool valid = value != NULL && PySequence_Check(value)
+ && PySequence_Length(value) == 4;
+ // check rows
+ for (int r = 0; valid && r < 4; ++r)
+ {
+ // get row object
+ PyObject * row = PySequence_Fast_GET_ITEM(value, r);
+ // check sequence
+ valid = PySequence_Check(row) && PySequence_Length(row) == 2;
+ // check items
+ for (int c = 0; valid && c < 2; ++c)
+ {
+ // item must be int
+ valid = PyInt_Check(PySequence_Fast_GET_ITEM(row, c));
+ // if it is valid, save it in matrix
+ if (valid)
+ lev[r][c] = (unsigned short)(PyInt_AsLong(PySequence_Fast_GET_ITEM(row, c)));
+ }
+ }
+ // if parameter is not valid, report error
+ if (!valid)
+ {
+ PyErr_SetString(PyExc_TypeError, "The value must be a matrix [4][2] of ints");
+ return -1;
+ }
+ // set color matrix
+ getFilterLevel(self)->setLevels(lev);
+ // success
+ return 0;
+}
+
+
+// attributes structure
+static PyGetSetDef filterLevelGetSets[] =
+{
+ {(char*)"levels", (getter)getLevels, (setter)setLevels, (char*)"levels matrix [4] (min, max)", NULL},
+ // attributes from FilterBase class
+ {(char*)"previous", (getter)Filter_getPrevious, (setter)Filter_setPrevious, (char*)"previous pixel filter", NULL},
+ {NULL}
+};
+
+// define python type
+PyTypeObject FilterLevelType =
+{
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "VideoTexture.FilterLevel", /*tp_name*/
+ sizeof(PyFilter), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)Filter_dealloc,/*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash */
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ "Filter for levels calculations", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ NULL, /* tp_methods */
+ 0, /* tp_members */
+ filterLevelGetSets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)Filter_init<FilterLevel>, /* tp_init */
+ 0, /* tp_alloc */
+ Filter_allocNew, /* tp_new */
+};
+
diff --git a/source/gameengine/VideoTexture/FilterColor.h b/source/gameengine/VideoTexture/FilterColor.h
new file mode 100644
index 00000000000..b7e52c4521c
--- /dev/null
+++ b/source/gameengine/VideoTexture/FilterColor.h
@@ -0,0 +1,168 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of blendTex library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+#if !defined FILTERCOLOR_H
+#define FILTERCOLOR_H
+
+#include "Common.h"
+
+#include "FilterBase.h"
+
+
+/// pixel filter for gray scale
+class FilterGray : public FilterBase
+{
+public:
+ /// constructor
+ FilterGray (void) {}
+ /// destructor
+ virtual ~FilterGray (void) {}
+
+protected:
+ /// filter pixel template, source int buffer
+ template <class SRC> unsigned int tFilter (SRC src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val)
+ {
+ // calculate gray value
+ unsigned int gray = (28 * (VT_B(val)) + 151 * (VT_G(val))
+ + 77 * (VT_R(val))) >> 8;
+ // return gray scale value
+ VT_R(val) = gray;
+ VT_G(val) = gray;
+ VT_B(val) = gray;
+ return val;
+ }
+
+ /// virtual filtering function for byte source
+ virtual unsigned int filter (unsigned char * src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val = 0)
+ { return tFilter(src, x, y, size, pixSize, val); }
+ /// virtual filtering function for unsigned int source
+ virtual unsigned int filter (unsigned int * src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val = 0)
+ { return tFilter(src, x, y, size, pixSize, val); }
+};
+
+
+/// type for color matrix
+typedef short ColorMatrix[4][5];
+
+/// pixel filter for color calculation
+class FilterColor : public FilterBase
+{
+public:
+ /// constructor
+ FilterColor (void);
+ /// destructor
+ virtual ~FilterColor (void) {}
+
+ /// get color matrix
+ ColorMatrix & getMatrix (void) { return m_matrix; }
+ /// set color matrix
+ void setMatrix (ColorMatrix & mat);
+
+protected:
+ /// color calculation matrix
+ ColorMatrix m_matrix;
+
+ /// calculate one color component
+ unsigned char calcColor (unsigned int val, short idx)
+ {
+ return (((m_matrix[idx][0] * (VT_R(val)) + m_matrix[idx][1] * (VT_G(val))
+ + m_matrix[idx][2] * (VT_B(val)) + m_matrix[idx][3] * (VT_A(val))
+ + m_matrix[idx][4]) >> 8) & 0xFF);
+ }
+
+ /// filter pixel template, source int buffer
+ template <class SRC> unsigned int tFilter (SRC src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val)
+ {
+ // return calculated color
+ int color;
+ VT_RGBA(color, calcColor(val, 0), calcColor(val, 1), calcColor(val, 2), calcColor(val, 3));
+ return color;
+ }
+
+ /// virtual filtering function for byte source
+ virtual unsigned int filter (unsigned char * src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val = 0)
+ { return tFilter(src, x, y, size, pixSize, val); }
+ /// virtual filtering function for unsigned int source
+ virtual unsigned int filter (unsigned int * src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val = 0)
+ { return tFilter(src, x, y, size, pixSize, val); }
+};
+
+
+/// type for color levels
+typedef unsigned short ColorLevel[4][3];
+
+/// pixel filter for color calculation
+class FilterLevel : public FilterBase
+{
+public:
+ /// constructor
+ FilterLevel (void);
+ /// destructor
+ virtual ~FilterLevel (void) {}
+
+ /// get color matrix
+ ColorLevel & getLevels (void) { return levels; }
+ /// set color matrix
+ void setLevels (ColorLevel & lev);
+
+protected:
+ /// color calculation matrix
+ ColorLevel levels;
+
+ /// calculate one color component
+ unsigned int calcColor (unsigned int val, short idx)
+ {
+ unsigned int col = VT_C(val,idx);;
+ if (col <= levels[idx][0]) col = 0;
+ else if (col >= levels[idx][1]) col = 0xFF;
+ else col = (((col - levels[idx][0]) << 8) / levels[idx][2]) & 0xFF;
+ return col;
+ }
+
+ /// filter pixel template, source int buffer
+ template <class SRC> unsigned int tFilter (SRC src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val)
+ {
+ // return calculated color
+ int color;
+ VT_RGBA(color, calcColor(val, 0), calcColor(val, 1), calcColor(val, 2), calcColor(val, 3));
+ return color;
+ }
+
+ /// virtual filtering function for byte source
+ virtual unsigned int filter (unsigned char * src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val = 0)
+ { return tFilter(src, x, y, size, pixSize, val); }
+ /// virtual filtering function for unsigned int source
+ virtual unsigned int filter (unsigned int * src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val = 0)
+ { return tFilter(src, x, y, size, pixSize, val); }
+};
+
+
+#endif
diff --git a/source/gameengine/VideoTexture/FilterNormal.cpp b/source/gameengine/VideoTexture/FilterNormal.cpp
new file mode 100644
index 00000000000..03a79c1c8ce
--- /dev/null
+++ b/source/gameengine/VideoTexture/FilterNormal.cpp
@@ -0,0 +1,162 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+
+#include <PyObjectPlus.h>
+#include <structmember.h>
+
+#include "FilterNormal.h"
+
+#include "FilterBase.h"
+#include "PyTypeList.h"
+
+// implementation FilterNormal
+
+// constructor
+FilterNormal::FilterNormal (void) : m_colIdx(0)
+{
+ // set default depth
+ setDepth(4);
+}
+
+// set color shift
+void FilterNormal::setColor (unsigned short colIdx)
+{
+ // check validity of index
+ if (colIdx < 3)
+ // set color shift
+ m_colIdx = colIdx;
+}
+
+// set depth
+void FilterNormal::setDepth (float depth)
+{
+ m_depth = depth;
+ m_depthScale = depth / depthScaleKoef;
+}
+
+
+// cast Filter pointer to FilterNormal
+inline FilterNormal * getFilter (PyFilter * self)
+{ return static_cast<FilterNormal*>(self->m_filter); }
+
+
+// python methods and get/sets
+
+// get index of color used to calculate normal
+static PyObject * getColor (PyFilter * self, void * closure)
+{
+ return Py_BuildValue("H", getFilter(self)->getColor());
+}
+
+// set index of color used to calculate normal
+static int setColor (PyFilter * self, PyObject * value, void * closure)
+{
+ // check validity of parameter
+ if (value == NULL || !PyInt_Check(value))
+ {
+ PyErr_SetString(PyExc_TypeError, "The value must be a int");
+ return -1;
+ }
+ // set color index
+ getFilter(self)->setColor((unsigned short)(PyInt_AsLong(value)));
+ // success
+ return 0;
+}
+
+
+// get depth
+static PyObject * getDepth (PyFilter * self, void * closure)
+{
+ return Py_BuildValue("f", getFilter(self)->getDepth());
+}
+
+// set depth
+static int setDepth (PyFilter * self, PyObject * value, void * closure)
+{
+ // check validity of parameter
+ if (value == NULL || !PyFloat_Check(value))
+ {
+ PyErr_SetString(PyExc_TypeError, "The value must be a float");
+ return -1;
+ }
+ // set depth
+ getFilter(self)->setDepth(float(PyFloat_AsDouble(value)));
+ // success
+ return 0;
+}
+
+
+// attributes structure
+static PyGetSetDef filterNormalGetSets[] =
+{
+ {(char*)"colorIdx", (getter)getColor, (setter)setColor, (char*)"index of color used to calculate normal (0 - red, 1 - green, 2 - blue)", NULL},
+ {(char*)"depth", (getter)getDepth, (setter)setDepth, (char*)"depth of relief", NULL},
+ // attributes from FilterBase class
+ {(char*)"previous", (getter)Filter_getPrevious, (setter)Filter_setPrevious, (char*)"previous pixel filter", NULL},
+ {NULL}
+};
+
+// define python type
+PyTypeObject FilterNormalType =
+{
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "VideoTexture.FilterNormal", /*tp_name*/
+ sizeof(PyFilter), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)Filter_dealloc,/*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash */
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ "Filter for Blue Screen objects", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ NULL, /* tp_methods */
+ 0, /* tp_members */
+ filterNormalGetSets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)Filter_init<FilterNormal>, /* tp_init */
+ 0, /* tp_alloc */
+ Filter_allocNew, /* tp_new */
+};
+
diff --git a/source/gameengine/VideoTexture/FilterNormal.h b/source/gameengine/VideoTexture/FilterNormal.h
new file mode 100644
index 00000000000..840043be9a1
--- /dev/null
+++ b/source/gameengine/VideoTexture/FilterNormal.h
@@ -0,0 +1,107 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of blendTex library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+#if !defined FILTERNORMAL_H
+#define FILTERNORMAL_H
+
+#include "Common.h"
+
+#include "FilterBase.h"
+
+
+// scale constants for normals
+const float depthScaleKoef = 255.0;
+const float normScaleKoef = float(depthScaleKoef / 2.0);
+
+
+/// pixel filter for normal mapping
+class FilterNormal : public FilterBase
+{
+public:
+ /// constructor
+ FilterNormal (void);
+ /// destructor
+ virtual ~FilterNormal (void) {}
+
+ /// get index of color used to calculate normals
+ unsigned short getColor (void) { return m_colIdx; }
+ /// set index of color used to calculate normals
+ void setColor (unsigned short colIdx);
+
+ /// get depth
+ float getDepth (void) { return m_depth; }
+ /// set depth
+ void setDepth (float depth);
+
+protected:
+ /// depth of normal relief
+ float m_depth;
+ /// scale to calculate normals
+ float m_depthScale;
+
+ /// color index, 0=red, 1=green, 2=blue, 3=alpha
+ unsigned short m_colIdx;
+
+ /// filter pixel, source int buffer
+ template <class SRC> unsigned int tFilter (SRC * src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val = 0)
+ {
+ // get value of required color
+ int actPix = int(VT_C(val,m_colIdx));
+ int upPix = actPix;
+ int leftPix = actPix;
+ // get upper and left pixel from actual pixel
+ if (y > 0)
+ {
+ val = convertPrevious(src - pixSize * size[0], x, y - 1, size, pixSize);
+ upPix = VT_C(val,m_colIdx);
+ }
+ if (x > 0)
+ {
+ val = convertPrevious(src - pixSize, x - 1, y, size, pixSize);
+ leftPix = VT_C(val,m_colIdx);
+ }
+ // height differences (from blue color)
+ float dx = (actPix - leftPix) * m_depthScale;
+ float dy = (actPix - upPix) * m_depthScale;
+ // normalize vector
+ float dz = float(normScaleKoef / sqrt(dx * dx + dy * dy + 1.0));
+ dx = dx * dz + normScaleKoef;
+ dy = dy * dz + normScaleKoef;
+ dz += normScaleKoef;
+ // return normal vector converted to color
+ VT_RGBA(val, dx, dy, dz, 0xFF);
+ return val;
+ }
+
+ /// filter pixel, source byte buffer
+ virtual unsigned int filter (unsigned char * src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val = 0)
+ { return tFilter(src, x, y, size, pixSize, val); }
+ /// filter pixel, source int buffer
+ virtual unsigned int filter (unsigned int * src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val = 0)
+ { return tFilter(src, x, y, size, pixSize, val); }
+};
+
+
+#endif
diff --git a/source/gameengine/VideoTexture/FilterSource.cpp b/source/gameengine/VideoTexture/FilterSource.cpp
new file mode 100644
index 00000000000..f3676e93a6d
--- /dev/null
+++ b/source/gameengine/VideoTexture/FilterSource.cpp
@@ -0,0 +1,171 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+// implementation
+
+#include <PyObjectPlus.h>
+#include <structmember.h>
+
+#include "FilterSource.h"
+
+#include "FilterBase.h"
+#include "PyTypeList.h"
+
+
+// FilterRGB24
+
+// define python type
+PyTypeObject FilterRGB24Type =
+{
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "VideoTexture.FilterRGB24", /*tp_name*/
+ sizeof(PyFilter), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)Filter_dealloc,/*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash */
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ "Source filter RGB24 objects", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ NULL, /* tp_methods */
+ 0, /* tp_members */
+ NULL, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)Filter_init<FilterRGB24>, /* tp_init */
+ 0, /* tp_alloc */
+ Filter_allocNew, /* tp_new */
+};
+
+// FilterRGBA32
+
+// define python type
+PyTypeObject FilterRGBA32Type =
+{
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "VideoTexture.FilterRGBA32", /*tp_name*/
+ sizeof(PyFilter), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)Filter_dealloc,/*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash */
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ "Source filter RGBA32 objects", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ NULL, /* tp_methods */
+ 0, /* tp_members */
+ NULL, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)Filter_init<FilterRGBA32>, /* tp_init */
+ 0, /* tp_alloc */
+ Filter_allocNew, /* tp_new */
+};
+
+// FilterBGR24
+
+// define python type
+PyTypeObject FilterBGR24Type =
+{
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "VideoTexture.FilterBGR24", /*tp_name*/
+ sizeof(PyFilter), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)Filter_dealloc,/*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash */
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ "Source filter BGR24 objects", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ NULL, /* tp_methods */
+ 0, /* tp_members */
+ NULL, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)Filter_init<FilterBGR24>, /* tp_init */
+ 0, /* tp_alloc */
+ Filter_allocNew, /* tp_new */
+};
+
diff --git a/source/gameengine/VideoTexture/FilterSource.h b/source/gameengine/VideoTexture/FilterSource.h
new file mode 100644
index 00000000000..7e90747d252
--- /dev/null
+++ b/source/gameengine/VideoTexture/FilterSource.h
@@ -0,0 +1,258 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of blendTex library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+#if !defined FILTERSOURCE_H
+#define FILTERSOURCE_H
+
+#include "Common.h"
+
+#include "FilterBase.h"
+
+
+/// class for RGB24 conversion
+class FilterRGB24 : public FilterBase
+{
+public:
+ /// constructor
+ FilterRGB24 (void) {}
+ /// destructor
+ virtual ~FilterRGB24 (void) {}
+
+ /// get source pixel size
+ virtual unsigned int getPixelSize (void) { return 3; }
+
+protected:
+ /// filter pixel, source byte buffer
+ virtual unsigned int filter (unsigned char * src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val)
+ { VT_RGBA(val,src[0],src[1],src[2],0xFF); return val; }
+};
+
+/// class for RGBA32 conversion
+class FilterRGBA32 : public FilterBase
+{
+public:
+ /// constructor
+ FilterRGBA32 (void) {}
+ /// destructor
+ virtual ~FilterRGBA32 (void) {}
+
+ /// get source pixel size
+ virtual unsigned int getPixelSize (void) { return 4; }
+
+protected:
+ /// filter pixel, source byte buffer
+ virtual unsigned int filter (unsigned char * src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val)
+ {
+ if ((intptr_t(src)&0x3) == 0)
+ return *(unsigned int*)src;
+ else
+ {
+ VT_RGBA(val,src[0],src[1],src[2],src[3]);
+ return val;
+ }
+ }
+};
+
+/// class for BGR24 conversion
+class FilterBGR24 : public FilterBase
+{
+public:
+ /// constructor
+ FilterBGR24 (void) {}
+ /// destructor
+ virtual ~FilterBGR24 (void) {}
+
+ /// get source pixel size
+ virtual unsigned int getPixelSize (void) { return 3; }
+
+protected:
+ /// filter pixel, source byte buffer
+ virtual unsigned int filter (unsigned char * src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val)
+ { VT_RGBA(val,src[2],src[1],src[0],0xFF); return val; }
+};
+
+/// class for YV12 conversion
+class FilterYV12 : public FilterBase
+{
+public:
+ /// constructor
+ FilterYV12 (void) {}
+ /// destructor
+ virtual ~FilterYV12 (void) {}
+
+ /// get source pixel size
+ virtual unsigned int getPixelSize (void) { return 1; }
+
+ /// set pointers to color buffers
+ void setBuffs (unsigned char * buff, short * size)
+ {
+ unsigned int buffSize = size[0] * size[1];
+ m_buffV = buff + buffSize;
+ m_buffU = m_buffV + (buffSize >> 2);
+ m_pitchUV = size[0] >> 1;
+ }
+
+protected:
+ /// begin of V buffer
+ unsigned char * m_buffV;
+ /// begin of U buffer
+ unsigned char * m_buffU;
+ /// pitch for V & U buffers
+ short m_pitchUV;
+
+ /// interpolation function
+ int interpol (int a, int b, int c, int d)
+ { return (9 * (b + c) - a - d + 8) >> 4; }
+
+ /// common horizontal interpolation
+ int interpolH (unsigned char * src)
+ { return interpol(*(src-1), *src, *(src+1), *(src+2)); }
+
+ /// common vertical interpolation
+ int interpolV (unsigned char * src)
+ { return interpol(*(src-m_pitchUV), *src, *(src+m_pitchUV), *(src+2*m_pitchUV)); }
+
+ /// common joined vertical and horizontal interpolation
+ int interpolVH (unsigned char * src)
+ {
+ return interpol(interpolV(src-1), interpolV(src), interpolV(src+1),
+ interpolV(src+2));
+ }
+
+ /// is pixel on edge
+ bool isEdge (short x, short y, short * size)
+ { return x <= 1 || x >= size[0] - 4 || y <= 1 || y >= size[1] - 4; }
+
+ /// get the first parameter on the low edge
+ unsigned char * interParA (unsigned char * src, short x, short size, short shift)
+ { return x > 1 ? src - shift : src; }
+ /// get the third parameter on the high edge
+ unsigned char * interParC (unsigned char * src, short x, short size, short shift)
+ { return x < size - 2 ? src + shift : src; }
+ /// get the fourth parameter on the high edge
+ unsigned char * interParD (unsigned char * src, short x, short size, short shift)
+ { return x < size - 4 ? src + 2 * shift : x < size - 2 ? src + shift : src; }
+
+ /// horizontal interpolation on edges
+ int interpolEH (unsigned char * src, short x, short size)
+ {
+ return interpol(*interParA(src, x, size, 1), *src,
+ *interParC(src, x, size, 1), *interParD(src, x, size, 1));
+ }
+
+ /// vertical interpolation on edges
+ int interpolEV (unsigned char * src, short y, short size)
+ {
+ return interpol(*interParA(src, y, size, m_pitchUV), *src,
+ *interParC(src, y, size, m_pitchUV), *interParD(src, y, size, m_pitchUV));
+ }
+
+ /// joined vertical and horizontal interpolation on edges
+ int interpolEVH (unsigned char * src, short x, short y, short * size)
+ {
+ return interpol(interpolEV(interParA(src, x, size[0], 1), y, size[1]),
+ interpolEV(src, y, size[1]), interpolEV(interParC(src, x, size[0], 1), y, size[1]),
+ interpolEV(interParD(src, x, size[0], 1), y, size[1]));
+ }
+
+
+ /// filter pixel, source byte buffer
+ virtual unsigned int filter (unsigned char * src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val)
+ {
+ // V & U offset
+ long offset = (x >> 1) + m_pitchUV * (y >> 1);
+ // get modified YUV -> CDE: C = Y - 16; D = U - 128; E = V - 128
+ int c = *src - 16;
+ int d = m_buffU[offset] - 128;
+ int e = m_buffV[offset] - 128;
+ // if horizontal interpolation is needed
+ if ((x & 1) == 1)
+ // if vertical interpolation is needed too
+ if ((y & 1) == 1)
+ // if this pixel is on the edge
+ if (isEdge(x, y, size))
+ {
+ // get U & V from edge
+ d = interpolEVH(m_buffU + offset, x, y, size) - 128;
+ e = interpolEVH(m_buffV + offset, x, y, size) - 128;
+ }
+ // otherwise get U & V from inner range
+ else
+ {
+ d = interpolVH(m_buffU + offset) - 128;
+ e = interpolVH(m_buffV + offset) - 128;
+ }
+ // otherwise use horizontal interpolation only
+ else
+ // if this pixel is on the edge
+ if (isEdge(x, y, size))
+ {
+ // get U & V from edge
+ d = interpolEH(m_buffU + offset, x, size[0]) - 128;
+ e = interpolEH(m_buffV + offset, x, size[0]) - 128;
+ }
+ // otherwise get U & V from inner range
+ else
+ {
+ d = interpolH(m_buffU + offset) - 128;
+ e = interpolH(m_buffV + offset) - 128;
+ }
+ // otherwise if only vertical interpolation is needed
+ else if ((y & 1) == 1)
+ // if this pixel is on the edge
+ if (isEdge(x, y, size))
+ {
+ // get U & V from edge
+ d = interpolEV(m_buffU + offset, y, size[1]) - 128;
+ e = interpolEV(m_buffV + offset, y, size[1]) - 128;
+ }
+ // otherwise get U & V from inner range
+ else
+ {
+ d = interpolV(m_buffU + offset) - 128;
+ e = interpolV(m_buffV + offset) - 128;
+ }
+ // convert to RGB
+ // R = clip(( 298 * C + 409 * E + 128) >> 8)
+ // G = clip(( 298 * C - 100 * D - 208 * E + 128) >> 8)
+ // B = clip(( 298 * C + 516 * D + 128) >> 8)
+ int red = (298 * c + 409 * e + 128) >> 8;
+ if (red >= 0x100) red = 0xFF;
+ else if (red < 0) red = 0;
+ int green = (298 * c - 100 * d - 208 * e) >> 8;
+ if (green >= 0x100) green = 0xFF;
+ else if (green < 0) green = 0;
+ int blue = (298 * c + 516 * d + 128) >> 8;
+ if (blue >= 0x100) blue = 0xFF;
+ else if (blue < 0) blue = 0;
+ // return result
+ VT_RGBA(val, red, green, blue, 0xFF);
+ return val;
+ }
+};
+
+
+#endif
diff --git a/source/gameengine/VideoTexture/ImageBase.cpp b/source/gameengine/VideoTexture/ImageBase.cpp
new file mode 100644
index 00000000000..dcca20de24a
--- /dev/null
+++ b/source/gameengine/VideoTexture/ImageBase.cpp
@@ -0,0 +1,529 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+#include "ImageBase.h"
+
+#include <vector>
+#include <string.h>
+
+#include <PyObjectPlus.h>
+#include <structmember.h>
+
+#include "FilterBase.h"
+
+#include "Exception.h"
+
+
+
+// ImageBase class implementation
+
+// constructor
+ImageBase::ImageBase (bool staticSrc) : m_image(NULL), m_imgSize(0),
+m_avail(false), m_scale(false), m_scaleChange(false), m_flip(false),
+m_staticSources(staticSrc), m_pyfilter(NULL)
+{
+ m_size[0] = m_size[1] = 0;
+}
+
+
+// destructor
+ImageBase::~ImageBase (void)
+{
+ // release image
+ delete [] m_image;
+}
+
+
+// release python objects
+bool ImageBase::release (void)
+{
+ // iterate sources
+ for (ImageSourceList::iterator it = m_sources.begin(); it != m_sources.end(); ++it)
+ {
+ // release source object
+ delete *it;
+ *it = NULL;
+ }
+ // release filter object
+ Py_XDECREF(m_pyfilter);
+ m_pyfilter = NULL;
+ return true;
+}
+
+
+// get image
+unsigned int * ImageBase::getImage (unsigned int texId)
+{
+ // if image is not available
+ if (!m_avail)
+ {
+ // if there are any sources
+ if (!m_sources.empty())
+ {
+ // get images from sources
+ for (ImageSourceList::iterator it = m_sources.begin(); it != m_sources.end(); ++it)
+ // get source image
+ (*it)->getImage();
+ // init image
+ init(m_sources[0]->getSize()[0], m_sources[0]->getSize()[1]);
+ }
+ // calculate new image
+ calcImage(texId);
+ }
+ // if image is available, return it, otherwise NULL
+ return m_avail ? m_image : NULL;
+}
+
+
+// refresh image source
+void ImageBase::refresh (void)
+{
+ // invalidate this image
+ m_avail = false;
+ // refresh all sources
+ for (ImageSourceList::iterator it = m_sources.begin(); it != m_sources.end(); ++it)
+ (*it)->refresh();
+}
+
+
+// get source object
+PyImage * ImageBase::getSource (const char * id)
+{
+ // find source
+ ImageSourceList::iterator src = findSource(id);
+ // return it, if found
+ return src != m_sources.end() ? (*src)->getSource() : NULL;
+}
+
+
+// set source object
+bool ImageBase::setSource (const char * id, PyImage * source)
+{
+ // find source
+ ImageSourceList::iterator src = findSource(id);
+ // check source loop
+ if (source != NULL && source->m_image->loopDetect(this))
+ return false;
+ // if found, set new object
+ if (src != m_sources.end())
+ // if new object is not empty or sources are static
+ if (source != NULL || m_staticSources)
+ // replace previous source
+ (*src)->setSource(source);
+ // otherwise delete source
+ else
+ m_sources.erase(src);
+ // if source is not found and adding is allowed
+ else
+ if (!m_staticSources)
+ {
+ // create new source
+ ImageSource * newSrc = newSource(id);
+ newSrc->setSource(source);
+ // if source was created, add it to source list
+ if (newSrc != NULL) m_sources.push_back(newSrc);
+ }
+ // otherwise source wasn't set
+ else
+ return false;
+ // source was set
+ return true;
+}
+
+
+// set pixel filter
+void ImageBase::setFilter (PyFilter * filt)
+{
+ // reference new filter
+ if (filt != NULL) Py_INCREF(filt);
+ // release previous filter
+ Py_XDECREF(m_pyfilter);
+ // set new filter
+ m_pyfilter = filt;
+}
+
+
+// initialize image data
+void ImageBase::init (short width, short height)
+{
+ // if image has to be scaled
+ if (m_scale)
+ {
+ // recalc sizes of image
+ width = calcSize(width);
+ height = calcSize(height);
+ }
+ // if sizes differ
+ if (width != m_size[0] || height != m_size[1])
+ {
+ // new buffer size
+ unsigned int newSize = width * height;
+ // if new buffer is larger than previous
+ if (newSize > m_imgSize)
+ {
+ // set new buffer size
+ m_imgSize = newSize;
+ // release previous and create new buffer
+ delete [] m_image;
+ m_image = new unsigned int[m_imgSize];
+ }
+ // new image size
+ m_size[0] = width;
+ m_size[1] = height;
+ // scale was processed
+ m_scaleChange = false;
+ }
+}
+
+
+// find source
+ImageSourceList::iterator ImageBase::findSource (const char * id)
+{
+ // iterate sources
+ ImageSourceList::iterator it;
+ for (it = m_sources.begin(); it != m_sources.end(); ++it)
+ // if id matches, return iterator
+ if ((*it)->is(id)) return it;
+ // source not found
+ return it;
+}
+
+
+// check sources sizes
+bool ImageBase::checkSourceSizes (void)
+{
+ // reference size
+ short * refSize = NULL;
+ // iterate sources
+ for (ImageSourceList::iterator it = m_sources.begin(); it != m_sources.end(); ++it)
+ {
+ // get size of current source
+ short * curSize = (*it)->getSize();
+ // if size is available and is not empty
+ if (curSize[0] != 0 && curSize[1] != 0)
+ // if reference size is not set
+ if (refSize == NULL)
+ // set current size as reference
+ refSize = curSize;
+ // otherwise check with current size
+ else if (curSize[0] != refSize[0] || curSize[1] != refSize[1])
+ // if they don't match, report it
+ return false;
+ }
+ // all sizes match
+ return true;
+}
+
+
+// compute nearest power of 2 value
+short ImageBase::calcSize (short size)
+{
+ // while there is more than 1 bit in size value
+ while ((size & (size - 1)) != 0)
+ // clear last bit
+ size = size & (size - 1);
+ // return result
+ return size;
+}
+
+
+// perform loop detection
+bool ImageBase::loopDetect (ImageBase * img)
+{
+ // if this object is the same as parameter, loop is detected
+ if (this == img) return true;
+ // check all sources
+ for (ImageSourceList::iterator it = m_sources.begin(); it != m_sources.end(); ++it)
+ // if source detected loop, return this result
+ if ((*it)->getSource() != NULL && (*it)->getSource()->m_image->loopDetect(img))
+ return true;
+ // no loop detected
+ return false;
+}
+
+
+// ImageSource class implementation
+
+// constructor
+ImageSource::ImageSource (const char * id) : m_source(NULL), m_image(NULL)
+{
+ // copy id
+ int idx;
+ for (idx = 0; id[idx] != '\0' && idx < SourceIdSize - 1; ++idx)
+ m_id[idx] = id[idx];
+ m_id[idx] = '\0';
+}
+
+// destructor
+ImageSource::~ImageSource (void)
+{
+ // release source
+ setSource(NULL);
+}
+
+
+// compare id
+bool ImageSource::is (const char * id)
+{
+ for (char * myId = m_id; *myId != '\0'; ++myId, ++id)
+ if (*myId != *id) return false;
+ return *id == '\0';
+}
+
+
+// set source object
+void ImageSource::setSource (PyImage * source)
+{
+ // reference new source
+ if (source != NULL) Py_INCREF(source);
+ // release previous source
+ Py_XDECREF(m_source);
+ // set new source
+ m_source = source;
+}
+
+
+// get image from source
+unsigned int * ImageSource::getImage (void)
+{
+ // if source is available
+ if (m_source != NULL)
+ // get image from source
+ m_image = m_source->m_image->getImage();
+ // otherwise reset buffer
+ else
+ m_image = NULL;
+ // return image
+ return m_image;
+}
+
+
+// refresh source
+void ImageSource::refresh (void)
+{
+ // if source is available, refresh it
+ if (m_source != NULL) m_source->m_image->refresh();
+}
+
+
+
+// list of image types
+PyTypeList pyImageTypes;
+
+
+
+// functions for python interface
+
+// object allocation
+PyObject * Image_allocNew (PyTypeObject * type, PyObject * args, PyObject * kwds)
+{
+ // allocate object
+ PyImage * self = reinterpret_cast<PyImage*>(type->tp_alloc(type, 0));
+ // initialize object structure
+ self->m_image = NULL;
+ // return allocated object
+ return reinterpret_cast<PyObject*>(self);
+}
+
+// object deallocation
+void Image_dealloc (PyImage * self)
+{
+ // release object attributes
+ if (self->m_image != NULL)
+ {
+ // if release requires deleting of object, do it
+ if (self->m_image->release())
+ delete self->m_image;
+ self->m_image = NULL;
+ }
+}
+
+// get image data
+PyObject * Image_getImage (PyImage * self, void * closure)
+{
+ try
+ {
+ // get image
+ unsigned int * image = self->m_image->getImage();
+ return Py_BuildValue("s#", image, self->m_image->getBuffSize());
+ }
+ catch (Exception & exp)
+ {
+ exp.report();
+ }
+ Py_RETURN_NONE;
+}
+
+// get image size
+PyObject * Image_getSize (PyImage * self, void * closure)
+{
+ return Py_BuildValue("(hh)", self->m_image->getSize()[0],
+ self->m_image->getSize()[1]);
+}
+
+// refresh image
+PyObject * Image_refresh (PyImage * self)
+{
+ self->m_image->refresh();
+ Py_RETURN_NONE;
+}
+
+// get scale
+PyObject * Image_getScale (PyImage * self, void * closure)
+{
+ if (self->m_image != NULL && self->m_image->getScale()) Py_RETURN_TRUE;
+ else Py_RETURN_FALSE;
+}
+
+// set scale
+int Image_setScale (PyImage * self, PyObject * value, void * closure)
+{
+ // check parameter, report failure
+ if (value == NULL || !PyBool_Check(value))
+ {
+ PyErr_SetString(PyExc_TypeError, "The value must be a bool");
+ return -1;
+ }
+ // set scale
+ if (self->m_image != NULL) self->m_image->setScale(value == Py_True);
+ // success
+ return 0;
+}
+
+// get flip
+PyObject * Image_getFlip (PyImage * self, void * closure)
+{
+ if (self->m_image != NULL && self->m_image->getFlip()) Py_RETURN_TRUE;
+ else Py_RETURN_FALSE;
+}
+
+// set flip
+int Image_setFlip (PyImage * self, PyObject * value, void * closure)
+{
+ // check parameter, report failure
+ if (value == NULL || !PyBool_Check(value))
+ {
+ PyErr_SetString(PyExc_TypeError, "The value must be a bool");
+ return -1;
+ }
+ // set scale
+ if (self->m_image != NULL) self->m_image->setFlip(value == Py_True);
+ // success
+ return 0;
+}
+
+
+// get filter source object
+PyObject * Image_getSource (PyImage * self, PyObject * args)
+{
+ // get arguments
+ char * id;
+ if (self->m_image != NULL && PyArg_ParseTuple(args, "s", &id))
+ {
+ // get source object
+ PyObject * src = reinterpret_cast<PyObject*>(self->m_image->getSource(id));
+ // if source is available
+ if (src != NULL)
+ {
+ // return source
+ Py_INCREF(src);
+ return src;
+ }
+ }
+ // source was not found
+ Py_RETURN_NONE;
+}
+
+
+// set filter source object
+PyObject * Image_setSource (PyImage * self, PyObject * args)
+{
+ // get arguments
+ char * id;
+ PyObject * obj;
+ if (self->m_image != NULL && PyArg_ParseTuple(args, "sO", &id, &obj))
+ {
+ // check type of object
+ if (pyImageTypes.in(obj->ob_type))
+ {
+ // convert to image struct
+ PyImage * img = reinterpret_cast<PyImage*>(obj);
+ // set source
+ if (!self->m_image->setSource(id, img))
+ {
+ // if not set, retport error
+ PyErr_SetString(PyExc_RuntimeError, "Invalid source or id");
+ return NULL;
+ }
+ }
+ // else report error
+ else
+ {
+ PyErr_SetString(PyExc_RuntimeError, "Invalid type of object");
+ return NULL;
+ }
+ }
+ // return none
+ Py_RETURN_NONE;
+}
+
+
+// get pixel filter object
+PyObject * Image_getFilter (PyImage * self, void * closure)
+{
+ // if image object is available
+ if (self->m_image != NULL)
+ {
+ // pixel filter object
+ PyObject * filt = reinterpret_cast<PyObject*>(self->m_image->getFilter());
+ // if filter is present
+ if (filt != NULL)
+ {
+ // return it
+ Py_INCREF(filt);
+ return filt;
+ }
+ }
+ // otherwise return none
+ Py_RETURN_NONE;
+}
+
+
+// set pixel filter object
+int Image_setFilter (PyImage * self, PyObject * value, void * closure)
+{
+ // if image object is available
+ if (self->m_image != NULL)
+ {
+ // check new value
+ if (value == NULL || !pyFilterTypes.in(value->ob_type))
+ {
+ // report value error
+ PyErr_SetString(PyExc_TypeError, "Invalid type of value");
+ return -1;
+ }
+ // set new value
+ self->m_image->setFilter(reinterpret_cast<PyFilter*>(value));
+ }
+ // return success
+ return 0;
+}
diff --git a/source/gameengine/VideoTexture/ImageBase.h b/source/gameengine/VideoTexture/ImageBase.h
new file mode 100644
index 00000000000..138580ce701
--- /dev/null
+++ b/source/gameengine/VideoTexture/ImageBase.h
@@ -0,0 +1,349 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of blendTex library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+#if !defined IMAGEBASE_H
+#define IMAGEBASE_H
+
+#include "Common.h"
+
+#include <vector>
+#include <PyObjectPlus.h>
+
+#include "PyTypeList.h"
+
+#include "FilterBase.h"
+
+
+// forward declarations
+struct PyImage;
+class ImageSource;
+
+
+/// type for list of image sources
+typedef std::vector<ImageSource*> ImageSourceList;
+
+
+/// base class for image filters
+class ImageBase
+{
+public:
+ /// constructor
+ ImageBase (bool staticSrc = false);
+ /// destructor
+ virtual ~ImageBase (void);
+ /// release contained objects, if returns true, object should be deleted
+ virtual bool release (void);
+
+ /// get image
+ unsigned int * getImage (unsigned int texId = 0);
+ /// get image size
+ short * getSize (void) { return m_size; }
+ /// get image buffer size
+ unsigned long getBuffSize (void)
+ { return m_size[0] * m_size[1] * sizeof(unsigned int); }
+ /// refresh image - invalidate its current content
+ virtual void refresh (void);
+
+ /// get scale
+ bool getScale (void) { return m_scale; }
+ /// set scale
+ void setScale (bool scale) { m_scale = scale; m_scaleChange = true; }
+ /// get vertical flip
+ bool getFlip (void) { return m_flip; }
+ /// set vertical flip
+ void setFlip (bool flip) { m_flip = flip; }
+
+ /// get source object
+ PyImage * getSource (const char * id);
+ /// set source object, return true, if source was set
+ bool setSource (const char * id, PyImage * source);
+
+ /// get pixel filter
+ PyFilter * getFilter (void) { return m_pyfilter; }
+ /// set pixel filter
+ void setFilter (PyFilter * filt);
+
+ /// calculate size (nearest power of 2)
+ static short calcSize (short size);
+
+protected:
+ /// image buffer
+ unsigned int * m_image;
+ /// image buffer size
+ unsigned int m_imgSize;
+ /// image size
+ short m_size[2];
+ /// image is available
+ bool m_avail;
+
+ /// scale image to power 2 sizes
+ bool m_scale;
+ /// scale was changed
+ bool m_scaleChange;
+ /// flip image vertically
+ bool m_flip;
+
+ /// source image list
+ ImageSourceList m_sources;
+ /// flag for disabling addition and deletion of sources
+ bool m_staticSources;
+
+ /// pixel filter
+ PyFilter * m_pyfilter;
+
+ /// initialize image data
+ void init (short width, short height);
+
+ /// find source
+ ImageSourceList::iterator findSource (const char * id);
+
+ /// create new source
+ virtual ImageSource * newSource (const char * id) { return NULL; }
+
+ /// check source sizes
+ bool checkSourceSizes (void);
+
+ /// calculate image from sources and set its availability
+ virtual void calcImage (unsigned int texId) {}
+
+ /// perform loop detection
+ bool loopDetect (ImageBase * img);
+
+ /// template for image conversion
+ template<class FLT, class SRC> void convImage (FLT & filter, SRC srcBuff,
+ short * srcSize)
+ {
+ // destination buffer
+ unsigned int * dstBuff = m_image;
+ // pixel size from filter
+ unsigned int pixSize = filter.firstPixelSize();
+ // if no scaling is needed
+ if (srcSize[0] == m_size[0] && srcSize[1] == m_size[1])
+ // if flipping isn't required
+ if (!m_flip)
+ // copy bitmap
+ for (short y = 0; y < m_size[1]; ++y)
+ for (short x = 0; x < m_size[0]; ++x, ++dstBuff, srcBuff += pixSize)
+ // copy pixel
+ *dstBuff = filter.convert(srcBuff, x, y, srcSize, pixSize);
+ // otherwise flip image top to bottom
+ else
+ {
+ // go to last row of image
+ srcBuff += srcSize[0] * (srcSize[1] - 1) * pixSize;
+ // copy bitmap
+ for (short y = m_size[1] - 1; y >= 0; --y, srcBuff -= 2 * srcSize[0] * pixSize)
+ for (short x = 0; x < m_size[0]; ++x, ++dstBuff, srcBuff += pixSize)
+ // copy pixel
+ *dstBuff = filter.convert(srcBuff, x, y, srcSize, pixSize);
+ }
+ // else scale picture (nearest neighbour)
+ else
+ {
+ // interpolation accumulator
+ int accHeight = srcSize[1] >> 1;
+ // if flipping is required
+ if (m_flip)
+ // go to last row of image
+ srcBuff += srcSize[0] * (srcSize[1] - 1) * pixSize;
+ // process image rows
+ for (int y = 0; y < srcSize[1]; ++y)
+ {
+ // increase height accum
+ accHeight += m_size[1];
+ // if pixel row has to be drawn
+ if (accHeight >= srcSize[1])
+ {
+ // decrease accum
+ accHeight -= srcSize[1];
+ // width accum
+ int accWidth = srcSize[0] >> 1;
+ // process row
+ for (int x = 0; x < srcSize[0]; ++x)
+ {
+ // increase width accum
+ accWidth += m_size[0];
+ // if pixel has to be drawn
+ if (accWidth >= srcSize[0])
+ {
+ // decrease accum
+ accWidth -= srcSize[0];
+ // convert pixel
+ *dstBuff = filter.convert(srcBuff, x, m_flip ? srcSize[1] - y - 1 : y,
+ srcSize, pixSize);
+ // next pixel
+ ++dstBuff;
+ }
+ // shift source pointer
+ srcBuff += pixSize;
+ }
+ }
+ // if pixel row will not be drawn
+ else
+ // move source pointer to next row
+ srcBuff += pixSize * srcSize[0];
+ // if y flipping is required
+ if (m_flip)
+ // go to previous row of image
+ srcBuff -= 2 * pixSize * srcSize[0];
+ }
+ }
+ }
+
+ // template for specific filter preprocessing
+ template <class F, class SRC> void filterImage (F & filt, SRC srcBuff, short * srcSize)
+ {
+ // find first filter in chain
+ FilterBase * firstFilter = NULL;
+ if (m_pyfilter != NULL) firstFilter = m_pyfilter->m_filter->findFirst();
+ // if first filter is available
+ if (firstFilter != NULL)
+ {
+ // python wrapper for filter
+ PyFilter pyFilt;
+ pyFilt.m_filter = &filt;
+ // set specified filter as first in chain
+ firstFilter->setPrevious(&pyFilt, false);
+ // convert video image
+ convImage(*(m_pyfilter->m_filter), srcBuff, srcSize);
+ // delete added filter
+ firstFilter->setPrevious(NULL, false);
+ }
+ // otherwise use given filter for conversion
+ else convImage(filt, srcBuff, srcSize);
+ // source was processed
+ m_avail = true;
+ }
+};
+
+
+// python structure for image filter
+struct PyImage
+{
+ PyObject_HEAD
+ // source object
+ ImageBase * m_image;
+};
+
+
+// size of id
+const int SourceIdSize = 32;
+
+
+/// class for source of image
+class ImageSource
+{
+public:
+ /// constructor
+ ImageSource (const char * id);
+ /// destructor
+ virtual ~ImageSource (void);
+
+ /// get id
+ const char * getId (void) { return m_id; }
+ /// compare id to argument
+ bool is (const char * id);
+
+ /// get source object
+ PyImage * getSource (void) { return m_source; }
+ /// set source object
+ void setSource (PyImage * source);
+
+ /// get image from source
+ unsigned int * getImage (void);
+ /// get buffered image
+ unsigned int * getImageBuf (void) { return m_image; }
+ /// refresh source
+ void refresh (void);
+
+ /// get image size
+ short * getSize (void)
+ {
+ static short defSize [] = {0, 0};
+ return m_source != NULL ? m_source->m_image->getSize() : defSize;
+ }
+
+protected:
+ /// id of source
+ char m_id [SourceIdSize];
+ /// pointer to source structure
+ PyImage * m_source;
+ /// buffered image from source
+ unsigned int * m_image;
+
+private:
+ /// default constructor is forbidden
+ ImageSource (void) {}
+};
+
+
+
+// list of python image types
+extern PyTypeList pyImageTypes;
+
+
+// functions for python interface
+
+// object initialization
+template <class T> static int Image_init (PyObject * pySelf, PyObject * args, PyObject * kwds)
+{
+ PyImage * self = reinterpret_cast<PyImage*>(pySelf);
+ // create source object
+ if (self->m_image != NULL) delete self->m_image;
+ self->m_image = new T();
+ // initialization succeded
+ return 0;
+}
+
+// object allocation
+PyObject * Image_allocNew (PyTypeObject * type, PyObject * args, PyObject * kwds);
+// object deallocation
+void Image_dealloc (PyImage * self);
+
+// get image data
+PyObject * Image_getImage (PyImage * self, void * closure);
+// get image size
+PyObject * Image_getSize (PyImage * self, void * closure);
+// refresh image - invalidate current content
+PyObject * Image_refresh (PyImage * self);
+
+// get scale
+PyObject * Image_getScale (PyImage * self, void * closure);
+// set scale
+int Image_setScale (PyImage * self, PyObject * value, void * closure);
+// get flip
+PyObject * Image_getFlip (PyImage * self, void * closure);
+// set flip
+int Image_setFlip (PyImage * self, PyObject * value, void * closure);
+
+// get filter source object
+PyObject * Image_getSource (PyImage * self, PyObject * args);
+// set filter source object
+PyObject * Image_setSource (PyImage * self, PyObject * args);
+
+// get pixel filter object
+PyObject * Image_getFilter (PyImage * self, void * closure);
+// set pixel filter object
+int Image_setFilter (PyImage * self, PyObject * value, void * closure);
+
+
+#endif
diff --git a/source/gameengine/VideoTexture/ImageBuff.cpp b/source/gameengine/VideoTexture/ImageBuff.cpp
new file mode 100644
index 00000000000..19ad17ac643
--- /dev/null
+++ b/source/gameengine/VideoTexture/ImageBuff.cpp
@@ -0,0 +1,166 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+// implementation
+
+#include <PyObjectPlus.h>
+#include <structmember.h>
+
+#include "ImageBuff.h"
+
+#include "ImageBase.h"
+#include "FilterSource.h"
+
+
+// default filter
+FilterRGB24 defFilter;
+
+
+// load image from buffer
+void ImageBuff::load (unsigned char * img, short width, short height)
+{
+ // initialize image buffer
+ init(width, height);
+ // original size
+ short orgSize[2] = {width, height};
+ // is filter available
+ if (m_pyfilter != NULL)
+ // use it to process image
+ convImage(*(m_pyfilter->m_filter), img, orgSize);
+ else
+ // otherwise use default filter
+ convImage(defFilter, img, orgSize);
+ // image is available
+ m_avail = true;
+}
+
+
+
+// cast Image pointer to ImageBuff
+inline ImageBuff * getImageBuff (PyImage * self)
+{ return static_cast<ImageBuff*>(self->m_image); }
+
+
+// python methods
+
+// load image
+static PyObject * load (PyImage * self, PyObject * args)
+{
+ // parameters: string image buffer, its size, width, height
+ unsigned char * buff;
+ unsigned int buffSize;
+ short width;
+ short height;
+ // parse parameters
+ if (!PyArg_ParseTuple(args, "s#hh", &buff, &buffSize, &width, &height))
+ {
+ // report error
+ PyErr_SetString(PyExc_TypeError, "Parameters are not correct");
+ return NULL;
+ }
+ // else check buffer size
+ else
+ {
+ // calc proper buffer size
+ unsigned int propSize = width * height;
+ // use pixel size from filter
+ if (self->m_image->getFilter() != NULL)
+ propSize *= self->m_image->getFilter()->m_filter->firstPixelSize();
+ else
+ propSize *= defFilter.firstPixelSize();
+ // check if buffer size is correct
+ if (propSize != buffSize)
+ {
+ // if not, report error
+ PyErr_SetString(PyExc_TypeError, "Buffer hasn't correct size");
+ return NULL;
+ }
+ else
+ // if correct, load image
+ getImageBuff(self)->load(buff, width, height);
+ }
+ Py_RETURN_NONE;
+}
+
+
+// methods structure
+static PyMethodDef imageBuffMethods[] =
+{
+ {"load", (PyCFunction)load, METH_VARARGS, "Load image from buffer"},
+ {NULL}
+};
+// attributes structure
+static PyGetSetDef imageBuffGetSets[] =
+{ // attributes from ImageBase class
+ {(char*)"image", (getter)Image_getImage, NULL, (char*)"image data", NULL},
+ {(char*)"size", (getter)Image_getSize, NULL, (char*)"image size", NULL},
+ {(char*)"scale", (getter)Image_getScale, (setter)Image_setScale, (char*)"fast scale of image (near neighbour)", NULL},
+ {(char*)"flip", (getter)Image_getFlip, (setter)Image_setFlip, (char*)"flip image vertically", NULL},
+ {(char*)"filter", (getter)Image_getFilter, (setter)Image_setFilter, (char*)"pixel filter", NULL},
+ {NULL}
+};
+
+
+// define python type
+PyTypeObject ImageBuffType =
+{
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "VideoTexture.ImageBuff", /*tp_name*/
+ sizeof(PyImage), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)Image_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash */
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ "Image source from image buffer", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ imageBuffMethods, /* tp_methods */
+ 0, /* tp_members */
+ imageBuffGetSets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)Image_init<ImageBuff>, /* tp_init */
+ 0, /* tp_alloc */
+ Image_allocNew, /* tp_new */
+};
+
diff --git a/source/gameengine/VideoTexture/ImageBuff.h b/source/gameengine/VideoTexture/ImageBuff.h
new file mode 100644
index 00000000000..fa2025fa8c4
--- /dev/null
+++ b/source/gameengine/VideoTexture/ImageBuff.h
@@ -0,0 +1,51 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+#if !defined IMAGEBUFF_H
+#define IMAGEBUFF_H
+
+
+#include "Common.h"
+
+#include "ImageBase.h"
+
+
+/// class for image buffer
+class ImageBuff : public ImageBase
+{
+public:
+ /// constructor
+ ImageBuff (void) : ImageBase(true) {}
+
+ /// destructor
+ virtual ~ImageBuff (void) {}
+
+ /// load image from buffer
+ void load (unsigned char * img, short width, short height);
+
+ /// refresh image - do nothing
+ virtual void refresh (void) {}
+};
+
+
+#endif
+
diff --git a/source/gameengine/VideoTexture/ImageMix.cpp b/source/gameengine/VideoTexture/ImageMix.cpp
new file mode 100644
index 00000000000..b07b362818c
--- /dev/null
+++ b/source/gameengine/VideoTexture/ImageMix.cpp
@@ -0,0 +1,205 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+// implementation
+
+#include <PyObjectPlus.h>
+#include <structmember.h>
+
+#include "ImageMix.h"
+
+#include "ImageBase.h"
+
+#include "Exception.h"
+
+
+// cast ImageSource pointer to ImageSourceMix
+inline ImageSourceMix * getImageSourceMix (ImageSource * src)
+{ return static_cast<ImageSourceMix*>(src); }
+
+
+// get weight
+short ImageMix::getWeight (const char * id)
+{
+ // find source
+ ImageSourceList::iterator src = findSource(id);
+ // if found, return its weight
+ return src != m_sources.end() ? getImageSourceMix(*src)->getWeight() : 0;
+}
+
+// set weight
+bool ImageMix::setWeight (const char * id, short weight)
+{
+ // find source
+ ImageSourceList::iterator src = findSource(id);
+ // if source isn't found, report it
+ if (src == m_sources.end()) return false;
+ // set its weight
+ getImageSourceMix(*src)->setWeight(weight);
+ return true;
+}
+
+ExceptionID ImageSizesNotMatch;
+
+ExpDesc ImageSizesNotMatchDesc (ImageSizesNotMatch, "Image sizes of sources are different");
+
+// calculate image from sources and set its availability
+void ImageMix::calcImage (unsigned int texId)
+{
+ // check source sizes
+ if (!checkSourceSizes()) THRWEXCP(ImageSizesNotMatch, S_OK);
+ // set offsets to image buffers
+ for (ImageSourceList::iterator it = m_sources.begin(); it != m_sources.end(); ++it)
+ // if image buffer is available
+ if ((*it)->getImageBuf() != NULL)
+ // set its offset
+ getImageSourceMix(*it)->setOffset(m_sources[0]->getImageBuf());
+ // otherwise don't calculate image
+ else
+ return;
+ // if there is only single source
+ if (m_sources.size() == 1)
+ {
+ // use single filter
+ FilterBase mixFilt;
+ // fiter and convert image
+ filterImage(mixFilt, m_sources[0]->getImageBuf(), m_sources[0]->getSize());
+ }
+ // otherwise use mix filter to merge source images
+ else
+ {
+ FilterImageMix mixFilt (m_sources);
+ // fiter and convert image
+ filterImage(mixFilt, m_sources[0]->getImageBuf(), m_sources[0]->getSize());
+ }
+}
+
+
+
+// cast Image pointer to ImageMix
+inline ImageMix * getImageMix (PyImage * self)
+{ return static_cast<ImageMix*>(self->m_image); }
+
+
+// python methods
+
+// get source weight
+PyObject * getWeight (PyImage * self, PyObject * args)
+{
+ // weight
+ short weight = 0;
+ // get arguments
+ char * id;
+ if (self->m_image != NULL && PyArg_ParseTuple(args, "s", &id))
+ // get weight
+ weight = getImageMix(self)->getWeight(id);
+ // return weight
+ return Py_BuildValue("h", weight);
+}
+
+
+// set source weight
+PyObject * setWeight (PyImage * self, PyObject * args)
+{
+ // get arguments
+ char * id;
+ short weight = 0;
+ if (self->m_image != NULL && PyArg_ParseTuple(args, "sh", &id, &weight))
+ // set weight
+ if (!getImageMix(self)->setWeight(id, weight))
+ {
+ // if not set, report error
+ PyErr_SetString(PyExc_RuntimeError, "Invalid id of source");;
+ return NULL;
+ }
+ // return none
+ Py_RETURN_NONE;
+}
+
+
+// methods structure
+static PyMethodDef imageMixMethods[] =
+{
+ {"getSource", (PyCFunction)Image_getSource, METH_VARARGS, "get image source"},
+ {"setSource", (PyCFunction)Image_setSource, METH_VARARGS, "set image source"},
+ {"getWeight", (PyCFunction)getWeight, METH_VARARGS, "get image source weight"},
+ {"setWeight", (PyCFunction)setWeight, METH_VARARGS, "set image source weight"},
+ // methods from ImageBase class
+ {"refresh", (PyCFunction)Image_refresh, METH_NOARGS, "Refresh image - invalidate its current content"},
+ {NULL}
+};
+// attributes structure
+static PyGetSetDef imageMixGetSets[] =
+{ // attributes from ImageBase class
+ {(char*)"image", (getter)Image_getImage, NULL, (char*)"image data", NULL},
+ {(char*)"size", (getter)Image_getSize, NULL, (char*)"image size", NULL},
+ {(char*)"scale", (getter)Image_getScale, (setter)Image_setScale, (char*)"fast scale of image (near neighbour)", NULL},
+ {(char*)"flip", (getter)Image_getFlip, (setter)Image_setFlip, (char*)"flip image vertically", NULL},
+ {(char*)"filter", (getter)Image_getFilter, (setter)Image_setFilter, (char*)"pixel filter", NULL},
+ {NULL}
+};
+
+
+// define python type
+PyTypeObject ImageMixType =
+{
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "VideoTexture.ImageMix", /*tp_name*/
+ sizeof(PyImage), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)Image_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash */
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ "Image mixer", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ imageMixMethods, /* tp_methods */
+ 0, /* tp_members */
+ imageMixGetSets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)Image_init<ImageMix>, /* tp_init */
+ 0, /* tp_alloc */
+ Image_allocNew, /* tp_new */
+};
+
diff --git a/source/gameengine/VideoTexture/ImageMix.h b/source/gameengine/VideoTexture/ImageMix.h
new file mode 100644
index 00000000000..b4842bd6b40
--- /dev/null
+++ b/source/gameengine/VideoTexture/ImageMix.h
@@ -0,0 +1,123 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+#if !defined IMAGEMIX_H
+#define IMAGEMIX_H
+
+
+#include "Common.h"
+
+#include "ImageBase.h"
+#include "FilterBase.h"
+
+
+/// class for source mixing
+class ImageSourceMix : public ImageSource
+{
+public:
+ /// constructor
+ ImageSourceMix (const char * id) : ImageSource(id), m_weight(0x100) {}
+ /// destructor
+ virtual ~ImageSourceMix (void) {}
+
+ /// get offset
+ long long getOffset (void) { return m_offset; }
+ /// set offset
+ void setOffset (unsigned int * firstImg) { m_offset = m_image - firstImg; }
+
+ /// get weight
+ short getWeight (void) { return m_weight; }
+ /// set weight
+ void setWeight (short weight) { m_weight = weight; }
+
+protected:
+ /// buffer offset to the first source buffer
+ long long m_offset;
+ /// source weight
+ short m_weight;
+};
+
+
+/// class for image mixer
+class ImageMix : public ImageBase
+{
+public:
+ /// constructor
+ ImageMix (void) : ImageBase(false) {}
+
+ /// destructor
+ virtual ~ImageMix (void) {}
+
+ /// get weight
+ short getWeight (const char * id);
+ /// set weight
+ bool setWeight (const char * id, short weight);
+
+protected:
+
+ /// create new source
+ virtual ImageSource * newSource (const char * id) { return new ImageSourceMix(id); }
+
+ /// calculate image from sources and set its availability
+ virtual void calcImage (unsigned int texId);
+};
+
+
+/// pixel filter for image mixer
+class FilterImageMix : public FilterBase
+{
+public:
+ /// constructor
+ FilterImageMix (ImageSourceList & sources) : m_sources(sources) {}
+ /// destructor
+ virtual ~FilterImageMix (void) {}
+
+protected:
+ /// source list
+ ImageSourceList & m_sources;
+
+ /// filter pixel, source int buffer
+ virtual unsigned int filter (unsigned int * src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val = 0)
+ {
+ // resulting pixel color
+ int color[] = {0, 0, 0, 0};
+ // iterate sources
+ for (ImageSourceList::iterator it = m_sources.begin(); it != m_sources.end(); ++it)
+ {
+ // get pointer to mixer source
+ ImageSourceMix * mixSrc = static_cast<ImageSourceMix*>(*it);
+ // add weighted source pixel to result
+ color[0] += mixSrc->getWeight() * (src[mixSrc->getOffset()] & 0xFF);
+ color[1] += mixSrc->getWeight() * ((src[mixSrc->getOffset()] >> 8) & 0xFF);
+ color[2] += mixSrc->getWeight() * ((src[mixSrc->getOffset()] >> 16) & 0xFF);
+ color[3] += mixSrc->getWeight() * ((src[mixSrc->getOffset()] >> 24) & 0xFF);
+ }
+ // return resulting color
+ return ((color[0] >> 8) & 0xFF) | (color[1] & 0xFF00)
+ | ((color[2] << 8) & 0xFF0000) | ((color[3] << 16) & 0xFF000000);
+ }
+};
+
+
+#endif
+
diff --git a/source/gameengine/VideoTexture/ImageRender.cpp b/source/gameengine/VideoTexture/ImageRender.cpp
new file mode 100644
index 00000000000..a8f7871fa21
--- /dev/null
+++ b/source/gameengine/VideoTexture/ImageRender.cpp
@@ -0,0 +1,267 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+// implementation
+
+#include <PyObjectPlus.h>
+#include <structmember.h>
+
+#include <KX_BlenderCanvas.h>
+#include <KX_BlenderRenderTools.h>
+#include <RAS_IRasterizer.h>
+#include <RAS_OpenGLRasterizer.h>
+#include <KX_WorldInfo.h>
+#include <KX_Light.h>
+
+#include "ImageRender.h"
+
+#include "ImageBase.h"
+#include "BlendType.h"
+#include "Exception.h"
+
+ExceptionID SceneInvalid, CameraInvalid;
+ExpDesc SceneInvalidDesc (SceneInvalid, "Scene object is invalid");
+ExpDesc CameraInvalidDesc (CameraInvalid, "Camera object is invalid");
+
+#if 0 // not yet supported
+
+// constructor
+ImageRender::ImageRender (KX_Scene * scene, KX_Camera * camera) : m_scene(scene),
+m_camera(camera)
+{
+ // create screen area
+ m_area.winrct.xmin = m_upLeft[0];
+ m_area.winrct.ymin = m_upLeft[1];
+ m_area.winx = m_size[0];
+ m_area.winy = m_size[1];
+ // create canvas
+ m_canvas = new KX_BlenderCanvas(&m_area);
+ // create render tools
+ m_rendertools = new KX_BlenderRenderTools();
+ // create rasterizer
+ m_rasterizer = new RAS_OpenGLRasterizer(m_canvas);
+ m_rasterizer->Init();
+ // initialize background colour
+ setBackground(0, 0, 255);
+ // refresh lights
+ refreshLights();
+}
+
+// destructor
+ImageRender::~ImageRender (void)
+{
+ // release allocated objects
+ delete m_rasterizer;
+ delete m_rendertools;
+ delete m_canvas;
+}
+
+
+// set background color
+void ImageRender::setBackground (unsigned char red, unsigned char green, unsigned char blue)
+{
+ m_background[0] = red;
+ m_background[1] = green;
+ m_background[2] = blue;
+ m_rasterizer->SetBackColor(m_background[0], m_background[1], m_background[2], 1.0);
+}
+
+
+// capture image from viewport
+void ImageRender::calcImage (unsigned int texId)
+{
+ // setup camera
+ bool cameraPasive = !m_camera->GetViewport();
+ // render scene
+ Render();
+ // reset camera
+ if (cameraPasive) m_camera->EnableViewport(false);
+ // get image from viewport
+ ImageViewport::calcImage(texId);
+}
+
+void ImageRender::Render()
+{
+ //
+}
+
+// refresh lights
+void ImageRender::refreshLights (void)
+{
+ // clear lights list
+ //m_rendertools->RemoveAllLights();
+ // set lights
+ //for (int idx = 0; idx < scene->GetLightList()->GetCount(); ++idx)
+ // m_rendertools->AddLight(((KX_LightObject*)(scene->GetLightList()->GetValue(idx)))->GetLightData());
+}
+
+
+
+// cast Image pointer to ImageRender
+inline ImageRender * getImageRender (PyImage * self)
+{ return static_cast<ImageRender*>(self->m_image); }
+
+
+// python methods
+
+// Blender Scene type
+BlendType<KX_Scene> sceneType ("KX_Scene");
+// Blender Camera type
+BlendType<KX_Camera> cameraType ("KX_Camera");
+
+
+// object initialization
+static int ImageRender_init (PyObject * pySelf, PyObject * args, PyObject * kwds)
+{
+ // parameters - scene object
+ PyObject * scene;
+ // camera object
+ PyObject * camera;
+ // parameter keywords
+ static char *kwlist[] = {"sceneObj", "cameraObj", NULL};
+ // get parameters
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO", kwlist, &scene, &camera))
+ return -1;
+ try
+ {
+ // get scene pointer
+ KX_Scene * scenePtr (NULL);
+ if (scene != NULL) scenePtr = sceneType.checkType(scene);
+ // throw exception if scene is not available
+ if (scenePtr == NULL) THRWEXCP(SceneInvalid, S_OK);
+
+ // get camera pointer
+ KX_Camera * cameraPtr (NULL);
+ if (camera != NULL) cameraPtr = cameraType.checkType(camera);
+ // throw exception if camera is not available
+ if (cameraPtr == NULL) THRWEXCP(CameraInvalid, S_OK);
+
+ // get pointer to image structure
+ PyImage * self = reinterpret_cast<PyImage*>(pySelf);
+ // create source object
+ if (self->m_image != NULL) delete self->m_image;
+ self->m_image = new ImageRender(scenePtr, cameraPtr);
+ }
+ catch (Exception & exp)
+ {
+ exp.report();
+ return -1;
+ }
+ // initialization succeded
+ return 0;
+}
+
+
+// get background color
+PyObject * getBackground (PyImage * self, void * closure)
+{
+ return Py_BuildValue("[BBB]", getImageRender(self)->getBackground()[0],
+ getImageRender(self)->getBackground()[1], getImageRender(self)->getBackground()[2]);
+}
+
+// set color
+static int setBackground (PyImage * self, PyObject * value, void * closure)
+{
+ // check validity of parameter
+ if (value == NULL || !PySequence_Check(value) || PySequence_Length(value) != 3
+ || !PyInt_Check(PySequence_Fast_GET_ITEM(value, 0))
+ || !PyInt_Check(PySequence_Fast_GET_ITEM(value, 1))
+ || !PyInt_Check(PySequence_Fast_GET_ITEM(value, 2)))
+ {
+ PyErr_SetString(PyExc_TypeError, "The value must be a sequence of 3 ints");
+ return -1;
+ }
+ // set background color
+ getImageRender(self)->setBackground((unsigned char)(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 0))),
+ (unsigned char)(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 1))),
+ (unsigned char)(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 2))));
+ // success
+ return 0;
+}
+
+
+// methods structure
+static PyMethodDef imageRenderMethods[] =
+{ // methods from ImageBase class
+ {"refresh", (PyCFunction)Image_refresh, METH_NOARGS, "Refresh image - invalidate its current content"},
+ {NULL}
+};
+// attributes structure
+static PyGetSetDef imageRenderGetSets[] =
+{
+ {(char*)"background", (getter)getBackground, (setter)setBackground, (char*)"background color", NULL},
+ // attributes from ImageBase class
+ {(char*)"image", (getter)Image_getImage, NULL, (char*)"image data", NULL},
+ {(char*)"size", (getter)Image_getSize, NULL, (char*)"image size", NULL},
+ {(char*)"scale", (getter)Image_getScale, (setter)Image_setScale, (char*)"fast scale of image (near neighbour)", NULL},
+ {(char*)"flip", (getter)Image_getFlip, (setter)Image_setFlip, (char*)"flip image vertically", NULL},
+ {(char*)"filter", (getter)Image_getFilter, (setter)Image_setFilter, (char*)"pixel filter", NULL},
+ {NULL}
+};
+
+
+// define python type
+PyTypeObject ImageRenderType =
+{
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "VideoTexture.ImageRender", /*tp_name*/
+ sizeof(PyImage), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)Image_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash */
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ "Image source from render", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ imageRenderMethods, /* tp_methods */
+ 0, /* tp_members */
+ imageRenderGetSets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)ImageRender_init, /* tp_init */
+ 0, /* tp_alloc */
+ Image_allocNew, /* tp_new */
+};
+
+
+#endif // #if 0
diff --git a/source/gameengine/VideoTexture/ImageRender.h b/source/gameengine/VideoTexture/ImageRender.h
new file mode 100644
index 00000000000..66255f04d2c
--- /dev/null
+++ b/source/gameengine/VideoTexture/ImageRender.h
@@ -0,0 +1,90 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+#if !defined IMAGERENDER_H
+#define IMAGERENDER_H
+
+
+#include "Common.h"
+
+#include <KX_Scene.h>
+#include <KX_Camera.h>
+#include <DNA_screen_types.h>
+#include <RAS_ICanvas.h>
+#include <RAS_IRasterizer.h>
+#include <RAS_IRenderTools.h>
+
+#include "ImageViewport.h"
+
+
+/// class for render 3d scene
+class ImageRender : public ImageViewport
+{
+public:
+ /// constructor
+ ImageRender (KX_Scene * scene, KX_Camera * camera);
+
+ /// destructor
+ virtual ~ImageRender (void);
+
+ /// get background color
+ unsigned char * getBackground (void) { return m_background; }
+ /// set background color
+ void setBackground (unsigned char red, unsigned char green, unsigned char blue);
+
+protected:
+ /// rendered scene
+ KX_Scene * m_scene;
+ /// camera for render
+ KX_Camera * m_camera;
+
+ /// screen area for rendering
+ ScrArea m_area;
+ /// rendering device
+ RAS_ICanvas * m_canvas;
+ /// rasterizer
+ RAS_IRasterizer * m_rasterizer;
+ /// render tools
+ RAS_IRenderTools * m_rendertools;
+
+ /// background colour
+ unsigned char m_background[3];
+
+
+ /// render 3d scene to image
+ virtual void calcImage (unsigned int texId);
+
+ /// refresh lights
+ void refreshLights (void);
+ /// methods from KX_KetsjiEngine
+ bool BeginFrame();
+ void EndFrame();
+ void Render();
+ void SetupRenderFrame(KX_Scene *scene, KX_Camera* cam);
+ void RenderFrame(KX_Scene* scene, KX_Camera* cam);
+ void SetBackGround(KX_WorldInfo* wi);
+ void SetWorldSettings(KX_WorldInfo* wi);
+};
+
+
+#endif
+
diff --git a/source/gameengine/VideoTexture/ImageViewport.cpp b/source/gameengine/VideoTexture/ImageViewport.cpp
new file mode 100644
index 00000000000..deb66ffb6ba
--- /dev/null
+++ b/source/gameengine/VideoTexture/ImageViewport.cpp
@@ -0,0 +1,297 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+// implementation
+
+#include <PyObjectPlus.h>
+#include <structmember.h>
+
+#include <BIF_gl.h>
+
+#include "Texture.h"
+#include "ImageBase.h"
+#include "FilterSource.h"
+#include "ImageViewport.h"
+
+
+// constructor
+ImageViewport::ImageViewport (void) : m_texInit(false)
+{
+ // get viewport rectangle
+ glGetIntegerv(GL_VIEWPORT, m_viewport);
+ // create buffer for viewport image
+ m_viewportImage = new BYTE [3 * getViewportSize()[0] * getViewportSize()[1]];
+ // set attributes
+ setWhole(false);
+}
+
+// destructor
+ImageViewport::~ImageViewport (void)
+{ delete m_viewportImage; }
+
+
+// use whole viewport to capture image
+void ImageViewport::setWhole (bool whole)
+{
+ // set whole
+ m_whole = whole;
+ // set capture size to viewport size, if whole,
+ // otherwise place area in the middle of viewport
+ for (int idx = 0; idx < 2; ++idx)
+ {
+ // capture size
+ m_capSize[idx] = whole ? short(getViewportSize()[idx])
+ : calcSize(short(getViewportSize()[idx]));
+ // position
+ m_position[idx] = whole ? 0 : (getViewportSize()[idx] - m_capSize[idx]) >> 1;
+ }
+ // init image
+ init(m_capSize[0], m_capSize[1]);
+ // set capture position
+ setPosition();
+}
+
+void ImageViewport::setCaptureSize (short * size)
+{
+ m_whole = false;
+ if (size == NULL)
+ size = m_capSize;
+ for (int idx = 0; idx < 2; ++idx)
+ {
+ if (size[idx] < 1)
+ m_capSize[idx] = 1;
+ else if (size[idx] > getViewportSize()[idx])
+ m_capSize[idx] = short(getViewportSize()[idx]);
+ else
+ m_capSize[idx] = size[idx];
+ }
+ init(m_capSize[0], m_capSize[1]);
+ // set capture position
+ setPosition();
+}
+
+// set position of capture rectangle
+void ImageViewport::setPosition (GLint * pos)
+{
+ // if new position is not provided, use existing position
+ if (pos == NULL) pos = m_position;
+ // save position
+ for (int idx = 0; idx < 2; ++idx)
+ m_position[idx] = pos[idx] < 0 ? 0 : pos[idx] >= getViewportSize()[idx]
+ - m_capSize[idx] ? getViewportSize()[idx] - m_capSize[idx] : pos[idx];
+ // recalc up left corner
+ for (int idx = 0; idx < 2; ++idx)
+ m_upLeft[idx] = m_position[idx] + m_viewport[idx];
+}
+
+
+// capture image from viewport
+void ImageViewport::calcImage (unsigned int texId)
+{
+ // if scale was changed
+ if (m_scaleChange)
+ // reset image
+ init(m_capSize[0], m_capSize[1]);
+ // if texture wasn't initialized
+ if (!m_texInit)
+ {
+ // initialize it
+ loadTexture(texId, m_image, m_size);
+ m_texInit = true;
+ }
+ // if texture can be directly created
+ if (texId != 0 && m_pyfilter == NULL && m_capSize[0] == calcSize(m_capSize[0])
+ && m_capSize[1] == calcSize(m_capSize[1]) && !m_flip)
+ {
+ // just copy current viewport to texture
+ glBindTexture(GL_TEXTURE_2D, texId);
+ glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_upLeft[0], m_upLeft[1], (GLsizei)m_capSize[0], (GLsizei)m_capSize[1]);
+ // image is not available
+ m_avail = false;
+ }
+ // otherwise copy viewport to buffer, if image is not available
+ else if (!m_avail)
+ {
+ // get frame buffer data
+ glReadPixels(m_upLeft[0], m_upLeft[1], (GLsizei)m_capSize[0], (GLsizei)m_capSize[1], GL_RGB,
+ GL_UNSIGNED_BYTE, m_viewportImage);
+ // filter loaded data
+ FilterRGB24 filt;
+ filterImage(filt, m_viewportImage, m_capSize);
+ }
+}
+
+
+
+// cast Image pointer to ImageViewport
+inline ImageViewport * getImageViewport (PyImage * self)
+{ return static_cast<ImageViewport*>(self->m_image); }
+
+
+// python methods
+
+
+// get whole
+static PyObject * ImageViewport_getWhole (PyImage * self, void * closure)
+{
+ if (self->m_image != NULL && getImageViewport(self)->getWhole()) Py_RETURN_TRUE;
+ else Py_RETURN_FALSE;
+}
+
+// set whole
+static int ImageViewport_setWhole (PyImage * self, PyObject * value, void * closure)
+{
+ // check parameter, report failure
+ if (value == NULL || !PyBool_Check(value))
+ {
+ PyErr_SetString(PyExc_TypeError, "The value must be a bool");
+ return -1;
+ }
+ // set whole
+ if (self->m_image != NULL) getImageViewport(self)->setWhole(value == Py_True);
+ // success
+ return 0;
+}
+
+
+// get position
+static PyObject * ImageViewport_getPosition (PyImage * self, void * closure)
+{
+ return Py_BuildValue("(ii)", getImageViewport(self)->getPosition()[0],
+ getImageViewport(self)->getPosition()[1]);
+}
+
+// set position
+static int ImageViewport_setPosition (PyImage * self, PyObject * value, void * closure)
+{
+ // check validity of parameter
+ if (value == NULL || !PySequence_Check(value) || PySequence_Length(value) != 2
+ || !PyInt_Check(PySequence_Fast_GET_ITEM(value, 0))
+ || !PyInt_Check(PySequence_Fast_GET_ITEM(value, 1)))
+ {
+ PyErr_SetString(PyExc_TypeError, "The value must be a sequence of 2 ints");
+ return -1;
+ }
+ // set position
+ GLint pos [] = {
+ GLint(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 0))),
+ GLint(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 1)))
+ };
+ getImageViewport(self)->setPosition(pos);
+ // success
+ return 0;
+}
+
+// get capture size
+static PyObject * ImageViewport_getCaptureSize (PyImage * self, void * closure)
+{
+ return Py_BuildValue("(ii)", getImageViewport(self)->getCaptureSize()[0],
+ getImageViewport(self)->getCaptureSize()[1]);
+}
+
+// set capture size
+static int ImageViewport_setCaptureSize (PyImage * self, PyObject * value, void * closure)
+{
+ // check validity of parameter
+ if (value == NULL || !PySequence_Check(value) || PySequence_Length(value) != 2
+ || !PyInt_Check(PySequence_Fast_GET_ITEM(value, 0))
+ || !PyInt_Check(PySequence_Fast_GET_ITEM(value, 1)))
+ {
+ PyErr_SetString(PyExc_TypeError, "The value must be a sequence of 2 ints");
+ return -1;
+ }
+ // set capture size
+ short size [] = {
+ short(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 0))),
+ short(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 1)))
+ };
+ getImageViewport(self)->setCaptureSize(size);
+ // success
+ return 0;
+}
+
+
+// methods structure
+static PyMethodDef imageViewportMethods[] =
+{ // methods from ImageBase class
+ {"refresh", (PyCFunction)Image_refresh, METH_NOARGS, "Refresh image - invalidate its current content"},
+ {NULL}
+};
+// attributes structure
+static PyGetSetDef imageViewportGetSets[] =
+{
+ {(char*)"whole", (getter)ImageViewport_getWhole, (setter)ImageViewport_setWhole, (char*)"use whole viewport to capture", NULL},
+ {(char*)"position", (getter)ImageViewport_getPosition, (setter)ImageViewport_setPosition, (char*)"upper left corner of captured area", NULL},
+ {(char*)"capsize", (getter)ImageViewport_getCaptureSize, (setter)ImageViewport_setCaptureSize, (char*)"size of viewport area being captured", NULL},
+ // attributes from ImageBase class
+ {(char*)"image", (getter)Image_getImage, NULL, (char*)"image data", NULL},
+ {(char*)"size", (getter)Image_getSize, NULL, (char*)"image size", NULL},
+ {(char*)"scale", (getter)Image_getScale, (setter)Image_setScale, (char*)"fast scale of image (near neighbour)", NULL},
+ {(char*)"flip", (getter)Image_getFlip, (setter)Image_setFlip, (char*)"flip image vertically", NULL},
+ {(char*)"filter", (getter)Image_getFilter, (setter)Image_setFilter, (char*)"pixel filter", NULL},
+ {NULL}
+};
+
+
+// define python type
+PyTypeObject ImageViewportType =
+{
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "VideoTexture.ImageViewport", /*tp_name*/
+ sizeof(PyImage), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)Image_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash */
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ "Image source from viewport", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ imageViewportMethods, /* tp_methods */
+ 0, /* tp_members */
+ imageViewportGetSets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)Image_init<ImageViewport>, /* tp_init */
+ 0, /* tp_alloc */
+ Image_allocNew, /* tp_new */
+};
diff --git a/source/gameengine/VideoTexture/ImageViewport.h b/source/gameengine/VideoTexture/ImageViewport.h
new file mode 100644
index 00000000000..4265906b8f5
--- /dev/null
+++ b/source/gameengine/VideoTexture/ImageViewport.h
@@ -0,0 +1,84 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+#if !defined IMAGEVIEWPORT_H
+#define IMAGEVIEWPORT_H
+
+
+#include "Common.h"
+
+#include "ImageBase.h"
+
+
+/// class for viewport access
+class ImageViewport : public ImageBase
+{
+public:
+ /// constructor
+ ImageViewport (void);
+
+ /// destructor
+ virtual ~ImageViewport (void);
+
+ /// is whole buffer used
+ bool getWhole (void) { return m_whole; }
+ /// set whole buffer use
+ void setWhole (bool whole);
+ /// get capture size in viewport
+ short * getCaptureSize (void) { return m_capSize; }
+ /// set capture size in viewport
+ void setCaptureSize (short * size = NULL);
+
+ /// get position in viewport
+ GLint * getPosition (void) { return m_position; }
+ /// set position in viewport
+ void setPosition (GLint * pos = NULL);
+
+protected:
+ /// frame buffer rectangle
+ GLint m_viewport[4];
+
+ /// size of captured area
+ short m_capSize[2];
+ /// use whole viewport
+ bool m_whole;
+
+ /// position of capture rectangle in viewport
+ GLint m_position[2];
+ /// upper left point for capturing
+ GLint m_upLeft[2];
+
+ /// buffer to copy viewport
+ BYTE * m_viewportImage;
+ /// texture is initialized
+ bool m_texInit;
+
+ /// capture image from viewport
+ virtual void calcImage (unsigned int texId);
+
+ /// get viewport size
+ GLint * getViewportSize (void) { return m_viewport + 2; }
+};
+
+
+#endif
+
diff --git a/source/gameengine/VideoTexture/Makefile b/source/gameengine/VideoTexture/Makefile
new file mode 100644
index 00000000000..bead176808b
--- /dev/null
+++ b/source/gameengine/VideoTexture/Makefile
@@ -0,0 +1,65 @@
+#
+# $Id$
+#
+# ***** BEGIN GPL LICENSE BLOCK *****
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software Foundation,
+# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+# The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+# All rights reserved.
+#
+# The Original Code is: all of this file.
+#
+# Contributor(s): none yet.
+#
+# ***** END GPL LICENSE BLOCK *****
+#
+#
+
+LIBNAME = videotex
+DIR = $(OCGDIR)/gameengine/$(LIBNAME)
+SOURCEDIR = source/gameengine/VideoTexture
+
+include nan_compile.mk
+
+CCFLAGS += $(LEVEL_1_CPP_WARNINGS)
+
+CPPFLAGS += $(OGL_CPPFLAGS)
+CPPFLAGS += -I$(NAN_GLEW)/include
+CPPFLAGS += -I$(OPENGL_HEADERS)
+CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION)
+CPPFLAGS += -I../../blender/python
+CPPFLAGS += -I$(NAN_STRING)/include
+CPPFLAGS += -I$(NAN_SOUNDSYSTEM)/include
+CPPFLAGS += -I$(NAN_MOTO)/include
+CPPFLAGS += -I../Rasterizer/RAS_OpenGLRasterizer
+CPPFLAGS += -I../Rasterizer -I../GameLogic -I../SceneGraph
+CPPFLAGS += -I../BlenderRoutines -I../Expressions -I../Ketsji
+CPPFLAGS += -I../../kernel/gen_system
+CPPFLAGS += -I.
+CPPFLAGS += -I../../blender/blenkernel
+CPPFLAGS += -I../../blender/blenlib
+CPPFLAGS += -I../../blender/include
+CPPFLAGS += -I../../blender/makesdna
+CPPFLAGS += -I../../blender/imbuf
+CPPFLAGS += -I../../blender/gpu
+CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include
+
+ifeq ($(WITH_FFMPEG),true)
+ CPPFLAGS += -DWITH_FFMPEG
+ CPPFLAGS += $(NAN_FFMPEGCFLAGS)
+endif
+
+
diff --git a/source/gameengine/VideoTexture/PyTypeList.cpp b/source/gameengine/VideoTexture/PyTypeList.cpp
new file mode 100644
index 00000000000..6d2676dce09
--- /dev/null
+++ b/source/gameengine/VideoTexture/PyTypeList.cpp
@@ -0,0 +1,83 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of blendTex library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+
+#include "PyTypeList.h"
+
+#include <memory>
+#include <vector>
+
+#include <PyObjectPlus.h>
+
+
+/// check, if type is in list
+bool PyTypeList::in (PyTypeObject * type)
+{
+ // if list exists
+ if (m_list.get() != NULL)
+ // iterate items in list
+ for (PyTypeListType::iterator it = m_list->begin(); it != m_list->end(); ++it)
+ // if item is found, return with success
+ if ((*it)->getType() == type) return true;
+ // otherwise return not found
+ return false;
+}
+
+/// add type to list
+void PyTypeList::add (PyTypeObject * type, const char * name)
+{
+ PyTypeListItem * typeItem;
+ // if list doesn't exist, create it
+ if (m_list.get() == NULL)
+ m_list.reset(new PyTypeListType());
+ if (!in(type))
+ // add new item to list
+ m_list->push_back(new PyTypeListItem(type, name));
+}
+
+/// prepare types
+bool PyTypeList::ready (void)
+{
+ // if list exists
+ if (m_list.get() != NULL)
+ // iterate items in list
+ for (PyTypeListType::iterator it = m_list->begin(); it != m_list->end(); ++it)
+ // if preparation failed, report it
+ if (PyType_Ready((*it)->getType()) < 0) return false;
+ // success
+ return true;
+}
+
+/// register types to module
+void PyTypeList::reg (PyObject * module)
+{
+ // if list exists
+ if (m_list.get() != NULL)
+ // iterate items in list
+ for (PyTypeListType::iterator it = m_list->begin(); it != m_list->end(); ++it)
+ {
+ // increase ref count
+ Py_INCREF((*it)->getType());
+ // add type to module
+ PyModule_AddObject(module, (char*)(*it)->getName(), (PyObject*)(*it)->getType());
+ }
+}
diff --git a/source/gameengine/VideoTexture/PyTypeList.h b/source/gameengine/VideoTexture/PyTypeList.h
new file mode 100644
index 00000000000..4daf88bfa19
--- /dev/null
+++ b/source/gameengine/VideoTexture/PyTypeList.h
@@ -0,0 +1,85 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of blendTex library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+#if !defined PYTYPELIST_H
+#define PYTYPELIST_H
+
+#include "Common.h"
+
+#include <memory>
+#include <vector>
+
+#include <PyObjectPlus.h>
+
+// forward declaration
+class PyTypeListItem;
+
+// type for list of types
+typedef std::vector<PyTypeListItem*> PyTypeListType;
+
+
+/// class to store list of python types
+class PyTypeList
+{
+public:
+ /// check, if type is in list
+ bool in (PyTypeObject * type);
+
+ /// add type to list
+ void add (PyTypeObject * type, const char * name);
+
+ /// prepare types
+ bool ready (void);
+
+ /// register types to module
+ void reg (PyObject * module);
+
+protected:
+ /// pointer to list of types
+ std::auto_ptr<PyTypeListType> m_list;
+};
+
+
+/// class for item of python type list
+class PyTypeListItem
+{
+public:
+ /// constructor adds type into list
+ PyTypeListItem (PyTypeObject * type, const char * name)
+ : m_type(type), m_name(name)
+ { }
+
+ /// does type match
+ PyTypeObject * getType (void) { return m_type; }
+
+ /// get name of type
+ const char * getName (void) { return m_name; }
+
+protected:
+ /// pointer to type object
+ PyTypeObject * m_type;
+ /// name of type
+ const char * m_name;
+};
+
+
+#endif
diff --git a/source/gameengine/VideoTexture/SConscript b/source/gameengine/VideoTexture/SConscript
new file mode 100644
index 00000000000..91a74516bc5
--- /dev/null
+++ b/source/gameengine/VideoTexture/SConscript
@@ -0,0 +1,32 @@
+#!/usr/bin/python
+import sys
+
+Import ('env')
+
+sources = env.Glob('*.cpp')
+
+incs = '. #source/gameengine/Ketsji #source/gameengine/Expressions'
+incs += ' #source/gameengine/GameLogic #source/gameengine/SceneGraph #source/gameengine/Rasterizer'
+incs += ' #source/gameengine/Rasterizer/RAS_OpenGLRasterizer'
+incs += ' #source/gameengine/BlenderRoutines'
+incs += ' #source/blender/editors/include #source/blender/blenlib #source/blender/blenkernel'
+incs += ' #source/blender/makesdna #source/blender/imbuf #source/blender/python'
+incs += ' #source/blender/gpu #source/kernel/gen_system #intern/string #intern/moto/include'
+incs += ' #intern/guardedalloc #intern/SoundSystem'
+incs += ' #extern/glew/include'
+
+cflags = []
+defs = ''
+if env['OURPLATFORM'] == 'win32-vc':
+ cflags.append('/GR')
+ cflags.append('/Ox')
+
+incs += ' ' + env['BF_PYTHON_INC']
+#incs += ' ' + env['BF_OPENGL_INC']
+
+if env['WITH_BF_FFMPEG']:
+ defs += ' WITH_FFMPEG'
+ incs += ' ' + env['BF_FFMPEG_INC']
+ defs += ' __STDC_CONSTANT_MACROS'
+
+env.BlenderLib ( 'bf_videotex', sources, Split(incs), Split(defs), libtype=['game','player'], priority=[25, 72], compileflags = cflags )
diff --git a/source/gameengine/VideoTexture/Texture.cpp b/source/gameengine/VideoTexture/Texture.cpp
new file mode 100644
index 00000000000..12d4e79ad89
--- /dev/null
+++ b/source/gameengine/VideoTexture/Texture.cpp
@@ -0,0 +1,475 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+// implementation
+
+#include <PyObjectPlus.h>
+#include <structmember.h>
+
+#include <KX_GameObject.h>
+#include <RAS_MeshObject.h>
+#include <DNA_mesh_types.h>
+#include <DNA_meshdata_types.h>
+#include <DNA_image_types.h>
+#include <IMB_imbuf_types.h>
+#include <KX_PolygonMaterial.h>
+
+#include <MEM_guardedalloc.h>
+
+#include <KX_BlenderMaterial.h>
+#include <BL_Texture.h>
+
+#include "KX_KetsjiEngine.h"
+#include "KX_PythonInit.h"
+#include "Texture.h"
+#include "ImageBase.h"
+#include "Exception.h"
+
+#include <memory.h>
+#include <BIF_gl.h>
+
+
+// macro for exception handling and logging
+#define CATCH_EXCP catch (Exception & exp) \
+{ exp.report(); }
+
+
+// Blender GameObject type
+BlendType<KX_GameObject> gameObjectType ("KX_GameObject");
+
+
+// load texture
+void loadTexture (unsigned int texId, unsigned int * texture, short * size,
+ bool mipmap)
+{
+ // load texture for rendering
+ glBindTexture(GL_TEXTURE_2D, texId);
+ if (mipmap)
+ {
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, size[0], size[1], GL_RGBA, GL_UNSIGNED_BYTE, texture);
+ }
+ else
+ {
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, size[0], size[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, texture);
+ }
+ glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
+}
+
+
+// get pointer to material
+RAS_IPolyMaterial * getMaterial (PyObject *obj, short matID)
+{
+ // if object is available
+ if (obj != NULL)
+ {
+ // get pointer to texture image
+ KX_GameObject * gameObj = gameObjectType.checkType(obj);
+ if (gameObj != NULL && gameObj->GetMeshCount() > 0)
+ {
+ // get material from mesh
+ RAS_MeshObject * mesh = gameObj->GetMesh(0);
+ RAS_MeshMaterial *meshMat = mesh->GetMeshMaterial(matID);
+ if (meshMat != NULL && meshMat->m_bucket != NULL)
+ // return pointer to polygon or blender material
+ return meshMat->m_bucket->GetPolyMaterial();
+ }
+ }
+ // otherwise material was not found
+ return NULL;
+}
+
+
+// get material ID
+short getMaterialID (PyObject * obj, char * name)
+{
+ // search for material
+ for (short matID = 0;; ++matID)
+ {
+ // get material
+ RAS_IPolyMaterial * mat = getMaterial(obj, matID);
+ // if material is not available, report that no material was found
+ if (mat == NULL)
+ break;
+ // name is a material name if it starts with MA and a UV texture name if it starts with IM
+ if (name[0] == 'I' && name[1] == 'M')
+ {
+ // if texture name matches
+ if (strcmp(mat->GetTextureName().ReadPtr(), name) == 0)
+ return matID;
+ } else
+ {
+ // if material name matches
+ if (strcmp(mat->GetMaterialName().ReadPtr(), name) == 0)
+ return matID;
+ }
+ }
+ // material was not found
+ return -1;
+}
+
+
+// Texture object allocation
+PyObject * Texture_new (PyTypeObject *type, PyObject *args, PyObject *kwds)
+{
+ // allocate object
+ Texture * self = reinterpret_cast<Texture*>(type->tp_alloc(type, 0));
+ // initialize object structure
+ self->m_actTex = 0;
+ self->m_orgSaved = false;
+ self->m_imgTexture = NULL;
+ self->m_matTexture = NULL;
+ self->m_mipmap = false;
+ self->m_scaledImg = NULL;
+ self->m_scaledImgSize = 0;
+ self->m_source = NULL;
+ self->m_lastClock = 0.0;
+ // return allocated object
+ return reinterpret_cast<PyObject*>(self);
+}
+
+
+// forward declaration
+PyObject * Texture_close(Texture * self);
+int Texture_setSource (Texture * self, PyObject * value, void * closure);
+
+
+// Texture object deallocation
+void Texture_dealloc (Texture * self)
+{
+ // release renderer
+ Py_XDECREF(self->m_source);
+ // close texture
+ Texture_close(self);
+ // release scaled image buffer
+ delete [] self->m_scaledImg;
+ // release object
+ self->ob_type->tp_free((PyObject*)self);
+}
+
+
+ExceptionID MaterialNotAvail;
+ExpDesc MaterialNotAvailDesc (MaterialNotAvail, "Texture material is not available");
+
+// Texture object initialization
+int Texture_init (Texture *self, PyObject *args, PyObject *kwds)
+{
+ // parameters - game object with video texture
+ PyObject * obj = NULL;
+ // material ID
+ short matID = 0;
+ // texture ID
+ short texID = 0;
+ // texture object with shared texture ID
+ Texture * texObj = NULL;
+
+ static char *kwlist[] = {"gameObj", "materialID", "textureID", "textureObj", NULL};
+
+ // get parameters
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|hhO!", kwlist, &obj, &matID,
+ &texID, &TextureType, &texObj))
+ return -1;
+
+ // if parameters are available
+ if (obj != NULL)
+ {
+ // process polygon material or blender material
+ try
+ {
+ // get pointer to texture image
+ RAS_IPolyMaterial * mat = getMaterial(obj, matID);
+ if (mat != NULL)
+ {
+ // is it blender material or polygon material
+ if (mat->GetFlag() & RAS_BLENDERGLSL)
+ {
+ self->m_imgTexture = static_cast<KX_BlenderMaterial*>(mat)->getImage(texID);
+ self->m_useMatTexture = false;
+ } else if (mat->GetFlag() & RAS_BLENDERMAT)
+ {
+ // get blender material texture
+ self->m_matTexture = static_cast<KX_BlenderMaterial*>(mat)->getTex(texID);
+ self->m_useMatTexture = true;
+ }
+ else
+ {
+ // get texture pointer from polygon material
+ MTFace * tface = static_cast<KX_PolygonMaterial*>(mat)->GetMTFace();
+ self->m_imgTexture = (Image*)tface->tpage;
+ self->m_useMatTexture = false;
+ }
+ }
+ // check if texture is available, if not, initialization failed
+ if (self->m_imgTexture == NULL && self->m_matTexture == NULL)
+ // throw exception if initialization failed
+ THRWEXCP(MaterialNotAvail, S_OK);
+
+ // if texture object is provided
+ if (texObj != NULL)
+ {
+ // copy texture code
+ self->m_actTex = texObj->m_actTex;
+ self->m_mipmap = texObj->m_mipmap;
+ if (texObj->m_source != NULL)
+ Texture_setSource(self, reinterpret_cast<PyObject*>(texObj->m_source), NULL);
+ }
+ else
+ // otherwise generate texture code
+ glGenTextures(1, (GLuint*)&self->m_actTex);
+ }
+ catch (Exception & exp)
+ {
+ exp.report();
+ return -1;
+ }
+ }
+ // initialization succeded
+ return 0;
+}
+
+
+// close added texture
+PyObject * Texture_close(Texture * self)
+{
+ // restore texture
+ if (self->m_orgSaved)
+ {
+ self->m_orgSaved = false;
+ // restore original texture code
+ if (self->m_useMatTexture)
+ self->m_matTexture->swapTexture(self->m_orgTex);
+ else
+ self->m_imgTexture->bindcode = self->m_orgTex;
+ // drop actual texture
+ if (self->m_actTex != 0)
+ {
+ glDeleteTextures(1, (GLuint *)&self->m_actTex);
+ self->m_actTex = 0;
+ }
+ }
+ Py_RETURN_NONE;
+}
+
+
+// refresh texture
+PyObject * Texture_refresh (Texture * self, PyObject * args)
+{
+ // get parameter - refresh source
+ PyObject * param;
+ if (!PyArg_ParseTuple(args, "O", &param) || !PyBool_Check(param))
+ {
+ // report error
+ PyErr_SetString(PyExc_TypeError, "The value must be a bool");
+ return NULL;
+ }
+ // some trick here: we are in the business of loading a texture,
+ // no use to do it if we are still in the same rendering frame.
+ // We find this out by looking at the engine current clock time
+ KX_KetsjiEngine* engine = KX_GetActiveEngine();
+ if (engine->GetClockTime() != self->m_lastClock)
+ {
+ self->m_lastClock = engine->GetClockTime();
+ // set source refresh
+ bool refreshSource = (param == Py_True);
+ // try to proces texture from source
+ try
+ {
+ // if source is available
+ if (self->m_source != NULL)
+ {
+ // check texture code
+ if (!self->m_orgSaved)
+ {
+ self->m_orgSaved = true;
+ // save original image code
+ if (self->m_useMatTexture)
+ self->m_orgTex = self->m_matTexture->swapTexture(self->m_actTex);
+ else
+ {
+ self->m_orgTex = self->m_imgTexture->bindcode;
+ self->m_imgTexture->bindcode = self->m_actTex;
+ }
+ }
+
+ // get texture
+ unsigned int * texture = self->m_source->m_image->getImage(self->m_actTex);
+ // if texture is available
+ if (texture != NULL)
+ {
+ // get texture size
+ short * orgSize = self->m_source->m_image->getSize();
+ // calc scaled sizes
+ short size[] = {ImageBase::calcSize(orgSize[0]), ImageBase::calcSize(orgSize[1])};
+ // scale texture if needed
+ if (size[0] != orgSize[0] || size[1] != orgSize[1])
+ {
+ // if scaled image buffer is smaller than needed
+ if (self->m_scaledImgSize < (unsigned int)(size[0] * size[1]))
+ {
+ // new size
+ self->m_scaledImgSize = size[0] * size[1];
+ // allocate scaling image
+ delete [] self->m_scaledImg;
+ self->m_scaledImg = new unsigned int[self->m_scaledImgSize];
+ }
+ // scale texture
+ gluScaleImage(GL_RGBA, orgSize[0], orgSize[1], GL_UNSIGNED_BYTE, texture,
+ size[0], size[1], GL_UNSIGNED_BYTE, self->m_scaledImg);
+ // use scaled image instead original
+ texture = self->m_scaledImg;
+ }
+ // load texture for rendering
+ loadTexture (self->m_actTex, texture, size, self->m_mipmap);
+
+ // refresh texture source, if required
+ if (refreshSource) self->m_source->m_image->refresh();
+ }
+ }
+ }
+ CATCH_EXCP;
+ }
+ Py_RETURN_NONE;
+}
+
+
+// get mipmap value
+PyObject * Texture_getMipmap (Texture * self, void * closure)
+{
+ // return true if flag is set, otherwise false
+ if (self->m_mipmap) Py_RETURN_TRUE;
+ else Py_RETURN_FALSE;
+}
+
+// set mipmap value
+int Texture_setMipmap (Texture * self, PyObject * value, void * closure)
+{
+ // check parameter, report failure
+ if (value == NULL || !PyBool_Check(value))
+ {
+ PyErr_SetString(PyExc_TypeError, "The value must be a bool");
+ return -1;
+ }
+ // set mipmap
+ self->m_mipmap = value == Py_True;
+ // success
+ return 0;
+}
+
+
+// get source object
+PyObject * Texture_getSource (Texture * self, PyObject * value, void * closure)
+{
+ // if source exists
+ if (self->m_source != NULL)
+ {
+ Py_INCREF(self->m_source);
+ return reinterpret_cast<PyObject*>(self->m_source);
+ }
+ // otherwise return None
+ Py_RETURN_NONE;
+}
+
+
+// set source object
+int Texture_setSource (Texture * self, PyObject * value, void * closure)
+{
+ // check new value
+ if (value == NULL || !pyImageTypes.in(value->ob_type))
+ {
+ // report value error
+ PyErr_SetString(PyExc_TypeError, "Invalid type of value");
+ return -1;
+ }
+ // increase ref count for new value
+ Py_INCREF(value);
+ // release previous
+ Py_XDECREF(self->m_source);
+ // set new value
+ self->m_source = reinterpret_cast<PyImage*>(value);
+ // return success
+ return 0;
+}
+
+
+// class Texture methods
+static PyMethodDef textureMethods[] =
+{
+ { "close", (PyCFunction)Texture_close, METH_NOARGS, "Close dynamic texture and restore original"},
+ { "refresh", (PyCFunction)Texture_refresh, METH_VARARGS, "Refresh texture from source"},
+ {NULL} /* Sentinel */
+};
+
+// class Texture attributes
+static PyGetSetDef textureGetSets[] =
+{
+ {(char*)"source", (getter)Texture_getSource, (setter)Texture_setSource, (char*)"source of texture", NULL},
+ {(char*)"mipmap", (getter)Texture_getMipmap, (setter)Texture_setMipmap, (char*)"mipmap texture", NULL},
+ {NULL}
+};
+
+
+// class Texture declaration
+PyTypeObject TextureType =
+{
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "VideoTexture.Texture", /*tp_name*/
+ sizeof(Texture), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)Texture_dealloc,/*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash */
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ "Texture objects", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ textureMethods, /* tp_methods */
+ 0, /* tp_members */
+ textureGetSets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)Texture_init, /* tp_init */
+ 0, /* tp_alloc */
+ Texture_new, /* tp_new */
+};
diff --git a/source/gameengine/VideoTexture/Texture.h b/source/gameengine/VideoTexture/Texture.h
new file mode 100644
index 00000000000..3c371e51537
--- /dev/null
+++ b/source/gameengine/VideoTexture/Texture.h
@@ -0,0 +1,86 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2006 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+#if !defined TEXTURE_H
+#define TEXTURE_H
+
+#include <PyObjectPlus.h>
+#include <structmember.h>
+
+#include <DNA_image_types.h>
+#include <BL_Texture.h>
+#include <KX_BlenderMaterial.h>
+
+#include "ImageBase.h"
+#include "BlendType.h"
+
+
+// type Texture declaration
+struct Texture
+{
+ PyObject_HEAD
+
+ // texture is using blender material
+ bool m_useMatTexture;
+
+ // video texture bind code
+ unsigned int m_actTex;
+ // original texture bind code
+ unsigned int m_orgTex;
+ // original texture saved
+ bool m_orgSaved;
+
+ // texture image for game materials
+ Image * m_imgTexture;
+ // texture for blender materials
+ BL_Texture * m_matTexture;
+
+ // use mipmapping
+ bool m_mipmap;
+
+ // scaled image buffer
+ unsigned int * m_scaledImg;
+ // scaled image buffer size
+ unsigned int m_scaledImgSize;
+ // last refresh
+ double m_lastClock;
+
+ // image source
+ PyImage * m_source;
+};
+
+
+// Texture type description
+extern PyTypeObject TextureType;
+
+// load texture
+void loadTexture (unsigned int texId, unsigned int * texture, short * size,
+ bool mipmap = false);
+
+// get material
+RAS_IPolyMaterial * getMaterial (PyObject *obj, short matID);
+
+// get material ID
+short getMaterialID (PyObject * obj, char * name);
+
+
+#endif
diff --git a/source/gameengine/VideoTexture/VideoBase.cpp b/source/gameengine/VideoTexture/VideoBase.cpp
new file mode 100644
index 00000000000..10117c3af9e
--- /dev/null
+++ b/source/gameengine/VideoTexture/VideoBase.cpp
@@ -0,0 +1,195 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+#if defined WIN32
+#define WINDOWS_LEAN_AND_MEAN
+#include <Windows.h>
+#endif
+
+#include "VideoBase.h"
+
+#include "FilterSource.h"
+
+// VideoBase implementation
+
+
+// initialize image data
+void VideoBase::init(short width, short height)
+{
+ // save original sizes
+ m_orgSize[0] = width;
+ m_orgSize[1] = height;
+ // call base class initialization
+ ImageBase::init(width, height);
+}
+
+
+// process video frame
+void VideoBase::process (BYTE * sample)
+{
+ // if scale was changed
+ if (m_scaleChange)
+ // reset image
+ init(m_orgSize[0], m_orgSize[1]);
+ // if image is allocated and is able to store new image
+ if (m_image != NULL && !m_avail)
+ {
+ // filters used
+ // convert video format to image
+ switch (m_format)
+ {
+ case RGBA32:
+ {
+ FilterRGBA32 filtRGBA;
+ // use filter object for format to convert image
+ filterImage(filtRGBA, sample, m_orgSize);
+ // finish
+ break;
+ }
+ case RGB24:
+ {
+ FilterRGB24 filtRGB;
+ // use filter object for format to convert image
+ filterImage(filtRGB, sample, m_orgSize);
+ // finish
+ break;
+ }
+ case YV12:
+ {
+ // use filter object for format to convert image
+ FilterYV12 filtYUV;
+ filtYUV.setBuffs(sample, m_orgSize);
+ filterImage(filtYUV, sample, m_orgSize);
+ // finish
+ break;
+ }
+ }
+ }
+}
+
+
+// python functions
+
+
+// exceptions for video source initialization
+ExceptionID SourceVideoEmpty, SourceVideoCreation;
+ExpDesc SourceVideoEmptyDesc (SourceVideoEmpty, "Source Video is empty");
+ExpDesc SourceVideoCreationDesc (SourceVideoCreation, "SourceVideo object was not created");
+
+// open video source
+void Video_open (VideoBase * self, char * file, short captureID)
+{
+ // if file is empty, throw exception
+ if (file == NULL) THRWEXCP(SourceVideoEmpty, S_OK);
+
+ // open video file or capture device
+ if (captureID >= 0)
+ self->openCam(file, captureID);
+ else
+ self->openFile(file);
+}
+
+
+// play video
+PyObject * Video_play (PyImage * self)
+{ if (getVideo(self)->play()) Py_RETURN_TRUE; else Py_RETURN_FALSE; }
+
+// stop video
+PyObject * Video_stop (PyImage * self)
+{ if (getVideo(self)->stop()) Py_RETURN_TRUE; else Py_RETURN_FALSE; }
+
+// get status
+PyObject * Video_getStatus (PyImage * self, void * closure)
+{
+ return Py_BuildValue("h", getVideo(self)->getStatus());
+}
+
+// refresh video
+PyObject * Video_refresh (PyImage * self)
+{
+ getVideo(self)->refresh();
+ return Video_getStatus(self, NULL);
+}
+
+
+// get range
+PyObject * Video_getRange (PyImage * self, void * closure)
+{
+ return Py_BuildValue("[ff]", getVideo(self)->getRange()[0],
+ getVideo(self)->getRange()[1]);
+}
+
+// set range
+int Video_setRange (PyImage * self, PyObject * value, void * closure)
+{
+ // check validity of parameter
+ if (value == NULL || !PySequence_Check(value) || PySequence_Length(value) != 2
+ || !PyFloat_Check(PySequence_Fast_GET_ITEM(value, 0))
+ || !PyFloat_Check(PySequence_Fast_GET_ITEM(value, 1)))
+ {
+ PyErr_SetString(PyExc_TypeError, "The value must be a sequence of 2 longs");
+ return -1;
+ }
+ // set range
+ getVideo(self)->setRange(PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 0)),
+ PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 1)));
+ // success
+ return 0;
+}
+
+// get repeat
+PyObject * Video_getRepeat (PyImage * self, void * closure)
+{ return Py_BuildValue("h", getVideo(self)->getRepeat()); }
+
+// set repeat
+int Video_setRepeat (PyImage * self, PyObject * value, void * closure)
+{
+ // check validity of parameter
+ if (value == NULL || !PyInt_Check(value))
+ {
+ PyErr_SetString(PyExc_TypeError, "The value must be an int");
+ return -1;
+ }
+ // set repeat
+ getVideo(self)->setRepeat(int(PyInt_AsLong(value)));
+ // success
+ return 0;
+}
+
+// get frame rate
+PyObject * Video_getFrameRate (PyImage * self, void * closure)
+{ return Py_BuildValue("f", double(getVideo(self)->getFrameRate())); }
+
+// set frame rate
+int Video_setFrameRate (PyImage * self, PyObject * value, void * closure)
+{
+ // check validity of parameter
+ if (value == NULL || !PyFloat_Check(value))
+ {
+ PyErr_SetString(PyExc_TypeError, "The value must be a float");
+ return -1;
+ }
+ // set repeat
+ getVideo(self)->setFrameRate(float(PyFloat_AsDouble(value)));
+ // success
+ return 0;
+}
diff --git a/source/gameengine/VideoTexture/VideoBase.h b/source/gameengine/VideoTexture/VideoBase.h
new file mode 100644
index 00000000000..15ecb7a78f4
--- /dev/null
+++ b/source/gameengine/VideoTexture/VideoBase.h
@@ -0,0 +1,185 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+#if !defined VIDEOBASE_H
+#define VIDEOBASE_H
+
+
+#include <PyObjectPlus.h>
+
+#include "ImageBase.h"
+
+#include "Exception.h"
+
+// source states
+const int SourceError = -1;
+const int SourceEmpty = 0;
+const int SourceReady = 1;
+const int SourcePlaying = 2;
+const int SourceStopped = 3;
+
+
+// video source formats
+enum VideoFormat { None, RGB24, YV12, RGBA32 };
+
+
+/// base class for video source
+class VideoBase : public ImageBase
+{
+public:
+ /// constructor
+ VideoBase (void) : ImageBase(true), m_format(None), m_status(SourceEmpty),
+ m_repeat(0), m_frameRate(1.0)
+ {
+ m_orgSize[0] = m_orgSize[1] = 0;
+ m_range[0] = m_range[1] = 0.0;
+ }
+
+ /// destructor
+ virtual ~VideoBase (void) {}
+
+ /// open video file
+ virtual void openFile (char * file)
+ {
+ m_isFile = true;
+ m_status = SourceReady;
+ }
+ /// open video capture device
+ virtual void openCam (char * file, short camIdx)
+ {
+ m_isFile = false;
+ m_status = SourceReady;
+ }
+
+ /// play video
+ virtual bool play (void)
+ {
+ if (m_status == SourceReady || m_status == SourceStopped)
+ {
+ m_status = SourcePlaying;
+ return true;
+ }
+ return false;
+ }
+ /// stop/pause video
+ virtual bool stop (void)
+ {
+ if (m_status == SourcePlaying)
+ {
+ m_status = SourceStopped;
+ return true;
+ }
+ return false;
+ }
+
+ // get video status
+ int getStatus (void) { return m_status; }
+
+ /// get play range
+ const double * getRange (void) { return m_range; }
+ /// set play range
+ virtual void setRange (double start, double stop)
+ {
+ if (m_isFile)
+ {
+ m_range[0] = start;
+ m_range[1] = stop;
+ }
+ }
+
+ // get video repeat
+ int getRepeat (void) { return m_repeat; }
+ /// set video repeat
+ virtual void setRepeat (int rep)
+ { if (m_isFile) m_repeat = rep; }
+
+ /// get frame rate
+ float getFrameRate (void) { return m_frameRate; }
+ /// set frame rate
+ virtual void setFrameRate (float rate)
+ { if (m_isFile) m_frameRate = rate > 0.0 ? rate : 1.0f; }
+
+protected:
+ /// video format
+ VideoFormat m_format;
+ /// original video size
+ short m_orgSize[2];
+
+ /// video status
+ int m_status;
+
+ /// is source file
+ bool m_isFile;
+
+ /// replay range
+ double m_range[2];
+ /// repeat count
+ int m_repeat;
+ /// frame rate
+ float m_frameRate;
+
+ /// initialize image data
+ void init (short width, short height);
+
+ /// process source data
+ void process (BYTE * sample);
+};
+
+
+
+// python fuctions
+
+
+// cast Image pointer to Video
+inline VideoBase * getVideo (PyImage * self)
+{ return static_cast<VideoBase*>(self->m_image); }
+
+
+extern ExceptionID SourceVideoCreation;
+
+// object initialization
+template <class T> void Video_init (PyImage * self)
+{
+ // create source video object
+ if (self->m_image != NULL) delete self->m_image;
+ HRESULT hRslt = S_OK;
+ self->m_image = new T(&hRslt);
+ CHCKHRSLT(hRslt, SourceVideoCreation);
+}
+
+
+// video functions
+void Video_open (VideoBase * self, char * file, short captureID);
+PyObject * Video_play (PyImage * self);
+PyObject * Video_stop (PyImage * self);
+PyObject * Video_refresh (PyImage * self);
+PyObject * Video_getStatus (PyImage * self, void * closure);
+PyObject * Video_getRange (PyImage * self, void * closure);
+int Video_setRange (PyImage * self, PyObject * value, void * closure);
+PyObject * Video_getRepeat (PyImage * self, void * closure);
+int Video_setRepeat (PyImage * self, PyObject * value, void * closure);
+PyObject * Video_getFrameRate (PyImage * self, void * closure);
+int Video_setFrameRate (PyImage * self, PyObject * value, void * closure);
+
+
+#endif
+
diff --git a/source/gameengine/VideoTexture/VideoFFmpeg.cpp b/source/gameengine/VideoTexture/VideoFFmpeg.cpp
new file mode 100644
index 00000000000..02798c7e596
--- /dev/null
+++ b/source/gameengine/VideoTexture/VideoFFmpeg.cpp
@@ -0,0 +1,927 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+#ifdef WITH_FFMPEG
+
+// INT64_C fix for some linux machines (C99ism)
+#define __STDC_CONSTANT_MACROS
+#include <stdint.h>
+
+
+#include "MEM_guardedalloc.h"
+#include "PIL_time.h"
+
+#include <string>
+
+#include "Exception.h"
+#include "VideoFFmpeg.h"
+
+
+// default framerate
+const double defFrameRate = 25.0;
+// time scale constant
+const long timeScale = 1000;
+
+// macro for exception handling and logging
+#define CATCH_EXCP catch (Exception & exp) \
+{ exp.report(); m_status = SourceError; }
+
+extern "C" void do_init_ffmpeg();
+
+// class RenderVideo
+
+// constructor
+VideoFFmpeg::VideoFFmpeg (HRESULT * hRslt) : VideoBase(),
+m_codec(NULL), m_formatCtx(NULL), m_codecCtx(NULL),
+m_frame(NULL), m_frameDeinterlaced(NULL), m_frameRGB(NULL), m_imgConvertCtx(NULL),
+m_deinterlace(false), m_preseek(0), m_videoStream(-1), m_baseFrameRate(25.0),
+m_lastFrame(-1), m_eof(false), m_curPosition(-1), m_startTime(0),
+m_captWidth(0), m_captHeight(0), m_captRate(0.f), m_isImage(false)
+{
+ // set video format
+ m_format = RGB24;
+ // force flip because ffmpeg always return the image in the wrong orientation for texture
+ setFlip(true);
+ // construction is OK
+ *hRslt = S_OK;
+}
+
+// destructor
+VideoFFmpeg::~VideoFFmpeg ()
+{
+}
+
+
+// release components
+bool VideoFFmpeg::release()
+{
+ // release
+ if (m_codecCtx)
+ {
+ avcodec_close(m_codecCtx);
+ m_codecCtx = NULL;
+ }
+ if (m_formatCtx)
+ {
+ av_close_input_file(m_formatCtx);
+ m_formatCtx = NULL;
+ }
+ if (m_frame)
+ {
+ av_free(m_frame);
+ m_frame = NULL;
+ }
+ if (m_frameDeinterlaced)
+ {
+ MEM_freeN(m_frameDeinterlaced->data[0]);
+ av_free(m_frameDeinterlaced);
+ m_frameDeinterlaced = NULL;
+ }
+ if (m_frameRGB)
+ {
+ MEM_freeN(m_frameRGB->data[0]);
+ av_free(m_frameRGB);
+ m_frameRGB = NULL;
+ }
+ if (m_imgConvertCtx)
+ {
+ sws_freeContext(m_imgConvertCtx);
+ m_imgConvertCtx = NULL;
+ }
+ m_codec = NULL;
+ m_status = SourceStopped;
+ return true;
+}
+
+
+// set initial parameters
+void VideoFFmpeg::initParams (short width, short height, float rate, bool image)
+{
+ m_captWidth = width;
+ m_captHeight = height;
+ m_captRate = rate;
+ m_isImage = image;
+}
+
+int VideoFFmpeg::openStream(const char *filename, AVInputFormat *inputFormat, AVFormatParameters *formatParams)
+{
+ AVFormatContext *formatCtx;
+ int i, videoStream;
+ AVCodec *codec;
+ AVCodecContext *codecCtx;
+
+ if(av_open_input_file(&formatCtx, filename, inputFormat, 0, formatParams)!=0)
+ return -1;
+
+ if(av_find_stream_info(formatCtx)<0)
+ {
+ av_close_input_file(formatCtx);
+ return -1;
+ }
+
+ /* Find the first video stream */
+ videoStream=-1;
+ for(i=0; i<formatCtx->nb_streams; i++)
+ {
+ if(formatCtx->streams[i] &&
+ get_codec_from_stream(formatCtx->streams[i]) &&
+ (get_codec_from_stream(formatCtx->streams[i])->codec_type==CODEC_TYPE_VIDEO))
+ {
+ videoStream=i;
+ break;
+ }
+ }
+
+ if(videoStream==-1)
+ {
+ av_close_input_file(formatCtx);
+ return -1;
+ }
+
+ codecCtx = get_codec_from_stream(formatCtx->streams[videoStream]);
+
+ /* Find the decoder for the video stream */
+ codec=avcodec_find_decoder(codecCtx->codec_id);
+ if(codec==NULL)
+ {
+ av_close_input_file(formatCtx);
+ return -1;
+ }
+ codecCtx->workaround_bugs = 1;
+ if(avcodec_open(codecCtx, codec)<0)
+ {
+ av_close_input_file(formatCtx);
+ return -1;
+ }
+
+#ifdef FFMPEG_OLD_FRAME_RATE
+ if(codecCtx->frame_rate>1000 && codecCtx->frame_rate_base==1)
+ codecCtx->frame_rate_base=1000;
+ m_baseFrameRate = (double)codecCtx->frame_rate / (double)codecCtx->frame_rate_base;
+#else
+ m_baseFrameRate = av_q2d(formatCtx->streams[videoStream]->r_frame_rate);
+#endif
+ if (m_baseFrameRate <= 0.0)
+ m_baseFrameRate = defFrameRate;
+
+ m_codec = codec;
+ m_codecCtx = codecCtx;
+ m_formatCtx = formatCtx;
+ m_videoStream = videoStream;
+ m_frame = avcodec_alloc_frame();
+ m_frameDeinterlaced = avcodec_alloc_frame();
+ m_frameRGB = avcodec_alloc_frame();
+
+ // allocate buffer if deinterlacing is required
+ avpicture_fill((AVPicture*)m_frameDeinterlaced,
+ (uint8_t*)MEM_callocN(avpicture_get_size(
+ m_codecCtx->pix_fmt,
+ m_codecCtx->width, m_codecCtx->height),
+ "ffmpeg deinterlace"),
+ m_codecCtx->pix_fmt, m_codecCtx->width, m_codecCtx->height);
+
+ // check if the pixel format supports Alpha
+ if (m_codecCtx->pix_fmt == PIX_FMT_RGB32 ||
+ m_codecCtx->pix_fmt == PIX_FMT_BGR32 ||
+ m_codecCtx->pix_fmt == PIX_FMT_RGB32_1 ||
+ m_codecCtx->pix_fmt == PIX_FMT_BGR32_1)
+ {
+ // allocate buffer to store final decoded frame
+ m_format = RGBA32;
+ avpicture_fill((AVPicture*)m_frameRGB,
+ (uint8_t*)MEM_callocN(avpicture_get_size(
+ PIX_FMT_RGBA,
+ m_codecCtx->width, m_codecCtx->height),
+ "ffmpeg rgba"),
+ PIX_FMT_RGBA, m_codecCtx->width, m_codecCtx->height);
+ // allocate sws context
+ m_imgConvertCtx = sws_getContext(
+ m_codecCtx->width,
+ m_codecCtx->height,
+ m_codecCtx->pix_fmt,
+ m_codecCtx->width,
+ m_codecCtx->height,
+ PIX_FMT_RGBA,
+ SWS_FAST_BILINEAR,
+ NULL, NULL, NULL);
+ } else
+ {
+ // allocate buffer to store final decoded frame
+ m_format = RGB24;
+ avpicture_fill((AVPicture*)m_frameRGB,
+ (uint8_t*)MEM_callocN(avpicture_get_size(
+ PIX_FMT_RGB24,
+ m_codecCtx->width, m_codecCtx->height),
+ "ffmpeg rgb"),
+ PIX_FMT_RGB24, m_codecCtx->width, m_codecCtx->height);
+ // allocate sws context
+ m_imgConvertCtx = sws_getContext(
+ m_codecCtx->width,
+ m_codecCtx->height,
+ m_codecCtx->pix_fmt,
+ m_codecCtx->width,
+ m_codecCtx->height,
+ PIX_FMT_RGB24,
+ SWS_FAST_BILINEAR,
+ NULL, NULL, NULL);
+ }
+ if (!m_imgConvertCtx) {
+ avcodec_close(m_codecCtx);
+ av_close_input_file(m_formatCtx);
+ av_free(m_frame);
+ MEM_freeN(m_frameDeinterlaced->data[0]);
+ av_free(m_frameDeinterlaced);
+ MEM_freeN(m_frameRGB->data[0]);
+ av_free(m_frameRGB);
+ return -1;
+ }
+ return 0;
+}
+
+// open video file
+void VideoFFmpeg::openFile (char * filename)
+{
+ do_init_ffmpeg();
+
+ if (openStream(filename, NULL, NULL) != 0)
+ return;
+
+ if (m_codecCtx->gop_size)
+ m_preseek = (m_codecCtx->gop_size < 25) ? m_codecCtx->gop_size+1 : 25;
+ else if (m_codecCtx->has_b_frames)
+ m_preseek = 25; // should determine gopsize
+ else
+ m_preseek = 0;
+
+ // get video time range
+ m_range[0] = 0.0;
+ m_range[1] = (double)m_formatCtx->duration / AV_TIME_BASE;
+
+ // open base class
+ VideoBase::openFile(filename);
+
+ if (
+#ifdef FFMPEG_PB_IS_POINTER
+ m_formatCtx->pb && m_formatCtx->pb->is_streamed
+#else
+ m_formatCtx->pb.is_streamed
+#endif
+ )
+ {
+ // the file is in fact a streaming source, prevent seeking
+ m_isFile = false;
+ // for streaming it is important to do non blocking read
+ m_formatCtx->flags |= AVFMT_FLAG_NONBLOCK;
+ }
+
+ if (m_isImage)
+ {
+ // the file is to be treated as an image, i.e. load the first frame only
+ m_isFile = false;
+ // in case of reload, the filename is taken from m_imageName, no need to change it
+ if (m_imageName.Ptr() != filename)
+ m_imageName = filename;
+ m_preseek = 0;
+ m_avail = false;
+ play();
+ }
+
+}
+
+
+// open video capture device
+void VideoFFmpeg::openCam (char * file, short camIdx)
+{
+ // open camera source
+ AVInputFormat *inputFormat;
+ AVFormatParameters formatParams;
+ AVRational frameRate;
+ char *p, filename[28], rateStr[20];
+
+ do_init_ffmpeg();
+
+ memset(&formatParams, 0, sizeof(formatParams));
+#ifdef WIN32
+ // video capture on windows only through Video For Windows driver
+ inputFormat = av_find_input_format("vfwcap");
+ if (!inputFormat)
+ // Video For Windows not supported??
+ return;
+ sprintf(filename, "%d", camIdx);
+#else
+ // In Linux we support two types of devices: VideoForLinux and DV1394.
+ // the user specify it with the filename:
+ // [<device_type>][:<standard>]
+ // <device_type> : 'v4l' for VideoForLinux, 'dv1394' for DV1394. By default 'v4l'
+ // <standard> : 'pal', 'secam' or 'ntsc'. By default 'ntsc'
+ // The driver name is constructed automatically from the device type:
+ // v4l : /dev/video<camIdx>
+ // dv1394: /dev/dv1394/<camIdx>
+ // If you have different driver name, you can specify the driver name explicitely
+ // instead of device type. Examples of valid filename:
+ // /dev/v4l/video0:pal
+ // /dev/ieee1394/1:ntsc
+ // dv1394:secam
+ // v4l:pal
+ if (file && strstr(file, "1394") != NULL)
+ {
+ // the user specifies a driver, check if it is v4l or d41394
+ inputFormat = av_find_input_format("dv1394");
+ sprintf(filename, "/dev/dv1394/%d", camIdx);
+ } else
+ {
+ inputFormat = av_find_input_format("video4linux");
+ sprintf(filename, "/dev/video%d", camIdx);
+ }
+ if (!inputFormat)
+ // these format should be supported, check ffmpeg compilation
+ return;
+ if (file && strncmp(file, "/dev", 4) == 0)
+ {
+ // user does not specify a driver
+ strncpy(filename, file, sizeof(filename));
+ filename[sizeof(filename)-1] = 0;
+ if ((p = strchr(filename, ':')) != 0)
+ *p = 0;
+ }
+ if (file && (p = strchr(file, ':')) != NULL)
+ formatParams.standard = p+1;
+#endif
+ //frame rate
+ if (m_captRate <= 0.f)
+ m_captRate = defFrameRate;
+ sprintf(rateStr, "%f", m_captRate);
+ av_parse_video_frame_rate(&frameRate, rateStr);
+ // populate format parameters
+ // need to specify the time base = inverse of rate
+ formatParams.time_base.num = frameRate.den;
+ formatParams.time_base.den = frameRate.num;
+ formatParams.width = m_captWidth;
+ formatParams.height = m_captHeight;
+
+ if (openStream(filename, inputFormat, &formatParams) != 0)
+ return;
+
+ // for video capture it is important to do non blocking read
+ m_formatCtx->flags |= AVFMT_FLAG_NONBLOCK;
+ // open base class
+ VideoBase::openCam(file, camIdx);
+}
+
+// play video
+bool VideoFFmpeg::play (void)
+{
+ try
+ {
+ // if object is able to play
+ if (VideoBase::play())
+ {
+ // set video position
+ setPositions();
+ // return success
+ return true;
+ }
+ }
+ CATCH_EXCP;
+ return false;
+}
+
+
+// stop video
+bool VideoFFmpeg::stop (void)
+{
+ try
+ {
+ if (VideoBase::stop())
+ {
+ return true;
+ }
+ }
+ CATCH_EXCP;
+ return false;
+}
+
+
+// set video range
+void VideoFFmpeg::setRange (double start, double stop)
+{
+ try
+ {
+ // set range
+ VideoBase::setRange(start, stop);
+ // set range for video
+ setPositions();
+ }
+ CATCH_EXCP;
+}
+
+// set framerate
+void VideoFFmpeg::setFrameRate (float rate)
+{
+ VideoBase::setFrameRate(rate);
+}
+
+
+// image calculation
+void VideoFFmpeg::calcImage (unsigned int texId)
+{
+ loadFrame();
+}
+
+
+// load frame from video
+void VideoFFmpeg::loadFrame (void)
+{
+ // get actual time
+ double actTime = PIL_check_seconds_timer() - m_startTime;
+ // if video has ended
+ if (m_isFile && actTime * m_frameRate >= m_range[1])
+ {
+ // if repeats are set, decrease them
+ if (m_repeat > 0)
+ --m_repeat;
+ // if video has to be replayed
+ if (m_repeat != 0)
+ {
+ // reset its position
+ actTime -= (m_range[1] - m_range[0]) / m_frameRate;
+ m_startTime += (m_range[1] - m_range[0]) / m_frameRate;
+ }
+ // if video has to be stopped, stop it
+ else
+ m_status = SourceStopped;
+ }
+ // if video is playing
+ if (m_status == SourcePlaying)
+ {
+ // actual frame
+ long actFrame = m_isFile ? long(actTime * actFrameRate()) : m_lastFrame + 1;
+ // if actual frame differs from last frame
+ if (actFrame != m_lastFrame)
+ {
+ // get image
+ if(grabFrame(actFrame))
+ {
+ AVFrame* frame = getFrame();
+ // save actual frame
+ m_lastFrame = actFrame;
+ // init image, if needed
+ init(short(m_codecCtx->width), short(m_codecCtx->height));
+ // process image
+ process((BYTE*)(frame->data[0]));
+ // in case it is an image, automatically stop reading it
+ if (m_isImage)
+ {
+ m_status = SourceStopped;
+ // close the file as we don't need it anymore
+ release();
+ }
+ }
+ }
+ }
+}
+
+
+// set actual position
+void VideoFFmpeg::setPositions (void)
+{
+ // set video start time
+ m_startTime = PIL_check_seconds_timer();
+ // if file is played and actual position is before end position
+ if (m_isFile && !m_eof && m_lastFrame >= 0 && m_lastFrame < m_range[1] * actFrameRate())
+ // continue from actual position
+ m_startTime -= double(m_lastFrame) / actFrameRate();
+ else
+ m_startTime -= m_range[0];
+}
+
+// position pointer in file, position in second
+bool VideoFFmpeg::grabFrame(long position)
+{
+ AVPacket packet;
+ int frameFinished;
+ int posFound = 1;
+ bool frameLoaded = false;
+ long long targetTs = 0;
+
+ // first check if the position that we are looking for is in the preseek range
+ // if so, just read the frame until we get there
+ if (position > m_curPosition + 1
+ && m_preseek
+ && position - (m_curPosition + 1) < m_preseek)
+ {
+ while(av_read_frame(m_formatCtx, &packet)>=0)
+ {
+ if (packet.stream_index == m_videoStream)
+ {
+ avcodec_decode_video(
+ m_codecCtx,
+ m_frame, &frameFinished,
+ packet.data, packet.size);
+ if (frameFinished)
+ m_curPosition++;
+ }
+ av_free_packet(&packet);
+ if (position == m_curPosition+1)
+ break;
+ }
+ }
+ // if the position is not in preseek, do a direct jump
+ if (position != m_curPosition + 1)
+ {
+ double timeBase = av_q2d(m_formatCtx->streams[m_videoStream]->time_base);
+ long long pos = (long long)
+ ((long long) (position - m_preseek) * AV_TIME_BASE / m_baseFrameRate);
+ long long startTs = m_formatCtx->streams[m_videoStream]->start_time;
+
+ if (pos < 0)
+ pos = 0;
+
+ if (startTs != AV_NOPTS_VALUE)
+ pos += (long long)(startTs * AV_TIME_BASE * timeBase);
+
+ if (position <= m_curPosition || !m_eof)
+ {
+ // no need to seek past the end of the file
+ if (av_seek_frame(m_formatCtx, -1, pos, AVSEEK_FLAG_BACKWARD) >= 0)
+ {
+ // current position is now lost, guess a value.
+ // It's not important because it will be set at this end of this function
+ m_curPosition = position - m_preseek - 1;
+ }
+ }
+ // this is the timestamp of the frame we're looking for
+ targetTs = (long long)(((double) position) / m_baseFrameRate / timeBase);
+ if (startTs != AV_NOPTS_VALUE)
+ targetTs += startTs;
+
+ posFound = 0;
+ avcodec_flush_buffers(m_codecCtx);
+ }
+
+ while(av_read_frame(m_formatCtx, &packet)>=0)
+ {
+ if(packet.stream_index == m_videoStream)
+ {
+ avcodec_decode_video(m_codecCtx,
+ m_frame, &frameFinished,
+ packet.data, packet.size);
+
+ if (frameFinished && !posFound)
+ {
+ if (packet.dts >= targetTs)
+ posFound = 1;
+ }
+
+ if(frameFinished && posFound == 1)
+ {
+ AVFrame * input = m_frame;
+
+ /* This means the data wasnt read properly,
+ this check stops crashing */
+ if ( input->data[0]==0 && input->data[1]==0
+ && input->data[2]==0 && input->data[3]==0)
+ {
+ av_free_packet(&packet);
+ break;
+ }
+
+ if (m_deinterlace)
+ {
+ if (avpicture_deinterlace(
+ (AVPicture*) m_frameDeinterlaced,
+ (const AVPicture*) m_frame,
+ m_codecCtx->pix_fmt,
+ m_codecCtx->width,
+ m_codecCtx->height) >= 0)
+ {
+ input = m_frameDeinterlaced;
+ }
+ }
+ // convert to RGB24
+ sws_scale(m_imgConvertCtx,
+ input->data,
+ input->linesize,
+ 0,
+ m_codecCtx->height,
+ m_frameRGB->data,
+ m_frameRGB->linesize);
+ av_free_packet(&packet);
+ frameLoaded = true;
+ break;
+ }
+ }
+ av_free_packet(&packet);
+ }
+ m_eof = !frameLoaded;
+ if (frameLoaded)
+ m_curPosition = position;
+ return frameLoaded;
+}
+
+
+// python methods
+
+
+// cast Image pointer to VideoFFmpeg
+inline VideoFFmpeg * getVideoFFmpeg (PyImage * self)
+{ return static_cast<VideoFFmpeg*>(self->m_image); }
+
+
+// object initialization
+static int VideoFFmpeg_init (PyObject * pySelf, PyObject * args, PyObject * kwds)
+{
+ PyImage * self = reinterpret_cast<PyImage*>(pySelf);
+ // parameters - video source
+ // file name or format type for capture (only for Linux: video4linux or dv1394)
+ char * file = NULL;
+ // capture device number
+ short capt = -1;
+ // capture width, only if capt is >= 0
+ short width = 0;
+ // capture height, only if capt is >= 0
+ short height = 0;
+ // capture rate, only if capt is >= 0
+ float rate = 25.f;
+
+ static char *kwlist[] = {"file", "capture", "rate", "width", "height", NULL};
+
+ // get parameters
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|hfhh", kwlist, &file, &capt,
+ &rate, &width, &height))
+ return -1;
+
+ try
+ {
+ // create video object
+ Video_init<VideoFFmpeg>(self);
+
+ // set thread usage
+ getVideoFFmpeg(self)->initParams(width, height, rate);
+
+ // open video source
+ Video_open(getVideo(self), file, capt);
+ }
+ catch (Exception & exp)
+ {
+ exp.report();
+ return -1;
+ }
+ // initialization succeded
+ return 0;
+}
+
+PyObject * VideoFFmpeg_getPreseek (PyImage *self, void * closure)
+{
+ return Py_BuildValue("h", getFFmpeg(self)->getPreseek());
+}
+
+// set range
+int VideoFFmpeg_setPreseek (PyImage * self, PyObject * value, void * closure)
+{
+ // check validity of parameter
+ if (value == NULL || !PyInt_Check(value))
+ {
+ PyErr_SetString(PyExc_TypeError, "The value must be an integer");
+ return -1;
+ }
+ // set preseek
+ getFFmpeg(self)->setPreseek(PyInt_AsLong(value));
+ // success
+ return 0;
+}
+
+// get deinterlace
+PyObject * VideoFFmpeg_getDeinterlace (PyImage * self, void * closure)
+{
+ if (getFFmpeg(self)->getDeinterlace())
+ Py_RETURN_TRUE;
+ else
+ Py_RETURN_FALSE;
+}
+
+// set flip
+int VideoFFmpeg_setDeinterlace (PyImage * self, PyObject * value, void * closure)
+{
+ // check parameter, report failure
+ if (value == NULL || !PyBool_Check(value))
+ {
+ PyErr_SetString(PyExc_TypeError, "The value must be a bool");
+ return -1;
+ }
+ // set deinterlace
+ getFFmpeg(self)->setDeinterlace(value == Py_True);
+ // success
+ return 0;
+}
+
+// methods structure
+static PyMethodDef videoMethods[] =
+{ // methods from VideoBase class
+ {"play", (PyCFunction)Video_play, METH_NOARGS, "Play video"},
+ {"stop", (PyCFunction)Video_stop, METH_NOARGS, "Stop (pause) video"},
+ {"refresh", (PyCFunction)Video_refresh, METH_NOARGS, "Refresh video - get its status"},
+ {NULL}
+};
+// attributes structure
+static PyGetSetDef videoGetSets[] =
+{ // methods from VideoBase class
+ {(char*)"status", (getter)Video_getStatus, NULL, (char*)"video status", NULL},
+ {(char*)"range", (getter)Video_getRange, (setter)Video_setRange, (char*)"replay range", NULL},
+ {(char*)"repeat", (getter)Video_getRepeat, (setter)Video_setRepeat, (char*)"repeat count, -1 for infinite repeat", NULL},
+ {(char*)"framerate", (getter)Video_getFrameRate, (setter)Video_setFrameRate, (char*)"frame rate", NULL},
+ // attributes from ImageBase class
+ {(char*)"image", (getter)Image_getImage, NULL, (char*)"image data", NULL},
+ {(char*)"size", (getter)Image_getSize, NULL, (char*)"image size", NULL},
+ {(char*)"scale", (getter)Image_getScale, (setter)Image_setScale, (char*)"fast scale of image (near neighbour)", NULL},
+ {(char*)"flip", (getter)Image_getFlip, (setter)Image_setFlip, (char*)"flip image vertically", NULL},
+ {(char*)"filter", (getter)Image_getFilter, (setter)Image_setFilter, (char*)"pixel filter", NULL},
+ {(char*)"preseek", (getter)VideoFFmpeg_getPreseek, (setter)VideoFFmpeg_setPreseek, (char*)"nb of frames of preseek", NULL},
+ {(char*)"deinterlace", (getter)VideoFFmpeg_getDeinterlace, (setter)VideoFFmpeg_setDeinterlace, (char*)"deinterlace image", NULL},
+ {NULL}
+};
+
+// python type declaration
+PyTypeObject VideoFFmpegType =
+{
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "VideoTexture.VideoFFmpeg", /*tp_name*/
+ sizeof(PyImage), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)Image_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash */
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ "FFmpeg video source", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ videoMethods, /* tp_methods */
+ 0, /* tp_members */
+ videoGetSets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)VideoFFmpeg_init, /* tp_init */
+ 0, /* tp_alloc */
+ Image_allocNew, /* tp_new */
+};
+
+// object initialization
+static int ImageFFmpeg_init (PyObject * pySelf, PyObject * args, PyObject * kwds)
+{
+ PyImage * self = reinterpret_cast<PyImage*>(pySelf);
+ // parameters - video source
+ // file name or format type for capture (only for Linux: video4linux or dv1394)
+ char * file = NULL;
+
+ // get parameters
+ if (!PyArg_ParseTuple(args, "s", &file))
+ return -1;
+
+ try
+ {
+ // create video object
+ Video_init<VideoFFmpeg>(self);
+
+ getVideoFFmpeg(self)->initParams(0, 0, 1.0, true);
+
+ // open video source
+ Video_open(getVideo(self), file, -1);
+ }
+ catch (Exception & exp)
+ {
+ exp.report();
+ return -1;
+ }
+ // initialization succeded
+ return 0;
+}
+
+PyObject * Image_reload (PyImage * self, PyObject *args)
+{
+ char * newname = NULL;
+
+ if (self->m_image != NULL && PyArg_ParseTuple(args, "|s", &newname))
+ {
+ VideoFFmpeg* video = getFFmpeg(self);
+ // check type of object
+ if (!newname)
+ newname = video->getImageName();
+ if (!newname) {
+ // if not set, retport error
+ PyErr_SetString(PyExc_RuntimeError, "No image file name given");
+ return NULL;
+ }
+ // make sure the previous file is cleared
+ video->release();
+ // open the new file
+ video->openFile(newname);
+ }
+ Py_RETURN_NONE;
+}
+
+// methods structure
+static PyMethodDef imageMethods[] =
+{ // methods from VideoBase class
+ {"refresh", (PyCFunction)Video_refresh, METH_NOARGS, "Refresh image, i.e. load it"},
+ {"reload", (PyCFunction)Image_reload, METH_VARARGS, "Reload image, i.e. reopen it"},
+ {NULL}
+};
+// attributes structure
+static PyGetSetDef imageGetSets[] =
+{ // methods from VideoBase class
+ {(char*)"status", (getter)Video_getStatus, NULL, (char*)"video status", NULL},
+ // attributes from ImageBase class
+ {(char*)"image", (getter)Image_getImage, NULL, (char*)"image data", NULL},
+ {(char*)"size", (getter)Image_getSize, NULL, (char*)"image size", NULL},
+ {(char*)"scale", (getter)Image_getScale, (setter)Image_setScale, (char*)"fast scale of image (near neighbour)", NULL},
+ {(char*)"flip", (getter)Image_getFlip, (setter)Image_setFlip, (char*)"flip image vertically", NULL},
+ {(char*)"filter", (getter)Image_getFilter, (setter)Image_setFilter, (char*)"pixel filter", NULL},
+ {NULL}
+};
+
+// python type declaration
+PyTypeObject ImageFFmpegType =
+{
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "VideoTexture.ImageFFmpeg", /*tp_name*/
+ sizeof(PyImage), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)Image_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash */
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ "FFmpeg image source", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ imageMethods, /* tp_methods */
+ 0, /* tp_members */
+ imageGetSets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)ImageFFmpeg_init, /* tp_init */
+ 0, /* tp_alloc */
+ Image_allocNew, /* tp_new */
+};
+
+#endif //WITH_FFMPEG
+
+
diff --git a/source/gameengine/VideoTexture/VideoFFmpeg.h b/source/gameengine/VideoTexture/VideoFFmpeg.h
new file mode 100644
index 00000000000..e60f1727aab
--- /dev/null
+++ b/source/gameengine/VideoTexture/VideoFFmpeg.h
@@ -0,0 +1,173 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexture library
+
+Copyright (c) 2007 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+#if !defined VIDEOFFMPEG_H
+#define VIDEOFFMPEG_H
+
+#ifdef WITH_FFMPEG
+extern "C" {
+#include <ffmpeg/avformat.h>
+#include <ffmpeg/avcodec.h>
+#include <ffmpeg/rational.h>
+#include <ffmpeg/swscale.h>
+}
+
+#if LIBAVFORMAT_VERSION_INT < (49 << 16)
+#define FFMPEG_OLD_FRAME_RATE 1
+#else
+#define FFMPEG_CODEC_IS_POINTER 1
+#endif
+
+#if LIBAVFORMAT_VERSION_INT >= (52 << 16)
+#define FFMPEG_PB_IS_POINTER 1
+#endif
+
+#ifdef FFMPEG_CODEC_IS_POINTER
+static inline AVCodecContext* get_codec_from_stream(AVStream* stream)
+{
+ return stream->codec;
+}
+#else
+static inline AVCodecContext* get_codec_from_stream(AVStream* stream)
+{
+ return &stream->codec;
+}
+#endif
+
+#include "VideoBase.h"
+
+
+// type VideoFFmpeg declaration
+class VideoFFmpeg : public VideoBase
+{
+public:
+ /// constructor
+ VideoFFmpeg (HRESULT * hRslt);
+ /// destructor
+ virtual ~VideoFFmpeg ();
+
+ /// set initial parameters
+ void initParams (short width, short height, float rate, bool image=false);
+ /// open video/image file
+ virtual void openFile (char * file);
+ /// open video capture device
+ virtual void openCam (char * driver, short camIdx);
+
+ /// release video source
+ virtual bool release (void);
+
+ /// play video
+ virtual bool play (void);
+ /// stop/pause video
+ virtual bool stop (void);
+
+ /// set play range
+ virtual void setRange (double start, double stop);
+ /// set frame rate
+ virtual void setFrameRate (float rate);
+ // some specific getters and setters
+ int getPreseek(void) { return m_preseek; }
+ void setPreseek(int preseek) { if (preseek >= 0) m_preseek = preseek; }
+ bool getDeinterlace(void) { return m_deinterlace; }
+ void setDeinterlace(bool deinterlace) { m_deinterlace = deinterlace; }
+ char *getImageName(void) { return (m_isImage) ? m_imageName.Ptr() : NULL; }
+
+protected:
+
+ // format and codec information
+ AVCodec *m_codec;
+ AVFormatContext *m_formatCtx;
+ AVCodecContext *m_codecCtx;
+ // raw frame extracted from video file
+ AVFrame *m_frame;
+ // deinterlaced frame if codec requires it
+ AVFrame *m_frameDeinterlaced;
+ // decoded RGB24 frame if codec requires it
+ AVFrame *m_frameRGB;
+ // conversion from raw to RGB is done with sws_scale
+ struct SwsContext *m_imgConvertCtx;
+ // should the codec be deinterlaced?
+ bool m_deinterlace;
+ // number of frame of preseek
+ int m_preseek;
+ // order number of stream holding the video in format context
+ int m_videoStream;
+
+ // the actual frame rate
+ double m_baseFrameRate;
+
+ /// last displayed frame
+ long m_lastFrame;
+
+ /// end of file reached
+ bool m_eof;
+
+ /// current file pointer position in file expressed in frame number
+ long m_curPosition;
+
+ /// time of video play start
+ double m_startTime;
+
+ /// width of capture in pixel
+ short m_captWidth;
+
+ /// height of capture in pixel
+ short m_captHeight;
+
+ /// frame rate of capture in frames per seconds
+ float m_captRate;
+
+ /// is file an image?
+ bool m_isImage;
+
+ /// keep last image name
+ STR_String m_imageName;
+
+ /// image calculation
+ virtual void calcImage (unsigned int texId);
+
+ /// load frame from video
+ void loadFrame (void);
+
+ /// set actual position
+ void setPositions (void);
+
+ /// get actual framerate
+ double actFrameRate (void) { return m_frameRate * m_baseFrameRate; }
+
+ /// common function to video file and capture
+ int openStream(const char *filename, AVInputFormat *inputFormat, AVFormatParameters *formatParams);
+
+ /// check if a frame is available and load it in pFrame, return true if a frame could be retrieved
+ bool grabFrame(long frame);
+
+ /// return the frame in RGB24 format, the image data is found in AVFrame.data[0]
+ AVFrame* getFrame(void) { return m_frameRGB; }
+};
+
+inline VideoFFmpeg * getFFmpeg (PyImage * self)
+{
+ return static_cast<VideoFFmpeg*>(self->m_image);
+}
+
+#endif //WITH_FFMPEG
+
+#endif
diff --git a/source/gameengine/VideoTexture/blendVideoTex.cpp b/source/gameengine/VideoTexture/blendVideoTex.cpp
new file mode 100644
index 00000000000..b38882f8164
--- /dev/null
+++ b/source/gameengine/VideoTexture/blendVideoTex.cpp
@@ -0,0 +1,194 @@
+/* $Id$
+-----------------------------------------------------------------------------
+This source file is part of VideoTexure library
+
+Copyright (c) 2006 The Zdeno Ash Miklas
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+
+#include <PyObjectPlus.h>
+
+#include <RAS_GLExtensionManager.h>
+
+#include <RAS_IPolygonMaterial.h>
+
+//Old API
+//#include "TexPlayer.h"
+//#include "TexImage.h"
+//#include "TexFrameBuff.h"
+
+//#include "TexPlayerGL.h"
+
+#include "ImageBase.h"
+#include "FilterBase.h"
+#include "Texture.h"
+
+#include "Exception.h"
+
+
+// get material id
+static PyObject * getMaterialID (PyObject *self, PyObject *args)
+{
+ // parameters - game object with video texture
+ PyObject * obj = NULL;
+ // material name
+ char * matName;
+
+ // get parameters
+ if (!PyArg_ParseTuple(args, "Os", &obj, &matName))
+ return NULL;
+ // get material id
+ short matID = getMaterialID(obj, matName);
+ // if material was not found, report errot
+ if (matID < 0)
+ {
+ PyErr_SetString(PyExc_RuntimeError, "object doesn't have material with given name");
+ return NULL;
+ }
+ // return material ID
+ return Py_BuildValue("h", matID);
+}
+
+
+// get last error description
+static PyObject * getLastError (PyObject *self, PyObject *args)
+{
+ return Py_BuildValue("s", Exception::m_lastError.c_str());
+}
+
+// set log file
+static PyObject * setLogFile (PyObject *self, PyObject *args)
+{
+ // get parameters
+ if (!PyArg_ParseTuple(args, "s", &Exception::m_logFile))
+ return Py_BuildValue("i", -1);
+ // log file was loaded
+ return Py_BuildValue("i", 0);
+}
+
+
+// image to numpy array
+static PyObject * imageToArray (PyObject * self, PyObject *args)
+{
+ // parameter is Image object
+ PyObject * pyImg;
+ if (!PyArg_ParseTuple(args, "O", &pyImg) || !pyImageTypes.in(pyImg->ob_type))
+ {
+ // if object is incorect, report error
+ PyErr_SetString(PyExc_TypeError, "The value must be a image source object");
+ return NULL;
+ }
+ // get image structure
+ PyImage * img = reinterpret_cast<PyImage*>(pyImg);
+ // create array object
+ unsigned int * imgBuff = img->m_image->getImage();
+ // if image is available, convert it to array
+ if (imgBuff != NULL)
+ // Nasty problem here: the image buffer is an array of integers
+ // in the processor endian format. The user must take care of that in the script.
+ // Need to find an elegant solution to this problem
+ return Py_BuildValue("s#", imgBuff, img->m_image->getBuffSize());
+ // otherwise return None
+ Py_RETURN_NONE;
+}
+
+
+// metody modulu
+static PyMethodDef moduleMethods[] =
+{
+ {"materialID", getMaterialID, METH_VARARGS, "Gets object's Blender Material ID"},
+ {"getLastError", getLastError, METH_NOARGS, "Gets last error description"},
+ {"setLogFile", setLogFile, METH_VARARGS, "Sets log file name"},
+ {"imageToArray", imageToArray, METH_VARARGS, "get array from image source"},
+ {NULL} /* Sentinel */
+};
+
+#if WITH_FFMPEG
+extern PyTypeObject VideoFFmpegType;
+extern PyTypeObject ImageFFmpegType;
+#endif
+extern PyTypeObject FilterBlueScreenType;
+extern PyTypeObject FilterGrayType;
+extern PyTypeObject FilterColorType;
+extern PyTypeObject FilterLevelType;
+extern PyTypeObject FilterNormalType;
+extern PyTypeObject FilterRGB24Type;
+extern PyTypeObject FilterRGBA32Type;
+extern PyTypeObject FilterBGR24Type;
+extern PyTypeObject ImageBuffType;
+extern PyTypeObject ImageMixType;
+extern PyTypeObject ImageRenderType;
+extern PyTypeObject ImageViewportType;
+extern PyTypeObject ImageViewportType;
+
+
+static void registerAllTypes(void)
+{
+#if WITH_FFMPEG
+ pyImageTypes.add(&VideoFFmpegType, "VideoFFmpeg");
+ pyImageTypes.add(&ImageFFmpegType, "ImageFFmpeg");
+#endif
+ pyImageTypes.add(&ImageBuffType, "ImageBuff");
+ pyImageTypes.add(&ImageMixType, "ImageMix");
+ //pyImageTypes.add(&ImageRenderType, "ImageRender");
+ pyImageTypes.add(&ImageViewportType, "ImageViewport");
+
+ pyFilterTypes.add(&FilterBlueScreenType, "FilterBlueScreen");
+ pyFilterTypes.add(&FilterGrayType, "FilterGray");
+ pyFilterTypes.add(&FilterColorType, "FilterColor");
+ pyFilterTypes.add(&FilterLevelType, "FilterLevel");
+ pyFilterTypes.add(&FilterNormalType, "FilterNormal");
+ pyFilterTypes.add(&FilterRGB24Type, "FilterRGB24");
+ pyFilterTypes.add(&FilterRGBA32Type, "FilterRGBA32");
+ pyFilterTypes.add(&FilterBGR24Type, "FilterBGR24");
+}
+
+PyObject* initVideoTexture(void)
+{
+ // initialize GL extensions
+ //bgl::InitExtensions(0);
+
+ // prepare classes
+ registerAllTypes();
+ registerAllExceptions();
+
+ if (!pyImageTypes.ready())
+ return NULL;
+ if (!pyFilterTypes.ready())
+ return NULL;
+ if (PyType_Ready(&TextureType) < 0)
+ return NULL;
+
+ PyObject * m = Py_InitModule4("VideoTexture", moduleMethods,
+ "Module that allows to play video files on textures in GameBlender.",
+ (PyObject*)NULL,PYTHON_API_VERSION);
+ if (m == NULL)
+ return NULL;
+
+ // initialize classes
+ pyImageTypes.reg(m);
+ pyFilterTypes.reg(m);
+
+ Py_INCREF(&TextureType);
+ PyModule_AddObject(m, (char*)"Texture", (PyObject*)&TextureType);
+
+ // init last error description
+ Exception::m_lastError[0] = '\0';
+ return m;
+}
+
+// registration to Image types, put here because of silly linker bug
diff --git a/source/kernel/CMakeLists.txt b/source/kernel/CMakeLists.txt
index 3d966152cc5..ac759393326 100644
--- a/source/kernel/CMakeLists.txt
+++ b/source/kernel/CMakeLists.txt
@@ -24,7 +24,7 @@
#
# ***** END GPL LICENSE BLOCK *****
-SET(INC gen_messaging gen_system ../../intern/string ../../intern/moto/include)
+SET(INC gen_messaging gen_system ../../intern/string ../../intern/moto/include ../../source/blender/blenloader )
FILE(GLOB SRC
gen_messaging/intern/messaging.c
diff --git a/source/kernel/SConscript b/source/kernel/SConscript
index dd883e161c4..8bd1a18f835 100644
--- a/source/kernel/SConscript
+++ b/source/kernel/SConscript
@@ -5,6 +5,6 @@ sources = 'gen_messaging/intern/messaging.c gen_system/GEN_HashedPtr.cpp'
sources += ' gen_system/GEN_Matrix4x4.cpp gen_system/SYS_SingletonSystem.cpp'
sources += ' gen_system/SYS_System.cpp'
-incs = 'gen_messaging gen_system #/intern/string #/intern/moto/include'
+incs = 'gen_messaging gen_system #/intern/string #/intern/moto/include #/source/blender/blenloader '
-env.BlenderLib ( 'bf_kernel', Split(sources), Split(incs), [], libtype = ['common','game2', 'player'], priority = [15, 10, 140] )
+env.BlenderLib ( 'bf_kernel', Split(sources), Split(incs), [], libtype = ['common','game2', 'player'], priority = [15, 10, 150] )
diff --git a/source/kernel/gen_system/GEN_HashedPtr.cpp b/source/kernel/gen_system/GEN_HashedPtr.cpp
index 49ccb252246..6dbed1fb7a8 100644
--- a/source/kernel/gen_system/GEN_HashedPtr.cpp
+++ b/source/kernel/gen_system/GEN_HashedPtr.cpp
@@ -33,6 +33,8 @@
#include <config.h>
#endif
+#include "BLO_sys_types.h" // for intptr_t support
+
//
// Build hash index from pointer. Even though the final result
// is a 32-bit integer, use all the bits of the pointer as long
@@ -41,11 +43,7 @@
unsigned int GEN_Hash(void * inDWord)
{
-#if defined(_WIN64)
- unsigned __int64 key = (unsigned __int64)inDWord;
-#else
- unsigned long key = (unsigned long)inDWord;
-#endif
+ uintptr_t key = (uintptr_t)inDWord;
key += ~(key << 16);
key ^= (key >> 5);
diff --git a/source/kernel/gen_system/GEN_HashedPtr.h b/source/kernel/gen_system/GEN_HashedPtr.h
index 777ec76e067..13faa5f227b 100644
--- a/source/kernel/gen_system/GEN_HashedPtr.h
+++ b/source/kernel/gen_system/GEN_HashedPtr.h
@@ -39,6 +39,7 @@ public:
GEN_HashedPtr(void* val) : m_valptr(val) {};
unsigned int hash() const { return GEN_Hash(m_valptr);};
inline friend bool operator ==(const GEN_HashedPtr & rhs, const GEN_HashedPtr & lhs) { return rhs.m_valptr == lhs.m_valptr;};
+ void *getValue() const { return m_valptr; }
};
#endif //__GEN_HASHEDPTR
diff --git a/source/kernel/gen_system/GEN_Map.h b/source/kernel/gen_system/GEN_Map.h
index f9c14800499..88c79293223 100644
--- a/source/kernel/gen_system/GEN_Map.h
+++ b/source/kernel/gen_system/GEN_Map.h
@@ -50,6 +50,19 @@ public:
m_buckets[i] = 0;
}
}
+
+ GEN_Map(const GEN_Map& map)
+ {
+ m_num_buckets = map.m_num_buckets;
+ m_buckets = new Entry *[m_num_buckets];
+
+ for (int i = 0; i < m_num_buckets; ++i) {
+ m_buckets[i] = 0;
+
+ for(Entry *entry = map.m_buckets[i]; entry; entry=entry->m_next)
+ insert(entry->m_key, entry->m_value);
+ }
+ }
int size() {
int count=0;
@@ -82,6 +95,24 @@ public:
}
return 0;
}
+
+ Key* getKey(int index) {
+ int count=0;
+ for (int i=0;i<m_num_buckets;i++)
+ {
+ Entry* bucket = m_buckets[i];
+ while(bucket)
+ {
+ if (count==index)
+ {
+ return &bucket->m_key;
+ }
+ bucket = bucket->m_next;
+ count++;
+ }
+ }
+ return 0;
+ }
void clear() {
for (int i = 0; i < m_num_buckets; ++i) {
diff --git a/source/kernel/gen_system/Makefile b/source/kernel/gen_system/Makefile
index 855af376615..31535ad2a97 100644
--- a/source/kernel/gen_system/Makefile
+++ b/source/kernel/gen_system/Makefile
@@ -37,4 +37,5 @@ CCFLAGS += $(LEVEL_2_CPP_WARNINGS)
CPPFLAGS += -I$(NAN_MOTO)/include
CPPFLAGS += -I$(NAN_STRING)/include
+CPPFLAGS += -I../../../source/blender/blenloader
diff --git a/source/nan_compile.mk b/source/nan_compile.mk
index fd7960dff24..4b13ef8f678 100644
--- a/source/nan_compile.mk
+++ b/source/nan_compile.mk
@@ -40,13 +40,18 @@ ifneq ($(NAN_NO_KETSJI), true)
CFLAGS += -DUSE_SUMO_SOLID
CCFLAGS += -DUSE_SUMO_SOLID
ifeq ($(NAN_USE_BULLET), true)
- CFLAGS += -DUSE_BULLET
- CCFLAGS += -DUSE_BULLET
+ CFLAGS += -DUSE_BULLET -DWITH_BULLET
+ CCFLAGS += -DUSE_BULLET -DWITH_BULLET
endif
else
CPPFLAGS += -DNO_KETSJI
endif
+ifeq ($(WITH_BF_OPENMP), true)
+ CFLAGS += -fopenmp
+ CCFLAGS += -fopenmp
+endif
+
ifdef NAN_DEBUG
CFLAGS += $(NAN_DEBUG)
CCFLAGS += $(NAN_DEBUG)
@@ -168,10 +173,17 @@ ifeq ($(OS),openbsd)
endif
ifeq ($(OS),solaris)
- CC = gcc
- CCC = g++
-# CC = cc
-# CCC = CC
+ # Adding gcc flag to $CC is not good, however if its not there makesdna wont build - Campbell
+ ifeq (x86_64, $(findstring x86_64, $(CPU)))
+ CC = gcc -m64
+ CCC = g++ -m64
+ else
+ CC = gcc
+ CCC = g++
+ #CC = cc
+ #CCC = CC
+ endif
+
JAVAC = javac
JAVAH = javah
CFLAGS += -pipe -fPIC -funsigned-char -fno-strict-aliasing
@@ -179,6 +191,7 @@ ifeq ($(OS),solaris)
# CFLAGS += "-fast -xdepend -xarch=v8plus -xO3 -xlibmil -KPIC -DPIC -xchar=unsigned"
# CCFLAGS += "-fast -xdepend -xarch=v8plus -xO3 -xlibmil -xlibmopt -features=tmplife -norunpath -KPIC -DPIC -xchar=unsigned"
+ # Note, you might still want to compile a 32 bit binary if you have a 64bit system. if so remove the following lines
# ifeq ($(findstring 64,$(CPU)), 64)
# CFLAGS += -m64
# CCFLAGS += -m64
@@ -195,7 +208,8 @@ ifeq ($(OS),solaris)
JAVA_HEADERS = /usr/java/include
JAVA_SYSTEM_HEADERS = /usr/java/include/solaris
else
- OPENGL_HEADERS = $(LCGDIR)/mesa/include
+ # OPENGL_HEADERS = /usr/X11/include/mesa
+ OPENGL_HEADERS = /usr/X11/include/
endif
AR = ar
ARFLAGS = ruv
diff --git a/source/nan_definitions.mk b/source/nan_definitions.mk
index b552be8fc05..424a7c558d7 100644
--- a/source/nan_definitions.mk
+++ b/source/nan_definitions.mk
@@ -61,7 +61,11 @@ all debug::
export WITH_BF_STATICOPENGL ?= false
export WITH_BF_BLENDERGAMEENGINE ?= true
export WITH_BF_BLENDERPLAYER ?= true
- export WITH_BF_WEBPLUGIN ?= false
+ ifeq ($(NAN_NO_PLUGIN), true)
+ export WITH_BF_WEBPLUGIN = false
+ else
+ export WITH_BF_WEBPLUGIN ?= false
+ endif
export NAN_MOTO ?= $(LCGDIR)/moto
ifeq ($(FREE_WINDOWS), true)
@@ -91,6 +95,7 @@ endif
export NAN_OPENNL ?= $(LCGDIR)/opennl
export NAN_ELBEEM ?= $(LCGDIR)/elbeem
export NAN_SUPERLU ?= $(LCGDIR)/superlu
+ export NAN_GLEW ?= $(LCGDIR)/glew
ifeq ($(FREE_WINDOWS), true)
export NAN_FTGL ?= $(LCGDIR)/gcc/ftgl
export NAN_FFMPEG ?= $(LCGDIR)/gcc/ffmpeg
@@ -135,7 +140,7 @@ endif
ifeq ($(WITH_OPENEXR), true)
NAN_OPENEXR?=$(shell pkg-config --variable=prefix OpenEXR )
NAN_OPENEXR_INC?=$(shell pkg-config --cflags OpenEXR )
- NAN_OPENEXR_LIBS?=$(addprefix ${NAN_OPENEXR}/lib/lib,$(addsuffix .a,$(shell pkg-config --libs OpenEXR | sed -s "s/-l//g" )))
+ NAN_OPENEXR_LIBS?=$(addprefix ${NAN_OPENEXR}/lib/lib,$(addsuffix .a,$(shell pkg-config --libs-only-l OpenEXR | sed -s "s/-l//g" )))
endif
else
ifeq ($(OS), solaris)
@@ -279,7 +284,7 @@ endif
export FREEDESKTOP ?= true
export NAN_PYTHON ?= /usr/local
- export NAN_PYTHON_VERSION ?= 2.3
+ export NAN_PYTHON_VERSION ?= 2.5
export NAN_PYTHON_BINARY ?= $(NAN_PYTHON)/bin/python$(NAN_PYTHON_VERSION)
export NAN_PYTHON_LIB ?= $(NAN_PYTHON)/lib/python$(NAN_PYTHON_VERSION)/config/libpython$(NAN_PYTHON_VERSION).a
export NAN_OPENAL ?= /usr/local
@@ -294,9 +299,9 @@ endif
export NAN_NSPR ?= /usr/local
export NAN_FREETYPE ?= $(LCGDIR)/freetype
export NAN_GETTEXT ?= $(LCGDIR)/gettext
- export NAN_SDL ?= $(shell sdl11-config --prefix)
- export NAN_SDLLIBS ?= $(shell sdl11-config --libs)
- export NAN_SDLCFLAGS ?= $(shell sdl11-config --cflags)
+ export NAN_SDL ?= $(shell sdl-config --prefix)
+ export NAN_SDLLIBS ?= $(shell sdl-config --libs)
+ export NAN_SDLCFLAGS ?= $(shell sdl-config --cflags)
# Uncomment the following line to use Mozilla inplace of netscape
# CPPFLAGS +=-DMOZ_NOT_NET
@@ -413,6 +418,8 @@ endif
# enable freetype2 support for text objects
export WITH_FREETYPE2 ?= true
+ export WITH_BINRELOC ?= true
+
# enable ffmpeg support
ifndef NAN_NO_FFMPEG
export WITH_FFMPEG ?= true
@@ -479,7 +486,7 @@ endif
export NAN_TIFF ?= /usr
export NAN_ODE ?= $(LCGDIR)/ode
export NAN_TERRAPLAY ?=
- export NAN_MESA ?= $(LCGDIR)/mesa
+ export NAN_MESA ?= /usr/X11
export NAN_ZLIB ?= $(LCGDIR)/zlib
export NAN_NSPR ?= $(LCGDIR)/nspr
export NAN_FREETYPE ?= $(LCGDIR)/freetype
diff --git a/source/nan_link.mk b/source/nan_link.mk
index 668955e5fb6..8dda3b8c2df 100644
--- a/source/nan_link.mk
+++ b/source/nan_link.mk
@@ -87,7 +87,7 @@ ifeq ($(OS),linux)
LLIBS += -lc -lm -ldl -lutil
LOPTS = -export-dynamic
endif
- ifeq ($(CPU),$(findstring $(CPU), "i386 x86_64 ia64"))
+ ifeq ($(CPU),$(findstring $(CPU), "i386 x86_64 ia64 parisc64 powerpc sparc64"))
COMMENT = "MESA 3.1"
LLIBS = -L$(NAN_MESA)/lib -L/usr/X11R6/lib -lXmu -lXext -lX11 -lXi
LLIBS += -lutil -lc -lm -ldl -lpthread
@@ -97,13 +97,6 @@ ifeq ($(OS),linux)
SADD = $(NAN_MESA)/lib/libGL.a $(NAN_MESA)/lib/libGLU.a
DYNLDFLAGS = -shared $(LDFLAGS)
endif
- ifeq ($(CPU),$(findstring $(CPU), "powerpc sparc64"))
- LLIBS = -L/usr/X11R6/lib/ -lXmu -lXext -lX11 -lc -ldl -lm -lutil
- DADD = -lGL -lGLU
- SADD = /usr/lib/libGL.a /usr/lib/libGLU.a
- LOPTS = -export-dynamic
- DYNLDFLAGS = -shared $(LDFLAGS)
- endif
LLIBS += -lz
endif
@@ -116,8 +109,12 @@ endif
ifeq ($(OS),solaris)
ifeq (x86_64, $(findstring x86_64, $(CPU)))
LLIBS = -lrt
+ LLIBS += -L$(NAN_MESA)/lib/amd64
+ else
+ LLIBS += -L$(NAN_MESA)/lib
endif
- LLIBS += -L$(NAN_MESA)/lib -lGLU -lGL -lXmu -lXext -lXi -lX11 -lc -lm -ldl -lsocket -lnsl
+
+ LLIBS += -lGLU -lGL -lXmu -lXext -lXi -lX11 -lc -lm -ldl -lsocket -lnsl
DYNLDFLAGS = -shared $(LDFLAGS)
endif
@@ -166,4 +163,8 @@ ifeq ($(INTERNATIONAL),true)
LLIBS += $(NAN_GETTEXT_LIB)
endif
+ifeq ($(WITH_BF_OPENMP),true)
+ LLIBS += -lgomp
+endif
+
LLIBS += $(NAN_PYTHON_LIB)